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);
65 array_pod_sort(TypeVec.begin(), TypeVec.end());
66 TypeVec.erase(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:
476 void DumpDepVars(MultipleUseVarSet &DepVars) {
477 if (DepVars.empty()) {
478 DEBUG(errs() << "<empty set>");
480 DEBUG(errs() << "[ ");
481 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
483 DEBUG(errs() << (*i) << " ");
485 DEBUG(errs() << "]");
490 //===----------------------------------------------------------------------===//
491 // PatternToMatch implementation
494 /// getPredicateCheck - Return a single string containing all of this
495 /// pattern's predicates concatenated with "&&" operators.
497 std::string PatternToMatch::getPredicateCheck() const {
498 std::string PredicateCheck;
499 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
500 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
501 Record *Def = Pred->getDef();
502 if (!Def->isSubClassOf("Predicate")) {
506 assert(0 && "Unknown predicate type!");
508 if (!PredicateCheck.empty())
509 PredicateCheck += " && ";
510 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
514 return PredicateCheck;
517 //===----------------------------------------------------------------------===//
518 // SDTypeConstraint implementation
521 SDTypeConstraint::SDTypeConstraint(Record *R) {
522 OperandNo = R->getValueAsInt("OperandNum");
524 if (R->isSubClassOf("SDTCisVT")) {
525 ConstraintType = SDTCisVT;
526 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
527 } else if (R->isSubClassOf("SDTCisPtrTy")) {
528 ConstraintType = SDTCisPtrTy;
529 } else if (R->isSubClassOf("SDTCisInt")) {
530 ConstraintType = SDTCisInt;
531 } else if (R->isSubClassOf("SDTCisFP")) {
532 ConstraintType = SDTCisFP;
533 } else if (R->isSubClassOf("SDTCisVec")) {
534 ConstraintType = SDTCisVec;
535 } else if (R->isSubClassOf("SDTCisSameAs")) {
536 ConstraintType = SDTCisSameAs;
537 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
538 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
539 ConstraintType = SDTCisVTSmallerThanOp;
540 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
541 R->getValueAsInt("OtherOperandNum");
542 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
543 ConstraintType = SDTCisOpSmallerThanOp;
544 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
545 R->getValueAsInt("BigOperandNum");
546 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
547 ConstraintType = SDTCisEltOfVec;
548 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
550 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
555 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
556 /// N, and the result number in ResNo.
557 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
558 const SDNodeInfo &NodeInfo,
560 unsigned NumResults = NodeInfo.getNumResults();
561 if (OpNo < NumResults) {
568 if (OpNo >= N->getNumChildren()) {
569 errs() << "Invalid operand number in type constraint "
570 << (OpNo+NumResults) << " ";
576 return N->getChild(OpNo);
579 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
580 /// constraint to the nodes operands. This returns true if it makes a
581 /// change, false otherwise. If a type contradiction is found, throw an
583 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
584 const SDNodeInfo &NodeInfo,
585 TreePattern &TP) const {
586 // Check that the number of operands is sane. Negative operands -> varargs.
587 if (NodeInfo.getNumOperands() >= 0) {
588 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
589 TP.error(N->getOperator()->getName() + " node requires exactly " +
590 itostr(NodeInfo.getNumOperands()) + " operands!");
593 unsigned ResNo = 0; // The result number being referenced.
594 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
596 switch (ConstraintType) {
597 default: assert(0 && "Unknown constraint type!");
599 // Operand must be a particular type.
600 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
602 // Operand must be same as target pointer type.
603 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
605 // Require it to be one of the legal integer VTs.
606 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
608 // Require it to be one of the legal fp VTs.
609 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
611 // Require it to be one of the legal vector VTs.
612 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
615 TreePatternNode *OtherNode =
616 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
617 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
618 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
620 case SDTCisVTSmallerThanOp: {
621 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
622 // have an integer type that is smaller than the VT.
623 if (!NodeToApply->isLeaf() ||
624 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
625 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
626 ->isSubClassOf("ValueType"))
627 TP.error(N->getOperator()->getName() + " expects a VT operand!");
628 MVT::SimpleValueType VT =
629 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
631 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
634 TreePatternNode *OtherNode =
635 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
638 // It must be integer.
639 bool MadeChange = OtherNode->getExtType(OResNo).EnforceInteger(TP);
641 // This doesn't try to enforce any information on the OtherNode, it just
642 // validates it when information is determined.
643 if (OtherNode->hasTypeSet(OResNo) && OtherNode->getType(OResNo) <= VT)
644 OtherNode->UpdateNodeType(OResNo, MVT::Other, TP); // Throw an error.
647 case SDTCisOpSmallerThanOp: {
649 TreePatternNode *BigOperand =
650 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
652 return NodeToApply->getExtType(ResNo).
653 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
655 case SDTCisEltOfVec: {
657 TreePatternNode *VecOperand =
658 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
661 // Filter vector types out of VecOperand that don't have the right element
663 return VecOperand->getExtType(VResNo).
664 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
670 //===----------------------------------------------------------------------===//
671 // SDNodeInfo implementation
673 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
674 EnumName = R->getValueAsString("Opcode");
675 SDClassName = R->getValueAsString("SDClass");
676 Record *TypeProfile = R->getValueAsDef("TypeProfile");
677 NumResults = TypeProfile->getValueAsInt("NumResults");
678 NumOperands = TypeProfile->getValueAsInt("NumOperands");
680 // Parse the properties.
682 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
683 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
684 if (PropList[i]->getName() == "SDNPCommutative") {
685 Properties |= 1 << SDNPCommutative;
686 } else if (PropList[i]->getName() == "SDNPAssociative") {
687 Properties |= 1 << SDNPAssociative;
688 } else if (PropList[i]->getName() == "SDNPHasChain") {
689 Properties |= 1 << SDNPHasChain;
690 } else if (PropList[i]->getName() == "SDNPOutFlag") {
691 Properties |= 1 << SDNPOutFlag;
692 } else if (PropList[i]->getName() == "SDNPInFlag") {
693 Properties |= 1 << SDNPInFlag;
694 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
695 Properties |= 1 << SDNPOptInFlag;
696 } else if (PropList[i]->getName() == "SDNPMayStore") {
697 Properties |= 1 << SDNPMayStore;
698 } else if (PropList[i]->getName() == "SDNPMayLoad") {
699 Properties |= 1 << SDNPMayLoad;
700 } else if (PropList[i]->getName() == "SDNPSideEffect") {
701 Properties |= 1 << SDNPSideEffect;
702 } else if (PropList[i]->getName() == "SDNPMemOperand") {
703 Properties |= 1 << SDNPMemOperand;
704 } else if (PropList[i]->getName() == "SDNPVariadic") {
705 Properties |= 1 << SDNPVariadic;
707 errs() << "Unknown SD Node property '" << PropList[i]->getName()
708 << "' on node '" << R->getName() << "'!\n";
714 // Parse the type constraints.
715 std::vector<Record*> ConstraintList =
716 TypeProfile->getValueAsListOfDefs("Constraints");
717 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
720 /// getKnownType - If the type constraints on this node imply a fixed type
721 /// (e.g. all stores return void, etc), then return it as an
722 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
723 MVT::SimpleValueType SDNodeInfo::getKnownType() const {
724 unsigned NumResults = getNumResults();
725 assert(NumResults <= 1 &&
726 "We only work with nodes with zero or one result so far!");
728 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
729 // Make sure that this applies to the correct node result.
730 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
733 switch (TypeConstraints[i].ConstraintType) {
735 case SDTypeConstraint::SDTCisVT:
736 return TypeConstraints[i].x.SDTCisVT_Info.VT;
737 case SDTypeConstraint::SDTCisPtrTy:
744 //===----------------------------------------------------------------------===//
745 // TreePatternNode implementation
748 TreePatternNode::~TreePatternNode() {
749 #if 0 // FIXME: implement refcounted tree nodes!
750 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
755 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
756 if (Operator->getName() == "set" ||
757 Operator->getName() == "implicit" ||
758 Operator->getName() == "parallel")
759 return 0; // All return nothing.
761 if (Operator->isSubClassOf("Intrinsic"))
762 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
764 if (Operator->isSubClassOf("SDNode"))
765 return CDP.getSDNodeInfo(Operator).getNumResults();
767 if (Operator->isSubClassOf("PatFrag")) {
768 // If we've already parsed this pattern fragment, get it. Otherwise, handle
769 // the forward reference case where one pattern fragment references another
770 // before it is processed.
771 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
772 return PFRec->getOnlyTree()->getNumTypes();
774 // Get the result tree.
775 DagInit *Tree = Operator->getValueAsDag("Fragment");
777 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
778 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
779 assert(Op && "Invalid Fragment");
780 return GetNumNodeResults(Op, CDP);
783 if (Operator->isSubClassOf("Instruction")) {
784 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
786 // FIXME: Handle implicit defs right.
787 if (InstInfo.NumDefs != 0)
788 return 1; // FIXME: Handle inst results right!
790 if (!InstInfo.ImplicitDefs.empty()) {
791 // Add on one implicit def if it has a resolvable type.
792 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
793 assert(FirstImplicitDef->isSubClassOf("Register"));
794 const std::vector<MVT::SimpleValueType> &RegVTs =
795 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
796 if (RegVTs.size() == 1)
802 if (Operator->isSubClassOf("SDNodeXForm"))
803 return 1; // FIXME: Generalize SDNodeXForm
806 errs() << "Unhandled node in GetNumNodeResults\n";
810 void TreePatternNode::print(raw_ostream &OS) const {
812 OS << *getLeafValue();
814 OS << '(' << getOperator()->getName();
816 for (unsigned i = 0, e = Types.size(); i != e; ++i)
817 OS << ':' << getExtType(i).getName();
820 if (getNumChildren() != 0) {
822 getChild(0)->print(OS);
823 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
825 getChild(i)->print(OS);
831 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
832 OS << "<<P:" << PredicateFns[i] << ">>";
834 OS << "<<X:" << TransformFn->getName() << ">>";
835 if (!getName().empty())
836 OS << ":$" << getName();
839 void TreePatternNode::dump() const {
843 /// isIsomorphicTo - Return true if this node is recursively
844 /// isomorphic to the specified node. For this comparison, the node's
845 /// entire state is considered. The assigned name is ignored, since
846 /// nodes with differing names are considered isomorphic. However, if
847 /// the assigned name is present in the dependent variable set, then
848 /// the assigned name is considered significant and the node is
849 /// isomorphic if the names match.
850 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
851 const MultipleUseVarSet &DepVars) const {
852 if (N == this) return true;
853 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
854 getPredicateFns() != N->getPredicateFns() ||
855 getTransformFn() != N->getTransformFn())
859 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
860 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
861 return ((DI->getDef() == NDI->getDef())
862 && (DepVars.find(getName()) == DepVars.end()
863 || getName() == N->getName()));
866 return getLeafValue() == N->getLeafValue();
869 if (N->getOperator() != getOperator() ||
870 N->getNumChildren() != getNumChildren()) return false;
871 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
872 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
877 /// clone - Make a copy of this tree and all of its children.
879 TreePatternNode *TreePatternNode::clone() const {
880 TreePatternNode *New;
882 New = new TreePatternNode(getLeafValue(), getNumTypes());
884 std::vector<TreePatternNode*> CChildren;
885 CChildren.reserve(Children.size());
886 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
887 CChildren.push_back(getChild(i)->clone());
888 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
890 New->setName(getName());
892 New->setPredicateFns(getPredicateFns());
893 New->setTransformFn(getTransformFn());
897 /// RemoveAllTypes - Recursively strip all the types of this tree.
898 void TreePatternNode::RemoveAllTypes() {
899 for (unsigned i = 0, e = Types.size(); i != e; ++i)
900 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
901 if (isLeaf()) return;
902 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
903 getChild(i)->RemoveAllTypes();
907 /// SubstituteFormalArguments - Replace the formal arguments in this tree
908 /// with actual values specified by ArgMap.
909 void TreePatternNode::
910 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
911 if (isLeaf()) return;
913 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
914 TreePatternNode *Child = getChild(i);
915 if (Child->isLeaf()) {
916 Init *Val = Child->getLeafValue();
917 if (dynamic_cast<DefInit*>(Val) &&
918 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
919 // We found a use of a formal argument, replace it with its value.
920 TreePatternNode *NewChild = ArgMap[Child->getName()];
921 assert(NewChild && "Couldn't find formal argument!");
922 assert((Child->getPredicateFns().empty() ||
923 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
924 "Non-empty child predicate clobbered!");
925 setChild(i, NewChild);
928 getChild(i)->SubstituteFormalArguments(ArgMap);
934 /// InlinePatternFragments - If this pattern refers to any pattern
935 /// fragments, inline them into place, giving us a pattern without any
936 /// PatFrag references.
937 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
938 if (isLeaf()) return this; // nothing to do.
939 Record *Op = getOperator();
941 if (!Op->isSubClassOf("PatFrag")) {
942 // Just recursively inline children nodes.
943 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
944 TreePatternNode *Child = getChild(i);
945 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
947 assert((Child->getPredicateFns().empty() ||
948 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
949 "Non-empty child predicate clobbered!");
951 setChild(i, NewChild);
956 // Otherwise, we found a reference to a fragment. First, look up its
957 // TreePattern record.
958 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
960 // Verify that we are passing the right number of operands.
961 if (Frag->getNumArgs() != Children.size())
962 TP.error("'" + Op->getName() + "' fragment requires " +
963 utostr(Frag->getNumArgs()) + " operands!");
965 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
967 std::string Code = Op->getValueAsCode("Predicate");
969 FragTree->addPredicateFn("Predicate_"+Op->getName());
971 // Resolve formal arguments to their actual value.
972 if (Frag->getNumArgs()) {
973 // Compute the map of formal to actual arguments.
974 std::map<std::string, TreePatternNode*> ArgMap;
975 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
976 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
978 FragTree->SubstituteFormalArguments(ArgMap);
981 FragTree->setName(getName());
982 for (unsigned i = 0, e = Types.size(); i != e; ++i)
983 FragTree->UpdateNodeType(i, getExtType(i), TP);
985 // Transfer in the old predicates.
986 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
987 FragTree->addPredicateFn(getPredicateFns()[i]);
989 // Get a new copy of this fragment to stitch into here.
990 //delete this; // FIXME: implement refcounting!
992 // The fragment we inlined could have recursive inlining that is needed. See
993 // if there are any pattern fragments in it and inline them as needed.
994 return FragTree->InlinePatternFragments(TP);
997 /// getImplicitType - Check to see if the specified record has an implicit
998 /// type which should be applied to it. This will infer the type of register
999 /// references from the register file information, for example.
1001 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1002 bool NotRegisters, TreePattern &TP) {
1003 // Check to see if this is a register or a register class.
1004 if (R->isSubClassOf("RegisterClass")) {
1005 assert(ResNo == 0 && "Regclass ref only has one result!");
1007 return EEVT::TypeSet(); // Unknown.
1008 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1009 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1012 if (R->isSubClassOf("PatFrag")) {
1013 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1014 // Pattern fragment types will be resolved when they are inlined.
1015 return EEVT::TypeSet(); // Unknown.
1018 if (R->isSubClassOf("Register")) {
1019 assert(ResNo == 0 && "Registers only produce one result!");
1021 return EEVT::TypeSet(); // Unknown.
1022 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1023 return EEVT::TypeSet(T.getRegisterVTs(R));
1026 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1027 assert(ResNo == 0 && "This node only has one result!");
1028 // Using a VTSDNode or CondCodeSDNode.
1029 return EEVT::TypeSet(MVT::Other, TP);
1032 if (R->isSubClassOf("ComplexPattern")) {
1033 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1035 return EEVT::TypeSet(); // Unknown.
1036 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1039 if (R->isSubClassOf("PointerLikeRegClass")) {
1040 assert(ResNo == 0 && "Regclass can only have one result!");
1041 return EEVT::TypeSet(MVT::iPTR, TP);
1044 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1045 R->getName() == "zero_reg") {
1047 return EEVT::TypeSet(); // Unknown.
1050 TP.error("Unknown node flavor used in pattern: " + R->getName());
1051 return EEVT::TypeSet(MVT::Other, TP);
1055 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1056 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1057 const CodeGenIntrinsic *TreePatternNode::
1058 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1059 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1060 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1061 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1065 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1066 return &CDP.getIntrinsicInfo(IID);
1069 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1070 /// return the ComplexPattern information, otherwise return null.
1071 const ComplexPattern *
1072 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1073 if (!isLeaf()) return 0;
1075 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1076 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1077 return &CGP.getComplexPattern(DI->getDef());
1081 /// NodeHasProperty - Return true if this node has the specified property.
1082 bool TreePatternNode::NodeHasProperty(SDNP Property,
1083 const CodeGenDAGPatterns &CGP) const {
1085 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1086 return CP->hasProperty(Property);
1090 Record *Operator = getOperator();
1091 if (!Operator->isSubClassOf("SDNode")) return false;
1093 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1099 /// TreeHasProperty - Return true if any node in this tree has the specified
1101 bool TreePatternNode::TreeHasProperty(SDNP Property,
1102 const CodeGenDAGPatterns &CGP) const {
1103 if (NodeHasProperty(Property, CGP))
1105 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1106 if (getChild(i)->TreeHasProperty(Property, CGP))
1111 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1112 /// commutative intrinsic.
1114 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1115 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1116 return Int->isCommutative;
1121 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1122 /// this node and its children in the tree. This returns true if it makes a
1123 /// change, false otherwise. If a type contradiction is found, throw an
1125 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1126 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1128 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1129 // If it's a regclass or something else known, include the type.
1130 bool MadeChange = false;
1131 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1132 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1133 NotRegisters, TP), TP);
1137 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
1138 assert(Types.size() == 1 && "Invalid IntInit");
1140 // Int inits are always integers. :)
1141 bool MadeChange = Types[0].EnforceInteger(TP);
1143 if (!Types[0].isConcrete())
1146 MVT::SimpleValueType VT = getType(0);
1147 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1150 unsigned Size = EVT(VT).getSizeInBits();
1151 // Make sure that the value is representable for this type.
1152 if (Size >= 32) return MadeChange;
1154 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1155 if (Val == II->getValue()) return MadeChange;
1157 // If sign-extended doesn't fit, does it fit as unsigned?
1159 unsigned UnsignedVal;
1160 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1161 UnsignedVal = unsigned(II->getValue());
1163 if ((ValueMask & UnsignedVal) == UnsignedVal)
1166 TP.error("Integer value '" + itostr(II->getValue())+
1167 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1173 // special handling for set, which isn't really an SDNode.
1174 if (getOperator()->getName() == "set") {
1175 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1176 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1177 unsigned NC = getNumChildren();
1179 TreePatternNode *SetVal = getChild(NC-1);
1180 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1182 for (unsigned i = 0; i < NC-1; ++i) {
1183 TreePatternNode *Child = getChild(i);
1184 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1186 // Types of operands must match.
1187 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1188 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1193 if (getOperator()->getName() == "implicit" ||
1194 getOperator()->getName() == "parallel") {
1195 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1197 bool MadeChange = false;
1198 for (unsigned i = 0; i < getNumChildren(); ++i)
1199 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1203 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
1204 bool MadeChange = false;
1205 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1206 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1208 assert(getChild(0)->getNumTypes() == 1 &&
1209 getChild(1)->getNumTypes() == 1 && "Unhandled case");
1211 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1212 // what type it gets, so if it didn't get a concrete type just give it the
1213 // first viable type from the reg class.
1214 if (!getChild(1)->hasTypeSet(0) &&
1215 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1216 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1217 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
1222 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1223 bool MadeChange = false;
1225 // Apply the result type to the node.
1226 unsigned NumRetVTs = Int->IS.RetVTs.size();
1227 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1229 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1230 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1232 if (getNumChildren() != NumParamVTs + 1)
1233 TP.error("Intrinsic '" + Int->Name + "' expects " +
1234 utostr(NumParamVTs) + " operands, not " +
1235 utostr(getNumChildren() - 1) + " operands!");
1237 // Apply type info to the intrinsic ID.
1238 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1240 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1241 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1243 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1244 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1245 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1250 if (getOperator()->isSubClassOf("SDNode")) {
1251 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1253 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1254 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1255 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1259 if (getOperator()->isSubClassOf("Instruction")) {
1260 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1262 assert(Inst.getNumResults() <= 1 &&
1263 "FIXME: Only supports zero or one result instrs!");
1265 CodeGenInstruction &InstInfo =
1266 CDP.getTargetInfo().getInstruction(getOperator());
1268 EEVT::TypeSet ResultType;
1270 // Apply the result type to the node
1271 if (InstInfo.NumDefs != 0) { // # of elements in (outs) list
1272 Record *ResultNode = Inst.getResult(0);
1274 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1275 ResultType = EEVT::TypeSet(MVT::iPTR, TP);
1276 } else if (ResultNode->getName() == "unknown") {
1279 assert(ResultNode->isSubClassOf("RegisterClass") &&
1280 "Operands should be register classes!");
1281 const CodeGenRegisterClass &RC =
1282 CDP.getTargetInfo().getRegisterClass(ResultNode);
1283 ResultType = RC.getValueTypes();
1285 } else if (!InstInfo.ImplicitDefs.empty()) {
1286 // If the instruction has implicit defs, the first one defines the result
1288 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
1289 assert(FirstImplicitDef->isSubClassOf("Register"));
1290 const std::vector<MVT::SimpleValueType> &RegVTs =
1291 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
1292 if (RegVTs.size() == 1) // FIXME: Generalize.
1293 ResultType = EEVT::TypeSet(RegVTs);
1295 // Otherwise, the instruction produces no value result.
1298 bool MadeChange = false;
1300 if (!ResultType.isCompletelyUnknown())
1301 MadeChange |= UpdateNodeType(ResNo, ResultType, TP);
1303 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1305 if (getOperator()->getName() == "INSERT_SUBREG") {
1306 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1307 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1308 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1311 unsigned ChildNo = 0;
1312 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1313 Record *OperandNode = Inst.getOperand(i);
1315 // If the instruction expects a predicate or optional def operand, we
1316 // codegen this by setting the operand to it's default value if it has a
1317 // non-empty DefaultOps field.
1318 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1319 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1320 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1323 // Verify that we didn't run out of provided operands.
1324 if (ChildNo >= getNumChildren())
1325 TP.error("Instruction '" + getOperator()->getName() +
1326 "' expects more operands than were provided.");
1328 MVT::SimpleValueType VT;
1329 TreePatternNode *Child = getChild(ChildNo++);
1330 assert(Child->getNumTypes() == 1 && "Unknown case?");
1332 if (OperandNode->isSubClassOf("RegisterClass")) {
1333 const CodeGenRegisterClass &RC =
1334 CDP.getTargetInfo().getRegisterClass(OperandNode);
1335 MadeChange |= Child->UpdateNodeType(0, RC.getValueTypes(), TP);
1336 } else if (OperandNode->isSubClassOf("Operand")) {
1337 VT = getValueType(OperandNode->getValueAsDef("Type"));
1338 MadeChange |= Child->UpdateNodeType(0, VT, TP);
1339 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1340 MadeChange |= Child->UpdateNodeType(0, MVT::iPTR, TP);
1341 } else if (OperandNode->getName() == "unknown") {
1344 assert(0 && "Unknown operand type!");
1347 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1350 if (ChildNo != getNumChildren())
1351 TP.error("Instruction '" + getOperator()->getName() +
1352 "' was provided too many operands!");
1357 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1359 // Node transforms always take one operand.
1360 if (getNumChildren() != 1)
1361 TP.error("Node transform '" + getOperator()->getName() +
1362 "' requires one operand!");
1364 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1367 // If either the output or input of the xform does not have exact
1368 // type info. We assume they must be the same. Otherwise, it is perfectly
1369 // legal to transform from one type to a completely different type.
1371 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1372 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1373 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1380 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1381 /// RHS of a commutative operation, not the on LHS.
1382 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1383 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1385 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1391 /// canPatternMatch - If it is impossible for this pattern to match on this
1392 /// target, fill in Reason and return false. Otherwise, return true. This is
1393 /// used as a sanity check for .td files (to prevent people from writing stuff
1394 /// that can never possibly work), and to prevent the pattern permuter from
1395 /// generating stuff that is useless.
1396 bool TreePatternNode::canPatternMatch(std::string &Reason,
1397 const CodeGenDAGPatterns &CDP) {
1398 if (isLeaf()) return true;
1400 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1401 if (!getChild(i)->canPatternMatch(Reason, CDP))
1404 // If this is an intrinsic, handle cases that would make it not match. For
1405 // example, if an operand is required to be an immediate.
1406 if (getOperator()->isSubClassOf("Intrinsic")) {
1411 // If this node is a commutative operator, check that the LHS isn't an
1413 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1414 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1415 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1416 // Scan all of the operands of the node and make sure that only the last one
1417 // is a constant node, unless the RHS also is.
1418 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1419 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1420 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1421 if (OnlyOnRHSOfCommutative(getChild(i))) {
1422 Reason="Immediate value must be on the RHS of commutative operators!";
1431 //===----------------------------------------------------------------------===//
1432 // TreePattern implementation
1435 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1436 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1437 isInputPattern = isInput;
1438 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1439 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1442 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1443 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1444 isInputPattern = isInput;
1445 Trees.push_back(ParseTreePattern(Pat));
1448 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1449 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1450 isInputPattern = isInput;
1451 Trees.push_back(Pat);
1454 void TreePattern::error(const std::string &Msg) const {
1456 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1459 void TreePattern::ComputeNamedNodes() {
1460 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1461 ComputeNamedNodes(Trees[i]);
1464 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1465 if (!N->getName().empty())
1466 NamedNodes[N->getName()].push_back(N);
1468 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1469 ComputeNamedNodes(N->getChild(i));
1473 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1474 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1475 if (!OpDef) error("Pattern has unexpected operator type!");
1476 Record *Operator = OpDef->getDef();
1478 if (Operator->isSubClassOf("ValueType")) {
1479 // If the operator is a ValueType, then this must be "type cast" of a leaf
1481 if (Dag->getNumArgs() != 1)
1482 error("Type cast only takes one operand!");
1484 Init *Arg = Dag->getArg(0);
1485 TreePatternNode *New;
1486 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1487 Record *R = DI->getDef();
1488 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1489 Dag->setArg(0, new DagInit(DI, "",
1490 std::vector<std::pair<Init*, std::string> >()));
1491 return ParseTreePattern(Dag);
1495 if (R->getName() == "node") {
1496 if (Dag->getArgName(0).empty())
1497 error("'node' argument requires a name to match with operand list");
1498 Args.push_back(Dag->getArgName(0));
1501 New = new TreePatternNode(DI, 1);
1502 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1503 New = ParseTreePattern(DI);
1504 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1505 New = new TreePatternNode(II, 1);
1506 if (!Dag->getArgName(0).empty())
1507 error("Constant int argument should not have a name!");
1508 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1509 // Turn this into an IntInit.
1510 Init *II = BI->convertInitializerTo(new IntRecTy());
1511 if (II == 0 || !dynamic_cast<IntInit*>(II))
1512 error("Bits value must be constants!");
1514 New = new TreePatternNode(dynamic_cast<IntInit*>(II), 1);
1515 if (!Dag->getArgName(0).empty())
1516 error("Constant int argument should not have a name!");
1519 error("Unknown leaf value for tree pattern!");
1523 // Apply the type cast.
1524 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1525 New->UpdateNodeType(0, getValueType(Operator), *this);
1526 if (New->getNumChildren() == 0)
1527 New->setName(Dag->getArgName(0));
1531 // Verify that this is something that makes sense for an operator.
1532 if (!Operator->isSubClassOf("PatFrag") &&
1533 !Operator->isSubClassOf("SDNode") &&
1534 !Operator->isSubClassOf("Instruction") &&
1535 !Operator->isSubClassOf("SDNodeXForm") &&
1536 !Operator->isSubClassOf("Intrinsic") &&
1537 Operator->getName() != "set" &&
1538 Operator->getName() != "implicit" &&
1539 Operator->getName() != "parallel")
1540 error("Unrecognized node '" + Operator->getName() + "'!");
1542 // Check to see if this is something that is illegal in an input pattern.
1543 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1544 Operator->isSubClassOf("SDNodeXForm")))
1545 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1547 std::vector<TreePatternNode*> Children;
1549 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1550 Init *Arg = Dag->getArg(i);
1551 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1552 Children.push_back(ParseTreePattern(DI));
1553 if (Children.back()->getName().empty())
1554 Children.back()->setName(Dag->getArgName(i));
1555 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1556 Record *R = DefI->getDef();
1557 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1558 // TreePatternNode if its own.
1559 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1560 Dag->setArg(i, new DagInit(DefI, "",
1561 std::vector<std::pair<Init*, std::string> >()));
1562 --i; // Revisit this node...
1564 TreePatternNode *Node = new TreePatternNode(DefI, 1);
1565 Node->setName(Dag->getArgName(i));
1566 Children.push_back(Node);
1569 if (R->getName() == "node") {
1570 if (Dag->getArgName(i).empty())
1571 error("'node' argument requires a name to match with operand list");
1572 Args.push_back(Dag->getArgName(i));
1575 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1576 TreePatternNode *Node = new TreePatternNode(II, 1);
1577 if (!Dag->getArgName(i).empty())
1578 error("Constant int argument should not have a name!");
1579 Children.push_back(Node);
1580 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1581 // Turn this into an IntInit.
1582 Init *II = BI->convertInitializerTo(new IntRecTy());
1583 if (II == 0 || !dynamic_cast<IntInit*>(II))
1584 error("Bits value must be constants!");
1586 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II),1);
1587 if (!Dag->getArgName(i).empty())
1588 error("Constant int argument should not have a name!");
1589 Children.push_back(Node);
1594 error("Unknown leaf value for tree pattern!");
1598 // If the operator is an intrinsic, then this is just syntactic sugar for for
1599 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1600 // convert the intrinsic name to a number.
1601 if (Operator->isSubClassOf("Intrinsic")) {
1602 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1603 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1605 // If this intrinsic returns void, it must have side-effects and thus a
1607 if (Int.IS.RetVTs.empty()) {
1608 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1609 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1610 // Has side-effects, requires chain.
1611 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1613 // Otherwise, no chain.
1614 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1617 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID), 1);
1618 Children.insert(Children.begin(), IIDNode);
1621 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1622 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
1623 Result->setName(Dag->getName());
1627 /// InferAllTypes - Infer/propagate as many types throughout the expression
1628 /// patterns as possible. Return true if all types are inferred, false
1629 /// otherwise. Throw an exception if a type contradiction is found.
1631 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1632 if (NamedNodes.empty())
1633 ComputeNamedNodes();
1635 bool MadeChange = true;
1636 while (MadeChange) {
1638 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1639 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1641 // If there are constraints on our named nodes, apply them.
1642 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1643 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1644 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1646 // If we have input named node types, propagate their types to the named
1649 // FIXME: Should be error?
1650 assert(InNamedTypes->count(I->getKey()) &&
1651 "Named node in output pattern but not input pattern?");
1653 const SmallVectorImpl<TreePatternNode*> &InNodes =
1654 InNamedTypes->find(I->getKey())->second;
1656 // The input types should be fully resolved by now.
1657 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1658 // If this node is a register class, and it is the root of the pattern
1659 // then we're mapping something onto an input register. We allow
1660 // changing the type of the input register in this case. This allows
1661 // us to match things like:
1662 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1663 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1664 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1665 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1669 assert(Nodes[i]->getNumTypes() == 1 &&
1670 InNodes[0]->getNumTypes() == 1 &&
1671 "FIXME: cannot name multiple result nodes yet");
1672 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1677 // If there are multiple nodes with the same name, they must all have the
1679 if (I->second.size() > 1) {
1680 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1681 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
1682 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
1683 "FIXME: cannot name multiple result nodes yet");
1685 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1686 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
1692 bool HasUnresolvedTypes = false;
1693 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1694 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1695 return !HasUnresolvedTypes;
1698 void TreePattern::print(raw_ostream &OS) const {
1699 OS << getRecord()->getName();
1700 if (!Args.empty()) {
1701 OS << "(" << Args[0];
1702 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1703 OS << ", " << Args[i];
1708 if (Trees.size() > 1)
1710 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1712 Trees[i]->print(OS);
1716 if (Trees.size() > 1)
1720 void TreePattern::dump() const { print(errs()); }
1722 //===----------------------------------------------------------------------===//
1723 // CodeGenDAGPatterns implementation
1726 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1727 Intrinsics = LoadIntrinsics(Records, false);
1728 TgtIntrinsics = LoadIntrinsics(Records, true);
1730 ParseNodeTransforms();
1731 ParseComplexPatterns();
1732 ParsePatternFragments();
1733 ParseDefaultOperands();
1734 ParseInstructions();
1737 // Generate variants. For example, commutative patterns can match
1738 // multiple ways. Add them to PatternsToMatch as well.
1741 // Infer instruction flags. For example, we can detect loads,
1742 // stores, and side effects in many cases by examining an
1743 // instruction's pattern.
1744 InferInstructionFlags();
1747 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1748 for (pf_iterator I = PatternFragments.begin(),
1749 E = PatternFragments.end(); I != E; ++I)
1754 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1755 Record *N = Records.getDef(Name);
1756 if (!N || !N->isSubClassOf("SDNode")) {
1757 errs() << "Error getting SDNode '" << Name << "'!\n";
1763 // Parse all of the SDNode definitions for the target, populating SDNodes.
1764 void CodeGenDAGPatterns::ParseNodeInfo() {
1765 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1766 while (!Nodes.empty()) {
1767 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1771 // Get the builtin intrinsic nodes.
1772 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1773 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1774 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1777 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1778 /// map, and emit them to the file as functions.
1779 void CodeGenDAGPatterns::ParseNodeTransforms() {
1780 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1781 while (!Xforms.empty()) {
1782 Record *XFormNode = Xforms.back();
1783 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1784 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1785 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1791 void CodeGenDAGPatterns::ParseComplexPatterns() {
1792 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1793 while (!AMs.empty()) {
1794 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1800 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1801 /// file, building up the PatternFragments map. After we've collected them all,
1802 /// inline fragments together as necessary, so that there are no references left
1803 /// inside a pattern fragment to a pattern fragment.
1805 void CodeGenDAGPatterns::ParsePatternFragments() {
1806 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1808 // First step, parse all of the fragments.
1809 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1810 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1811 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1812 PatternFragments[Fragments[i]] = P;
1814 // Validate the argument list, converting it to set, to discard duplicates.
1815 std::vector<std::string> &Args = P->getArgList();
1816 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1818 if (OperandsSet.count(""))
1819 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1821 // Parse the operands list.
1822 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1823 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1824 // Special cases: ops == outs == ins. Different names are used to
1825 // improve readability.
1827 (OpsOp->getDef()->getName() != "ops" &&
1828 OpsOp->getDef()->getName() != "outs" &&
1829 OpsOp->getDef()->getName() != "ins"))
1830 P->error("Operands list should start with '(ops ... '!");
1832 // Copy over the arguments.
1834 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1835 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1836 static_cast<DefInit*>(OpsList->getArg(j))->
1837 getDef()->getName() != "node")
1838 P->error("Operands list should all be 'node' values.");
1839 if (OpsList->getArgName(j).empty())
1840 P->error("Operands list should have names for each operand!");
1841 if (!OperandsSet.count(OpsList->getArgName(j)))
1842 P->error("'" + OpsList->getArgName(j) +
1843 "' does not occur in pattern or was multiply specified!");
1844 OperandsSet.erase(OpsList->getArgName(j));
1845 Args.push_back(OpsList->getArgName(j));
1848 if (!OperandsSet.empty())
1849 P->error("Operands list does not contain an entry for operand '" +
1850 *OperandsSet.begin() + "'!");
1852 // If there is a code init for this fragment, keep track of the fact that
1853 // this fragment uses it.
1854 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1856 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
1858 // If there is a node transformation corresponding to this, keep track of
1860 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1861 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1862 P->getOnlyTree()->setTransformFn(Transform);
1865 // Now that we've parsed all of the tree fragments, do a closure on them so
1866 // that there are not references to PatFrags left inside of them.
1867 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1868 TreePattern *ThePat = PatternFragments[Fragments[i]];
1869 ThePat->InlinePatternFragments();
1871 // Infer as many types as possible. Don't worry about it if we don't infer
1872 // all of them, some may depend on the inputs of the pattern.
1874 ThePat->InferAllTypes();
1876 // If this pattern fragment is not supported by this target (no types can
1877 // satisfy its constraints), just ignore it. If the bogus pattern is
1878 // actually used by instructions, the type consistency error will be
1882 // If debugging, print out the pattern fragment result.
1883 DEBUG(ThePat->dump());
1887 void CodeGenDAGPatterns::ParseDefaultOperands() {
1888 std::vector<Record*> DefaultOps[2];
1889 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1890 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1892 // Find some SDNode.
1893 assert(!SDNodes.empty() && "No SDNodes parsed?");
1894 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1896 for (unsigned iter = 0; iter != 2; ++iter) {
1897 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1898 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1900 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1901 // SomeSDnode so that we can parse this.
1902 std::vector<std::pair<Init*, std::string> > Ops;
1903 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1904 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1905 DefaultInfo->getArgName(op)));
1906 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
1908 // Create a TreePattern to parse this.
1909 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1910 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1912 // Copy the operands over into a DAGDefaultOperand.
1913 DAGDefaultOperand DefaultOpInfo;
1915 TreePatternNode *T = P.getTree(0);
1916 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1917 TreePatternNode *TPN = T->getChild(op);
1918 while (TPN->ApplyTypeConstraints(P, false))
1919 /* Resolve all types */;
1921 if (TPN->ContainsUnresolvedType()) {
1923 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1924 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1926 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1927 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1929 DefaultOpInfo.DefaultOps.push_back(TPN);
1932 // Insert it into the DefaultOperands map so we can find it later.
1933 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1938 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1939 /// instruction input. Return true if this is a real use.
1940 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1941 std::map<std::string, TreePatternNode*> &InstInputs,
1942 std::vector<Record*> &InstImpInputs) {
1943 // No name -> not interesting.
1944 if (Pat->getName().empty()) {
1945 if (Pat->isLeaf()) {
1946 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1947 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1948 I->error("Input " + DI->getDef()->getName() + " must be named!");
1949 else if (DI && DI->getDef()->isSubClassOf("Register"))
1950 InstImpInputs.push_back(DI->getDef());
1956 if (Pat->isLeaf()) {
1957 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1958 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1961 Rec = Pat->getOperator();
1964 // SRCVALUE nodes are ignored.
1965 if (Rec->getName() == "srcvalue")
1968 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1974 if (Slot->isLeaf()) {
1975 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1977 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1978 SlotRec = Slot->getOperator();
1981 // Ensure that the inputs agree if we've already seen this input.
1983 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1984 if (Slot->getExtTypes() != Pat->getExtTypes())
1985 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1989 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1990 /// part of "I", the instruction), computing the set of inputs and outputs of
1991 /// the pattern. Report errors if we see anything naughty.
1992 void CodeGenDAGPatterns::
1993 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1994 std::map<std::string, TreePatternNode*> &InstInputs,
1995 std::map<std::string, TreePatternNode*>&InstResults,
1996 std::vector<Record*> &InstImpInputs,
1997 std::vector<Record*> &InstImpResults) {
1998 if (Pat->isLeaf()) {
1999 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
2000 if (!isUse && Pat->getTransformFn())
2001 I->error("Cannot specify a transform function for a non-input value!");
2005 if (Pat->getOperator()->getName() == "implicit") {
2006 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2007 TreePatternNode *Dest = Pat->getChild(i);
2008 if (!Dest->isLeaf())
2009 I->error("implicitly defined value should be a register!");
2011 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2012 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2013 I->error("implicitly defined value should be a register!");
2014 InstImpResults.push_back(Val->getDef());
2019 if (Pat->getOperator()->getName() != "set") {
2020 // If this is not a set, verify that the children nodes are not void typed,
2022 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2023 if (Pat->getChild(i)->getNumTypes() == 0)
2024 I->error("Cannot have void nodes inside of patterns!");
2025 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2026 InstImpInputs, InstImpResults);
2029 // If this is a non-leaf node with no children, treat it basically as if
2030 // it were a leaf. This handles nodes like (imm).
2031 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
2033 if (!isUse && Pat->getTransformFn())
2034 I->error("Cannot specify a transform function for a non-input value!");
2038 // Otherwise, this is a set, validate and collect instruction results.
2039 if (Pat->getNumChildren() == 0)
2040 I->error("set requires operands!");
2042 if (Pat->getTransformFn())
2043 I->error("Cannot specify a transform function on a set node!");
2045 // Check the set destinations.
2046 unsigned NumDests = Pat->getNumChildren()-1;
2047 for (unsigned i = 0; i != NumDests; ++i) {
2048 TreePatternNode *Dest = Pat->getChild(i);
2049 if (!Dest->isLeaf())
2050 I->error("set destination should be a register!");
2052 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2054 I->error("set destination should be a register!");
2056 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2057 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2058 if (Dest->getName().empty())
2059 I->error("set destination must have a name!");
2060 if (InstResults.count(Dest->getName()))
2061 I->error("cannot set '" + Dest->getName() +"' multiple times");
2062 InstResults[Dest->getName()] = Dest;
2063 } else if (Val->getDef()->isSubClassOf("Register")) {
2064 InstImpResults.push_back(Val->getDef());
2066 I->error("set destination should be a register!");
2070 // Verify and collect info from the computation.
2071 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2072 InstInputs, InstResults,
2073 InstImpInputs, InstImpResults);
2076 //===----------------------------------------------------------------------===//
2077 // Instruction Analysis
2078 //===----------------------------------------------------------------------===//
2080 class InstAnalyzer {
2081 const CodeGenDAGPatterns &CDP;
2084 bool &HasSideEffects;
2087 InstAnalyzer(const CodeGenDAGPatterns &cdp,
2088 bool &maystore, bool &mayload, bool &hse, bool &isv)
2089 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse),
2093 /// Analyze - Analyze the specified instruction, returning true if the
2094 /// instruction had a pattern.
2095 bool Analyze(Record *InstRecord) {
2096 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2099 return false; // No pattern.
2102 // FIXME: Assume only the first tree is the pattern. The others are clobber
2104 AnalyzeNode(Pattern->getTree(0));
2109 void AnalyzeNode(const TreePatternNode *N) {
2111 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2112 Record *LeafRec = DI->getDef();
2113 // Handle ComplexPattern leaves.
2114 if (LeafRec->isSubClassOf("ComplexPattern")) {
2115 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2116 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2117 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2118 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2124 // Analyze children.
2125 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2126 AnalyzeNode(N->getChild(i));
2128 // Ignore set nodes, which are not SDNodes.
2129 if (N->getOperator()->getName() == "set")
2132 // Get information about the SDNode for the operator.
2133 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2135 // Notice properties of the node.
2136 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2137 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2138 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2139 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
2141 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2142 // If this is an intrinsic, analyze it.
2143 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2144 mayLoad = true;// These may load memory.
2146 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2147 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2149 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2150 // WriteMem intrinsics can have other strange effects.
2151 HasSideEffects = true;
2157 static void InferFromPattern(const CodeGenInstruction &Inst,
2158 bool &MayStore, bool &MayLoad,
2159 bool &HasSideEffects, bool &IsVariadic,
2160 const CodeGenDAGPatterns &CDP) {
2161 MayStore = MayLoad = HasSideEffects = IsVariadic = false;
2164 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects, IsVariadic)
2165 .Analyze(Inst.TheDef);
2167 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2168 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2169 // If we decided that this is a store from the pattern, then the .td file
2170 // entry is redundant.
2173 "Warning: mayStore flag explicitly set on instruction '%s'"
2174 " but flag already inferred from pattern.\n",
2175 Inst.TheDef->getName().c_str());
2179 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2180 // If we decided that this is a load from the pattern, then the .td file
2181 // entry is redundant.
2184 "Warning: mayLoad flag explicitly set on instruction '%s'"
2185 " but flag already inferred from pattern.\n",
2186 Inst.TheDef->getName().c_str());
2190 if (Inst.neverHasSideEffects) {
2192 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2193 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2194 HasSideEffects = false;
2197 if (Inst.hasSideEffects) {
2199 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2200 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2201 HasSideEffects = true;
2204 if (Inst.isVariadic)
2205 IsVariadic = true; // Can warn if we want.
2208 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2209 /// any fragments involved. This populates the Instructions list with fully
2210 /// resolved instructions.
2211 void CodeGenDAGPatterns::ParseInstructions() {
2212 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2214 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2217 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2218 LI = Instrs[i]->getValueAsListInit("Pattern");
2220 // If there is no pattern, only collect minimal information about the
2221 // instruction for its operand list. We have to assume that there is one
2222 // result, as we have no detailed info.
2223 if (!LI || LI->getSize() == 0) {
2224 std::vector<Record*> Results;
2225 std::vector<Record*> Operands;
2227 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2229 if (InstInfo.OperandList.size() != 0) {
2230 if (InstInfo.NumDefs == 0) {
2231 // These produce no results
2232 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2233 Operands.push_back(InstInfo.OperandList[j].Rec);
2235 // Assume the first operand is the result.
2236 Results.push_back(InstInfo.OperandList[0].Rec);
2238 // The rest are inputs.
2239 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2240 Operands.push_back(InstInfo.OperandList[j].Rec);
2244 // Create and insert the instruction.
2245 std::vector<Record*> ImpResults;
2246 std::vector<Record*> ImpOperands;
2247 Instructions.insert(std::make_pair(Instrs[i],
2248 DAGInstruction(0, Results, Operands, ImpResults,
2250 continue; // no pattern.
2253 // Parse the instruction.
2254 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2255 // Inline pattern fragments into it.
2256 I->InlinePatternFragments();
2258 // Infer as many types as possible. If we cannot infer all of them, we can
2259 // never do anything with this instruction pattern: report it to the user.
2260 if (!I->InferAllTypes())
2261 I->error("Could not infer all types in pattern!");
2263 // InstInputs - Keep track of all of the inputs of the instruction, along
2264 // with the record they are declared as.
2265 std::map<std::string, TreePatternNode*> InstInputs;
2267 // InstResults - Keep track of all the virtual registers that are 'set'
2268 // in the instruction, including what reg class they are.
2269 std::map<std::string, TreePatternNode*> InstResults;
2271 std::vector<Record*> InstImpInputs;
2272 std::vector<Record*> InstImpResults;
2274 // Verify that the top-level forms in the instruction are of void type, and
2275 // fill in the InstResults map.
2276 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2277 TreePatternNode *Pat = I->getTree(j);
2278 if (Pat->getNumTypes() != 0)
2279 I->error("Top-level forms in instruction pattern should have"
2282 // Find inputs and outputs, and verify the structure of the uses/defs.
2283 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2284 InstImpInputs, InstImpResults);
2287 // Now that we have inputs and outputs of the pattern, inspect the operands
2288 // list for the instruction. This determines the order that operands are
2289 // added to the machine instruction the node corresponds to.
2290 unsigned NumResults = InstResults.size();
2292 // Parse the operands list from the (ops) list, validating it.
2293 assert(I->getArgList().empty() && "Args list should still be empty here!");
2294 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2296 // Check that all of the results occur first in the list.
2297 std::vector<Record*> Results;
2298 TreePatternNode *Res0Node = 0;
2299 for (unsigned i = 0; i != NumResults; ++i) {
2300 if (i == CGI.OperandList.size())
2301 I->error("'" + InstResults.begin()->first +
2302 "' set but does not appear in operand list!");
2303 const std::string &OpName = CGI.OperandList[i].Name;
2305 // Check that it exists in InstResults.
2306 TreePatternNode *RNode = InstResults[OpName];
2308 I->error("Operand $" + OpName + " does not exist in operand list!");
2312 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2314 I->error("Operand $" + OpName + " should be a set destination: all "
2315 "outputs must occur before inputs in operand list!");
2317 if (CGI.OperandList[i].Rec != R)
2318 I->error("Operand $" + OpName + " class mismatch!");
2320 // Remember the return type.
2321 Results.push_back(CGI.OperandList[i].Rec);
2323 // Okay, this one checks out.
2324 InstResults.erase(OpName);
2327 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2328 // the copy while we're checking the inputs.
2329 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2331 std::vector<TreePatternNode*> ResultNodeOperands;
2332 std::vector<Record*> Operands;
2333 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2334 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2335 const std::string &OpName = Op.Name;
2337 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2339 if (!InstInputsCheck.count(OpName)) {
2340 // If this is an predicate operand or optional def operand with an
2341 // DefaultOps set filled in, we can ignore this. When we codegen it,
2342 // we will do so as always executed.
2343 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2344 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2345 // Does it have a non-empty DefaultOps field? If so, ignore this
2347 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2350 I->error("Operand $" + OpName +
2351 " does not appear in the instruction pattern");
2353 TreePatternNode *InVal = InstInputsCheck[OpName];
2354 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2356 if (InVal->isLeaf() &&
2357 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2358 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2359 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2360 I->error("Operand $" + OpName + "'s register class disagrees"
2361 " between the operand and pattern");
2363 Operands.push_back(Op.Rec);
2365 // Construct the result for the dest-pattern operand list.
2366 TreePatternNode *OpNode = InVal->clone();
2368 // No predicate is useful on the result.
2369 OpNode->clearPredicateFns();
2371 // Promote the xform function to be an explicit node if set.
2372 if (Record *Xform = OpNode->getTransformFn()) {
2373 OpNode->setTransformFn(0);
2374 std::vector<TreePatternNode*> Children;
2375 Children.push_back(OpNode);
2376 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2379 ResultNodeOperands.push_back(OpNode);
2382 if (!InstInputsCheck.empty())
2383 I->error("Input operand $" + InstInputsCheck.begin()->first +
2384 " occurs in pattern but not in operands list!");
2386 TreePatternNode *ResultPattern =
2387 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2388 GetNumNodeResults(I->getRecord(), *this));
2389 // Copy fully inferred output node type to instruction result pattern.
2390 for (unsigned i = 0; i != NumResults; ++i)
2391 ResultPattern->setType(i, Res0Node->getExtType(i));
2393 // Create and insert the instruction.
2394 // FIXME: InstImpResults and InstImpInputs should not be part of
2396 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2397 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2399 // Use a temporary tree pattern to infer all types and make sure that the
2400 // constructed result is correct. This depends on the instruction already
2401 // being inserted into the Instructions map.
2402 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2403 Temp.InferAllTypes(&I->getNamedNodesMap());
2405 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2406 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2411 // If we can, convert the instructions to be patterns that are matched!
2412 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2413 Instructions.begin(),
2414 E = Instructions.end(); II != E; ++II) {
2415 DAGInstruction &TheInst = II->second;
2416 const TreePattern *I = TheInst.getPattern();
2417 if (I == 0) continue; // No pattern.
2419 // FIXME: Assume only the first tree is the pattern. The others are clobber
2421 TreePatternNode *Pattern = I->getTree(0);
2422 TreePatternNode *SrcPattern;
2423 if (Pattern->getOperator()->getName() == "set") {
2424 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2426 // Not a set (store or something?)
2427 SrcPattern = Pattern;
2430 Record *Instr = II->first;
2431 AddPatternToMatch(I,
2432 PatternToMatch(Instr->getValueAsListInit("Predicates"),
2434 TheInst.getResultPattern(),
2435 TheInst.getImpResults(),
2436 Instr->getValueAsInt("AddedComplexity"),
2442 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2444 static void FindNames(const TreePatternNode *P,
2445 std::map<std::string, NameRecord> &Names,
2446 const TreePattern *PatternTop) {
2447 if (!P->getName().empty()) {
2448 NameRecord &Rec = Names[P->getName()];
2449 // If this is the first instance of the name, remember the node.
2450 if (Rec.second++ == 0)
2452 else if (Rec.first->getExtTypes() != P->getExtTypes())
2453 PatternTop->error("repetition of value: $" + P->getName() +
2454 " where different uses have different types!");
2458 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2459 FindNames(P->getChild(i), Names, PatternTop);
2463 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2464 const PatternToMatch &PTM) {
2465 // Do some sanity checking on the pattern we're about to match.
2467 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2468 Pattern->error("Pattern can never match: " + Reason);
2470 // If the source pattern's root is a complex pattern, that complex pattern
2471 // must specify the nodes it can potentially match.
2472 if (const ComplexPattern *CP =
2473 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2474 if (CP->getRootNodes().empty())
2475 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2479 // Find all of the named values in the input and output, ensure they have the
2481 std::map<std::string, NameRecord> SrcNames, DstNames;
2482 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2483 FindNames(PTM.getDstPattern(), DstNames, Pattern);
2485 // Scan all of the named values in the destination pattern, rejecting them if
2486 // they don't exist in the input pattern.
2487 for (std::map<std::string, NameRecord>::iterator
2488 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2489 if (SrcNames[I->first].first == 0)
2490 Pattern->error("Pattern has input without matching name in output: $" +
2494 // Scan all of the named values in the source pattern, rejecting them if the
2495 // name isn't used in the dest, and isn't used to tie two values together.
2496 for (std::map<std::string, NameRecord>::iterator
2497 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2498 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2499 Pattern->error("Pattern has dead named input: $" + I->first);
2501 PatternsToMatch.push_back(PTM);
2506 void CodeGenDAGPatterns::InferInstructionFlags() {
2507 const std::vector<const CodeGenInstruction*> &Instructions =
2508 Target.getInstructionsByEnumValue();
2509 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2510 CodeGenInstruction &InstInfo =
2511 const_cast<CodeGenInstruction &>(*Instructions[i]);
2512 // Determine properties of the instruction from its pattern.
2513 bool MayStore, MayLoad, HasSideEffects, IsVariadic;
2514 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, IsVariadic,
2516 InstInfo.mayStore = MayStore;
2517 InstInfo.mayLoad = MayLoad;
2518 InstInfo.hasSideEffects = HasSideEffects;
2519 InstInfo.isVariadic = IsVariadic;
2523 /// Given a pattern result with an unresolved type, see if we can find one
2524 /// instruction with an unresolved result type. Force this result type to an
2525 /// arbitrary element if it's possible types to converge results.
2526 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2530 // Analyze children.
2531 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2532 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2535 if (!N->getOperator()->isSubClassOf("Instruction"))
2538 // If this type is already concrete or completely unknown we can't do
2540 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2541 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2544 // Otherwise, force its type to the first possibility (an arbitrary choice).
2545 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2552 void CodeGenDAGPatterns::ParsePatterns() {
2553 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2555 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2556 Record *CurPattern = Patterns[i];
2557 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
2558 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2559 Record *Operator = OpDef->getDef();
2560 TreePattern *Pattern;
2561 if (Operator->getName() != "parallel")
2562 Pattern = new TreePattern(CurPattern, Tree, true, *this);
2564 std::vector<Init*> Values;
2566 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
2567 Values.push_back(Tree->getArg(j));
2568 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2570 errs() << "In dag: " << Tree->getAsString();
2571 errs() << " -- Untyped argument in pattern\n";
2572 assert(0 && "Untyped argument in pattern");
2575 ListTy = resolveTypes(ListTy, TArg->getType());
2577 errs() << "In dag: " << Tree->getAsString();
2578 errs() << " -- Incompatible types in pattern arguments\n";
2579 assert(0 && "Incompatible types in pattern arguments");
2583 ListTy = TArg->getType();
2586 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
2587 Pattern = new TreePattern(CurPattern, LI, true, *this);
2590 // Inline pattern fragments into it.
2591 Pattern->InlinePatternFragments();
2593 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
2594 if (LI->getSize() == 0) continue; // no pattern.
2596 // Parse the instruction.
2597 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
2599 // Inline pattern fragments into it.
2600 Result->InlinePatternFragments();
2602 if (Result->getNumTrees() != 1)
2603 Result->error("Cannot handle instructions producing instructions "
2604 "with temporaries yet!");
2606 bool IterateInference;
2607 bool InferredAllPatternTypes, InferredAllResultTypes;
2609 // Infer as many types as possible. If we cannot infer all of them, we
2610 // can never do anything with this pattern: report it to the user.
2611 InferredAllPatternTypes =
2612 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
2614 // Infer as many types as possible. If we cannot infer all of them, we
2615 // can never do anything with this pattern: report it to the user.
2616 InferredAllResultTypes =
2617 Result->InferAllTypes(&Pattern->getNamedNodesMap());
2619 IterateInference = false;
2621 // Apply the type of the result to the source pattern. This helps us
2622 // resolve cases where the input type is known to be a pointer type (which
2623 // is considered resolved), but the result knows it needs to be 32- or
2624 // 64-bits. Infer the other way for good measure.
2625 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2626 Pattern->getTree(0)->getNumTypes());
2628 IterateInference = Pattern->getTree(0)->
2629 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
2630 IterateInference |= Result->getTree(0)->
2631 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
2634 // If our iteration has converged and the input pattern's types are fully
2635 // resolved but the result pattern is not fully resolved, we may have a
2636 // situation where we have two instructions in the result pattern and
2637 // the instructions require a common register class, but don't care about
2638 // what actual MVT is used. This is actually a bug in our modelling:
2639 // output patterns should have register classes, not MVTs.
2641 // In any case, to handle this, we just go through and disambiguate some
2642 // arbitrary types to the result pattern's nodes.
2643 if (!IterateInference && InferredAllPatternTypes &&
2644 !InferredAllResultTypes)
2645 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2647 } while (IterateInference);
2649 // Verify that we inferred enough types that we can do something with the
2650 // pattern and result. If these fire the user has to add type casts.
2651 if (!InferredAllPatternTypes)
2652 Pattern->error("Could not infer all types in pattern!");
2653 if (!InferredAllResultTypes) {
2655 Result->error("Could not infer all types in pattern result!");
2658 // Validate that the input pattern is correct.
2659 std::map<std::string, TreePatternNode*> InstInputs;
2660 std::map<std::string, TreePatternNode*> InstResults;
2661 std::vector<Record*> InstImpInputs;
2662 std::vector<Record*> InstImpResults;
2663 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2664 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2665 InstInputs, InstResults,
2666 InstImpInputs, InstImpResults);
2668 // Promote the xform function to be an explicit node if set.
2669 TreePatternNode *DstPattern = Result->getOnlyTree();
2670 std::vector<TreePatternNode*> ResultNodeOperands;
2671 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2672 TreePatternNode *OpNode = DstPattern->getChild(ii);
2673 if (Record *Xform = OpNode->getTransformFn()) {
2674 OpNode->setTransformFn(0);
2675 std::vector<TreePatternNode*> Children;
2676 Children.push_back(OpNode);
2677 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2679 ResultNodeOperands.push_back(OpNode);
2681 DstPattern = Result->getOnlyTree();
2682 if (!DstPattern->isLeaf())
2683 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2685 DstPattern->getNumTypes());
2687 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2688 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
2690 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2691 Temp.InferAllTypes();
2694 AddPatternToMatch(Pattern,
2695 PatternToMatch(CurPattern->getValueAsListInit("Predicates"),
2696 Pattern->getTree(0),
2697 Temp.getOnlyTree(), InstImpResults,
2698 CurPattern->getValueAsInt("AddedComplexity"),
2699 CurPattern->getID()));
2703 /// CombineChildVariants - Given a bunch of permutations of each child of the
2704 /// 'operator' node, put them together in all possible ways.
2705 static void CombineChildVariants(TreePatternNode *Orig,
2706 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2707 std::vector<TreePatternNode*> &OutVariants,
2708 CodeGenDAGPatterns &CDP,
2709 const MultipleUseVarSet &DepVars) {
2710 // Make sure that each operand has at least one variant to choose from.
2711 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2712 if (ChildVariants[i].empty())
2715 // The end result is an all-pairs construction of the resultant pattern.
2716 std::vector<unsigned> Idxs;
2717 Idxs.resize(ChildVariants.size());
2721 DEBUG(if (!Idxs.empty()) {
2722 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2723 for (unsigned i = 0; i < Idxs.size(); ++i) {
2724 errs() << Idxs[i] << " ";
2729 // Create the variant and add it to the output list.
2730 std::vector<TreePatternNode*> NewChildren;
2731 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2732 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2733 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
2734 Orig->getNumTypes());
2736 // Copy over properties.
2737 R->setName(Orig->getName());
2738 R->setPredicateFns(Orig->getPredicateFns());
2739 R->setTransformFn(Orig->getTransformFn());
2740 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
2741 R->setType(i, Orig->getExtType(i));
2743 // If this pattern cannot match, do not include it as a variant.
2744 std::string ErrString;
2745 if (!R->canPatternMatch(ErrString, CDP)) {
2748 bool AlreadyExists = false;
2750 // Scan to see if this pattern has already been emitted. We can get
2751 // duplication due to things like commuting:
2752 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2753 // which are the same pattern. Ignore the dups.
2754 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2755 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2756 AlreadyExists = true;
2763 OutVariants.push_back(R);
2766 // Increment indices to the next permutation by incrementing the
2767 // indicies from last index backward, e.g., generate the sequence
2768 // [0, 0], [0, 1], [1, 0], [1, 1].
2770 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2771 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2776 NotDone = (IdxsIdx >= 0);
2780 /// CombineChildVariants - A helper function for binary operators.
2782 static void CombineChildVariants(TreePatternNode *Orig,
2783 const std::vector<TreePatternNode*> &LHS,
2784 const std::vector<TreePatternNode*> &RHS,
2785 std::vector<TreePatternNode*> &OutVariants,
2786 CodeGenDAGPatterns &CDP,
2787 const MultipleUseVarSet &DepVars) {
2788 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2789 ChildVariants.push_back(LHS);
2790 ChildVariants.push_back(RHS);
2791 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2795 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2796 std::vector<TreePatternNode *> &Children) {
2797 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2798 Record *Operator = N->getOperator();
2800 // Only permit raw nodes.
2801 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2802 N->getTransformFn()) {
2803 Children.push_back(N);
2807 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2808 Children.push_back(N->getChild(0));
2810 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2812 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2813 Children.push_back(N->getChild(1));
2815 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2818 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2819 /// the (potentially recursive) pattern by using algebraic laws.
2821 static void GenerateVariantsOf(TreePatternNode *N,
2822 std::vector<TreePatternNode*> &OutVariants,
2823 CodeGenDAGPatterns &CDP,
2824 const MultipleUseVarSet &DepVars) {
2825 // We cannot permute leaves.
2827 OutVariants.push_back(N);
2831 // Look up interesting info about the node.
2832 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2834 // If this node is associative, re-associate.
2835 if (NodeInfo.hasProperty(SDNPAssociative)) {
2836 // Re-associate by pulling together all of the linked operators
2837 std::vector<TreePatternNode*> MaximalChildren;
2838 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2840 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2842 if (MaximalChildren.size() == 3) {
2843 // Find the variants of all of our maximal children.
2844 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2845 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2846 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2847 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2849 // There are only two ways we can permute the tree:
2850 // (A op B) op C and A op (B op C)
2851 // Within these forms, we can also permute A/B/C.
2853 // Generate legal pair permutations of A/B/C.
2854 std::vector<TreePatternNode*> ABVariants;
2855 std::vector<TreePatternNode*> BAVariants;
2856 std::vector<TreePatternNode*> ACVariants;
2857 std::vector<TreePatternNode*> CAVariants;
2858 std::vector<TreePatternNode*> BCVariants;
2859 std::vector<TreePatternNode*> CBVariants;
2860 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2861 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2862 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2863 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2864 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2865 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2867 // Combine those into the result: (x op x) op x
2868 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2869 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2870 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2871 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2872 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2873 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2875 // Combine those into the result: x op (x op x)
2876 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2877 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2878 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2879 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2880 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2881 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2886 // Compute permutations of all children.
2887 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2888 ChildVariants.resize(N->getNumChildren());
2889 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2890 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2892 // Build all permutations based on how the children were formed.
2893 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2895 // If this node is commutative, consider the commuted order.
2896 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2897 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2898 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2899 "Commutative but doesn't have 2 children!");
2900 // Don't count children which are actually register references.
2902 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2903 TreePatternNode *Child = N->getChild(i);
2904 if (Child->isLeaf())
2905 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2906 Record *RR = DI->getDef();
2907 if (RR->isSubClassOf("Register"))
2912 // Consider the commuted order.
2913 if (isCommIntrinsic) {
2914 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2915 // operands are the commutative operands, and there might be more operands
2918 "Commutative intrinsic should have at least 3 childrean!");
2919 std::vector<std::vector<TreePatternNode*> > Variants;
2920 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2921 Variants.push_back(ChildVariants[2]);
2922 Variants.push_back(ChildVariants[1]);
2923 for (unsigned i = 3; i != NC; ++i)
2924 Variants.push_back(ChildVariants[i]);
2925 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2927 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2928 OutVariants, CDP, DepVars);
2933 // GenerateVariants - Generate variants. For example, commutative patterns can
2934 // match multiple ways. Add them to PatternsToMatch as well.
2935 void CodeGenDAGPatterns::GenerateVariants() {
2936 DEBUG(errs() << "Generating instruction variants.\n");
2938 // Loop over all of the patterns we've collected, checking to see if we can
2939 // generate variants of the instruction, through the exploitation of
2940 // identities. This permits the target to provide aggressive matching without
2941 // the .td file having to contain tons of variants of instructions.
2943 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2944 // intentionally do not reconsider these. Any variants of added patterns have
2945 // already been added.
2947 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2948 MultipleUseVarSet DepVars;
2949 std::vector<TreePatternNode*> Variants;
2950 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2951 DEBUG(errs() << "Dependent/multiply used variables: ");
2952 DEBUG(DumpDepVars(DepVars));
2953 DEBUG(errs() << "\n");
2954 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2956 assert(!Variants.empty() && "Must create at least original variant!");
2957 Variants.erase(Variants.begin()); // Remove the original pattern.
2959 if (Variants.empty()) // No variants for this pattern.
2962 DEBUG(errs() << "FOUND VARIANTS OF: ";
2963 PatternsToMatch[i].getSrcPattern()->dump();
2966 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2967 TreePatternNode *Variant = Variants[v];
2969 DEBUG(errs() << " VAR#" << v << ": ";
2973 // Scan to see if an instruction or explicit pattern already matches this.
2974 bool AlreadyExists = false;
2975 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2976 // Skip if the top level predicates do not match.
2977 if (PatternsToMatch[i].getPredicates() !=
2978 PatternsToMatch[p].getPredicates())
2980 // Check to see if this variant already exists.
2981 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2982 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
2983 AlreadyExists = true;
2987 // If we already have it, ignore the variant.
2988 if (AlreadyExists) continue;
2990 // Otherwise, add it to the list of patterns we have.
2992 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2993 Variant, PatternsToMatch[i].getDstPattern(),
2994 PatternsToMatch[i].getDstRegs(),
2995 PatternsToMatch[i].getAddedComplexity(),
2996 Record::getNewUID()));
2999 DEBUG(errs() << "\n");