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 VT.
398 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
400 TypeSet InputSet(*this);
401 bool MadeChange = false;
403 // If we know nothing, then get the full set.
405 MadeChange = FillWithPossibleTypes(TP, isVector, "vector");
407 // Filter out all the non-vector types and types which don't have the right
409 for (unsigned i = 0; i != TypeVec.size(); ++i)
410 if (!isVector(TypeVec[i]) ||
411 EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
412 TypeVec.erase(TypeVec.begin()+i--);
416 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
417 TP.error("Type inference contradiction found, forcing '" +
418 InputSet.getName() + "' to have a vector element");
422 //===----------------------------------------------------------------------===//
423 // Helpers for working with extended types.
425 bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
426 return LHS->getID() < RHS->getID();
429 /// Dependent variable map for CodeGenDAGPattern variant generation
430 typedef std::map<std::string, int> DepVarMap;
432 /// Const iterator shorthand for DepVarMap
433 typedef DepVarMap::const_iterator DepVarMap_citer;
436 void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
438 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL) {
439 DepMap[N->getName()]++;
442 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
443 FindDepVarsOf(N->getChild(i), DepMap);
447 //! Find dependent variables within child patterns
450 void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
452 FindDepVarsOf(N, depcounts);
453 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
454 if (i->second > 1) { // std::pair<std::string, int>
455 DepVars.insert(i->first);
460 //! Dump the dependent variable set:
461 void DumpDepVars(MultipleUseVarSet &DepVars) {
462 if (DepVars.empty()) {
463 DEBUG(errs() << "<empty set>");
465 DEBUG(errs() << "[ ");
466 for (MultipleUseVarSet::const_iterator i = DepVars.begin(), e = DepVars.end();
468 DEBUG(errs() << (*i) << " ");
470 DEBUG(errs() << "]");
475 //===----------------------------------------------------------------------===//
476 // PatternToMatch implementation
479 /// getPredicateCheck - Return a single string containing all of this
480 /// pattern's predicates concatenated with "&&" operators.
482 std::string PatternToMatch::getPredicateCheck() const {
483 std::string PredicateCheck;
484 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
485 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
486 Record *Def = Pred->getDef();
487 if (!Def->isSubClassOf("Predicate")) {
491 assert(0 && "Unknown predicate type!");
493 if (!PredicateCheck.empty())
494 PredicateCheck += " && ";
495 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
499 return PredicateCheck;
502 //===----------------------------------------------------------------------===//
503 // SDTypeConstraint implementation
506 SDTypeConstraint::SDTypeConstraint(Record *R) {
507 OperandNo = R->getValueAsInt("OperandNum");
509 if (R->isSubClassOf("SDTCisVT")) {
510 ConstraintType = SDTCisVT;
511 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
512 } else if (R->isSubClassOf("SDTCisPtrTy")) {
513 ConstraintType = SDTCisPtrTy;
514 } else if (R->isSubClassOf("SDTCisInt")) {
515 ConstraintType = SDTCisInt;
516 } else if (R->isSubClassOf("SDTCisFP")) {
517 ConstraintType = SDTCisFP;
518 } else if (R->isSubClassOf("SDTCisVec")) {
519 ConstraintType = SDTCisVec;
520 } else if (R->isSubClassOf("SDTCisSameAs")) {
521 ConstraintType = SDTCisSameAs;
522 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
523 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
524 ConstraintType = SDTCisVTSmallerThanOp;
525 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
526 R->getValueAsInt("OtherOperandNum");
527 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
528 ConstraintType = SDTCisOpSmallerThanOp;
529 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
530 R->getValueAsInt("BigOperandNum");
531 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
532 ConstraintType = SDTCisEltOfVec;
533 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
535 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
540 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
541 /// N, which has NumResults results.
542 TreePatternNode *SDTypeConstraint::getOperandNum(unsigned OpNo,
544 unsigned NumResults) const {
545 assert(NumResults <= 1 &&
546 "We only work with nodes with zero or one result so far!");
548 if (OpNo >= (NumResults + N->getNumChildren())) {
549 errs() << "Invalid operand number " << OpNo << " ";
555 if (OpNo < NumResults)
556 return N; // FIXME: need value #
558 return N->getChild(OpNo-NumResults);
561 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
562 /// constraint to the nodes operands. This returns true if it makes a
563 /// change, false otherwise. If a type contradiction is found, throw an
565 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
566 const SDNodeInfo &NodeInfo,
567 TreePattern &TP) const {
568 unsigned NumResults = NodeInfo.getNumResults();
569 assert(NumResults <= 1 &&
570 "We only work with nodes with zero or one result so far!");
572 // Check that the number of operands is sane. Negative operands -> varargs.
573 if (NodeInfo.getNumOperands() >= 0) {
574 if (N->getNumChildren() != (unsigned)NodeInfo.getNumOperands())
575 TP.error(N->getOperator()->getName() + " node requires exactly " +
576 itostr(NodeInfo.getNumOperands()) + " operands!");
579 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NumResults);
581 switch (ConstraintType) {
582 default: assert(0 && "Unknown constraint type!");
584 // Operand must be a particular type.
585 return NodeToApply->UpdateNodeType(x.SDTCisVT_Info.VT, TP);
587 // Operand must be same as target pointer type.
588 return NodeToApply->UpdateNodeType(MVT::iPTR, TP);
590 // Require it to be one of the legal integer VTs.
591 return NodeToApply->getExtType().EnforceInteger(TP);
593 // Require it to be one of the legal fp VTs.
594 return NodeToApply->getExtType().EnforceFloatingPoint(TP);
596 // Require it to be one of the legal vector VTs.
597 return NodeToApply->getExtType().EnforceVector(TP);
599 TreePatternNode *OtherNode =
600 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NumResults);
601 return NodeToApply->UpdateNodeType(OtherNode->getExtType(), TP) |
602 OtherNode->UpdateNodeType(NodeToApply->getExtType(), TP);
604 case SDTCisVTSmallerThanOp: {
605 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
606 // have an integer type that is smaller than the VT.
607 if (!NodeToApply->isLeaf() ||
608 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
609 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
610 ->isSubClassOf("ValueType"))
611 TP.error(N->getOperator()->getName() + " expects a VT operand!");
612 MVT::SimpleValueType VT =
613 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
615 TP.error(N->getOperator()->getName() + " VT operand must be integer!");
617 TreePatternNode *OtherNode =
618 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N,NumResults);
620 // It must be integer.
621 bool MadeChange = OtherNode->getExtType().EnforceInteger(TP);
623 // This doesn't try to enforce any information on the OtherNode, it just
624 // validates it when information is determined.
625 if (OtherNode->hasTypeSet() && OtherNode->getType() <= VT)
626 OtherNode->UpdateNodeType(MVT::Other, TP); // Throw an error.
629 case SDTCisOpSmallerThanOp: {
630 TreePatternNode *BigOperand =
631 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NumResults);
632 return NodeToApply->getExtType().
633 EnforceSmallerThan(BigOperand->getExtType(), TP);
635 case SDTCisEltOfVec: {
636 TreePatternNode *VecOperand =
637 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NumResults);
638 if (VecOperand->hasTypeSet()) {
639 if (!isVector(VecOperand->getType()))
640 TP.error(N->getOperator()->getName() + " VT operand must be a vector!");
641 EVT IVT = VecOperand->getType();
642 IVT = IVT.getVectorElementType();
643 return NodeToApply->UpdateNodeType(IVT.getSimpleVT().SimpleTy, TP);
646 if (NodeToApply->hasTypeSet() && VecOperand->getExtType().hasVectorTypes()){
647 // Filter vector types out of VecOperand that don't have the right element
649 return VecOperand->getExtType().
650 EnforceVectorEltTypeIs(NodeToApply->getType(), TP);
658 //===----------------------------------------------------------------------===//
659 // SDNodeInfo implementation
661 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
662 EnumName = R->getValueAsString("Opcode");
663 SDClassName = R->getValueAsString("SDClass");
664 Record *TypeProfile = R->getValueAsDef("TypeProfile");
665 NumResults = TypeProfile->getValueAsInt("NumResults");
666 NumOperands = TypeProfile->getValueAsInt("NumOperands");
668 // Parse the properties.
670 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
671 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
672 if (PropList[i]->getName() == "SDNPCommutative") {
673 Properties |= 1 << SDNPCommutative;
674 } else if (PropList[i]->getName() == "SDNPAssociative") {
675 Properties |= 1 << SDNPAssociative;
676 } else if (PropList[i]->getName() == "SDNPHasChain") {
677 Properties |= 1 << SDNPHasChain;
678 } else if (PropList[i]->getName() == "SDNPOutFlag") {
679 Properties |= 1 << SDNPOutFlag;
680 } else if (PropList[i]->getName() == "SDNPInFlag") {
681 Properties |= 1 << SDNPInFlag;
682 } else if (PropList[i]->getName() == "SDNPOptInFlag") {
683 Properties |= 1 << SDNPOptInFlag;
684 } else if (PropList[i]->getName() == "SDNPMayStore") {
685 Properties |= 1 << SDNPMayStore;
686 } else if (PropList[i]->getName() == "SDNPMayLoad") {
687 Properties |= 1 << SDNPMayLoad;
688 } else if (PropList[i]->getName() == "SDNPSideEffect") {
689 Properties |= 1 << SDNPSideEffect;
690 } else if (PropList[i]->getName() == "SDNPMemOperand") {
691 Properties |= 1 << SDNPMemOperand;
692 } else if (PropList[i]->getName() == "SDNPVariadic") {
693 Properties |= 1 << SDNPVariadic;
695 errs() << "Unknown SD Node property '" << PropList[i]->getName()
696 << "' on node '" << R->getName() << "'!\n";
702 // Parse the type constraints.
703 std::vector<Record*> ConstraintList =
704 TypeProfile->getValueAsListOfDefs("Constraints");
705 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
708 /// getKnownType - If the type constraints on this node imply a fixed type
709 /// (e.g. all stores return void, etc), then return it as an
710 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
711 MVT::SimpleValueType SDNodeInfo::getKnownType() const {
712 unsigned NumResults = getNumResults();
713 assert(NumResults <= 1 &&
714 "We only work with nodes with zero or one result so far!");
716 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
717 // Make sure that this applies to the correct node result.
718 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
721 switch (TypeConstraints[i].ConstraintType) {
723 case SDTypeConstraint::SDTCisVT:
724 return TypeConstraints[i].x.SDTCisVT_Info.VT;
725 case SDTypeConstraint::SDTCisPtrTy:
732 //===----------------------------------------------------------------------===//
733 // TreePatternNode implementation
736 TreePatternNode::~TreePatternNode() {
737 #if 0 // FIXME: implement refcounted tree nodes!
738 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
745 void TreePatternNode::print(raw_ostream &OS) const {
747 OS << *getLeafValue();
749 OS << '(' << getOperator()->getName();
752 if (!isTypeCompletelyUnknown())
753 OS << ':' << getExtType().getName();
756 if (getNumChildren() != 0) {
758 getChild(0)->print(OS);
759 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
761 getChild(i)->print(OS);
767 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
768 OS << "<<P:" << PredicateFns[i] << ">>";
770 OS << "<<X:" << TransformFn->getName() << ">>";
771 if (!getName().empty())
772 OS << ":$" << getName();
775 void TreePatternNode::dump() const {
779 /// isIsomorphicTo - Return true if this node is recursively
780 /// isomorphic to the specified node. For this comparison, the node's
781 /// entire state is considered. The assigned name is ignored, since
782 /// nodes with differing names are considered isomorphic. However, if
783 /// the assigned name is present in the dependent variable set, then
784 /// the assigned name is considered significant and the node is
785 /// isomorphic if the names match.
786 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
787 const MultipleUseVarSet &DepVars) const {
788 if (N == this) return true;
789 if (N->isLeaf() != isLeaf() || getExtType() != N->getExtType() ||
790 getPredicateFns() != N->getPredicateFns() ||
791 getTransformFn() != N->getTransformFn())
795 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
796 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
797 return ((DI->getDef() == NDI->getDef())
798 && (DepVars.find(getName()) == DepVars.end()
799 || getName() == N->getName()));
802 return getLeafValue() == N->getLeafValue();
805 if (N->getOperator() != getOperator() ||
806 N->getNumChildren() != getNumChildren()) return false;
807 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
808 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
813 /// clone - Make a copy of this tree and all of its children.
815 TreePatternNode *TreePatternNode::clone() const {
816 TreePatternNode *New;
818 New = new TreePatternNode(getLeafValue());
820 std::vector<TreePatternNode*> CChildren;
821 CChildren.reserve(Children.size());
822 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
823 CChildren.push_back(getChild(i)->clone());
824 New = new TreePatternNode(getOperator(), CChildren);
826 New->setName(getName());
827 New->setType(getExtType());
828 New->setPredicateFns(getPredicateFns());
829 New->setTransformFn(getTransformFn());
833 /// RemoveAllTypes - Recursively strip all the types of this tree.
834 void TreePatternNode::RemoveAllTypes() {
835 setType(EEVT::TypeSet()); // Reset to unknown type.
836 if (isLeaf()) return;
837 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
838 getChild(i)->RemoveAllTypes();
842 /// SubstituteFormalArguments - Replace the formal arguments in this tree
843 /// with actual values specified by ArgMap.
844 void TreePatternNode::
845 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
846 if (isLeaf()) return;
848 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
849 TreePatternNode *Child = getChild(i);
850 if (Child->isLeaf()) {
851 Init *Val = Child->getLeafValue();
852 if (dynamic_cast<DefInit*>(Val) &&
853 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
854 // We found a use of a formal argument, replace it with its value.
855 TreePatternNode *NewChild = ArgMap[Child->getName()];
856 assert(NewChild && "Couldn't find formal argument!");
857 assert((Child->getPredicateFns().empty() ||
858 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
859 "Non-empty child predicate clobbered!");
860 setChild(i, NewChild);
863 getChild(i)->SubstituteFormalArguments(ArgMap);
869 /// InlinePatternFragments - If this pattern refers to any pattern
870 /// fragments, inline them into place, giving us a pattern without any
871 /// PatFrag references.
872 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
873 if (isLeaf()) return this; // nothing to do.
874 Record *Op = getOperator();
876 if (!Op->isSubClassOf("PatFrag")) {
877 // Just recursively inline children nodes.
878 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
879 TreePatternNode *Child = getChild(i);
880 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
882 assert((Child->getPredicateFns().empty() ||
883 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
884 "Non-empty child predicate clobbered!");
886 setChild(i, NewChild);
891 // Otherwise, we found a reference to a fragment. First, look up its
892 // TreePattern record.
893 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
895 // Verify that we are passing the right number of operands.
896 if (Frag->getNumArgs() != Children.size())
897 TP.error("'" + Op->getName() + "' fragment requires " +
898 utostr(Frag->getNumArgs()) + " operands!");
900 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
902 std::string Code = Op->getValueAsCode("Predicate");
904 FragTree->addPredicateFn("Predicate_"+Op->getName());
906 // Resolve formal arguments to their actual value.
907 if (Frag->getNumArgs()) {
908 // Compute the map of formal to actual arguments.
909 std::map<std::string, TreePatternNode*> ArgMap;
910 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
911 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
913 FragTree->SubstituteFormalArguments(ArgMap);
916 FragTree->setName(getName());
917 FragTree->UpdateNodeType(getExtType(), TP);
919 // Transfer in the old predicates.
920 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
921 FragTree->addPredicateFn(getPredicateFns()[i]);
923 // Get a new copy of this fragment to stitch into here.
924 //delete this; // FIXME: implement refcounting!
926 // The fragment we inlined could have recursive inlining that is needed. See
927 // if there are any pattern fragments in it and inline them as needed.
928 return FragTree->InlinePatternFragments(TP);
931 /// getImplicitType - Check to see if the specified record has an implicit
932 /// type which should be applied to it. This will infer the type of register
933 /// references from the register file information, for example.
935 static EEVT::TypeSet getImplicitType(Record *R, bool NotRegisters,
937 // Check to see if this is a register or a register class.
938 if (R->isSubClassOf("RegisterClass")) {
940 return EEVT::TypeSet(); // Unknown.
941 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
942 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
943 } else if (R->isSubClassOf("PatFrag")) {
944 // Pattern fragment types will be resolved when they are inlined.
945 return EEVT::TypeSet(); // Unknown.
946 } else if (R->isSubClassOf("Register")) {
948 return EEVT::TypeSet(); // Unknown.
949 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
950 return EEVT::TypeSet(T.getRegisterVTs(R));
951 } else if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
952 // Using a VTSDNode or CondCodeSDNode.
953 return EEVT::TypeSet(MVT::Other, TP);
954 } else if (R->isSubClassOf("ComplexPattern")) {
956 return EEVT::TypeSet(); // Unknown.
957 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
959 } else if (R->isSubClassOf("PointerLikeRegClass")) {
960 return EEVT::TypeSet(MVT::iPTR, TP);
961 } else if (R->getName() == "node" || R->getName() == "srcvalue" ||
962 R->getName() == "zero_reg") {
964 return EEVT::TypeSet(); // Unknown.
967 TP.error("Unknown node flavor used in pattern: " + R->getName());
968 return EEVT::TypeSet(MVT::Other, TP);
972 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
973 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
974 const CodeGenIntrinsic *TreePatternNode::
975 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
976 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
977 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
978 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
982 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
983 return &CDP.getIntrinsicInfo(IID);
986 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
987 /// return the ComplexPattern information, otherwise return null.
988 const ComplexPattern *
989 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
990 if (!isLeaf()) return 0;
992 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
993 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
994 return &CGP.getComplexPattern(DI->getDef());
998 /// NodeHasProperty - Return true if this node has the specified property.
999 bool TreePatternNode::NodeHasProperty(SDNP Property,
1000 const CodeGenDAGPatterns &CGP) const {
1002 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1003 return CP->hasProperty(Property);
1007 Record *Operator = getOperator();
1008 if (!Operator->isSubClassOf("SDNode")) return false;
1010 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1016 /// TreeHasProperty - Return true if any node in this tree has the specified
1018 bool TreePatternNode::TreeHasProperty(SDNP Property,
1019 const CodeGenDAGPatterns &CGP) const {
1020 if (NodeHasProperty(Property, CGP))
1022 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1023 if (getChild(i)->TreeHasProperty(Property, CGP))
1028 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1029 /// commutative intrinsic.
1031 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1032 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1033 return Int->isCommutative;
1038 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1039 /// this node and its children in the tree. This returns true if it makes a
1040 /// change, false otherwise. If a type contradiction is found, throw an
1042 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1043 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1045 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1046 // If it's a regclass or something else known, include the type.
1047 return UpdateNodeType(getImplicitType(DI->getDef(), NotRegisters, TP),TP);
1050 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
1051 // Int inits are always integers. :)
1052 bool MadeChange = Type.EnforceInteger(TP);
1057 MVT::SimpleValueType VT = getType();
1058 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1061 unsigned Size = EVT(VT).getSizeInBits();
1062 // Make sure that the value is representable for this type.
1063 if (Size >= 32) return MadeChange;
1065 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1066 if (Val == II->getValue()) return MadeChange;
1068 // If sign-extended doesn't fit, does it fit as unsigned?
1070 unsigned UnsignedVal;
1071 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1072 UnsignedVal = unsigned(II->getValue());
1074 if ((ValueMask & UnsignedVal) == UnsignedVal)
1077 TP.error("Integer value '" + itostr(II->getValue())+
1078 "' is out of range for type '" + getEnumName(getType()) + "'!");
1084 // special handling for set, which isn't really an SDNode.
1085 if (getOperator()->getName() == "set") {
1086 assert (getNumChildren() >= 2 && "Missing RHS of a set?");
1087 unsigned NC = getNumChildren();
1088 bool MadeChange = false;
1089 for (unsigned i = 0; i < NC-1; ++i) {
1090 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1091 MadeChange |= getChild(NC-1)->ApplyTypeConstraints(TP, NotRegisters);
1093 // Types of operands must match.
1094 MadeChange |=getChild(i)->UpdateNodeType(getChild(NC-1)->getExtType(),TP);
1095 MadeChange |=getChild(NC-1)->UpdateNodeType(getChild(i)->getExtType(),TP);
1096 MadeChange |=UpdateNodeType(MVT::isVoid, TP);
1101 if (getOperator()->getName() == "implicit" ||
1102 getOperator()->getName() == "parallel") {
1103 bool MadeChange = false;
1104 for (unsigned i = 0; i < getNumChildren(); ++i)
1105 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1106 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
1110 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
1111 bool MadeChange = false;
1112 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1113 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1115 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1116 // what type it gets, so if it didn't get a concrete type just give it the
1117 // first viable type from the reg class.
1118 if (!getChild(1)->hasTypeSet() &&
1119 !getChild(1)->getExtType().isCompletelyUnknown()) {
1120 MVT::SimpleValueType RCVT = getChild(1)->getExtType().getTypeList()[0];
1121 MadeChange |= getChild(1)->UpdateNodeType(RCVT, TP);
1126 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1127 bool MadeChange = false;
1129 // Apply the result type to the node.
1130 unsigned NumRetVTs = Int->IS.RetVTs.size();
1131 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1133 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1134 MadeChange |= UpdateNodeType(Int->IS.RetVTs[i], TP);
1136 if (getNumChildren() != NumParamVTs + NumRetVTs)
1137 TP.error("Intrinsic '" + Int->Name + "' expects " +
1138 utostr(NumParamVTs + NumRetVTs - 1) + " operands, not " +
1139 utostr(getNumChildren() - 1) + " operands!");
1141 // Apply type info to the intrinsic ID.
1142 MadeChange |= getChild(0)->UpdateNodeType(MVT::iPTR, TP);
1144 for (unsigned i = NumRetVTs, e = getNumChildren(); i != e; ++i) {
1145 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i - NumRetVTs];
1146 MadeChange |= getChild(i)->UpdateNodeType(OpVT, TP);
1147 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1152 if (getOperator()->isSubClassOf("SDNode")) {
1153 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1155 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1156 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1157 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1158 // Branch, etc. do not produce results and top-level forms in instr pattern
1159 // must have void types.
1160 if (NI.getNumResults() == 0)
1161 MadeChange |= UpdateNodeType(MVT::isVoid, TP);
1166 if (getOperator()->isSubClassOf("Instruction")) {
1167 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1168 assert(Inst.getNumResults() <= 1 &&
1169 "Only supports zero or one result instrs!");
1171 CodeGenInstruction &InstInfo =
1172 CDP.getTargetInfo().getInstruction(getOperator());
1174 EEVT::TypeSet ResultType;
1176 // Apply the result type to the node
1177 if (InstInfo.NumDefs != 0) { // # of elements in (outs) list
1178 Record *ResultNode = Inst.getResult(0);
1180 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1181 ResultType = EEVT::TypeSet(MVT::iPTR, TP);
1182 } else if (ResultNode->getName() == "unknown") {
1185 assert(ResultNode->isSubClassOf("RegisterClass") &&
1186 "Operands should be register classes!");
1187 const CodeGenRegisterClass &RC =
1188 CDP.getTargetInfo().getRegisterClass(ResultNode);
1189 ResultType = RC.getValueTypes();
1191 } else if (!InstInfo.ImplicitDefs.empty()) {
1192 // If the instruction has implicit defs, the first one defines the result
1194 Record *FirstImplicitDef = InstInfo.ImplicitDefs[0];
1195 assert(FirstImplicitDef->isSubClassOf("Register"));
1196 const std::vector<MVT::SimpleValueType> &RegVTs =
1197 CDP.getTargetInfo().getRegisterVTs(FirstImplicitDef);
1198 if (RegVTs.size() == 1)
1199 ResultType = EEVT::TypeSet(RegVTs);
1201 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
1203 // Otherwise, the instruction produces no value result.
1204 // FIXME: Model "no result" different than "one result that is void"
1205 ResultType = EEVT::TypeSet(MVT::isVoid, TP);
1208 bool MadeChange = UpdateNodeType(ResultType, TP);
1210 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1212 if (getOperator()->getName() == "INSERT_SUBREG") {
1213 MadeChange |= UpdateNodeType(getChild(0)->getExtType(), TP);
1214 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1217 unsigned ChildNo = 0;
1218 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1219 Record *OperandNode = Inst.getOperand(i);
1221 // If the instruction expects a predicate or optional def operand, we
1222 // codegen this by setting the operand to it's default value if it has a
1223 // non-empty DefaultOps field.
1224 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1225 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1226 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1229 // Verify that we didn't run out of provided operands.
1230 if (ChildNo >= getNumChildren())
1231 TP.error("Instruction '" + getOperator()->getName() +
1232 "' expects more operands than were provided.");
1234 MVT::SimpleValueType VT;
1235 TreePatternNode *Child = getChild(ChildNo++);
1236 if (OperandNode->isSubClassOf("RegisterClass")) {
1237 const CodeGenRegisterClass &RC =
1238 CDP.getTargetInfo().getRegisterClass(OperandNode);
1239 MadeChange |= Child->UpdateNodeType(RC.getValueTypes(), TP);
1240 } else if (OperandNode->isSubClassOf("Operand")) {
1241 VT = getValueType(OperandNode->getValueAsDef("Type"));
1242 MadeChange |= Child->UpdateNodeType(VT, TP);
1243 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1244 MadeChange |= Child->UpdateNodeType(MVT::iPTR, TP);
1245 } else if (OperandNode->getName() == "unknown") {
1248 assert(0 && "Unknown operand type!");
1251 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1254 if (ChildNo != getNumChildren())
1255 TP.error("Instruction '" + getOperator()->getName() +
1256 "' was provided too many operands!");
1261 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1263 // Node transforms always take one operand.
1264 if (getNumChildren() != 1)
1265 TP.error("Node transform '" + getOperator()->getName() +
1266 "' requires one operand!");
1268 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1271 // If either the output or input of the xform does not have exact
1272 // type info. We assume they must be the same. Otherwise, it is perfectly
1273 // legal to transform from one type to a completely different type.
1275 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1276 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1277 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1284 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1285 /// RHS of a commutative operation, not the on LHS.
1286 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1287 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1289 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1295 /// canPatternMatch - If it is impossible for this pattern to match on this
1296 /// target, fill in Reason and return false. Otherwise, return true. This is
1297 /// used as a sanity check for .td files (to prevent people from writing stuff
1298 /// that can never possibly work), and to prevent the pattern permuter from
1299 /// generating stuff that is useless.
1300 bool TreePatternNode::canPatternMatch(std::string &Reason,
1301 const CodeGenDAGPatterns &CDP) {
1302 if (isLeaf()) return true;
1304 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1305 if (!getChild(i)->canPatternMatch(Reason, CDP))
1308 // If this is an intrinsic, handle cases that would make it not match. For
1309 // example, if an operand is required to be an immediate.
1310 if (getOperator()->isSubClassOf("Intrinsic")) {
1315 // If this node is a commutative operator, check that the LHS isn't an
1317 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1318 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1319 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1320 // Scan all of the operands of the node and make sure that only the last one
1321 // is a constant node, unless the RHS also is.
1322 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1323 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1324 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1325 if (OnlyOnRHSOfCommutative(getChild(i))) {
1326 Reason="Immediate value must be on the RHS of commutative operators!";
1335 //===----------------------------------------------------------------------===//
1336 // TreePattern implementation
1339 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1340 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1341 isInputPattern = isInput;
1342 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1343 Trees.push_back(ParseTreePattern((DagInit*)RawPat->getElement(i)));
1346 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1347 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1348 isInputPattern = isInput;
1349 Trees.push_back(ParseTreePattern(Pat));
1352 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1353 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1354 isInputPattern = isInput;
1355 Trees.push_back(Pat);
1358 void TreePattern::error(const std::string &Msg) const {
1360 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1363 void TreePattern::ComputeNamedNodes() {
1364 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1365 ComputeNamedNodes(Trees[i]);
1368 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1369 if (!N->getName().empty())
1370 NamedNodes[N->getName()].push_back(N);
1372 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1373 ComputeNamedNodes(N->getChild(i));
1376 TreePatternNode *TreePattern::ParseTreePattern(DagInit *Dag) {
1377 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1378 if (!OpDef) error("Pattern has unexpected operator type!");
1379 Record *Operator = OpDef->getDef();
1381 if (Operator->isSubClassOf("ValueType")) {
1382 // If the operator is a ValueType, then this must be "type cast" of a leaf
1384 if (Dag->getNumArgs() != 1)
1385 error("Type cast only takes one operand!");
1387 Init *Arg = Dag->getArg(0);
1388 TreePatternNode *New;
1389 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
1390 Record *R = DI->getDef();
1391 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1392 Dag->setArg(0, new DagInit(DI, "",
1393 std::vector<std::pair<Init*, std::string> >()));
1394 return ParseTreePattern(Dag);
1398 if (R->getName() == "node") {
1399 if (Dag->getArgName(0).empty())
1400 error("'node' argument requires a name to match with operand list");
1401 Args.push_back(Dag->getArgName(0));
1404 New = new TreePatternNode(DI);
1405 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1406 New = ParseTreePattern(DI);
1407 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1408 New = new TreePatternNode(II);
1409 if (!Dag->getArgName(0).empty())
1410 error("Constant int argument should not have a name!");
1411 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1412 // Turn this into an IntInit.
1413 Init *II = BI->convertInitializerTo(new IntRecTy());
1414 if (II == 0 || !dynamic_cast<IntInit*>(II))
1415 error("Bits value must be constants!");
1417 New = new TreePatternNode(dynamic_cast<IntInit*>(II));
1418 if (!Dag->getArgName(0).empty())
1419 error("Constant int argument should not have a name!");
1422 error("Unknown leaf value for tree pattern!");
1426 // Apply the type cast.
1427 New->UpdateNodeType(getValueType(Operator), *this);
1428 if (New->getNumChildren() == 0)
1429 New->setName(Dag->getArgName(0));
1433 // Verify that this is something that makes sense for an operator.
1434 if (!Operator->isSubClassOf("PatFrag") &&
1435 !Operator->isSubClassOf("SDNode") &&
1436 !Operator->isSubClassOf("Instruction") &&
1437 !Operator->isSubClassOf("SDNodeXForm") &&
1438 !Operator->isSubClassOf("Intrinsic") &&
1439 Operator->getName() != "set" &&
1440 Operator->getName() != "implicit" &&
1441 Operator->getName() != "parallel")
1442 error("Unrecognized node '" + Operator->getName() + "'!");
1444 // Check to see if this is something that is illegal in an input pattern.
1445 if (isInputPattern && (Operator->isSubClassOf("Instruction") ||
1446 Operator->isSubClassOf("SDNodeXForm")))
1447 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1449 std::vector<TreePatternNode*> Children;
1451 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
1452 Init *Arg = Dag->getArg(i);
1453 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
1454 Children.push_back(ParseTreePattern(DI));
1455 if (Children.back()->getName().empty())
1456 Children.back()->setName(Dag->getArgName(i));
1457 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
1458 Record *R = DefI->getDef();
1459 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1460 // TreePatternNode if its own.
1461 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) {
1462 Dag->setArg(i, new DagInit(DefI, "",
1463 std::vector<std::pair<Init*, std::string> >()));
1464 --i; // Revisit this node...
1466 TreePatternNode *Node = new TreePatternNode(DefI);
1467 Node->setName(Dag->getArgName(i));
1468 Children.push_back(Node);
1471 if (R->getName() == "node") {
1472 if (Dag->getArgName(i).empty())
1473 error("'node' argument requires a name to match with operand list");
1474 Args.push_back(Dag->getArgName(i));
1477 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
1478 TreePatternNode *Node = new TreePatternNode(II);
1479 if (!Dag->getArgName(i).empty())
1480 error("Constant int argument should not have a name!");
1481 Children.push_back(Node);
1482 } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Arg)) {
1483 // Turn this into an IntInit.
1484 Init *II = BI->convertInitializerTo(new IntRecTy());
1485 if (II == 0 || !dynamic_cast<IntInit*>(II))
1486 error("Bits value must be constants!");
1488 TreePatternNode *Node = new TreePatternNode(dynamic_cast<IntInit*>(II));
1489 if (!Dag->getArgName(i).empty())
1490 error("Constant int argument should not have a name!");
1491 Children.push_back(Node);
1496 error("Unknown leaf value for tree pattern!");
1500 // If the operator is an intrinsic, then this is just syntactic sugar for for
1501 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1502 // convert the intrinsic name to a number.
1503 if (Operator->isSubClassOf("Intrinsic")) {
1504 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1505 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1507 // If this intrinsic returns void, it must have side-effects and thus a
1509 if (Int.IS.RetVTs[0] == MVT::isVoid) {
1510 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1511 } else if (Int.ModRef != CodeGenIntrinsic::NoMem) {
1512 // Has side-effects, requires chain.
1513 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1515 // Otherwise, no chain.
1516 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1519 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID));
1520 Children.insert(Children.begin(), IIDNode);
1523 TreePatternNode *Result = new TreePatternNode(Operator, Children);
1524 Result->setName(Dag->getName());
1528 /// InferAllTypes - Infer/propagate as many types throughout the expression
1529 /// patterns as possible. Return true if all types are inferred, false
1530 /// otherwise. Throw an exception if a type contradiction is found.
1532 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1533 if (NamedNodes.empty())
1534 ComputeNamedNodes();
1536 bool MadeChange = true;
1537 while (MadeChange) {
1539 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1540 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1542 // If there are constraints on our named nodes, apply them.
1543 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1544 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1545 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1547 // If we have input named node types, propagate their types to the named
1550 // FIXME: Should be error?
1551 assert(InNamedTypes->count(I->getKey()) &&
1552 "Named node in output pattern but not input pattern?");
1554 const SmallVectorImpl<TreePatternNode*> &InNodes =
1555 InNamedTypes->find(I->getKey())->second;
1557 // The input types should be fully resolved by now.
1558 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1559 // If this node is a register class, and it is the root of the pattern
1560 // then we're mapping something onto an input register. We allow
1561 // changing the type of the input register in this case. This allows
1562 // us to match things like:
1563 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1564 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1565 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1566 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1570 MadeChange |=Nodes[i]->UpdateNodeType(InNodes[0]->getExtType(),*this);
1574 // If there are multiple nodes with the same name, they must all have the
1576 if (I->second.size() > 1) {
1577 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1578 MadeChange |=Nodes[i]->UpdateNodeType(Nodes[i+1]->getExtType(),*this);
1579 MadeChange |=Nodes[i+1]->UpdateNodeType(Nodes[i]->getExtType(),*this);
1585 bool HasUnresolvedTypes = false;
1586 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1587 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1588 return !HasUnresolvedTypes;
1591 void TreePattern::print(raw_ostream &OS) const {
1592 OS << getRecord()->getName();
1593 if (!Args.empty()) {
1594 OS << "(" << Args[0];
1595 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1596 OS << ", " << Args[i];
1601 if (Trees.size() > 1)
1603 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1605 Trees[i]->print(OS);
1609 if (Trees.size() > 1)
1613 void TreePattern::dump() const { print(errs()); }
1615 //===----------------------------------------------------------------------===//
1616 // CodeGenDAGPatterns implementation
1619 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : Records(R) {
1620 Intrinsics = LoadIntrinsics(Records, false);
1621 TgtIntrinsics = LoadIntrinsics(Records, true);
1623 ParseNodeTransforms();
1624 ParseComplexPatterns();
1625 ParsePatternFragments();
1626 ParseDefaultOperands();
1627 ParseInstructions();
1630 // Generate variants. For example, commutative patterns can match
1631 // multiple ways. Add them to PatternsToMatch as well.
1634 // Infer instruction flags. For example, we can detect loads,
1635 // stores, and side effects in many cases by examining an
1636 // instruction's pattern.
1637 InferInstructionFlags();
1640 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
1641 for (pf_iterator I = PatternFragments.begin(),
1642 E = PatternFragments.end(); I != E; ++I)
1647 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
1648 Record *N = Records.getDef(Name);
1649 if (!N || !N->isSubClassOf("SDNode")) {
1650 errs() << "Error getting SDNode '" << Name << "'!\n";
1656 // Parse all of the SDNode definitions for the target, populating SDNodes.
1657 void CodeGenDAGPatterns::ParseNodeInfo() {
1658 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
1659 while (!Nodes.empty()) {
1660 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
1664 // Get the builtin intrinsic nodes.
1665 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
1666 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
1667 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
1670 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
1671 /// map, and emit them to the file as functions.
1672 void CodeGenDAGPatterns::ParseNodeTransforms() {
1673 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
1674 while (!Xforms.empty()) {
1675 Record *XFormNode = Xforms.back();
1676 Record *SDNode = XFormNode->getValueAsDef("Opcode");
1677 std::string Code = XFormNode->getValueAsCode("XFormFunction");
1678 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
1684 void CodeGenDAGPatterns::ParseComplexPatterns() {
1685 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
1686 while (!AMs.empty()) {
1687 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
1693 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
1694 /// file, building up the PatternFragments map. After we've collected them all,
1695 /// inline fragments together as necessary, so that there are no references left
1696 /// inside a pattern fragment to a pattern fragment.
1698 void CodeGenDAGPatterns::ParsePatternFragments() {
1699 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
1701 // First step, parse all of the fragments.
1702 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1703 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
1704 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
1705 PatternFragments[Fragments[i]] = P;
1707 // Validate the argument list, converting it to set, to discard duplicates.
1708 std::vector<std::string> &Args = P->getArgList();
1709 std::set<std::string> OperandsSet(Args.begin(), Args.end());
1711 if (OperandsSet.count(""))
1712 P->error("Cannot have unnamed 'node' values in pattern fragment!");
1714 // Parse the operands list.
1715 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
1716 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
1717 // Special cases: ops == outs == ins. Different names are used to
1718 // improve readability.
1720 (OpsOp->getDef()->getName() != "ops" &&
1721 OpsOp->getDef()->getName() != "outs" &&
1722 OpsOp->getDef()->getName() != "ins"))
1723 P->error("Operands list should start with '(ops ... '!");
1725 // Copy over the arguments.
1727 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
1728 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
1729 static_cast<DefInit*>(OpsList->getArg(j))->
1730 getDef()->getName() != "node")
1731 P->error("Operands list should all be 'node' values.");
1732 if (OpsList->getArgName(j).empty())
1733 P->error("Operands list should have names for each operand!");
1734 if (!OperandsSet.count(OpsList->getArgName(j)))
1735 P->error("'" + OpsList->getArgName(j) +
1736 "' does not occur in pattern or was multiply specified!");
1737 OperandsSet.erase(OpsList->getArgName(j));
1738 Args.push_back(OpsList->getArgName(j));
1741 if (!OperandsSet.empty())
1742 P->error("Operands list does not contain an entry for operand '" +
1743 *OperandsSet.begin() + "'!");
1745 // If there is a code init for this fragment, keep track of the fact that
1746 // this fragment uses it.
1747 std::string Code = Fragments[i]->getValueAsCode("Predicate");
1749 P->getOnlyTree()->addPredicateFn("Predicate_"+Fragments[i]->getName());
1751 // If there is a node transformation corresponding to this, keep track of
1753 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
1754 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
1755 P->getOnlyTree()->setTransformFn(Transform);
1758 // Now that we've parsed all of the tree fragments, do a closure on them so
1759 // that there are not references to PatFrags left inside of them.
1760 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
1761 TreePattern *ThePat = PatternFragments[Fragments[i]];
1762 ThePat->InlinePatternFragments();
1764 // Infer as many types as possible. Don't worry about it if we don't infer
1765 // all of them, some may depend on the inputs of the pattern.
1767 ThePat->InferAllTypes();
1769 // If this pattern fragment is not supported by this target (no types can
1770 // satisfy its constraints), just ignore it. If the bogus pattern is
1771 // actually used by instructions, the type consistency error will be
1775 // If debugging, print out the pattern fragment result.
1776 DEBUG(ThePat->dump());
1780 void CodeGenDAGPatterns::ParseDefaultOperands() {
1781 std::vector<Record*> DefaultOps[2];
1782 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
1783 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
1785 // Find some SDNode.
1786 assert(!SDNodes.empty() && "No SDNodes parsed?");
1787 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
1789 for (unsigned iter = 0; iter != 2; ++iter) {
1790 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
1791 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
1793 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
1794 // SomeSDnode so that we can parse this.
1795 std::vector<std::pair<Init*, std::string> > Ops;
1796 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
1797 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
1798 DefaultInfo->getArgName(op)));
1799 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
1801 // Create a TreePattern to parse this.
1802 TreePattern P(DefaultOps[iter][i], DI, false, *this);
1803 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
1805 // Copy the operands over into a DAGDefaultOperand.
1806 DAGDefaultOperand DefaultOpInfo;
1808 TreePatternNode *T = P.getTree(0);
1809 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
1810 TreePatternNode *TPN = T->getChild(op);
1811 while (TPN->ApplyTypeConstraints(P, false))
1812 /* Resolve all types */;
1814 if (TPN->ContainsUnresolvedType()) {
1816 throw "Value #" + utostr(i) + " of PredicateOperand '" +
1817 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1819 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
1820 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
1822 DefaultOpInfo.DefaultOps.push_back(TPN);
1825 // Insert it into the DefaultOperands map so we can find it later.
1826 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
1831 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
1832 /// instruction input. Return true if this is a real use.
1833 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
1834 std::map<std::string, TreePatternNode*> &InstInputs,
1835 std::vector<Record*> &InstImpInputs) {
1836 // No name -> not interesting.
1837 if (Pat->getName().empty()) {
1838 if (Pat->isLeaf()) {
1839 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1840 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1841 I->error("Input " + DI->getDef()->getName() + " must be named!");
1842 else if (DI && DI->getDef()->isSubClassOf("Register"))
1843 InstImpInputs.push_back(DI->getDef());
1849 if (Pat->isLeaf()) {
1850 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
1851 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
1854 Rec = Pat->getOperator();
1857 // SRCVALUE nodes are ignored.
1858 if (Rec->getName() == "srcvalue")
1861 TreePatternNode *&Slot = InstInputs[Pat->getName()];
1867 if (Slot->isLeaf()) {
1868 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
1870 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
1871 SlotRec = Slot->getOperator();
1874 // Ensure that the inputs agree if we've already seen this input.
1876 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1877 if (Slot->getExtType() != Pat->getExtType())
1878 I->error("All $" + Pat->getName() + " inputs must agree with each other");
1882 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
1883 /// part of "I", the instruction), computing the set of inputs and outputs of
1884 /// the pattern. Report errors if we see anything naughty.
1885 void CodeGenDAGPatterns::
1886 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
1887 std::map<std::string, TreePatternNode*> &InstInputs,
1888 std::map<std::string, TreePatternNode*>&InstResults,
1889 std::vector<Record*> &InstImpInputs,
1890 std::vector<Record*> &InstImpResults) {
1891 if (Pat->isLeaf()) {
1892 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1893 if (!isUse && Pat->getTransformFn())
1894 I->error("Cannot specify a transform function for a non-input value!");
1898 if (Pat->getOperator()->getName() == "implicit") {
1899 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1900 TreePatternNode *Dest = Pat->getChild(i);
1901 if (!Dest->isLeaf())
1902 I->error("implicitly defined value should be a register!");
1904 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1905 if (!Val || !Val->getDef()->isSubClassOf("Register"))
1906 I->error("implicitly defined value should be a register!");
1907 InstImpResults.push_back(Val->getDef());
1912 if (Pat->getOperator()->getName() != "set") {
1913 // If this is not a set, verify that the children nodes are not void typed,
1915 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
1916 if (Pat->getChild(i)->getType() == MVT::isVoid)
1917 I->error("Cannot have void nodes inside of patterns!");
1918 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
1919 InstImpInputs, InstImpResults);
1922 // If this is a non-leaf node with no children, treat it basically as if
1923 // it were a leaf. This handles nodes like (imm).
1924 bool isUse = HandleUse(I, Pat, InstInputs, InstImpInputs);
1926 if (!isUse && Pat->getTransformFn())
1927 I->error("Cannot specify a transform function for a non-input value!");
1931 // Otherwise, this is a set, validate and collect instruction results.
1932 if (Pat->getNumChildren() == 0)
1933 I->error("set requires operands!");
1935 if (Pat->getTransformFn())
1936 I->error("Cannot specify a transform function on a set node!");
1938 // Check the set destinations.
1939 unsigned NumDests = Pat->getNumChildren()-1;
1940 for (unsigned i = 0; i != NumDests; ++i) {
1941 TreePatternNode *Dest = Pat->getChild(i);
1942 if (!Dest->isLeaf())
1943 I->error("set destination should be a register!");
1945 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
1947 I->error("set destination should be a register!");
1949 if (Val->getDef()->isSubClassOf("RegisterClass") ||
1950 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
1951 if (Dest->getName().empty())
1952 I->error("set destination must have a name!");
1953 if (InstResults.count(Dest->getName()))
1954 I->error("cannot set '" + Dest->getName() +"' multiple times");
1955 InstResults[Dest->getName()] = Dest;
1956 } else if (Val->getDef()->isSubClassOf("Register")) {
1957 InstImpResults.push_back(Val->getDef());
1959 I->error("set destination should be a register!");
1963 // Verify and collect info from the computation.
1964 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
1965 InstInputs, InstResults,
1966 InstImpInputs, InstImpResults);
1969 //===----------------------------------------------------------------------===//
1970 // Instruction Analysis
1971 //===----------------------------------------------------------------------===//
1973 class InstAnalyzer {
1974 const CodeGenDAGPatterns &CDP;
1977 bool &HasSideEffects;
1980 InstAnalyzer(const CodeGenDAGPatterns &cdp,
1981 bool &maystore, bool &mayload, bool &hse, bool &isv)
1982 : CDP(cdp), mayStore(maystore), mayLoad(mayload), HasSideEffects(hse),
1986 /// Analyze - Analyze the specified instruction, returning true if the
1987 /// instruction had a pattern.
1988 bool Analyze(Record *InstRecord) {
1989 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
1992 return false; // No pattern.
1995 // FIXME: Assume only the first tree is the pattern. The others are clobber
1997 AnalyzeNode(Pattern->getTree(0));
2002 void AnalyzeNode(const TreePatternNode *N) {
2004 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2005 Record *LeafRec = DI->getDef();
2006 // Handle ComplexPattern leaves.
2007 if (LeafRec->isSubClassOf("ComplexPattern")) {
2008 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2009 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2010 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2011 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2017 // Analyze children.
2018 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2019 AnalyzeNode(N->getChild(i));
2021 // Ignore set nodes, which are not SDNodes.
2022 if (N->getOperator()->getName() == "set")
2025 // Get information about the SDNode for the operator.
2026 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2028 // Notice properties of the node.
2029 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2030 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2031 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2032 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
2034 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2035 // If this is an intrinsic, analyze it.
2036 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2037 mayLoad = true;// These may load memory.
2039 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteArgMem)
2040 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2042 if (IntInfo->ModRef >= CodeGenIntrinsic::WriteMem)
2043 // WriteMem intrinsics can have other strange effects.
2044 HasSideEffects = true;
2050 static void InferFromPattern(const CodeGenInstruction &Inst,
2051 bool &MayStore, bool &MayLoad,
2052 bool &HasSideEffects, bool &IsVariadic,
2053 const CodeGenDAGPatterns &CDP) {
2054 MayStore = MayLoad = HasSideEffects = IsVariadic = false;
2057 InstAnalyzer(CDP, MayStore, MayLoad, HasSideEffects, IsVariadic)
2058 .Analyze(Inst.TheDef);
2060 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2061 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2062 // If we decided that this is a store from the pattern, then the .td file
2063 // entry is redundant.
2066 "Warning: mayStore flag explicitly set on instruction '%s'"
2067 " but flag already inferred from pattern.\n",
2068 Inst.TheDef->getName().c_str());
2072 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2073 // If we decided that this is a load from the pattern, then the .td file
2074 // entry is redundant.
2077 "Warning: mayLoad flag explicitly set on instruction '%s'"
2078 " but flag already inferred from pattern.\n",
2079 Inst.TheDef->getName().c_str());
2083 if (Inst.neverHasSideEffects) {
2085 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2086 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2087 HasSideEffects = false;
2090 if (Inst.hasSideEffects) {
2092 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2093 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2094 HasSideEffects = true;
2097 if (Inst.isVariadic)
2098 IsVariadic = true; // Can warn if we want.
2101 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2102 /// any fragments involved. This populates the Instructions list with fully
2103 /// resolved instructions.
2104 void CodeGenDAGPatterns::ParseInstructions() {
2105 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2107 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2110 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2111 LI = Instrs[i]->getValueAsListInit("Pattern");
2113 // If there is no pattern, only collect minimal information about the
2114 // instruction for its operand list. We have to assume that there is one
2115 // result, as we have no detailed info.
2116 if (!LI || LI->getSize() == 0) {
2117 std::vector<Record*> Results;
2118 std::vector<Record*> Operands;
2120 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2122 if (InstInfo.OperandList.size() != 0) {
2123 if (InstInfo.NumDefs == 0) {
2124 // These produce no results
2125 for (unsigned j = 0, e = InstInfo.OperandList.size(); j < e; ++j)
2126 Operands.push_back(InstInfo.OperandList[j].Rec);
2128 // Assume the first operand is the result.
2129 Results.push_back(InstInfo.OperandList[0].Rec);
2131 // The rest are inputs.
2132 for (unsigned j = 1, e = InstInfo.OperandList.size(); j < e; ++j)
2133 Operands.push_back(InstInfo.OperandList[j].Rec);
2137 // Create and insert the instruction.
2138 std::vector<Record*> ImpResults;
2139 std::vector<Record*> ImpOperands;
2140 Instructions.insert(std::make_pair(Instrs[i],
2141 DAGInstruction(0, Results, Operands, ImpResults,
2143 continue; // no pattern.
2146 // Parse the instruction.
2147 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2148 // Inline pattern fragments into it.
2149 I->InlinePatternFragments();
2151 // Infer as many types as possible. If we cannot infer all of them, we can
2152 // never do anything with this instruction pattern: report it to the user.
2153 if (!I->InferAllTypes())
2154 I->error("Could not infer all types in pattern!");
2156 // InstInputs - Keep track of all of the inputs of the instruction, along
2157 // with the record they are declared as.
2158 std::map<std::string, TreePatternNode*> InstInputs;
2160 // InstResults - Keep track of all the virtual registers that are 'set'
2161 // in the instruction, including what reg class they are.
2162 std::map<std::string, TreePatternNode*> InstResults;
2164 std::vector<Record*> InstImpInputs;
2165 std::vector<Record*> InstImpResults;
2167 // Verify that the top-level forms in the instruction are of void type, and
2168 // fill in the InstResults map.
2169 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2170 TreePatternNode *Pat = I->getTree(j);
2171 if (!Pat->hasTypeSet() || Pat->getType() != MVT::isVoid)
2172 I->error("Top-level forms in instruction pattern should have"
2175 // Find inputs and outputs, and verify the structure of the uses/defs.
2176 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2177 InstImpInputs, InstImpResults);
2180 // Now that we have inputs and outputs of the pattern, inspect the operands
2181 // list for the instruction. This determines the order that operands are
2182 // added to the machine instruction the node corresponds to.
2183 unsigned NumResults = InstResults.size();
2185 // Parse the operands list from the (ops) list, validating it.
2186 assert(I->getArgList().empty() && "Args list should still be empty here!");
2187 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2189 // Check that all of the results occur first in the list.
2190 std::vector<Record*> Results;
2191 TreePatternNode *Res0Node = NULL;
2192 for (unsigned i = 0; i != NumResults; ++i) {
2193 if (i == CGI.OperandList.size())
2194 I->error("'" + InstResults.begin()->first +
2195 "' set but does not appear in operand list!");
2196 const std::string &OpName = CGI.OperandList[i].Name;
2198 // Check that it exists in InstResults.
2199 TreePatternNode *RNode = InstResults[OpName];
2201 I->error("Operand $" + OpName + " does not exist in operand list!");
2205 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2207 I->error("Operand $" + OpName + " should be a set destination: all "
2208 "outputs must occur before inputs in operand list!");
2210 if (CGI.OperandList[i].Rec != R)
2211 I->error("Operand $" + OpName + " class mismatch!");
2213 // Remember the return type.
2214 Results.push_back(CGI.OperandList[i].Rec);
2216 // Okay, this one checks out.
2217 InstResults.erase(OpName);
2220 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2221 // the copy while we're checking the inputs.
2222 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2224 std::vector<TreePatternNode*> ResultNodeOperands;
2225 std::vector<Record*> Operands;
2226 for (unsigned i = NumResults, e = CGI.OperandList.size(); i != e; ++i) {
2227 CodeGenInstruction::OperandInfo &Op = CGI.OperandList[i];
2228 const std::string &OpName = Op.Name;
2230 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2232 if (!InstInputsCheck.count(OpName)) {
2233 // If this is an predicate operand or optional def operand with an
2234 // DefaultOps set filled in, we can ignore this. When we codegen it,
2235 // we will do so as always executed.
2236 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2237 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2238 // Does it have a non-empty DefaultOps field? If so, ignore this
2240 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2243 I->error("Operand $" + OpName +
2244 " does not appear in the instruction pattern");
2246 TreePatternNode *InVal = InstInputsCheck[OpName];
2247 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2249 if (InVal->isLeaf() &&
2250 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2251 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2252 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2253 I->error("Operand $" + OpName + "'s register class disagrees"
2254 " between the operand and pattern");
2256 Operands.push_back(Op.Rec);
2258 // Construct the result for the dest-pattern operand list.
2259 TreePatternNode *OpNode = InVal->clone();
2261 // No predicate is useful on the result.
2262 OpNode->clearPredicateFns();
2264 // Promote the xform function to be an explicit node if set.
2265 if (Record *Xform = OpNode->getTransformFn()) {
2266 OpNode->setTransformFn(0);
2267 std::vector<TreePatternNode*> Children;
2268 Children.push_back(OpNode);
2269 OpNode = new TreePatternNode(Xform, Children);
2272 ResultNodeOperands.push_back(OpNode);
2275 if (!InstInputsCheck.empty())
2276 I->error("Input operand $" + InstInputsCheck.begin()->first +
2277 " occurs in pattern but not in operands list!");
2279 TreePatternNode *ResultPattern =
2280 new TreePatternNode(I->getRecord(), ResultNodeOperands);
2281 // Copy fully inferred output node type to instruction result pattern.
2283 ResultPattern->setType(Res0Node->getExtType());
2285 // Create and insert the instruction.
2286 // FIXME: InstImpResults and InstImpInputs should not be part of
2288 DAGInstruction TheInst(I, Results, Operands, InstImpResults, InstImpInputs);
2289 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2291 // Use a temporary tree pattern to infer all types and make sure that the
2292 // constructed result is correct. This depends on the instruction already
2293 // being inserted into the Instructions map.
2294 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2295 Temp.InferAllTypes(&I->getNamedNodesMap());
2297 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2298 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2303 // If we can, convert the instructions to be patterns that are matched!
2304 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2305 Instructions.begin(),
2306 E = Instructions.end(); II != E; ++II) {
2307 DAGInstruction &TheInst = II->second;
2308 const TreePattern *I = TheInst.getPattern();
2309 if (I == 0) continue; // No pattern.
2311 // FIXME: Assume only the first tree is the pattern. The others are clobber
2313 TreePatternNode *Pattern = I->getTree(0);
2314 TreePatternNode *SrcPattern;
2315 if (Pattern->getOperator()->getName() == "set") {
2316 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2318 // Not a set (store or something?)
2319 SrcPattern = Pattern;
2322 Record *Instr = II->first;
2323 AddPatternToMatch(I,
2324 PatternToMatch(Instr->getValueAsListInit("Predicates"),
2326 TheInst.getResultPattern(),
2327 TheInst.getImpResults(),
2328 Instr->getValueAsInt("AddedComplexity"),
2334 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2336 static void FindNames(const TreePatternNode *P,
2337 std::map<std::string, NameRecord> &Names,
2338 const TreePattern *PatternTop) {
2339 if (!P->getName().empty()) {
2340 NameRecord &Rec = Names[P->getName()];
2341 // If this is the first instance of the name, remember the node.
2342 if (Rec.second++ == 0)
2344 else if (Rec.first->getType() != P->getType())
2345 PatternTop->error("repetition of value: $" + P->getName() +
2346 " where different uses have different types!");
2350 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2351 FindNames(P->getChild(i), Names, PatternTop);
2355 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2356 const PatternToMatch &PTM) {
2357 // Do some sanity checking on the pattern we're about to match.
2359 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2360 Pattern->error("Pattern can never match: " + Reason);
2362 // If the source pattern's root is a complex pattern, that complex pattern
2363 // must specify the nodes it can potentially match.
2364 if (const ComplexPattern *CP =
2365 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2366 if (CP->getRootNodes().empty())
2367 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2371 // Find all of the named values in the input and output, ensure they have the
2373 std::map<std::string, NameRecord> SrcNames, DstNames;
2374 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2375 FindNames(PTM.getDstPattern(), DstNames, Pattern);
2377 // Scan all of the named values in the destination pattern, rejecting them if
2378 // they don't exist in the input pattern.
2379 for (std::map<std::string, NameRecord>::iterator
2380 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2381 if (SrcNames[I->first].first == 0)
2382 Pattern->error("Pattern has input without matching name in output: $" +
2386 // Scan all of the named values in the source pattern, rejecting them if the
2387 // name isn't used in the dest, and isn't used to tie two values together.
2388 for (std::map<std::string, NameRecord>::iterator
2389 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2390 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2391 Pattern->error("Pattern has dead named input: $" + I->first);
2393 PatternsToMatch.push_back(PTM);
2398 void CodeGenDAGPatterns::InferInstructionFlags() {
2399 const std::vector<const CodeGenInstruction*> &Instructions =
2400 Target.getInstructionsByEnumValue();
2401 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2402 CodeGenInstruction &InstInfo =
2403 const_cast<CodeGenInstruction &>(*Instructions[i]);
2404 // Determine properties of the instruction from its pattern.
2405 bool MayStore, MayLoad, HasSideEffects, IsVariadic;
2406 InferFromPattern(InstInfo, MayStore, MayLoad, HasSideEffects, IsVariadic,
2408 InstInfo.mayStore = MayStore;
2409 InstInfo.mayLoad = MayLoad;
2410 InstInfo.hasSideEffects = HasSideEffects;
2411 InstInfo.isVariadic = IsVariadic;
2415 /// Given a pattern result with an unresolved type, see if we can find one
2416 /// instruction with an unresolved result type. Force this result type to an
2417 /// arbitrary element if it's possible types to converge results.
2418 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2422 // Analyze children.
2423 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2424 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2427 if (!N->getOperator()->isSubClassOf("Instruction"))
2430 // If this type is already concrete or completely unknown we can't do
2432 if (N->getExtType().isCompletelyUnknown() || N->getExtType().isConcrete())
2435 // Otherwise, force its type to the first possibility (an arbitrary choice).
2436 return N->getExtType().MergeInTypeInfo(N->getExtType().getTypeList()[0], TP);
2439 void CodeGenDAGPatterns::ParsePatterns() {
2440 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2442 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2443 DagInit *Tree = Patterns[i]->getValueAsDag("PatternToMatch");
2444 DefInit *OpDef = dynamic_cast<DefInit*>(Tree->getOperator());
2445 Record *Operator = OpDef->getDef();
2446 TreePattern *Pattern;
2447 if (Operator->getName() != "parallel")
2448 Pattern = new TreePattern(Patterns[i], Tree, true, *this);
2450 std::vector<Init*> Values;
2452 for (unsigned j = 0, ee = Tree->getNumArgs(); j != ee; ++j) {
2453 Values.push_back(Tree->getArg(j));
2454 TypedInit *TArg = dynamic_cast<TypedInit*>(Tree->getArg(j));
2456 errs() << "In dag: " << Tree->getAsString();
2457 errs() << " -- Untyped argument in pattern\n";
2458 assert(0 && "Untyped argument in pattern");
2461 ListTy = resolveTypes(ListTy, TArg->getType());
2463 errs() << "In dag: " << Tree->getAsString();
2464 errs() << " -- Incompatible types in pattern arguments\n";
2465 assert(0 && "Incompatible types in pattern arguments");
2469 ListTy = TArg->getType();
2472 ListInit *LI = new ListInit(Values, new ListRecTy(ListTy));
2473 Pattern = new TreePattern(Patterns[i], LI, true, *this);
2476 // Inline pattern fragments into it.
2477 Pattern->InlinePatternFragments();
2479 ListInit *LI = Patterns[i]->getValueAsListInit("ResultInstrs");
2480 if (LI->getSize() == 0) continue; // no pattern.
2482 // Parse the instruction.
2483 TreePattern *Result = new TreePattern(Patterns[i], LI, false, *this);
2485 // Inline pattern fragments into it.
2486 Result->InlinePatternFragments();
2488 if (Result->getNumTrees() != 1)
2489 Result->error("Cannot handle instructions producing instructions "
2490 "with temporaries yet!");
2492 bool IterateInference;
2493 bool InferredAllPatternTypes, InferredAllResultTypes;
2495 // Infer as many types as possible. If we cannot infer all of them, we
2496 // can never do anything with this pattern: report it to the user.
2497 InferredAllPatternTypes =
2498 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
2500 // Infer as many types as possible. If we cannot infer all of them, we
2501 // can never do anything with this pattern: report it to the user.
2502 InferredAllResultTypes =
2503 Result->InferAllTypes(&Pattern->getNamedNodesMap());
2505 IterateInference = false;
2507 // Apply the type of the result to the source pattern. This helps us
2508 // resolve cases where the input type is known to be a pointer type (which
2509 // is considered resolved), but the result knows it needs to be 32- or
2510 // 64-bits. Infer the other way for good measure.
2511 if (!Result->getTree(0)->getExtType().isVoid() &&
2512 !Pattern->getTree(0)->getExtType().isVoid()) {
2513 IterateInference = Pattern->getTree(0)->
2514 UpdateNodeType(Result->getTree(0)->getExtType(), *Result);
2515 IterateInference |= Result->getTree(0)->
2516 UpdateNodeType(Pattern->getTree(0)->getExtType(), *Result);
2519 // If our iteration has converged and the input pattern's types are fully
2520 // resolved but the result pattern is not fully resolved, we may have a
2521 // situation where we have two instructions in the result pattern and
2522 // the instructions require a common register class, but don't care about
2523 // what actual MVT is used. This is actually a bug in our modelling:
2524 // output patterns should have register classes, not MVTs.
2526 // In any case, to handle this, we just go through and disambiguate some
2527 // arbitrary types to the result pattern's nodes.
2528 if (!IterateInference && InferredAllPatternTypes &&
2529 !InferredAllResultTypes)
2530 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2532 } while (IterateInference);
2534 // Verify that we inferred enough types that we can do something with the
2535 // pattern and result. If these fire the user has to add type casts.
2536 if (!InferredAllPatternTypes)
2537 Pattern->error("Could not infer all types in pattern!");
2538 if (!InferredAllResultTypes) {
2540 Result->error("Could not infer all types in pattern result!");
2543 // Validate that the input pattern is correct.
2544 std::map<std::string, TreePatternNode*> InstInputs;
2545 std::map<std::string, TreePatternNode*> InstResults;
2546 std::vector<Record*> InstImpInputs;
2547 std::vector<Record*> InstImpResults;
2548 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2549 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2550 InstInputs, InstResults,
2551 InstImpInputs, InstImpResults);
2553 // Promote the xform function to be an explicit node if set.
2554 TreePatternNode *DstPattern = Result->getOnlyTree();
2555 std::vector<TreePatternNode*> ResultNodeOperands;
2556 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2557 TreePatternNode *OpNode = DstPattern->getChild(ii);
2558 if (Record *Xform = OpNode->getTransformFn()) {
2559 OpNode->setTransformFn(0);
2560 std::vector<TreePatternNode*> Children;
2561 Children.push_back(OpNode);
2562 OpNode = new TreePatternNode(Xform, Children);
2564 ResultNodeOperands.push_back(OpNode);
2566 DstPattern = Result->getOnlyTree();
2567 if (!DstPattern->isLeaf())
2568 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2569 ResultNodeOperands);
2570 DstPattern->setType(Result->getOnlyTree()->getExtType());
2571 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2572 Temp.InferAllTypes();
2575 AddPatternToMatch(Pattern,
2576 PatternToMatch(Patterns[i]->getValueAsListInit("Predicates"),
2577 Pattern->getTree(0),
2578 Temp.getOnlyTree(), InstImpResults,
2579 Patterns[i]->getValueAsInt("AddedComplexity"),
2580 Patterns[i]->getID()));
2584 /// CombineChildVariants - Given a bunch of permutations of each child of the
2585 /// 'operator' node, put them together in all possible ways.
2586 static void CombineChildVariants(TreePatternNode *Orig,
2587 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2588 std::vector<TreePatternNode*> &OutVariants,
2589 CodeGenDAGPatterns &CDP,
2590 const MultipleUseVarSet &DepVars) {
2591 // Make sure that each operand has at least one variant to choose from.
2592 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2593 if (ChildVariants[i].empty())
2596 // The end result is an all-pairs construction of the resultant pattern.
2597 std::vector<unsigned> Idxs;
2598 Idxs.resize(ChildVariants.size());
2602 DEBUG(if (!Idxs.empty()) {
2603 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2604 for (unsigned i = 0; i < Idxs.size(); ++i) {
2605 errs() << Idxs[i] << " ";
2610 // Create the variant and add it to the output list.
2611 std::vector<TreePatternNode*> NewChildren;
2612 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2613 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2614 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren);
2616 // Copy over properties.
2617 R->setName(Orig->getName());
2618 R->setPredicateFns(Orig->getPredicateFns());
2619 R->setTransformFn(Orig->getTransformFn());
2620 R->setType(Orig->getExtType());
2622 // If this pattern cannot match, do not include it as a variant.
2623 std::string ErrString;
2624 if (!R->canPatternMatch(ErrString, CDP)) {
2627 bool AlreadyExists = false;
2629 // Scan to see if this pattern has already been emitted. We can get
2630 // duplication due to things like commuting:
2631 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
2632 // which are the same pattern. Ignore the dups.
2633 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
2634 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
2635 AlreadyExists = true;
2642 OutVariants.push_back(R);
2645 // Increment indices to the next permutation by incrementing the
2646 // indicies from last index backward, e.g., generate the sequence
2647 // [0, 0], [0, 1], [1, 0], [1, 1].
2649 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2650 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
2655 NotDone = (IdxsIdx >= 0);
2659 /// CombineChildVariants - A helper function for binary operators.
2661 static void CombineChildVariants(TreePatternNode *Orig,
2662 const std::vector<TreePatternNode*> &LHS,
2663 const std::vector<TreePatternNode*> &RHS,
2664 std::vector<TreePatternNode*> &OutVariants,
2665 CodeGenDAGPatterns &CDP,
2666 const MultipleUseVarSet &DepVars) {
2667 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2668 ChildVariants.push_back(LHS);
2669 ChildVariants.push_back(RHS);
2670 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
2674 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
2675 std::vector<TreePatternNode *> &Children) {
2676 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
2677 Record *Operator = N->getOperator();
2679 // Only permit raw nodes.
2680 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
2681 N->getTransformFn()) {
2682 Children.push_back(N);
2686 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
2687 Children.push_back(N->getChild(0));
2689 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
2691 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
2692 Children.push_back(N->getChild(1));
2694 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
2697 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
2698 /// the (potentially recursive) pattern by using algebraic laws.
2700 static void GenerateVariantsOf(TreePatternNode *N,
2701 std::vector<TreePatternNode*> &OutVariants,
2702 CodeGenDAGPatterns &CDP,
2703 const MultipleUseVarSet &DepVars) {
2704 // We cannot permute leaves.
2706 OutVariants.push_back(N);
2710 // Look up interesting info about the node.
2711 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
2713 // If this node is associative, re-associate.
2714 if (NodeInfo.hasProperty(SDNPAssociative)) {
2715 // Re-associate by pulling together all of the linked operators
2716 std::vector<TreePatternNode*> MaximalChildren;
2717 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
2719 // Only handle child sizes of 3. Otherwise we'll end up trying too many
2721 if (MaximalChildren.size() == 3) {
2722 // Find the variants of all of our maximal children.
2723 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
2724 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
2725 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
2726 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
2728 // There are only two ways we can permute the tree:
2729 // (A op B) op C and A op (B op C)
2730 // Within these forms, we can also permute A/B/C.
2732 // Generate legal pair permutations of A/B/C.
2733 std::vector<TreePatternNode*> ABVariants;
2734 std::vector<TreePatternNode*> BAVariants;
2735 std::vector<TreePatternNode*> ACVariants;
2736 std::vector<TreePatternNode*> CAVariants;
2737 std::vector<TreePatternNode*> BCVariants;
2738 std::vector<TreePatternNode*> CBVariants;
2739 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
2740 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
2741 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
2742 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
2743 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
2744 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
2746 // Combine those into the result: (x op x) op x
2747 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
2748 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
2749 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
2750 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
2751 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
2752 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
2754 // Combine those into the result: x op (x op x)
2755 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
2756 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
2757 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
2758 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
2759 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
2760 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
2765 // Compute permutations of all children.
2766 std::vector<std::vector<TreePatternNode*> > ChildVariants;
2767 ChildVariants.resize(N->getNumChildren());
2768 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2769 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
2771 // Build all permutations based on how the children were formed.
2772 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
2774 // If this node is commutative, consider the commuted order.
2775 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
2776 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2777 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
2778 "Commutative but doesn't have 2 children!");
2779 // Don't count children which are actually register references.
2781 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2782 TreePatternNode *Child = N->getChild(i);
2783 if (Child->isLeaf())
2784 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
2785 Record *RR = DI->getDef();
2786 if (RR->isSubClassOf("Register"))
2791 // Consider the commuted order.
2792 if (isCommIntrinsic) {
2793 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
2794 // operands are the commutative operands, and there might be more operands
2797 "Commutative intrinsic should have at least 3 childrean!");
2798 std::vector<std::vector<TreePatternNode*> > Variants;
2799 Variants.push_back(ChildVariants[0]); // Intrinsic id.
2800 Variants.push_back(ChildVariants[2]);
2801 Variants.push_back(ChildVariants[1]);
2802 for (unsigned i = 3; i != NC; ++i)
2803 Variants.push_back(ChildVariants[i]);
2804 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
2806 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
2807 OutVariants, CDP, DepVars);
2812 // GenerateVariants - Generate variants. For example, commutative patterns can
2813 // match multiple ways. Add them to PatternsToMatch as well.
2814 void CodeGenDAGPatterns::GenerateVariants() {
2815 DEBUG(errs() << "Generating instruction variants.\n");
2817 // Loop over all of the patterns we've collected, checking to see if we can
2818 // generate variants of the instruction, through the exploitation of
2819 // identities. This permits the target to provide aggressive matching without
2820 // the .td file having to contain tons of variants of instructions.
2822 // Note that this loop adds new patterns to the PatternsToMatch list, but we
2823 // intentionally do not reconsider these. Any variants of added patterns have
2824 // already been added.
2826 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
2827 MultipleUseVarSet DepVars;
2828 std::vector<TreePatternNode*> Variants;
2829 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
2830 DEBUG(errs() << "Dependent/multiply used variables: ");
2831 DEBUG(DumpDepVars(DepVars));
2832 DEBUG(errs() << "\n");
2833 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, DepVars);
2835 assert(!Variants.empty() && "Must create at least original variant!");
2836 Variants.erase(Variants.begin()); // Remove the original pattern.
2838 if (Variants.empty()) // No variants for this pattern.
2841 DEBUG(errs() << "FOUND VARIANTS OF: ";
2842 PatternsToMatch[i].getSrcPattern()->dump();
2845 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
2846 TreePatternNode *Variant = Variants[v];
2848 DEBUG(errs() << " VAR#" << v << ": ";
2852 // Scan to see if an instruction or explicit pattern already matches this.
2853 bool AlreadyExists = false;
2854 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
2855 // Skip if the top level predicates do not match.
2856 if (PatternsToMatch[i].getPredicates() !=
2857 PatternsToMatch[p].getPredicates())
2859 // Check to see if this variant already exists.
2860 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), DepVars)) {
2861 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
2862 AlreadyExists = true;
2866 // If we already have it, ignore the variant.
2867 if (AlreadyExists) continue;
2869 // Otherwise, add it to the list of patterns we have.
2871 push_back(PatternToMatch(PatternsToMatch[i].getPredicates(),
2872 Variant, PatternsToMatch[i].getDstPattern(),
2873 PatternsToMatch[i].getDstRegs(),
2874 PatternsToMatch[i].getAddedComplexity(),
2875 Record::getNewUID()));
2878 DEBUG(errs() << "\n");