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/ADT/STLExtras.h"
19 #include "llvm/Support/Debug.h"
24 //===----------------------------------------------------------------------===//
25 // EEVT::TypeSet Implementation
26 //===----------------------------------------------------------------------===//
28 static inline bool isInteger(MVT::SimpleValueType VT) {
29 return EVT(VT).isInteger();
31 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
32 return EVT(VT).isFloatingPoint();
34 static inline bool isVector(MVT::SimpleValueType VT) {
35 return EVT(VT).isVector();
37 static inline bool isScalar(MVT::SimpleValueType VT) {
38 return !EVT(VT).isVector();
41 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
44 else if (VT == MVT::fAny)
45 EnforceFloatingPoint(TP);
46 else if (VT == MVT::vAny)
49 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
50 VT == MVT::iPTRAny) && "Not a concrete type!");
51 TypeVec.push_back(VT);
56 EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
57 assert(!VTList.empty() && "empty list?");
58 TypeVec.append(VTList.begin(), VTList.end());
61 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
62 VTList[0] != MVT::fAny);
64 // Verify no duplicates.
65 array_pod_sort(TypeVec.begin(), TypeVec.end());
66 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
69 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
70 /// on completely unknown type sets.
71 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
72 bool (*Pred)(MVT::SimpleValueType),
73 const char *PredicateName) {
74 assert(isCompletelyUnknown());
75 const std::vector<MVT::SimpleValueType> &LegalTypes =
76 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
78 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
79 if (Pred == 0 || Pred(LegalTypes[i]))
80 TypeVec.push_back(LegalTypes[i]);
82 // If we have nothing that matches the predicate, bail out.
84 TP.error("Type inference contradiction found, no " +
85 std::string(PredicateName) + " types found");
86 // No need to sort with one element.
87 if (TypeVec.size() == 1) return true;
90 array_pod_sort(TypeVec.begin(), TypeVec.end());
91 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
96 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
97 /// integer value type.
98 bool EEVT::TypeSet::hasIntegerTypes() const {
99 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
100 if (isInteger(TypeVec[i]))
105 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
106 /// a floating point value type.
107 bool EEVT::TypeSet::hasFloatingPointTypes() const {
108 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
109 if (isFloatingPoint(TypeVec[i]))
114 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
116 bool EEVT::TypeSet::hasVectorTypes() const {
117 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
118 if (isVector(TypeVec[i]))
124 std::string EEVT::TypeSet::getName() const {
125 if (TypeVec.empty()) return "<empty>";
129 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
130 std::string VTName = llvm::getEnumName(TypeVec[i]);
131 // Strip off MVT:: prefix if present.
132 if (VTName.substr(0,5) == "MVT::")
133 VTName = VTName.substr(5);
134 if (i) Result += ':';
138 if (TypeVec.size() == 1)
140 return "{" + Result + "}";
143 /// MergeInTypeInfo - This merges in type information from the specified
144 /// argument. If 'this' changes, it returns true. If the two types are
145 /// contradictory (e.g. merge f32 into i32) then this throws an exception.
146 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
147 if (InVT.isCompletelyUnknown() || *this == InVT)
150 if (isCompletelyUnknown()) {
155 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
157 // Handle the abstract cases, seeing if we can resolve them better.
158 switch (TypeVec[0]) {
162 if (InVT.hasIntegerTypes()) {
163 EEVT::TypeSet InCopy(InVT);
164 InCopy.EnforceInteger(TP);
165 InCopy.EnforceScalar(TP);
167 if (InCopy.isConcrete()) {
168 // If the RHS has one integer type, upgrade iPTR to i32.
169 TypeVec[0] = InVT.TypeVec[0];
173 // If the input has multiple scalar integers, this doesn't add any info.
174 if (!InCopy.isCompletelyUnknown())
180 // If the input constraint is iAny/iPTR and this is an integer type list,
181 // remove non-integer types from the list.
182 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
184 bool MadeChange = EnforceInteger(TP);
186 // If we're merging in iPTR/iPTRAny and the node currently has a list of
187 // multiple different integer types, replace them with a single iPTR.
188 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
189 TypeVec.size() != 1) {
191 TypeVec[0] = InVT.TypeVec[0];
198 // If this is a type list and the RHS is a typelist as well, eliminate entries
199 // from this list that aren't in the other one.
200 bool MadeChange = false;
201 TypeSet InputSet(*this);
203 for (unsigned i = 0; i != TypeVec.size(); ++i) {
205 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
206 if (TypeVec[i] == InVT.TypeVec[j]) {
211 if (InInVT) continue;
212 TypeVec.erase(TypeVec.begin()+i--);
216 // If we removed all of our types, we have a type contradiction.
217 if (!TypeVec.empty())
220 // FIXME: Really want an SMLoc here!
221 TP.error("Type inference contradiction found, merging '" +
222 InVT.getName() + "' into '" + InputSet.getName() + "'");
223 return true; // unreachable
226 /// EnforceInteger - Remove all non-integer types from this set.
227 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
228 // If we know nothing, then get the full set.
230 return FillWithPossibleTypes(TP, isInteger, "integer");
231 if (!hasFloatingPointTypes())
234 TypeSet InputSet(*this);
236 // Filter out all the fp types.
237 for (unsigned i = 0; i != TypeVec.size(); ++i)
238 if (!isInteger(TypeVec[i]))
239 TypeVec.erase(TypeVec.begin()+i--);
242 TP.error("Type inference contradiction found, '" +
243 InputSet.getName() + "' needs to be integer");
247 /// EnforceFloatingPoint - Remove all integer types from this set.
248 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
249 // If we know nothing, then get the full set.
251 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
253 if (!hasIntegerTypes())
256 TypeSet InputSet(*this);
258 // Filter out all the fp types.
259 for (unsigned i = 0; i != TypeVec.size(); ++i)
260 if (!isFloatingPoint(TypeVec[i]))
261 TypeVec.erase(TypeVec.begin()+i--);
264 TP.error("Type inference contradiction found, '" +
265 InputSet.getName() + "' needs to be floating point");
269 /// EnforceScalar - Remove all vector types from this.
270 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
271 // If we know nothing, then get the full set.
273 return FillWithPossibleTypes(TP, isScalar, "scalar");
275 if (!hasVectorTypes())
278 TypeSet InputSet(*this);
280 // Filter out all the vector types.
281 for (unsigned i = 0; i != TypeVec.size(); ++i)
282 if (!isScalar(TypeVec[i]))
283 TypeVec.erase(TypeVec.begin()+i--);
286 TP.error("Type inference contradiction found, '" +
287 InputSet.getName() + "' needs to be scalar");
291 /// EnforceVector - Remove all vector types from this.
292 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
293 // If we know nothing, then get the full set.
295 return FillWithPossibleTypes(TP, isVector, "vector");
297 TypeSet InputSet(*this);
298 bool MadeChange = false;
300 // Filter out all the scalar types.
301 for (unsigned i = 0; i != TypeVec.size(); ++i)
302 if (!isVector(TypeVec[i])) {
303 TypeVec.erase(TypeVec.begin()+i--);
308 TP.error("Type inference contradiction found, '" +
309 InputSet.getName() + "' needs to be a vector");
315 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
316 /// this an other based on this information.
317 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
318 // Both operands must be integer or FP, but we don't care which.
319 bool MadeChange = false;
321 if (isCompletelyUnknown())
322 MadeChange = FillWithPossibleTypes(TP);
324 if (Other.isCompletelyUnknown())
325 MadeChange = Other.FillWithPossibleTypes(TP);
327 // If one side is known to be integer or known to be FP but the other side has
328 // no information, get at least the type integrality info in there.
329 if (!hasFloatingPointTypes())
330 MadeChange |= Other.EnforceInteger(TP);
331 else if (!hasIntegerTypes())
332 MadeChange |= Other.EnforceFloatingPoint(TP);
333 if (!Other.hasFloatingPointTypes())
334 MadeChange |= EnforceInteger(TP);
335 else if (!Other.hasIntegerTypes())
336 MadeChange |= EnforceFloatingPoint(TP);
338 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
339 "Should have a type list now");
341 // If one contains vectors but the other doesn't pull vectors out.
342 if (!hasVectorTypes())
343 MadeChange |= Other.EnforceScalar(TP);
344 if (!hasVectorTypes())
345 MadeChange |= EnforceScalar(TP);
347 // This code does not currently handle nodes which have multiple types,
348 // where some types are integer, and some are fp. Assert that this is not
350 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
351 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
352 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
354 // Okay, find the smallest type from the current set and remove it from the
356 MVT::SimpleValueType Smallest = TypeVec[0];
357 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
358 if (TypeVec[i] < Smallest)
359 Smallest = TypeVec[i];
361 // If this is the only type in the large set, the constraint can never be
363 if (Other.TypeVec.size() == 1 && Other.TypeVec[0] == Smallest)
364 TP.error("Type inference contradiction found, '" +
365 Other.getName() + "' has nothing larger than '" + getName() +"'!");
367 SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
368 std::find(Other.TypeVec.begin(), Other.TypeVec.end(), Smallest);
369 if (TVI != Other.TypeVec.end()) {
370 Other.TypeVec.erase(TVI);
374 // Okay, find the largest type in the Other set and remove it from the
376 MVT::SimpleValueType Largest = Other.TypeVec[0];
377 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
378 if (Other.TypeVec[i] > Largest)
379 Largest = Other.TypeVec[i];
381 // If this is the only type in the small set, the constraint can never be
383 if (TypeVec.size() == 1 && TypeVec[0] == Largest)
384 TP.error("Type inference contradiction found, '" +
385 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
387 TVI = std::find(TypeVec.begin(), TypeVec.end(), Largest);
388 if (TVI != TypeVec.end()) {
396 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
397 /// whose element is specified by VTOperand.
398 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
400 // "This" must be a vector and "VTOperand" must be a scalar.
401 bool MadeChange = false;
402 MadeChange |= EnforceVector(TP);
403 MadeChange |= VTOperand.EnforceScalar(TP);
405 // If we know the vector type, it forces the scalar to agree.
407 EVT IVT = getConcrete();
408 IVT = IVT.getVectorElementType();
410 VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
413 // If the scalar type is known, filter out vector types whose element types
415 if (!VTOperand.isConcrete())
418 MVT::SimpleValueType VT = VTOperand.getConcrete();
420 TypeSet InputSet(*this);
422 // Filter out all the types which don't have the right element type.
423 for (unsigned i = 0; i != TypeVec.size(); ++i) {
424 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
425 if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
426 TypeVec.erase(TypeVec.begin()+i--);
431 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
432 TP.error("Type inference contradiction found, forcing '" +
433 InputSet.getName() + "' to have a vector element");
437 //===----------------------------------------------------------------------===//
438 // Helpers for working with extended types.
440 bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
441 return LHS->getID() < RHS->getID();
444 /// Dependent variable map for CodeGenDAGPattern variant generation
445 typedef std::map<std::string, int> DepVarMap;
447 /// Const iterator shorthand for DepVarMap
448 typedef DepVarMap::const_iterator DepVarMap_citer;
451 void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
453 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
454 DepMap[N->getName()]++;
457 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
458 FindDepVarsOf(N->getChild(i), DepMap);
462 //! Find dependent variables within child patterns
465 void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
467 FindDepVarsOf(N, depcounts);
468 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
469 if (i->second > 1) { // std::pair<std::string, int>
470 DepVars.insert(i->first);
475 //! Dump the dependent variable set:
477 void DumpDepVars(MultipleUseVarSet &DepVars) {
478 if (DepVars.empty()) {
479 DEBUG(errs() << "<empty set>");
481 DEBUG(errs() << "[ ");
482 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
484 DEBUG(errs() << (*i) << " ");
486 DEBUG(errs() << "]");
493 //===----------------------------------------------------------------------===//
494 // PatternToMatch implementation
498 /// getPatternSize - Return the 'size' of this pattern. We want to match large
499 /// patterns before small ones. This is used to determine the size of a
501 static unsigned getPatternSize(const TreePatternNode *P,
502 const CodeGenDAGPatterns &CGP) {
503 unsigned Size = 3; // The node itself.
504 // If the root node is a ConstantSDNode, increases its size.
505 // e.g. (set R32:$dst, 0).
506 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
509 // FIXME: This is a hack to statically increase the priority of patterns
510 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
511 // Later we can allow complexity / cost for each pattern to be (optionally)
512 // specified. To get best possible pattern match we'll need to dynamically
513 // calculate the complexity of all patterns a dag can potentially map to.
514 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
516 Size += AM->getNumOperands() * 3;
518 // If this node has some predicate function that must match, it adds to the
519 // complexity of this node.
520 if (!P->getPredicateFns().empty())
523 // Count children in the count if they are also nodes.
524 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
525 TreePatternNode *Child = P->getChild(i);
526 if (!Child->isLeaf() && Child->getNumTypes() &&
527 Child->getType(0) != MVT::Other)
528 Size += getPatternSize(Child, CGP);
529 else if (Child->isLeaf()) {
530 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
531 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
532 else if (Child->getComplexPatternInfo(CGP))
533 Size += getPatternSize(Child, CGP);
534 else if (!Child->getPredicateFns().empty())
542 /// Compute the complexity metric for the input pattern. This roughly
543 /// corresponds to the number of nodes that are covered.
544 unsigned PatternToMatch::
545 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
546 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
550 /// getPredicateCheck - Return a single string containing all of this
551 /// pattern's predicates concatenated with "&&" operators.
553 std::string PatternToMatch::getPredicateCheck() const {
554 std::string PredicateCheck;
555 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
556 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
557 Record *Def = Pred->getDef();
558 if (!Def->isSubClassOf("Predicate")) {
562 assert(0 && "Unknown predicate type!");
564 if (!PredicateCheck.empty())
565 PredicateCheck += " && ";
566 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
570 return PredicateCheck;
573 //===----------------------------------------------------------------------===//
574 // SDTypeConstraint implementation
577 SDTypeConstraint::SDTypeConstraint(Record *R) {
578 OperandNo = R->getValueAsInt("OperandNum");
580 if (R->isSubClassOf("SDTCisVT")) {
581 ConstraintType = SDTCisVT;
582 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
583 if (x.SDTCisVT_Info.VT == MVT::isVoid)
584 throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
586 } else if (R->isSubClassOf("SDTCisPtrTy")) {
587 ConstraintType = SDTCisPtrTy;
588 } else if (R->isSubClassOf("SDTCisInt")) {
589 ConstraintType = SDTCisInt;
590 } else if (R->isSubClassOf("SDTCisFP")) {
591 ConstraintType = SDTCisFP;
592 } else if (R->isSubClassOf("SDTCisVec")) {
593 ConstraintType = SDTCisVec;
594 } else if (R->isSubClassOf("SDTCisSameAs")) {
595 ConstraintType = SDTCisSameAs;
596 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
597 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
598 ConstraintType = SDTCisVTSmallerThanOp;
599 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
600 R->getValueAsInt("OtherOperandNum");
601 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
602 ConstraintType = SDTCisOpSmallerThanOp;
603 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
604 R->getValueAsInt("BigOperandNum");
605 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
606 ConstraintType = SDTCisEltOfVec;
607 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
609 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
614 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
615 /// N, and the result number in ResNo.
616 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
617 const SDNodeInfo &NodeInfo,
619 unsigned NumResults = NodeInfo.getNumResults();
620 if (OpNo < NumResults) {
627 if (OpNo >= N->getNumChildren()) {
628 errs() << "Invalid operand number in type constraint "
629 << (OpNo+NumResults) << " ";
635 return N->getChild(OpNo);
638 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
639 /// constraint to the nodes operands. This returns true if it makes a
640 /// change, false otherwise. If a type contradiction is found, throw an
642 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
643 const SDNodeInfo &NodeInfo,
644 TreePattern &TP) const {
645 unsigned ResNo = 0; // The result number being referenced.
646 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
648 switch (ConstraintType) {
649 default: assert(0 && "Unknown constraint type!");
651 // Operand must be a particular type.
652 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
654 // Operand must be same as target pointer type.
655 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
657 // Require it to be one of the legal integer VTs.
658 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
660 // Require it to be one of the legal fp VTs.
661 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
663 // Require it to be one of the legal vector VTs.
664 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
667 TreePatternNode *OtherNode =
668 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
669 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
670 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
672 case SDTCisVTSmallerThanOp: {
673 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
674 // have an integer type that is smaller than the VT.
675 if (!NodeToApply->isLeaf() ||
676 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
677 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
678 ->isSubClassOf("ValueType"))
679 TP.error(N->getOperator()->getName() + " expects a VT operand!");
680 MVT::SimpleValueType VT =
681 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
683 EEVT::TypeSet TypeListTmp(VT, TP);
686 TreePatternNode *OtherNode =
687 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
690 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
692 case SDTCisOpSmallerThanOp: {
694 TreePatternNode *BigOperand =
695 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
697 return NodeToApply->getExtType(ResNo).
698 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
700 case SDTCisEltOfVec: {
702 TreePatternNode *VecOperand =
703 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
706 // Filter vector types out of VecOperand that don't have the right element
708 return VecOperand->getExtType(VResNo).
709 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
715 //===----------------------------------------------------------------------===//
716 // SDNodeInfo implementation
718 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
719 EnumName = R->getValueAsString("Opcode");
720 SDClassName = R->getValueAsString("SDClass");
721 Record *TypeProfile = R->getValueAsDef("TypeProfile");
722 NumResults = TypeProfile->getValueAsInt("NumResults");
723 NumOperands = TypeProfile->getValueAsInt("NumOperands");
725 // Parse the properties.
727 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
728 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
729 if (PropList[i]->getName() == "SDNPCommutative") {
730 Properties |= 1 << SDNPCommutative;
731 } else if (PropList[i]->getName() == "SDNPAssociative") {
732 Properties |= 1 << SDNPAssociative;
733 } else if (PropList[i]->getName() == "SDNPHasChain") {
734 Properties |= 1 << SDNPHasChain;
735 } else if (PropList[i]->getName() == "SDNPOutFlag") {
736 Properties |= 1 << SDNPOutFlag;
737 } else if (PropList[i]->getName() == "SDNPInFlag") {
738 Properties |= 1 << SDNPInFlag;
739 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
740 Properties |= 1 << SDNPOptInFlag;
741 } else if (PropList[i]->getName() == "SDNPMayStore") {
742 Properties |= 1 << SDNPMayStore;
743 } else if (PropList[i]->getName() == "SDNPMayLoad") {
744 Properties |= 1 << SDNPMayLoad;
745 } else if (PropList[i]->getName() == "SDNPSideEffect") {
746 Properties |= 1 << SDNPSideEffect;
747 } else if (PropList[i]->getName() == "SDNPMemOperand") {
748 Properties |= 1 << SDNPMemOperand;
749 } else if (PropList[i]->getName() == "SDNPVariadic") {
750 Properties |= 1 << SDNPVariadic;
752 errs() << "Unknown SD Node property '" << PropList[i]->getName()
753 << "' on node '" << R->getName() << "'!\n";
759 // Parse the type constraints.
760 std::vector<Record*> ConstraintList =
761 TypeProfile->getValueAsListOfDefs("Constraints");
762 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
765 /// getKnownType - If the type constraints on this node imply a fixed type
766 /// (e.g. all stores return void, etc), then return it as an
767 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
768 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
769 unsigned NumResults = getNumResults();
770 assert(NumResults <= 1 &&
771 "We only work with nodes with zero or one result so far!");
772 assert(ResNo == 0 && "Only handles single result nodes so far");
774 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
775 // Make sure that this applies to the correct node result.
776 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
779 switch (TypeConstraints[i].ConstraintType) {
781 case SDTypeConstraint::SDTCisVT:
782 return TypeConstraints[i].x.SDTCisVT_Info.VT;
783 case SDTypeConstraint::SDTCisPtrTy:
790 //===----------------------------------------------------------------------===//
791 // TreePatternNode implementation
794 TreePatternNode::~TreePatternNode() {
795 #if 0 // FIXME: implement refcounted tree nodes!
796 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
801 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
802 if (Operator->getName() == "set" ||
803 Operator->getName() == "implicit")
804 return 0; // All return nothing.
806 if (Operator->isSubClassOf("Intrinsic"))
807 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
809 if (Operator->isSubClassOf("SDNode"))
810 return CDP.getSDNodeInfo(Operator).getNumResults();
812 if (Operator->isSubClassOf("PatFrag")) {
813 // If we've already parsed this pattern fragment, get it. Otherwise, handle
814 // the forward reference case where one pattern fragment references another
815 // before it is processed.
816 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
817 return PFRec->getOnlyTree()->getNumTypes();
819 // Get the result tree.
820 DagInit *Tree = Operator->getValueAsDag("Fragment");
822 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
823 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
824 assert(Op && "Invalid Fragment");
825 return GetNumNodeResults(Op, CDP);
828 if (Operator->isSubClassOf("Instruction")) {
829 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
831 // FIXME: Should allow access to all the results here.
832 unsigned NumDefsToAdd = InstInfo.NumDefs ? 1 : 0;
834 // Add on one implicit def if it has a resolvable type.
835 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
840 if (Operator->isSubClassOf("SDNodeXForm"))
841 return 1; // FIXME: Generalize SDNodeXForm
844 errs() << "Unhandled node in GetNumNodeResults\n";
848 void TreePatternNode::print(raw_ostream &OS) const {
850 OS << *getLeafValue();
852 OS << '(' << getOperator()->getName();
854 for (unsigned i = 0, e = Types.size(); i != e; ++i)
855 OS << ':' << getExtType(i).getName();
858 if (getNumChildren() != 0) {
860 getChild(0)->print(OS);
861 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
863 getChild(i)->print(OS);
869 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
870 OS << "<<P:" << PredicateFns[i] << ">>";
872 OS << "<<X:" << TransformFn->getName() << ">>";
873 if (!getName().empty())
874 OS << ":$" << getName();
877 void TreePatternNode::dump() const {
881 /// isIsomorphicTo - Return true if this node is recursively
882 /// isomorphic to the specified node. For this comparison, the node's
883 /// entire state is considered. The assigned name is ignored, since
884 /// nodes with differing names are considered isomorphic. However, if
885 /// the assigned name is present in the dependent variable set, then
886 /// the assigned name is considered significant and the node is
887 /// isomorphic if the names match.
888 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
889 const MultipleUseVarSet &DepVars) const {
890 if (N == this) return true;
891 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
892 getPredicateFns() != N->getPredicateFns() ||
893 getTransformFn() != N->getTransformFn())
897 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
898 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
899 return ((DI->getDef() == NDI->getDef())
900 && (DepVars.find(getName()) == DepVars.end()
901 || getName() == N->getName()));
904 return getLeafValue() == N->getLeafValue();
907 if (N->getOperator() != getOperator() ||
908 N->getNumChildren() != getNumChildren()) return false;
909 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
910 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
915 /// clone - Make a copy of this tree and all of its children.
917 TreePatternNode *TreePatternNode::clone() const {
918 TreePatternNode *New;
920 New = new TreePatternNode(getLeafValue(), getNumTypes());
922 std::vector<TreePatternNode*> CChildren;
923 CChildren.reserve(Children.size());
924 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
925 CChildren.push_back(getChild(i)->clone());
926 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
928 New->setName(getName());
930 New->setPredicateFns(getPredicateFns());
931 New->setTransformFn(getTransformFn());
935 /// RemoveAllTypes - Recursively strip all the types of this tree.
936 void TreePatternNode::RemoveAllTypes() {
937 for (unsigned i = 0, e = Types.size(); i != e; ++i)
938 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
939 if (isLeaf()) return;
940 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
941 getChild(i)->RemoveAllTypes();
945 /// SubstituteFormalArguments - Replace the formal arguments in this tree
946 /// with actual values specified by ArgMap.
947 void TreePatternNode::
948 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
949 if (isLeaf()) return;
951 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
952 TreePatternNode *Child = getChild(i);
953 if (Child->isLeaf()) {
954 Init *Val = Child->getLeafValue();
955 if (dynamic_cast<DefInit*>(Val) &&
956 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
957 // We found a use of a formal argument, replace it with its value.
958 TreePatternNode *NewChild = ArgMap[Child->getName()];
959 assert(NewChild && "Couldn't find formal argument!");
960 assert((Child->getPredicateFns().empty() ||
961 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
962 "Non-empty child predicate clobbered!");
963 setChild(i, NewChild);
966 getChild(i)->SubstituteFormalArguments(ArgMap);
972 /// InlinePatternFragments - If this pattern refers to any pattern
973 /// fragments, inline them into place, giving us a pattern without any
974 /// PatFrag references.
975 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
976 if (isLeaf()) return this; // nothing to do.
977 Record *Op = getOperator();
979 if (!Op->isSubClassOf("PatFrag")) {
980 // Just recursively inline children nodes.
981 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
982 TreePatternNode *Child = getChild(i);
983 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
985 assert((Child->getPredicateFns().empty() ||
986 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
987 "Non-empty child predicate clobbered!");
989 setChild(i, NewChild);
994 // Otherwise, we found a reference to a fragment. First, look up its
995 // TreePattern record.
996 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
998 // Verify that we are passing the right number of operands.
999 if (Frag->getNumArgs() != Children.size())
1000 TP.error("'" + Op->getName() + "' fragment requires " +
1001 utostr(Frag->getNumArgs()) + " operands!");
1003 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1005 std::string Code = Op->getValueAsCode("Predicate");
1007 FragTree->addPredicateFn("Predicate_"+Op->getName());
1009 // Resolve formal arguments to their actual value.
1010 if (Frag->getNumArgs()) {
1011 // Compute the map of formal to actual arguments.
1012 std::map<std::string, TreePatternNode*> ArgMap;
1013 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1014 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1016 FragTree->SubstituteFormalArguments(ArgMap);
1019 FragTree->setName(getName());
1020 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1021 FragTree->UpdateNodeType(i, getExtType(i), TP);
1023 // Transfer in the old predicates.
1024 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1025 FragTree->addPredicateFn(getPredicateFns()[i]);
1027 // Get a new copy of this fragment to stitch into here.
1028 //delete this; // FIXME: implement refcounting!
1030 // The fragment we inlined could have recursive inlining that is needed. See
1031 // if there are any pattern fragments in it and inline them as needed.
1032 return FragTree->InlinePatternFragments(TP);
1035 /// getImplicitType - Check to see if the specified record has an implicit
1036 /// type which should be applied to it. This will infer the type of register
1037 /// references from the register file information, for example.
1039 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1040 bool NotRegisters, TreePattern &TP) {
1041 // Check to see if this is a register or a register class.
1042 if (R->isSubClassOf("RegisterClass")) {
1043 assert(ResNo == 0 && "Regclass ref only has one result!");
1045 return EEVT::TypeSet(); // Unknown.
1046 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1047 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1050 if (R->isSubClassOf("PatFrag")) {
1051 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1052 // Pattern fragment types will be resolved when they are inlined.
1053 return EEVT::TypeSet(); // Unknown.
1056 if (R->isSubClassOf("Register")) {
1057 assert(ResNo == 0 && "Registers only produce one result!");
1059 return EEVT::TypeSet(); // Unknown.
1060 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1061 return EEVT::TypeSet(T.getRegisterVTs(R));
1064 if (R->isSubClassOf("SubRegIndex")) {
1065 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1066 return EEVT::TypeSet();
1069 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1070 assert(ResNo == 0 && "This node only has one result!");
1071 // Using a VTSDNode or CondCodeSDNode.
1072 return EEVT::TypeSet(MVT::Other, TP);
1075 if (R->isSubClassOf("ComplexPattern")) {
1076 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1078 return EEVT::TypeSet(); // Unknown.
1079 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1082 if (R->isSubClassOf("PointerLikeRegClass")) {
1083 assert(ResNo == 0 && "Regclass can only have one result!");
1084 return EEVT::TypeSet(MVT::iPTR, TP);
1087 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1088 R->getName() == "zero_reg") {
1090 return EEVT::TypeSet(); // Unknown.
1093 TP.error("Unknown node flavor used in pattern: " + R->getName());
1094 return EEVT::TypeSet(MVT::Other, TP);
1098 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1099 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1100 const CodeGenIntrinsic *TreePatternNode::
1101 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1102 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1103 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1104 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1108 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1109 return &CDP.getIntrinsicInfo(IID);
1112 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1113 /// return the ComplexPattern information, otherwise return null.
1114 const ComplexPattern *
1115 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1116 if (!isLeaf()) return 0;
1118 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1119 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1120 return &CGP.getComplexPattern(DI->getDef());
1124 /// NodeHasProperty - Return true if this node has the specified property.
1125 bool TreePatternNode::NodeHasProperty(SDNP Property,
1126 const CodeGenDAGPatterns &CGP) const {
1128 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1129 return CP->hasProperty(Property);
1133 Record *Operator = getOperator();
1134 if (!Operator->isSubClassOf("SDNode")) return false;
1136 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1142 /// TreeHasProperty - Return true if any node in this tree has the specified
1144 bool TreePatternNode::TreeHasProperty(SDNP Property,
1145 const CodeGenDAGPatterns &CGP) const {
1146 if (NodeHasProperty(Property, CGP))
1148 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1149 if (getChild(i)->TreeHasProperty(Property, CGP))
1154 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1155 /// commutative intrinsic.
1157 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1158 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1159 return Int->isCommutative;
1164 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1165 /// this node and its children in the tree. This returns true if it makes a
1166 /// change, false otherwise. If a type contradiction is found, throw an
1168 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1169 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1171 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1172 // If it's a regclass or something else known, include the type.
1173 bool MadeChange = false;
1174 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1175 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1176 NotRegisters, TP), TP);
1180 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
1181 assert(Types.size() == 1 && "Invalid IntInit");
1183 // Int inits are always integers. :)
1184 bool MadeChange = Types[0].EnforceInteger(TP);
1186 if (!Types[0].isConcrete())
1189 MVT::SimpleValueType VT = getType(0);
1190 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1193 unsigned Size = EVT(VT).getSizeInBits();
1194 // Make sure that the value is representable for this type.
1195 if (Size >= 32) return MadeChange;
1197 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1198 if (Val == II->getValue()) return MadeChange;
1200 // If sign-extended doesn't fit, does it fit as unsigned?
1202 unsigned UnsignedVal;
1203 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1204 UnsignedVal = unsigned(II->getValue());
1206 if ((ValueMask & UnsignedVal) == UnsignedVal)
1209 TP.error("Integer value '" + itostr(II->getValue())+
1210 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1216 // special handling for set, which isn't really an SDNode.
1217 if (getOperator()->getName() == "set") {
1218 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1219 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1220 unsigned NC = getNumChildren();
1222 TreePatternNode *SetVal = getChild(NC-1);
1223 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1225 for (unsigned i = 0; i < NC-1; ++i) {
1226 TreePatternNode *Child = getChild(i);
1227 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1229 // Types of operands must match.
1230 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1231 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1236 if (getOperator()->getName() == "implicit") {
1237 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1239 bool MadeChange = false;
1240 for (unsigned i = 0; i < getNumChildren(); ++i)
1241 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1245 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
1246 bool MadeChange = false;
1247 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1248 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1250 assert(getChild(0)->getNumTypes() == 1 &&
1251 getChild(1)->getNumTypes() == 1 && "Unhandled case");
1253 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1254 // what type it gets, so if it didn't get a concrete type just give it the
1255 // first viable type from the reg class.
1256 if (!getChild(1)->hasTypeSet(0) &&
1257 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1258 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1259 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
1264 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1265 bool MadeChange = false;
1267 // Apply the result type to the node.
1268 unsigned NumRetVTs = Int->IS.RetVTs.size();
1269 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1271 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1272 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1274 if (getNumChildren() != NumParamVTs + 1)
1275 TP.error("Intrinsic '" + Int->Name + "' expects " +
1276 utostr(NumParamVTs) + " operands, not " +
1277 utostr(getNumChildren() - 1) + " operands!");
1279 // Apply type info to the intrinsic ID.
1280 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1282 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1283 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1285 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1286 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1287 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1292 if (getOperator()->isSubClassOf("SDNode")) {
1293 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1295 // Check that the number of operands is sane. Negative operands -> varargs.
1296 if (NI.getNumOperands() >= 0 &&
1297 getNumChildren() != (unsigned)NI.getNumOperands())
1298 TP.error(getOperator()->getName() + " node requires exactly " +
1299 itostr(NI.getNumOperands()) + " operands!");
1301 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1302 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1303 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1307 if (getOperator()->isSubClassOf("Instruction")) {
1308 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1309 CodeGenInstruction &InstInfo =
1310 CDP.getTargetInfo().getInstruction(getOperator());
1312 bool MadeChange = false;
1314 // Apply the result types to the node, these come from the things in the
1315 // (outs) list of the instruction.
1316 // FIXME: Cap at one result so far.
1317 unsigned NumResultsToAdd = InstInfo.NumDefs ? 1 : 0;
1318 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1319 Record *ResultNode = Inst.getResult(ResNo);
1321 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1322 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
1323 } else if (ResultNode->getName() == "unknown") {
1326 assert(ResultNode->isSubClassOf("RegisterClass") &&
1327 "Operands should be register classes!");
1328 const CodeGenRegisterClass &RC =
1329 CDP.getTargetInfo().getRegisterClass(ResultNode);
1330 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
1334 // If the instruction has implicit defs, we apply the first one as a result.
1335 // FIXME: This sucks, it should apply all implicit defs.
1336 if (!InstInfo.ImplicitDefs.empty()) {
1337 unsigned ResNo = NumResultsToAdd;
1339 // FIXME: Generalize to multiple possible types and multiple possible
1341 MVT::SimpleValueType VT =
1342 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1344 if (VT != MVT::Other)
1345 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1348 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1350 if (getOperator()->getName() == "INSERT_SUBREG") {
1351 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1352 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1353 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1356 unsigned ChildNo = 0;
1357 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1358 Record *OperandNode = Inst.getOperand(i);
1360 // If the instruction expects a predicate or optional def operand, we
1361 // codegen this by setting the operand to it's default value if it has a
1362 // non-empty DefaultOps field.
1363 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1364 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1365 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1368 // Verify that we didn't run out of provided operands.
1369 if (ChildNo >= getNumChildren())
1370 TP.error("Instruction '" + getOperator()->getName() +
1371 "' expects more operands than were provided.");
1373 MVT::SimpleValueType VT;
1374 TreePatternNode *Child = getChild(ChildNo++);
1375 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1377 if (OperandNode->isSubClassOf("RegisterClass")) {
1378 const CodeGenRegisterClass &RC =
1379 CDP.getTargetInfo().getRegisterClass(OperandNode);
1380 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
1381 } else if (OperandNode->isSubClassOf("Operand")) {
1382 VT = getValueType(OperandNode->getValueAsDef("Type"));
1383 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
1384 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1385 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
1386 } else if (OperandNode->getName() == "unknown") {
1389 assert(0 && "Unknown operand type!");
1392 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1395 if (ChildNo != getNumChildren())
1396 TP.error("Instruction '" + getOperator()->getName() +
1397 "' was provided too many operands!");
1402 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1404 // Node transforms always take one operand.
1405 if (getNumChildren() != 1)
1406 TP.error("Node transform '" + getOperator()->getName() +
1407 "' requires one operand!");
1409 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1412 // If either the output or input of the xform does not have exact
1413 // type info. We assume they must be the same. Otherwise, it is perfectly
1414 // legal to transform from one type to a completely different type.
1416 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1417 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1418 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1425 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1426 /// RHS of a commutative operation, not the on LHS.
1427 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1428 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1430 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1436 /// canPatternMatch - If it is impossible for this pattern to match on this
1437 /// target, fill in Reason and return false. Otherwise, return true. This is
1438 /// used as a sanity check for .td files (to prevent people from writing stuff
1439 /// that can never possibly work), and to prevent the pattern permuter from
1440 /// generating stuff that is useless.
1441 bool TreePatternNode::canPatternMatch(std::string &Reason,
1442 const CodeGenDAGPatterns &CDP) {
1443 if (isLeaf()) return true;
1445 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1446 if (!getChild(i)->canPatternMatch(Reason, CDP))
1449 // If this is an intrinsic, handle cases that would make it not match. For
1450 // example, if an operand is required to be an immediate.
1451 if (getOperator()->isSubClassOf("Intrinsic")) {
1456 // If this node is a commutative operator, check that the LHS isn't an
1458 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1459 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1460 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1461 // Scan all of the operands of the node and make sure that only the last one
1462 // is a constant node, unless the RHS also is.
1463 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1464 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1465 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1466 if (OnlyOnRHSOfCommutative(getChild(i))) {
1467 Reason="Immediate value must be on the RHS of commutative operators!";
1476 //===----------------------------------------------------------------------===//
1477 // TreePattern implementation
1480 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1481 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1482 isInputPattern = isInput;
1483 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1484 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
1487 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1488 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1489 isInputPattern = isInput;
1490 Trees.push_back(ParseTreePattern(Pat, ""));
1493 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1494 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1495 isInputPattern = isInput;
1496 Trees.push_back(Pat);
1499 void TreePattern::error(const std::string &Msg) const {
1501 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1504 void TreePattern::ComputeNamedNodes() {
1505 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1506 ComputeNamedNodes(Trees[i]);
1509 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1510 if (!N->getName().empty())
1511 NamedNodes[N->getName()].push_back(N);
1513 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1514 ComputeNamedNodes(N->getChild(i));
1518 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
1519 if (DefInit *DI = dynamic_cast<DefInit*>(TheInit)) {
1520 Record *R = DI->getDef();
1522 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1523 // TreePatternNode if its own. For example:
1524 /// (foo GPR, imm) -> (foo GPR, (imm))
1525 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
1526 return ParseTreePattern(new DagInit(DI, "",
1527 std::vector<std::pair<Init*, std::string> >()),
1531 TreePatternNode *Res = new TreePatternNode(DI, 1);
1532 if (R->getName() == "node" && !OpName.empty()) {
1534 error("'node' argument requires a name to match with operand list");
1535 Args.push_back(OpName);
1538 Res->setName(OpName);
1542 if (IntInit *II = dynamic_cast<IntInit*>(TheInit)) {
1543 if (!OpName.empty())
1544 error("Constant int argument should not have a name!");
1545 return new TreePatternNode(II, 1);
1548 if (BitsInit *BI = dynamic_cast<BitsInit*>(TheInit)) {
1549 // Turn this into an IntInit.
1550 Init *II = BI->convertInitializerTo(new IntRecTy());
1551 if (II == 0 || !dynamic_cast<IntInit*>(II))
1552 error("Bits value must be constants!");
1553 return ParseTreePattern(II, OpName);
1556 DagInit *Dag = dynamic_cast<DagInit*>(TheInit);
1559 error("Pattern has unexpected init kind!");
1561 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1562 if (!OpDef) error("Pattern has unexpected operator type!");
1563 Record *Operator = OpDef->getDef();
1565 if (Operator->isSubClassOf("ValueType")) {
1566 // If the operator is a ValueType, then this must be "type cast" of a leaf
1568 if (Dag->getNumArgs() != 1)
1569 error("Type cast only takes one operand!");
1571 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
1573 // Apply the type cast.
1574 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1575 New->UpdateNodeType(0, getValueType(Operator), *this);
1577 if (!OpName.empty())
1578 error("ValueType cast should not have a name!");
1582 // Verify that this is something that makes sense for an operator.
1583 if (!Operator->isSubClassOf("PatFrag") &&
1584 !Operator->isSubClassOf("SDNode") &&
1585 !Operator->isSubClassOf("Instruction") &&
1586 !Operator->isSubClassOf("SDNodeXForm") &&
1587 !Operator->isSubClassOf("Intrinsic") &&
1588 Operator->getName() != "set" &&
1589 Operator->getName() != "implicit")
1590 error("Unrecognized node '" + Operator->getName() + "'!");
1592 // Check to see if this is something that is illegal in an input pattern.
1593 if (isInputPattern) {
1594 if (Operator->isSubClassOf("Instruction") ||
1595 Operator->isSubClassOf("SDNodeXForm"))
1596 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1598 if (Operator->isSubClassOf("Intrinsic"))
1599 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1601 if (Operator->isSubClassOf("SDNode") &&
1602 Operator->getName() != "imm" &&
1603 Operator->getName() != "fpimm" &&
1604 Operator->getName() != "tglobaltlsaddr" &&
1605 Operator->getName() != "tconstpool" &&
1606 Operator->getName() != "tjumptable" &&
1607 Operator->getName() != "tframeindex" &&
1608 Operator->getName() != "texternalsym" &&
1609 Operator->getName() != "tblockaddress" &&
1610 Operator->getName() != "tglobaladdr" &&
1611 Operator->getName() != "bb" &&
1612 Operator->getName() != "vt")
1613 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1616 std::vector<TreePatternNode*> Children;
1618 // Parse all the operands.
1619 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1620 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
1622 // If the operator is an intrinsic, then this is just syntactic sugar for for
1623 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1624 // convert the intrinsic name to a number.
1625 if (Operator->isSubClassOf("Intrinsic")) {
1626 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1627 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1629 // If this intrinsic returns void, it must have side-effects and thus a
1631 if (Int.IS.RetVTs.empty())
1632 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1633 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
1634 // Has side-effects, requires chain.
1635 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1636 else // Otherwise, no chain.
1637 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1639 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID), 1);
1640 Children.insert(Children.begin(), IIDNode);
1643 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1644 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
1645 Result->setName(OpName);
1647 if (!Dag->getName().empty()) {
1648 assert(Result->getName().empty());
1649 Result->setName(Dag->getName());
1654 /// SimplifyTree - See if we can simplify this tree to eliminate something that
1655 /// will never match in favor of something obvious that will. This is here
1656 /// strictly as a convenience to target authors because it allows them to write
1657 /// more type generic things and have useless type casts fold away.
1659 /// This returns true if any change is made.
1660 static bool SimplifyTree(TreePatternNode *&N) {
1664 // If we have a bitconvert with a resolved type and if the source and
1665 // destination types are the same, then the bitconvert is useless, remove it.
1666 if (N->getOperator()->getName() == "bitconvert" &&
1667 N->getExtType(0).isConcrete() &&
1668 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1669 N->getName().empty()) {
1675 // Walk all children.
1676 bool MadeChange = false;
1677 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1678 TreePatternNode *Child = N->getChild(i);
1679 MadeChange |= SimplifyTree(Child);
1680 N->setChild(i, Child);
1687 /// InferAllTypes - Infer/propagate as many types throughout the expression
1688 /// patterns as possible. Return true if all types are inferred, false
1689 /// otherwise. Throw an exception if a type contradiction is found.
1691 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1692 if (NamedNodes.empty())
1693 ComputeNamedNodes();
1695 bool MadeChange = true;
1696 while (MadeChange) {
1698 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1699 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1700 MadeChange |= SimplifyTree(Trees[i]);
1703 // If there are constraints on our named nodes, apply them.
1704 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1705 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1706 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1708 // If we have input named node types, propagate their types to the named
1711 // FIXME: Should be error?
1712 assert(InNamedTypes->count(I->getKey()) &&
1713 "Named node in output pattern but not input pattern?");
1715 const SmallVectorImpl<TreePatternNode*> &InNodes =
1716 InNamedTypes->find(I->getKey())->second;
1718 // The input types should be fully resolved by now.
1719 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1720 // If this node is a register class, and it is the root of the pattern
1721 // then we're mapping something onto an input register. We allow
1722 // changing the type of the input register in this case. This allows
1723 // us to match things like:
1724 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1725 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1726 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1727 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1731 assert(Nodes[i]->getNumTypes() == 1 &&
1732 InNodes[0]->getNumTypes() == 1 &&
1733 "FIXME: cannot name multiple result nodes yet");
1734 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1739 // If there are multiple nodes with the same name, they must all have the
1741 if (I->second.size() > 1) {
1742 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1743 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
1744 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
1745 "FIXME: cannot name multiple result nodes yet");
1747 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1748 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
1754 bool HasUnresolvedTypes = false;
1755 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1756 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1757 return !HasUnresolvedTypes;
1760 void TreePattern::print(raw_ostream &OS) const {
1761 OS << getRecord()->getName();
1762 if (!Args.empty()) {
1763 OS << "(" << Args[0];
1764 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1765 OS << ", " << Args[i];
1770 if (Trees.size() > 1)
1772 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1774 Trees[i]->print(OS);
1778 if (Trees.size() > 1)
1782 void TreePattern::dump() const { print(errs()); }
1784 //===----------------------------------------------------------------------===//
1785 // CodeGenDAGPatterns implementation
1788 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1789 Intrinsics = LoadIntrinsics(Records, false);
1790 TgtIntrinsics = LoadIntrinsics(Records, true);
1792 ParseNodeTransforms();
1793 ParseComplexPatterns();
1794 ParsePatternFragments();
1795 ParseDefaultOperands();
1796 ParseInstructions();
1799 // Generate variants. For example, commutative patterns can match
1800 // multiple ways. Add them to PatternsToMatch as well.
1803 // Infer instruction flags. For example, we can detect loads,
1804 // stores, and side effects in many cases by examining an
1805 // instruction's pattern.
1806 InferInstructionFlags();
1809 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1810 for (pf_iterator I = PatternFragments.begin(),
1811 E = PatternFragments.end(); I != E; ++I)
1816 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1817 Record *N = Records.getDef(Name);
1818 if (!N || !N->isSubClassOf("SDNode")) {
1819 errs() << "Error getting SDNode '" << Name << "'!\n";
1825 // Parse all of the SDNode definitions for the target, populating SDNodes.
1826 void CodeGenDAGPatterns::ParseNodeInfo() {
1827 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1828 while (!Nodes.empty()) {
1829 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1833 // Get the builtin intrinsic nodes.
1834 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1835 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1836 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1839 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1840 /// map, and emit them to the file as functions.
1841 void CodeGenDAGPatterns::ParseNodeTransforms() {
1842 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1843 while (!Xforms.empty()) {
1844 Record *XFormNode = Xforms.back();
1845 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1846 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1847 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1853 void CodeGenDAGPatterns::ParseComplexPatterns() {
1854 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1855 while (!AMs.empty()) {
1856 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1862 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1863 /// file, building up the PatternFragments map. After we've collected them all,
1864 /// inline fragments together as necessary, so that there are no references left
1865 /// inside a pattern fragment to a pattern fragment.
1867 void CodeGenDAGPatterns::ParsePatternFragments() {
1868 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1870 // First step, parse all of the fragments.
1871 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1872 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1873 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1874 PatternFragments[Fragments[i]] = P;
1876 // Validate the argument list, converting it to set, to discard duplicates.
1877 std::vector<std::string> &Args = P->getArgList();
1878 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1880 if (OperandsSet.count(""))
1881 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1883 // Parse the operands list.
1884 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1885 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1886 // Special cases: ops == outs == ins. Different names are used to
1887 // improve readability.
1889 (OpsOp->getDef()->getName() != "ops" &&
1890 OpsOp->getDef()->getName() != "outs" &&
1891 OpsOp->getDef()->getName() != "ins"))
1892 P->error("Operands list should start with '(ops ... '!");
1894 // Copy over the arguments.
1896 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1897 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1898 static_cast<DefInit*>(OpsList->getArg(j))->
1899 getDef()->getName() != "node")
1900 P->error("Operands list should all be 'node' values.");
1901 if (OpsList->getArgName(j).empty())
1902 P->error("Operands list should have names for each operand!");
1903 if (!OperandsSet.count(OpsList->getArgName(j)))
1904 P->error("'" + OpsList->getArgName(j) +
1905 "' does not occur in pattern or was multiply specified!");
1906 OperandsSet.erase(OpsList->getArgName(j));
1907 Args.push_back(OpsList->getArgName(j));
1910 if (!OperandsSet.empty())
1911 P->error("Operands list does not contain an entry for operand '" +
1912 *OperandsSet.begin() + "'!");
1914 // If there is a code init for this fragment, keep track of the fact that
1915 // this fragment uses it.
1916 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1918 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
1920 // If there is a node transformation corresponding to this, keep track of
1922 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1923 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1924 P->getOnlyTree()->setTransformFn(Transform);
1927 // Now that we've parsed all of the tree fragments, do a closure on them so
1928 // that there are not references to PatFrags left inside of them.
1929 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1930 TreePattern *ThePat = PatternFragments[Fragments[i]];
1931 ThePat->InlinePatternFragments();
1933 // Infer as many types as possible. Don't worry about it if we don't infer
1934 // all of them, some may depend on the inputs of the pattern.
1936 ThePat->InferAllTypes();
1938 // If this pattern fragment is not supported by this target (no types can
1939 // satisfy its constraints), just ignore it. If the bogus pattern is
1940 // actually used by instructions, the type consistency error will be
1944 // If debugging, print out the pattern fragment result.
1945 DEBUG(ThePat->dump());
1949 void CodeGenDAGPatterns::ParseDefaultOperands() {
1950 std::vector<Record*> DefaultOps[2];
1951 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1952 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1954 // Find some SDNode.
1955 assert(!SDNodes.empty() && "No SDNodes parsed?");
1956 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1958 for (unsigned iter = 0; iter != 2; ++iter) {
1959 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1960 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1962 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1963 // SomeSDnode so that we can parse this.
1964 std::vector<std::pair<Init*, std::string> > Ops;
1965 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1966 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1967 DefaultInfo->getArgName(op)));
1968 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
1970 // Create a TreePattern to parse this.
1971 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1972 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1974 // Copy the operands over into a DAGDefaultOperand.
1975 DAGDefaultOperand DefaultOpInfo;
1977 TreePatternNode *T = P.getTree(0);
1978 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1979 TreePatternNode *TPN = T->getChild(op);
1980 while (TPN->ApplyTypeConstraints(P, false))
1981 /* Resolve all types */;
1983 if (TPN->ContainsUnresolvedType()) {
1985 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1986 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1988 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1989 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1991 DefaultOpInfo.DefaultOps.push_back(TPN);
1994 // Insert it into the DefaultOperands map so we can find it later.
1995 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
2000 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2001 /// instruction input. Return true if this is a real use.
2002 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2003 std::map<std::string, TreePatternNode*> &InstInputs) {
2004 // No name -> not interesting.
2005 if (Pat->getName().empty()) {
2006 if (Pat->isLeaf()) {
2007 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2008 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
2009 I->error("Input " + DI->getDef()->getName() + " must be named!");
2015 if (Pat->isLeaf()) {
2016 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2017 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2020 Rec = Pat->getOperator();
2023 // SRCVALUE nodes are ignored.
2024 if (Rec->getName() == "srcvalue")
2027 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2033 if (Slot->isLeaf()) {
2034 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
2036 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2037 SlotRec = Slot->getOperator();
2040 // Ensure that the inputs agree if we've already seen this input.
2042 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2043 if (Slot->getExtTypes() != Pat->getExtTypes())
2044 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2048 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2049 /// part of "I", the instruction), computing the set of inputs and outputs of
2050 /// the pattern. Report errors if we see anything naughty.
2051 void CodeGenDAGPatterns::
2052 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2053 std::map<std::string, TreePatternNode*> &InstInputs,
2054 std::map<std::string, TreePatternNode*>&InstResults,
2055 std::vector<Record*> &InstImpResults) {
2056 if (Pat->isLeaf()) {
2057 bool isUse = HandleUse(I, Pat, InstInputs);
2058 if (!isUse && Pat->getTransformFn())
2059 I->error("Cannot specify a transform function for a non-input value!");
2063 if (Pat->getOperator()->getName() == "implicit") {
2064 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2065 TreePatternNode *Dest = Pat->getChild(i);
2066 if (!Dest->isLeaf())
2067 I->error("implicitly defined value should be a register!");
2069 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2070 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2071 I->error("implicitly defined value should be a register!");
2072 InstImpResults.push_back(Val->getDef());
2077 if (Pat->getOperator()->getName() != "set") {
2078 // If this is not a set, verify that the children nodes are not void typed,
2080 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2081 if (Pat->getChild(i)->getNumTypes() == 0)
2082 I->error("Cannot have void nodes inside of patterns!");
2083 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2087 // If this is a non-leaf node with no children, treat it basically as if
2088 // it were a leaf. This handles nodes like (imm).
2089 bool isUse = HandleUse(I, Pat, InstInputs);
2091 if (!isUse && Pat->getTransformFn())
2092 I->error("Cannot specify a transform function for a non-input value!");
2096 // Otherwise, this is a set, validate and collect instruction results.
2097 if (Pat->getNumChildren() == 0)
2098 I->error("set requires operands!");
2100 if (Pat->getTransformFn())
2101 I->error("Cannot specify a transform function on a set node!");
2103 // Check the set destinations.
2104 unsigned NumDests = Pat->getNumChildren()-1;
2105 for (unsigned i = 0; i != NumDests; ++i) {
2106 TreePatternNode *Dest = Pat->getChild(i);
2107 if (!Dest->isLeaf())
2108 I->error("set destination should be a register!");
2110 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2112 I->error("set destination should be a register!");
2114 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2115 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2116 if (Dest->getName().empty())
2117 I->error("set destination must have a name!");
2118 if (InstResults.count(Dest->getName()))
2119 I->error("cannot set '" + Dest->getName() +"' multiple times");
2120 InstResults[Dest->getName()] = Dest;
2121 } else if (Val->getDef()->isSubClassOf("Register")) {
2122 InstImpResults.push_back(Val->getDef());
2124 I->error("set destination should be a register!");
2128 // Verify and collect info from the computation.
2129 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2130 InstInputs, InstResults, InstImpResults);
2133 //===----------------------------------------------------------------------===//
2134 // Instruction Analysis
2135 //===----------------------------------------------------------------------===//
2137 class InstAnalyzer {
2138 const CodeGenDAGPatterns &CDP;
2141 bool &HasSideEffects;
2144 InstAnalyzer(const CodeGenDAGPatterns &cdp,
2145 bool &maystore, bool &mayload, bool &hse, bool &isv)
2146 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse),
2150 /// Analyze - Analyze the specified instruction, returning true if the
2151 /// instruction had a pattern.
2152 bool Analyze(Record *InstRecord) {
2153 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2156 return false; // No pattern.
2159 // FIXME: Assume only the first tree is the pattern. The others are clobber
2161 AnalyzeNode(Pattern->getTree(0));
2166 void AnalyzeNode(const TreePatternNode *N) {
2168 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2169 Record *LeafRec = DI->getDef();
2170 // Handle ComplexPattern leaves.
2171 if (LeafRec->isSubClassOf("ComplexPattern")) {
2172 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2173 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2174 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2175 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2181 // Analyze children.
2182 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2183 AnalyzeNode(N->getChild(i));
2185 // Ignore set nodes, which are not SDNodes.
2186 if (N->getOperator()->getName() == "set")
2189 // Get information about the SDNode for the operator.
2190 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2192 // Notice properties of the node.
2193 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2194 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2195 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2196 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
2198 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2199 // If this is an intrinsic, analyze it.
2200 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2201 mayLoad = true;// These may load memory.
2203 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2204 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2206 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2207 // WriteMem intrinsics can have other strange effects.
2208 HasSideEffects = true;
2214 static void InferFromPattern(const CodeGenInstruction &Inst,
2215 bool &MayStore, bool &MayLoad,
2216 bool &HasSideEffects, bool &IsVariadic,
2217 const CodeGenDAGPatterns &CDP) {
2218 MayStore = MayLoad = HasSideEffects = IsVariadic = false;
2221 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects, IsVariadic)
2222 .Analyze(Inst.TheDef);
2224 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2225 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2226 // If we decided that this is a store from the pattern, then the .td file
2227 // entry is redundant.
2230 "Warning: mayStore flag explicitly set on instruction '%s'"
2231 " but flag already inferred from pattern.\n",
2232 Inst.TheDef->getName().c_str());
2236 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2237 // If we decided that this is a load from the pattern, then the .td file
2238 // entry is redundant.
2241 "Warning: mayLoad flag explicitly set on instruction '%s'"
2242 " but flag already inferred from pattern.\n",
2243 Inst.TheDef->getName().c_str());
2247 if (Inst.neverHasSideEffects) {
2249 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2250 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2251 HasSideEffects = false;
2254 if (Inst.hasSideEffects) {
2256 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2257 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2258 HasSideEffects = true;
2261 if (Inst.isVariadic)
2262 IsVariadic = true; // Can warn if we want.
2265 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2266 /// any fragments involved. This populates the Instructions list with fully
2267 /// resolved instructions.
2268 void CodeGenDAGPatterns::ParseInstructions() {
2269 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2271 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2274 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2275 LI = Instrs[i]->getValueAsListInit("Pattern");
2277 // If there is no pattern, only collect minimal information about the
2278 // instruction for its operand list. We have to assume that there is one
2279 // result, as we have no detailed info.
2280 if (!LI || LI->getSize() == 0) {
2281 std::vector<Record*> Results;
2282 std::vector<Record*> Operands;
2284 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2286 if (InstInfo.OperandList.size() != 0) {
2287 if (InstInfo.NumDefs == 0) {
2288 // These produce no results
2289 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2290 Operands.push_back(InstInfo.OperandList[j].Rec);
2292 // Assume the first operand is the result.
2293 Results.push_back(InstInfo.OperandList[0].Rec);
2295 // The rest are inputs.
2296 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2297 Operands.push_back(InstInfo.OperandList[j].Rec);
2301 // Create and insert the instruction.
2302 std::vector<Record*> ImpResults;
2303 Instructions.insert(std::make_pair(Instrs[i],
2304 DAGInstruction(0, Results, Operands, ImpResults)));
2305 continue; // no pattern.
2308 // Parse the instruction.
2309 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2310 // Inline pattern fragments into it.
2311 I->InlinePatternFragments();
2313 // Infer as many types as possible. If we cannot infer all of them, we can
2314 // never do anything with this instruction pattern: report it to the user.
2315 if (!I->InferAllTypes())
2316 I->error("Could not infer all types in pattern!");
2318 // InstInputs - Keep track of all of the inputs of the instruction, along
2319 // with the record they are declared as.
2320 std::map<std::string, TreePatternNode*> InstInputs;
2322 // InstResults - Keep track of all the virtual registers that are 'set'
2323 // in the instruction, including what reg class they are.
2324 std::map<std::string, TreePatternNode*> InstResults;
2326 std::vector<Record*> InstImpResults;
2328 // Verify that the top-level forms in the instruction are of void type, and
2329 // fill in the InstResults map.
2330 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2331 TreePatternNode *Pat = I->getTree(j);
2332 if (Pat->getNumTypes() != 0)
2333 I->error("Top-level forms in instruction pattern should have"
2336 // Find inputs and outputs, and verify the structure of the uses/defs.
2337 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2341 // Now that we have inputs and outputs of the pattern, inspect the operands
2342 // list for the instruction. This determines the order that operands are
2343 // added to the machine instruction the node corresponds to.
2344 unsigned NumResults = InstResults.size();
2346 // Parse the operands list from the (ops) list, validating it.
2347 assert(I->getArgList().empty() && "Args list should still be empty here!");
2348 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2350 // Check that all of the results occur first in the list.
2351 std::vector<Record*> Results;
2352 TreePatternNode *Res0Node = 0;
2353 for (unsigned i = 0; i != NumResults; ++i) {
2354 if (i == CGI.OperandList.size())
2355 I->error("'" + InstResults.begin()->first +
2356 "' set but does not appear in operand list!");
2357 const std::string &OpName = CGI.OperandList[i].Name;
2359 // Check that it exists in InstResults.
2360 TreePatternNode *RNode = InstResults[OpName];
2362 I->error("Operand $" + OpName + " does not exist in operand list!");
2366 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2368 I->error("Operand $" + OpName + " should be a set destination: all "
2369 "outputs must occur before inputs in operand list!");
2371 if (CGI.OperandList[i].Rec != R)
2372 I->error("Operand $" + OpName + " class mismatch!");
2374 // Remember the return type.
2375 Results.push_back(CGI.OperandList[i].Rec);
2377 // Okay, this one checks out.
2378 InstResults.erase(OpName);
2381 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2382 // the copy while we're checking the inputs.
2383 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2385 std::vector<TreePatternNode*> ResultNodeOperands;
2386 std::vector<Record*> Operands;
2387 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2388 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2389 const std::string &OpName = Op.Name;
2391 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2393 if (!InstInputsCheck.count(OpName)) {
2394 // If this is an predicate operand or optional def operand with an
2395 // DefaultOps set filled in, we can ignore this. When we codegen it,
2396 // we will do so as always executed.
2397 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2398 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2399 // Does it have a non-empty DefaultOps field? If so, ignore this
2401 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2404 I->error("Operand $" + OpName +
2405 " does not appear in the instruction pattern");
2407 TreePatternNode *InVal = InstInputsCheck[OpName];
2408 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2410 if (InVal->isLeaf() &&
2411 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2412 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2413 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2414 I->error("Operand $" + OpName + "'s register class disagrees"
2415 " between the operand and pattern");
2417 Operands.push_back(Op.Rec);
2419 // Construct the result for the dest-pattern operand list.
2420 TreePatternNode *OpNode = InVal->clone();
2422 // No predicate is useful on the result.
2423 OpNode->clearPredicateFns();
2425 // Promote the xform function to be an explicit node if set.
2426 if (Record *Xform = OpNode->getTransformFn()) {
2427 OpNode->setTransformFn(0);
2428 std::vector<TreePatternNode*> Children;
2429 Children.push_back(OpNode);
2430 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2433 ResultNodeOperands.push_back(OpNode);
2436 if (!InstInputsCheck.empty())
2437 I->error("Input operand $" + InstInputsCheck.begin()->first +
2438 " occurs in pattern but not in operands list!");
2440 TreePatternNode *ResultPattern =
2441 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2442 GetNumNodeResults(I->getRecord(), *this));
2443 // Copy fully inferred output node type to instruction result pattern.
2444 for (unsigned i = 0; i != NumResults; ++i)
2445 ResultPattern->setType(i, Res0Node->getExtType(i));
2447 // Create and insert the instruction.
2448 // FIXME: InstImpResults should not be part of DAGInstruction.
2449 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
2450 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2452 // Use a temporary tree pattern to infer all types and make sure that the
2453 // constructed result is correct. This depends on the instruction already
2454 // being inserted into the Instructions map.
2455 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2456 Temp.InferAllTypes(&I->getNamedNodesMap());
2458 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2459 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2464 // If we can, convert the instructions to be patterns that are matched!
2465 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2466 Instructions.begin(),
2467 E = Instructions.end(); II != E; ++II) {
2468 DAGInstruction &TheInst = II->second;
2469 const TreePattern *I = TheInst.getPattern();
2470 if (I == 0) continue; // No pattern.
2472 // FIXME: Assume only the first tree is the pattern. The others are clobber
2474 TreePatternNode *Pattern = I->getTree(0);
2475 TreePatternNode *SrcPattern;
2476 if (Pattern->getOperator()->getName() == "set") {
2477 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2479 // Not a set (store or something?)
2480 SrcPattern = Pattern;
2483 Record *Instr = II->first;
2484 AddPatternToMatch(I,
2485 PatternToMatch(Instr->getValueAsListInit("Predicates"),
2487 TheInst.getResultPattern(),
2488 TheInst.getImpResults(),
2489 Instr->getValueAsInt("AddedComplexity"),
2495 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2497 static void FindNames(const TreePatternNode *P,
2498 std::map<std::string, NameRecord> &Names,
2499 const TreePattern *PatternTop) {
2500 if (!P->getName().empty()) {
2501 NameRecord &Rec = Names[P->getName()];
2502 // If this is the first instance of the name, remember the node.
2503 if (Rec.second++ == 0)
2505 else if (Rec.first->getExtTypes() != P->getExtTypes())
2506 PatternTop->error("repetition of value: $" + P->getName() +
2507 " where different uses have different types!");
2511 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2512 FindNames(P->getChild(i), Names, PatternTop);
2516 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2517 const PatternToMatch &PTM) {
2518 // Do some sanity checking on the pattern we're about to match.
2520 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2521 Pattern->error("Pattern can never match: " + Reason);
2523 // If the source pattern's root is a complex pattern, that complex pattern
2524 // must specify the nodes it can potentially match.
2525 if (const ComplexPattern *CP =
2526 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2527 if (CP->getRootNodes().empty())
2528 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2532 // Find all of the named values in the input and output, ensure they have the
2534 std::map<std::string, NameRecord> SrcNames, DstNames;
2535 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2536 FindNames(PTM.getDstPattern(), DstNames, Pattern);
2538 // Scan all of the named values in the destination pattern, rejecting them if
2539 // they don't exist in the input pattern.
2540 for (std::map<std::string, NameRecord>::iterator
2541 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2542 if (SrcNames[I->first].first == 0)
2543 Pattern->error("Pattern has input without matching name in output: $" +
2547 // Scan all of the named values in the source pattern, rejecting them if the
2548 // name isn't used in the dest, and isn't used to tie two values together.
2549 for (std::map<std::string, NameRecord>::iterator
2550 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2551 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2552 Pattern->error("Pattern has dead named input: $" + I->first);
2554 PatternsToMatch.push_back(PTM);
2559 void CodeGenDAGPatterns::InferInstructionFlags() {
2560 const std::vector<const CodeGenInstruction*> &Instructions =
2561 Target.getInstructionsByEnumValue();
2562 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2563 CodeGenInstruction &InstInfo =
2564 const_cast<CodeGenInstruction &>(*Instructions[i]);
2565 // Determine properties of the instruction from its pattern.
2566 bool MayStore, MayLoad, HasSideEffects, IsVariadic;
2567 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, IsVariadic,
2569 InstInfo.mayStore = MayStore;
2570 InstInfo.mayLoad = MayLoad;
2571 InstInfo.hasSideEffects = HasSideEffects;
2572 InstInfo.isVariadic = IsVariadic;
2576 /// Given a pattern result with an unresolved type, see if we can find one
2577 /// instruction with an unresolved result type. Force this result type to an
2578 /// arbitrary element if it's possible types to converge results.
2579 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2583 // Analyze children.
2584 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2585 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2588 if (!N->getOperator()->isSubClassOf("Instruction"))
2591 // If this type is already concrete or completely unknown we can't do
2593 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2594 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2597 // Otherwise, force its type to the first possibility (an arbitrary choice).
2598 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2605 void CodeGenDAGPatterns::ParsePatterns() {
2606 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2608 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2609 Record *CurPattern = Patterns[i];
2610 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
2611 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
2613 // Inline pattern fragments into it.
2614 Pattern->InlinePatternFragments();
2616 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
2617 if (LI->getSize() == 0) continue; // no pattern.
2619 // Parse the instruction.
2620 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
2622 // Inline pattern fragments into it.
2623 Result->InlinePatternFragments();
2625 if (Result->getNumTrees() != 1)
2626 Result->error("Cannot handle instructions producing instructions "
2627 "with temporaries yet!");
2629 bool IterateInference;
2630 bool InferredAllPatternTypes, InferredAllResultTypes;
2632 // Infer as many types as possible. If we cannot infer all of them, we
2633 // can never do anything with this pattern: report it to the user.
2634 InferredAllPatternTypes =
2635 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
2637 // Infer as many types as possible. If we cannot infer all of them, we
2638 // can never do anything with this pattern: report it to the user.
2639 InferredAllResultTypes =
2640 Result->InferAllTypes(&Pattern->getNamedNodesMap());
2642 IterateInference = false;
2644 // Apply the type of the result to the source pattern. This helps us
2645 // resolve cases where the input type is known to be a pointer type (which
2646 // is considered resolved), but the result knows it needs to be 32- or
2647 // 64-bits. Infer the other way for good measure.
2648 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2649 Pattern->getTree(0)->getNumTypes());
2651 IterateInference = Pattern->getTree(0)->
2652 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
2653 IterateInference |= Result->getTree(0)->
2654 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
2657 // If our iteration has converged and the input pattern's types are fully
2658 // resolved but the result pattern is not fully resolved, we may have a
2659 // situation where we have two instructions in the result pattern and
2660 // the instructions require a common register class, but don't care about
2661 // what actual MVT is used. This is actually a bug in our modelling:
2662 // output patterns should have register classes, not MVTs.
2664 // In any case, to handle this, we just go through and disambiguate some
2665 // arbitrary types to the result pattern's nodes.
2666 if (!IterateInference && InferredAllPatternTypes &&
2667 !InferredAllResultTypes)
2668 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2670 } while (IterateInference);
2672 // Verify that we inferred enough types that we can do something with the
2673 // pattern and result. If these fire the user has to add type casts.
2674 if (!InferredAllPatternTypes)
2675 Pattern->error("Could not infer all types in pattern!");
2676 if (!InferredAllResultTypes) {
2678 Result->error("Could not infer all types in pattern result!");
2681 // Validate that the input pattern is correct.
2682 std::map<std::string, TreePatternNode*> InstInputs;
2683 std::map<std::string, TreePatternNode*> InstResults;
2684 std::vector<Record*> InstImpResults;
2685 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2686 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2687 InstInputs, InstResults,
2690 // Promote the xform function to be an explicit node if set.
2691 TreePatternNode *DstPattern = Result->getOnlyTree();
2692 std::vector<TreePatternNode*> ResultNodeOperands;
2693 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2694 TreePatternNode *OpNode = DstPattern->getChild(ii);
2695 if (Record *Xform = OpNode->getTransformFn()) {
2696 OpNode->setTransformFn(0);
2697 std::vector<TreePatternNode*> Children;
2698 Children.push_back(OpNode);
2699 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2701 ResultNodeOperands.push_back(OpNode);
2703 DstPattern = Result->getOnlyTree();
2704 if (!DstPattern->isLeaf())
2705 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2707 DstPattern->getNumTypes());
2709 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2710 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
2712 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2713 Temp.InferAllTypes();
2716 AddPatternToMatch(Pattern,
2717 PatternToMatch(CurPattern->getValueAsListInit("Predicates"),
2718 Pattern->getTree(0),
2719 Temp.getOnlyTree(), InstImpResults,
2720 CurPattern->getValueAsInt("AddedComplexity"),
2721 CurPattern->getID()));
2725 /// CombineChildVariants - Given a bunch of permutations of each child of the
2726 /// 'operator' node, put them together in all possible ways.
2727 static void CombineChildVariants(TreePatternNode *Orig,
2728 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2729 std::vector<TreePatternNode*> &OutVariants,
2730 CodeGenDAGPatterns &CDP,
2731 const MultipleUseVarSet &DepVars) {
2732 // Make sure that each operand has at least one variant to choose from.
2733 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2734 if (ChildVariants[i].empty())
2737 // The end result is an all-pairs construction of the resultant pattern.
2738 std::vector<unsigned> Idxs;
2739 Idxs.resize(ChildVariants.size());
2743 DEBUG(if (!Idxs.empty()) {
2744 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2745 for (unsigned i = 0; i < Idxs.size(); ++i) {
2746 errs() << Idxs[i] << " ";
2751 // Create the variant and add it to the output list.
2752 std::vector<TreePatternNode*> NewChildren;
2753 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2754 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2755 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
2756 Orig->getNumTypes());
2758 // Copy over properties.
2759 R->setName(Orig->getName());
2760 R->setPredicateFns(Orig->getPredicateFns());
2761 R->setTransformFn(Orig->getTransformFn());
2762 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
2763 R->setType(i, Orig->getExtType(i));
2765 // If this pattern cannot match, do not include it as a variant.
2766 std::string ErrString;
2767 if (!R->canPatternMatch(ErrString, CDP)) {
2770 bool AlreadyExists = false;
2772 // Scan to see if this pattern has already been emitted. We can get
2773 // duplication due to things like commuting:
2774 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2775 // which are the same pattern. Ignore the dups.
2776 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2777 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2778 AlreadyExists = true;
2785 OutVariants.push_back(R);
2788 // Increment indices to the next permutation by incrementing the
2789 // indicies from last index backward, e.g., generate the sequence
2790 // [0, 0], [0, 1], [1, 0], [1, 1].
2792 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2793 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2798 NotDone = (IdxsIdx >= 0);
2802 /// CombineChildVariants - A helper function for binary operators.
2804 static void CombineChildVariants(TreePatternNode *Orig,
2805 const std::vector<TreePatternNode*> &LHS,
2806 const std::vector<TreePatternNode*> &RHS,
2807 std::vector<TreePatternNode*> &OutVariants,
2808 CodeGenDAGPatterns &CDP,
2809 const MultipleUseVarSet &DepVars) {
2810 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2811 ChildVariants.push_back(LHS);
2812 ChildVariants.push_back(RHS);
2813 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2817 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2818 std::vector<TreePatternNode *> &Children) {
2819 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2820 Record *Operator = N->getOperator();
2822 // Only permit raw nodes.
2823 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2824 N->getTransformFn()) {
2825 Children.push_back(N);
2829 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2830 Children.push_back(N->getChild(0));
2832 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2834 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2835 Children.push_back(N->getChild(1));
2837 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2840 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2841 /// the (potentially recursive) pattern by using algebraic laws.
2843 static void GenerateVariantsOf(TreePatternNode *N,
2844 std::vector<TreePatternNode*> &OutVariants,
2845 CodeGenDAGPatterns &CDP,
2846 const MultipleUseVarSet &DepVars) {
2847 // We cannot permute leaves.
2849 OutVariants.push_back(N);
2853 // Look up interesting info about the node.
2854 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2856 // If this node is associative, re-associate.
2857 if (NodeInfo.hasProperty(SDNPAssociative)) {
2858 // Re-associate by pulling together all of the linked operators
2859 std::vector<TreePatternNode*> MaximalChildren;
2860 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2862 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2864 if (MaximalChildren.size() == 3) {
2865 // Find the variants of all of our maximal children.
2866 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2867 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2868 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2869 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2871 // There are only two ways we can permute the tree:
2872 // (A op B) op C and A op (B op C)
2873 // Within these forms, we can also permute A/B/C.
2875 // Generate legal pair permutations of A/B/C.
2876 std::vector<TreePatternNode*> ABVariants;
2877 std::vector<TreePatternNode*> BAVariants;
2878 std::vector<TreePatternNode*> ACVariants;
2879 std::vector<TreePatternNode*> CAVariants;
2880 std::vector<TreePatternNode*> BCVariants;
2881 std::vector<TreePatternNode*> CBVariants;
2882 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2883 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2884 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2885 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2886 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2887 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2889 // Combine those into the result: (x op x) op x
2890 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2891 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2892 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2893 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2894 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2895 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2897 // Combine those into the result: x op (x op x)
2898 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2899 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2900 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2901 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2902 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2903 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2908 // Compute permutations of all children.
2909 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2910 ChildVariants.resize(N->getNumChildren());
2911 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2912 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2914 // Build all permutations based on how the children were formed.
2915 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2917 // If this node is commutative, consider the commuted order.
2918 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2919 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2920 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2921 "Commutative but doesn't have 2 children!");
2922 // Don't count children which are actually register references.
2924 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2925 TreePatternNode *Child = N->getChild(i);
2926 if (Child->isLeaf())
2927 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2928 Record *RR = DI->getDef();
2929 if (RR->isSubClassOf("Register"))
2934 // Consider the commuted order.
2935 if (isCommIntrinsic) {
2936 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2937 // operands are the commutative operands, and there might be more operands
2940 "Commutative intrinsic should have at least 3 childrean!");
2941 std::vector<std::vector<TreePatternNode*> > Variants;
2942 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2943 Variants.push_back(ChildVariants[2]);
2944 Variants.push_back(ChildVariants[1]);
2945 for (unsigned i = 3; i != NC; ++i)
2946 Variants.push_back(ChildVariants[i]);
2947 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2949 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2950 OutVariants, CDP, DepVars);
2955 // GenerateVariants - Generate variants. For example, commutative patterns can
2956 // match multiple ways. Add them to PatternsToMatch as well.
2957 void CodeGenDAGPatterns::GenerateVariants() {
2958 DEBUG(errs() << "Generating instruction variants.\n");
2960 // Loop over all of the patterns we've collected, checking to see if we can
2961 // generate variants of the instruction, through the exploitation of
2962 // identities. This permits the target to provide aggressive matching without
2963 // the .td file having to contain tons of variants of instructions.
2965 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2966 // intentionally do not reconsider these. Any variants of added patterns have
2967 // already been added.
2969 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2970 MultipleUseVarSet DepVars;
2971 std::vector<TreePatternNode*> Variants;
2972 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2973 DEBUG(errs() << "Dependent/multiply used variables: ");
2974 DEBUG(DumpDepVars(DepVars));
2975 DEBUG(errs() << "\n");
2976 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2978 assert(!Variants.empty() && "Must create at least original variant!");
2979 Variants.erase(Variants.begin()); // Remove the original pattern.
2981 if (Variants.empty()) // No variants for this pattern.
2984 DEBUG(errs() << "FOUND VARIANTS OF: ";
2985 PatternsToMatch[i].getSrcPattern()->dump();
2988 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2989 TreePatternNode *Variant = Variants[v];
2991 DEBUG(errs() << " VAR#" << v << ": ";
2995 // Scan to see if an instruction or explicit pattern already matches this.
2996 bool AlreadyExists = false;
2997 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2998 // Skip if the top level predicates do not match.
2999 if (PatternsToMatch[i].getPredicates() !=
3000 PatternsToMatch[p].getPredicates())
3002 // Check to see if this variant already exists.
3003 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
3004 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3005 AlreadyExists = true;
3009 // If we already have it, ignore the variant.
3010 if (AlreadyExists) continue;
3012 // Otherwise, add it to the list of patterns we have.
3014 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
3015 Variant, PatternsToMatch[i].getDstPattern(),
3016 PatternsToMatch[i].getDstRegs(),
3017 PatternsToMatch[i].getAddedComplexity(),
3018 Record::getNewUID()));
3021 DEBUG(errs() << "\n");