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"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/TableGen/Error.h"
22 #include "llvm/TableGen/Record.h"
28 #define DEBUG_TYPE "dag-patterns"
30 //===----------------------------------------------------------------------===//
31 // EEVT::TypeSet Implementation
32 //===----------------------------------------------------------------------===//
34 static inline bool isInteger(MVT::SimpleValueType VT) {
35 return MVT(VT).isInteger();
37 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
38 return MVT(VT).isFloatingPoint();
40 static inline bool isVector(MVT::SimpleValueType VT) {
41 return MVT(VT).isVector();
43 static inline bool isScalar(MVT::SimpleValueType VT) {
44 return !MVT(VT).isVector();
47 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
50 else if (VT == MVT::fAny)
51 EnforceFloatingPoint(TP);
52 else if (VT == MVT::vAny)
55 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
56 VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!");
57 TypeVec.push_back(VT);
62 EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
63 assert(!VTList.empty() && "empty list?");
64 TypeVec.append(VTList.begin(), VTList.end());
67 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
68 VTList[0] != MVT::fAny);
70 // Verify no duplicates.
71 array_pod_sort(TypeVec.begin(), TypeVec.end());
72 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
75 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
76 /// on completely unknown type sets.
77 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
78 bool (*Pred)(MVT::SimpleValueType),
79 const char *PredicateName) {
80 assert(isCompletelyUnknown());
81 ArrayRef<MVT::SimpleValueType> LegalTypes =
82 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
87 for (MVT::SimpleValueType VT : LegalTypes)
88 if (!Pred || Pred(VT))
89 TypeVec.push_back(VT);
91 // If we have nothing that matches the predicate, bail out.
92 if (TypeVec.empty()) {
93 TP.error("Type inference contradiction found, no " +
94 std::string(PredicateName) + " types found");
97 // No need to sort with one element.
98 if (TypeVec.size() == 1) return true;
100 // Remove duplicates.
101 array_pod_sort(TypeVec.begin(), TypeVec.end());
102 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
107 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
108 /// integer value type.
109 bool EEVT::TypeSet::hasIntegerTypes() const {
110 return std::any_of(TypeVec.begin(), TypeVec.end(), isInteger);
113 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
114 /// a floating point value type.
115 bool EEVT::TypeSet::hasFloatingPointTypes() const {
116 return std::any_of(TypeVec.begin(), TypeVec.end(), isFloatingPoint);
119 /// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
120 bool EEVT::TypeSet::hasScalarTypes() const {
121 return std::any_of(TypeVec.begin(), TypeVec.end(), isScalar);
124 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
126 bool EEVT::TypeSet::hasVectorTypes() const {
127 return std::any_of(TypeVec.begin(), TypeVec.end(), isVector);
131 std::string EEVT::TypeSet::getName() const {
132 if (TypeVec.empty()) return "<empty>";
136 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
137 std::string VTName = llvm::getEnumName(TypeVec[i]);
138 // Strip off MVT:: prefix if present.
139 if (VTName.substr(0,5) == "MVT::")
140 VTName = VTName.substr(5);
141 if (i) Result += ':';
145 if (TypeVec.size() == 1)
147 return "{" + Result + "}";
150 /// MergeInTypeInfo - This merges in type information from the specified
151 /// argument. If 'this' changes, it returns true. If the two types are
152 /// contradictory (e.g. merge f32 into i32) then this flags an error.
153 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
154 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
157 if (isCompletelyUnknown()) {
162 assert(!TypeVec.empty() && !InVT.TypeVec.empty() && "No unknowns");
164 // Handle the abstract cases, seeing if we can resolve them better.
165 switch (TypeVec[0]) {
169 if (InVT.hasIntegerTypes()) {
170 EEVT::TypeSet InCopy(InVT);
171 InCopy.EnforceInteger(TP);
172 InCopy.EnforceScalar(TP);
174 if (InCopy.isConcrete()) {
175 // If the RHS has one integer type, upgrade iPTR to i32.
176 TypeVec[0] = InVT.TypeVec[0];
180 // If the input has multiple scalar integers, this doesn't add any info.
181 if (!InCopy.isCompletelyUnknown())
187 // If the input constraint is iAny/iPTR and this is an integer type list,
188 // remove non-integer types from the list.
189 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
191 bool MadeChange = EnforceInteger(TP);
193 // If we're merging in iPTR/iPTRAny and the node currently has a list of
194 // multiple different integer types, replace them with a single iPTR.
195 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
196 TypeVec.size() != 1) {
197 TypeVec.assign(1, InVT.TypeVec[0]);
204 // If this is a type list and the RHS is a typelist as well, eliminate entries
205 // from this list that aren't in the other one.
206 TypeSet InputSet(*this);
209 std::set_intersection(InputSet.TypeVec.begin(), InputSet.TypeVec.end(),
210 InVT.TypeVec.begin(), InVT.TypeVec.end(),
211 std::back_inserter(TypeVec));
213 // If the intersection is the same size as the original set then we're done.
214 if (TypeVec.size() == InputSet.TypeVec.size())
217 // If we removed all of our types, we have a type contradiction.
218 if (!TypeVec.empty())
221 // FIXME: Really want an SMLoc here!
222 TP.error("Type inference contradiction found, merging '" +
223 InVT.getName() + "' into '" + InputSet.getName() + "'");
227 /// EnforceInteger - Remove all non-integer types from this set.
228 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
231 // If we know nothing, then get the full set.
233 return FillWithPossibleTypes(TP, isInteger, "integer");
235 if (!hasFloatingPointTypes())
238 TypeSet InputSet(*this);
240 // Filter out all the fp types.
241 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
242 std::not1(std::ptr_fun(isInteger))),
245 if (TypeVec.empty()) {
246 TP.error("Type inference contradiction found, '" +
247 InputSet.getName() + "' needs to be integer");
253 /// EnforceFloatingPoint - Remove all integer types from this set.
254 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
257 // If we know nothing, then get the full set.
259 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
261 if (!hasIntegerTypes())
264 TypeSet InputSet(*this);
266 // Filter out all the integer types.
267 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
268 std::not1(std::ptr_fun(isFloatingPoint))),
271 if (TypeVec.empty()) {
272 TP.error("Type inference contradiction found, '" +
273 InputSet.getName() + "' needs to be floating point");
279 /// EnforceScalar - Remove all vector types from this.
280 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
284 // If we know nothing, then get the full set.
286 return FillWithPossibleTypes(TP, isScalar, "scalar");
288 if (!hasVectorTypes())
291 TypeSet InputSet(*this);
293 // Filter out all the vector types.
294 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
295 std::not1(std::ptr_fun(isScalar))),
298 if (TypeVec.empty()) {
299 TP.error("Type inference contradiction found, '" +
300 InputSet.getName() + "' needs to be scalar");
306 /// EnforceVector - Remove all vector types from this.
307 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
311 // If we know nothing, then get the full set.
313 return FillWithPossibleTypes(TP, isVector, "vector");
315 TypeSet InputSet(*this);
316 bool MadeChange = false;
318 // Filter out all the scalar types.
319 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
320 std::not1(std::ptr_fun(isVector))),
323 if (TypeVec.empty()) {
324 TP.error("Type inference contradiction found, '" +
325 InputSet.getName() + "' needs to be a vector");
333 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
334 /// this should be based on the element type. Update this and other based on
335 /// this information.
336 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
340 // Both operands must be integer or FP, but we don't care which.
341 bool MadeChange = false;
343 if (isCompletelyUnknown())
344 MadeChange = FillWithPossibleTypes(TP);
346 if (Other.isCompletelyUnknown())
347 MadeChange = Other.FillWithPossibleTypes(TP);
349 // If one side is known to be integer or known to be FP but the other side has
350 // no information, get at least the type integrality info in there.
351 if (!hasFloatingPointTypes())
352 MadeChange |= Other.EnforceInteger(TP);
353 else if (!hasIntegerTypes())
354 MadeChange |= Other.EnforceFloatingPoint(TP);
355 if (!Other.hasFloatingPointTypes())
356 MadeChange |= EnforceInteger(TP);
357 else if (!Other.hasIntegerTypes())
358 MadeChange |= EnforceFloatingPoint(TP);
360 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
361 "Should have a type list now");
363 // If one contains vectors but the other doesn't pull vectors out.
364 if (!hasVectorTypes())
365 MadeChange |= Other.EnforceScalar(TP);
366 else if (!hasScalarTypes())
367 MadeChange |= Other.EnforceVector(TP);
368 if (!Other.hasVectorTypes())
369 MadeChange |= EnforceScalar(TP);
370 else if (!Other.hasScalarTypes())
371 MadeChange |= EnforceVector(TP);
373 // This code does not currently handle nodes which have multiple types,
374 // where some types are integer, and some are fp. Assert that this is not
376 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
377 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
378 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
383 // Okay, find the smallest type from current set and remove anything the
384 // same or smaller from the other set. We need to ensure that the scalar
385 // type size is smaller than the scalar size of the smallest type. For
386 // vectors, we also need to make sure that the total size is no larger than
387 // the size of the smallest type.
388 TypeSet InputSet(Other);
389 MVT Smallest = TypeVec[0];
390 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
391 MVT OtherVT = Other.TypeVec[i];
392 // Don't compare vector and non-vector types.
393 if (OtherVT.isVector() != Smallest.isVector())
395 // The getSizeInBits() check here is only needed for vectors, but is
396 // a subset of the scalar check for scalars so no need to qualify.
397 if (OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
398 OtherVT.getSizeInBits() < Smallest.getSizeInBits()) {
399 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
404 if (Other.TypeVec.empty()) {
405 TP.error("Type inference contradiction found, '" + InputSet.getName() +
406 "' has nothing larger than '" + getName() +"'!");
410 // Okay, find the largest type from the other set and remove anything the
411 // same or smaller from the current set. We need to ensure that the scalar
412 // type size is larger than the scalar size of the largest type. For
413 // vectors, we also need to make sure that the total size is no smaller than
414 // the size of the largest type.
415 InputSet = TypeSet(*this);
416 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
417 for (unsigned i = 0; i != TypeVec.size(); ++i) {
418 MVT OtherVT = TypeVec[i];
419 // Don't compare vector and non-vector types.
420 if (OtherVT.isVector() != Largest.isVector())
422 // The getSizeInBits() check here is only needed for vectors, but is
423 // a subset of the scalar check for scalars so no need to qualify.
424 if (OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
425 OtherVT.getSizeInBits() > Largest.getSizeInBits()) {
426 TypeVec.erase(TypeVec.begin()+i--);
431 if (TypeVec.empty()) {
432 TP.error("Type inference contradiction found, '" + InputSet.getName() +
433 "' has nothing smaller than '" + Other.getName() +"'!");
440 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
441 /// whose element is specified by VTOperand.
442 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
444 bool MadeChange = false;
446 MadeChange |= EnforceVector(TP);
448 TypeSet InputSet(*this);
450 // Filter out all the types which don't have the right element type.
451 for (unsigned i = 0; i != TypeVec.size(); ++i) {
452 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
453 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
454 TypeVec.erase(TypeVec.begin()+i--);
459 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
460 TP.error("Type inference contradiction found, forcing '" +
461 InputSet.getName() + "' to have a vector element");
468 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
469 /// whose element is specified by VTOperand.
470 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
475 // "This" must be a vector and "VTOperand" must be a scalar.
476 bool MadeChange = false;
477 MadeChange |= EnforceVector(TP);
478 MadeChange |= VTOperand.EnforceScalar(TP);
480 // If we know the vector type, it forces the scalar to agree.
482 MVT IVT = getConcrete();
483 IVT = IVT.getVectorElementType();
484 return MadeChange || VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
487 // If the scalar type is known, filter out vector types whose element types
489 if (!VTOperand.isConcrete())
492 MVT::SimpleValueType VT = VTOperand.getConcrete();
494 TypeSet InputSet(*this);
496 // Filter out all the types which don't have the right element type.
497 for (unsigned i = 0; i != TypeVec.size(); ++i) {
498 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
499 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
500 TypeVec.erase(TypeVec.begin()+i--);
505 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
506 TP.error("Type inference contradiction found, forcing '" +
507 InputSet.getName() + "' to have a vector element");
513 /// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
514 /// vector type specified by VTOperand.
515 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
520 // "This" must be a vector and "VTOperand" must be a vector.
521 bool MadeChange = false;
522 MadeChange |= EnforceVector(TP);
523 MadeChange |= VTOperand.EnforceVector(TP);
525 // If one side is known to be integer or known to be FP but the other side has
526 // no information, get at least the type integrality info in there.
527 if (!hasFloatingPointTypes())
528 MadeChange |= VTOperand.EnforceInteger(TP);
529 else if (!hasIntegerTypes())
530 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
531 if (!VTOperand.hasFloatingPointTypes())
532 MadeChange |= EnforceInteger(TP);
533 else if (!VTOperand.hasIntegerTypes())
534 MadeChange |= EnforceFloatingPoint(TP);
536 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
537 "Should have a type list now");
539 // If we know the vector type, it forces the scalar types to agree.
540 // Also force one vector to have more elements than the other.
542 MVT IVT = getConcrete();
543 unsigned NumElems = IVT.getVectorNumElements();
544 IVT = IVT.getVectorElementType();
546 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
547 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
549 // Only keep types that have less elements than VTOperand.
550 TypeSet InputSet(VTOperand);
552 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
553 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
554 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
555 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
559 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
560 TP.error("Type inference contradiction found, forcing '" +
561 InputSet.getName() + "' to have less vector elements than '" +
565 } else if (VTOperand.isConcrete()) {
566 MVT IVT = VTOperand.getConcrete();
567 unsigned NumElems = IVT.getVectorNumElements();
568 IVT = IVT.getVectorElementType();
570 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
571 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
573 // Only keep types that have more elements than 'this'.
574 TypeSet InputSet(*this);
576 for (unsigned i = 0; i != TypeVec.size(); ++i) {
577 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
578 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
579 TypeVec.erase(TypeVec.begin()+i--);
583 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
584 TP.error("Type inference contradiction found, forcing '" +
585 InputSet.getName() + "' to have more vector elements than '" +
586 VTOperand.getName() + "'");
594 /// EnforceVectorSameNumElts - 'this' is now constrained to
595 /// be a vector with same num elements as VTOperand.
596 bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
601 // "This" must be a vector and "VTOperand" must be a vector.
602 bool MadeChange = false;
603 MadeChange |= EnforceVector(TP);
604 MadeChange |= VTOperand.EnforceVector(TP);
606 // If we know one of the vector types, it forces the other type to agree.
608 MVT IVT = getConcrete();
609 unsigned NumElems = IVT.getVectorNumElements();
611 // Only keep types that have same elements as VTOperand.
612 TypeSet InputSet(VTOperand);
614 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
615 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
616 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
617 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
621 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
622 TP.error("Type inference contradiction found, forcing '" +
623 InputSet.getName() + "' to have same number elements as '" +
627 } else if (VTOperand.isConcrete()) {
628 MVT IVT = VTOperand.getConcrete();
629 unsigned NumElems = IVT.getVectorNumElements();
631 // Only keep types that have same elements as 'this'.
632 TypeSet InputSet(*this);
634 for (unsigned i = 0; i != TypeVec.size(); ++i) {
635 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
636 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
637 TypeVec.erase(TypeVec.begin()+i--);
641 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
642 TP.error("Type inference contradiction found, forcing '" +
643 InputSet.getName() + "' to have same number elements than '" +
644 VTOperand.getName() + "'");
652 //===----------------------------------------------------------------------===//
653 // Helpers for working with extended types.
655 /// Dependent variable map for CodeGenDAGPattern variant generation
656 typedef std::map<std::string, int> DepVarMap;
658 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
660 if (isa<DefInit>(N->getLeafValue()))
661 DepMap[N->getName()]++;
663 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
664 FindDepVarsOf(N->getChild(i), DepMap);
668 /// Find dependent variables within child patterns
669 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
671 FindDepVarsOf(N, depcounts);
672 for (const std::pair<std::string, int> &Pair : depcounts) {
674 DepVars.insert(Pair.first);
679 /// Dump the dependent variable set:
680 static void DumpDepVars(MultipleUseVarSet &DepVars) {
681 if (DepVars.empty()) {
682 DEBUG(errs() << "<empty set>");
684 DEBUG(errs() << "[ ");
685 for (const std::string &DepVar : DepVars) {
686 DEBUG(errs() << DepVar << " ");
688 DEBUG(errs() << "]");
694 //===----------------------------------------------------------------------===//
695 // TreePredicateFn Implementation
696 //===----------------------------------------------------------------------===//
698 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
699 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
700 assert((getPredCode().empty() || getImmCode().empty()) &&
701 ".td file corrupt: can't have a node predicate *and* an imm predicate");
704 std::string TreePredicateFn::getPredCode() const {
705 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
708 std::string TreePredicateFn::getImmCode() const {
709 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
713 /// isAlwaysTrue - Return true if this is a noop predicate.
714 bool TreePredicateFn::isAlwaysTrue() const {
715 return getPredCode().empty() && getImmCode().empty();
718 /// Return the name to use in the generated code to reference this, this is
719 /// "Predicate_foo" if from a pattern fragment "foo".
720 std::string TreePredicateFn::getFnName() const {
721 return "Predicate_" + PatFragRec->getRecord()->getName();
724 /// getCodeToRunOnSDNode - Return the code for the function body that
725 /// evaluates this predicate. The argument is expected to be in "Node",
726 /// not N. This handles casting and conversion to a concrete node type as
728 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
729 // Handle immediate predicates first.
730 std::string ImmCode = getImmCode();
731 if (!ImmCode.empty()) {
733 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
734 return Result + ImmCode;
737 // Handle arbitrary node predicates.
738 assert(!getPredCode().empty() && "Don't have any predicate code!");
739 std::string ClassName;
740 if (PatFragRec->getOnlyTree()->isLeaf())
741 ClassName = "SDNode";
743 Record *Op = PatFragRec->getOnlyTree()->getOperator();
744 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
747 if (ClassName == "SDNode")
748 Result = " SDNode *N = Node;\n";
750 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
752 return Result + getPredCode();
755 //===----------------------------------------------------------------------===//
756 // PatternToMatch implementation
760 /// getPatternSize - Return the 'size' of this pattern. We want to match large
761 /// patterns before small ones. This is used to determine the size of a
763 static unsigned getPatternSize(const TreePatternNode *P,
764 const CodeGenDAGPatterns &CGP) {
765 unsigned Size = 3; // The node itself.
766 // If the root node is a ConstantSDNode, increases its size.
767 // e.g. (set R32:$dst, 0).
768 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
771 // FIXME: This is a hack to statically increase the priority of patterns
772 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
773 // Later we can allow complexity / cost for each pattern to be (optionally)
774 // specified. To get best possible pattern match we'll need to dynamically
775 // calculate the complexity of all patterns a dag can potentially map to.
776 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
778 Size += AM->getNumOperands() * 3;
780 // We don't want to count any children twice, so return early.
784 // If this node has some predicate function that must match, it adds to the
785 // complexity of this node.
786 if (!P->getPredicateFns().empty())
789 // Count children in the count if they are also nodes.
790 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
791 TreePatternNode *Child = P->getChild(i);
792 if (!Child->isLeaf() && Child->getNumTypes() &&
793 Child->getType(0) != MVT::Other)
794 Size += getPatternSize(Child, CGP);
795 else if (Child->isLeaf()) {
796 if (isa<IntInit>(Child->getLeafValue()))
797 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
798 else if (Child->getComplexPatternInfo(CGP))
799 Size += getPatternSize(Child, CGP);
800 else if (!Child->getPredicateFns().empty())
808 /// Compute the complexity metric for the input pattern. This roughly
809 /// corresponds to the number of nodes that are covered.
811 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
812 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
816 /// getPredicateCheck - Return a single string containing all of this
817 /// pattern's predicates concatenated with "&&" operators.
819 std::string PatternToMatch::getPredicateCheck() const {
820 std::string PredicateCheck;
821 for (Init *I : Predicates->getValues()) {
822 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
823 Record *Def = Pred->getDef();
824 if (!Def->isSubClassOf("Predicate")) {
828 llvm_unreachable("Unknown predicate type!");
830 if (!PredicateCheck.empty())
831 PredicateCheck += " && ";
832 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
836 return PredicateCheck;
839 //===----------------------------------------------------------------------===//
840 // SDTypeConstraint implementation
843 SDTypeConstraint::SDTypeConstraint(Record *R) {
844 OperandNo = R->getValueAsInt("OperandNum");
846 if (R->isSubClassOf("SDTCisVT")) {
847 ConstraintType = SDTCisVT;
848 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
849 if (x.SDTCisVT_Info.VT == MVT::isVoid)
850 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
852 } else if (R->isSubClassOf("SDTCisPtrTy")) {
853 ConstraintType = SDTCisPtrTy;
854 } else if (R->isSubClassOf("SDTCisInt")) {
855 ConstraintType = SDTCisInt;
856 } else if (R->isSubClassOf("SDTCisFP")) {
857 ConstraintType = SDTCisFP;
858 } else if (R->isSubClassOf("SDTCisVec")) {
859 ConstraintType = SDTCisVec;
860 } else if (R->isSubClassOf("SDTCisSameAs")) {
861 ConstraintType = SDTCisSameAs;
862 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
863 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
864 ConstraintType = SDTCisVTSmallerThanOp;
865 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
866 R->getValueAsInt("OtherOperandNum");
867 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
868 ConstraintType = SDTCisOpSmallerThanOp;
869 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
870 R->getValueAsInt("BigOperandNum");
871 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
872 ConstraintType = SDTCisEltOfVec;
873 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
874 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
875 ConstraintType = SDTCisSubVecOfVec;
876 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
877 R->getValueAsInt("OtherOpNum");
878 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
879 ConstraintType = SDTCVecEltisVT;
880 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
881 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
882 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
883 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
884 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
885 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
886 "as SDTCVecEltisVT");
887 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
888 ConstraintType = SDTCisSameNumEltsAs;
889 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
890 R->getValueAsInt("OtherOperandNum");
892 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
896 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
897 /// N, and the result number in ResNo.
898 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
899 const SDNodeInfo &NodeInfo,
901 unsigned NumResults = NodeInfo.getNumResults();
902 if (OpNo < NumResults) {
909 if (OpNo >= N->getNumChildren()) {
911 raw_string_ostream OS(S);
912 OS << "Invalid operand number in type constraint "
913 << (OpNo+NumResults) << " ";
915 PrintFatalError(OS.str());
918 return N->getChild(OpNo);
921 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
922 /// constraint to the nodes operands. This returns true if it makes a
923 /// change, false otherwise. If a type contradiction is found, flag an error.
924 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
925 const SDNodeInfo &NodeInfo,
926 TreePattern &TP) const {
930 unsigned ResNo = 0; // The result number being referenced.
931 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
933 switch (ConstraintType) {
935 // Operand must be a particular type.
936 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
938 // Operand must be same as target pointer type.
939 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
941 // Require it to be one of the legal integer VTs.
942 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
944 // Require it to be one of the legal fp VTs.
945 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
947 // Require it to be one of the legal vector VTs.
948 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
951 TreePatternNode *OtherNode =
952 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
953 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
954 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
956 case SDTCisVTSmallerThanOp: {
957 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
958 // have an integer type that is smaller than the VT.
959 if (!NodeToApply->isLeaf() ||
960 !isa<DefInit>(NodeToApply->getLeafValue()) ||
961 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
962 ->isSubClassOf("ValueType")) {
963 TP.error(N->getOperator()->getName() + " expects a VT operand!");
966 MVT::SimpleValueType VT =
967 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
969 EEVT::TypeSet TypeListTmp(VT, TP);
972 TreePatternNode *OtherNode =
973 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
976 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
978 case SDTCisOpSmallerThanOp: {
980 TreePatternNode *BigOperand =
981 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
983 return NodeToApply->getExtType(ResNo).
984 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
986 case SDTCisEltOfVec: {
988 TreePatternNode *VecOperand =
989 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
992 // Filter vector types out of VecOperand that don't have the right element
994 return VecOperand->getExtType(VResNo).
995 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
997 case SDTCisSubVecOfVec: {
999 TreePatternNode *BigVecOperand =
1000 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1003 // Filter vector types out of BigVecOperand that don't have the
1004 // right subvector type.
1005 return BigVecOperand->getExtType(VResNo).
1006 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1008 case SDTCVecEltisVT: {
1009 return NodeToApply->getExtType(ResNo).
1010 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1012 case SDTCisSameNumEltsAs: {
1013 unsigned OResNo = 0;
1014 TreePatternNode *OtherNode =
1015 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1016 N, NodeInfo, OResNo);
1017 return OtherNode->getExtType(OResNo).
1018 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1021 llvm_unreachable("Invalid ConstraintType!");
1024 // Update the node type to match an instruction operand or result as specified
1025 // in the ins or outs lists on the instruction definition. Return true if the
1026 // type was actually changed.
1027 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1030 // The 'unknown' operand indicates that types should be inferred from the
1032 if (Operand->isSubClassOf("unknown_class"))
1035 // The Operand class specifies a type directly.
1036 if (Operand->isSubClassOf("Operand"))
1037 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1040 // PointerLikeRegClass has a type that is determined at runtime.
1041 if (Operand->isSubClassOf("PointerLikeRegClass"))
1042 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1044 // Both RegisterClass and RegisterOperand operands derive their types from a
1045 // register class def.
1046 Record *RC = nullptr;
1047 if (Operand->isSubClassOf("RegisterClass"))
1049 else if (Operand->isSubClassOf("RegisterOperand"))
1050 RC = Operand->getValueAsDef("RegClass");
1052 assert(RC && "Unknown operand type");
1053 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1054 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1058 //===----------------------------------------------------------------------===//
1059 // SDNodeInfo implementation
1061 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1062 EnumName = R->getValueAsString("Opcode");
1063 SDClassName = R->getValueAsString("SDClass");
1064 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1065 NumResults = TypeProfile->getValueAsInt("NumResults");
1066 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1068 // Parse the properties.
1070 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1071 if (Property->getName() == "SDNPCommutative") {
1072 Properties |= 1 << SDNPCommutative;
1073 } else if (Property->getName() == "SDNPAssociative") {
1074 Properties |= 1 << SDNPAssociative;
1075 } else if (Property->getName() == "SDNPHasChain") {
1076 Properties |= 1 << SDNPHasChain;
1077 } else if (Property->getName() == "SDNPOutGlue") {
1078 Properties |= 1 << SDNPOutGlue;
1079 } else if (Property->getName() == "SDNPInGlue") {
1080 Properties |= 1 << SDNPInGlue;
1081 } else if (Property->getName() == "SDNPOptInGlue") {
1082 Properties |= 1 << SDNPOptInGlue;
1083 } else if (Property->getName() == "SDNPMayStore") {
1084 Properties |= 1 << SDNPMayStore;
1085 } else if (Property->getName() == "SDNPMayLoad") {
1086 Properties |= 1 << SDNPMayLoad;
1087 } else if (Property->getName() == "SDNPSideEffect") {
1088 Properties |= 1 << SDNPSideEffect;
1089 } else if (Property->getName() == "SDNPMemOperand") {
1090 Properties |= 1 << SDNPMemOperand;
1091 } else if (Property->getName() == "SDNPVariadic") {
1092 Properties |= 1 << SDNPVariadic;
1094 PrintFatalError("Unknown SD Node property '" +
1095 Property->getName() + "' on node '" +
1096 R->getName() + "'!");
1101 // Parse the type constraints.
1102 std::vector<Record*> ConstraintList =
1103 TypeProfile->getValueAsListOfDefs("Constraints");
1104 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1107 /// getKnownType - If the type constraints on this node imply a fixed type
1108 /// (e.g. all stores return void, etc), then return it as an
1109 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1110 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1111 unsigned NumResults = getNumResults();
1112 assert(NumResults <= 1 &&
1113 "We only work with nodes with zero or one result so far!");
1114 assert(ResNo == 0 && "Only handles single result nodes so far");
1116 for (const SDTypeConstraint &Constraint : TypeConstraints) {
1117 // Make sure that this applies to the correct node result.
1118 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1121 switch (Constraint.ConstraintType) {
1123 case SDTypeConstraint::SDTCisVT:
1124 return Constraint.x.SDTCisVT_Info.VT;
1125 case SDTypeConstraint::SDTCisPtrTy:
1132 //===----------------------------------------------------------------------===//
1133 // TreePatternNode implementation
1136 TreePatternNode::~TreePatternNode() {
1137 #if 0 // FIXME: implement refcounted tree nodes!
1138 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1143 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1144 if (Operator->getName() == "set" ||
1145 Operator->getName() == "implicit")
1146 return 0; // All return nothing.
1148 if (Operator->isSubClassOf("Intrinsic"))
1149 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1151 if (Operator->isSubClassOf("SDNode"))
1152 return CDP.getSDNodeInfo(Operator).getNumResults();
1154 if (Operator->isSubClassOf("PatFrag")) {
1155 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1156 // the forward reference case where one pattern fragment references another
1157 // before it is processed.
1158 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1159 return PFRec->getOnlyTree()->getNumTypes();
1161 // Get the result tree.
1162 DagInit *Tree = Operator->getValueAsDag("Fragment");
1163 Record *Op = nullptr;
1165 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1167 assert(Op && "Invalid Fragment");
1168 return GetNumNodeResults(Op, CDP);
1171 if (Operator->isSubClassOf("Instruction")) {
1172 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1174 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1176 // Subtract any defaulted outputs.
1177 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1178 Record *OperandNode = InstInfo.Operands[i].Rec;
1180 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1181 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1185 // Add on one implicit def if it has a resolvable type.
1186 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1188 return NumDefsToAdd;
1191 if (Operator->isSubClassOf("SDNodeXForm"))
1192 return 1; // FIXME: Generalize SDNodeXForm
1194 if (Operator->isSubClassOf("ValueType"))
1195 return 1; // A type-cast of one result.
1197 if (Operator->isSubClassOf("ComplexPattern"))
1201 PrintFatalError("Unhandled node in GetNumNodeResults");
1204 void TreePatternNode::print(raw_ostream &OS) const {
1206 OS << *getLeafValue();
1208 OS << '(' << getOperator()->getName();
1210 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1211 OS << ':' << getExtType(i).getName();
1214 if (getNumChildren() != 0) {
1216 getChild(0)->print(OS);
1217 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1219 getChild(i)->print(OS);
1225 for (const TreePredicateFn &Pred : PredicateFns)
1226 OS << "<<P:" << Pred.getFnName() << ">>";
1228 OS << "<<X:" << TransformFn->getName() << ">>";
1229 if (!getName().empty())
1230 OS << ":$" << getName();
1233 void TreePatternNode::dump() const {
1237 /// isIsomorphicTo - Return true if this node is recursively
1238 /// isomorphic to the specified node. For this comparison, the node's
1239 /// entire state is considered. The assigned name is ignored, since
1240 /// nodes with differing names are considered isomorphic. However, if
1241 /// the assigned name is present in the dependent variable set, then
1242 /// the assigned name is considered significant and the node is
1243 /// isomorphic if the names match.
1244 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1245 const MultipleUseVarSet &DepVars) const {
1246 if (N == this) return true;
1247 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1248 getPredicateFns() != N->getPredicateFns() ||
1249 getTransformFn() != N->getTransformFn())
1253 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1254 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1255 return ((DI->getDef() == NDI->getDef())
1256 && (DepVars.find(getName()) == DepVars.end()
1257 || getName() == N->getName()));
1260 return getLeafValue() == N->getLeafValue();
1263 if (N->getOperator() != getOperator() ||
1264 N->getNumChildren() != getNumChildren()) return false;
1265 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1266 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1271 /// clone - Make a copy of this tree and all of its children.
1273 TreePatternNode *TreePatternNode::clone() const {
1274 TreePatternNode *New;
1276 New = new TreePatternNode(getLeafValue(), getNumTypes());
1278 std::vector<TreePatternNode*> CChildren;
1279 CChildren.reserve(Children.size());
1280 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1281 CChildren.push_back(getChild(i)->clone());
1282 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1284 New->setName(getName());
1286 New->setPredicateFns(getPredicateFns());
1287 New->setTransformFn(getTransformFn());
1291 /// RemoveAllTypes - Recursively strip all the types of this tree.
1292 void TreePatternNode::RemoveAllTypes() {
1293 // Reset to unknown type.
1294 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
1295 if (isLeaf()) return;
1296 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1297 getChild(i)->RemoveAllTypes();
1301 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1302 /// with actual values specified by ArgMap.
1303 void TreePatternNode::
1304 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1305 if (isLeaf()) return;
1307 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1308 TreePatternNode *Child = getChild(i);
1309 if (Child->isLeaf()) {
1310 Init *Val = Child->getLeafValue();
1311 // Note that, when substituting into an output pattern, Val might be an
1313 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1314 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1315 // We found a use of a formal argument, replace it with its value.
1316 TreePatternNode *NewChild = ArgMap[Child->getName()];
1317 assert(NewChild && "Couldn't find formal argument!");
1318 assert((Child->getPredicateFns().empty() ||
1319 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1320 "Non-empty child predicate clobbered!");
1321 setChild(i, NewChild);
1324 getChild(i)->SubstituteFormalArguments(ArgMap);
1330 /// InlinePatternFragments - If this pattern refers to any pattern
1331 /// fragments, inline them into place, giving us a pattern without any
1332 /// PatFrag references.
1333 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1338 return this; // nothing to do.
1339 Record *Op = getOperator();
1341 if (!Op->isSubClassOf("PatFrag")) {
1342 // Just recursively inline children nodes.
1343 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1344 TreePatternNode *Child = getChild(i);
1345 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1347 assert((Child->getPredicateFns().empty() ||
1348 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1349 "Non-empty child predicate clobbered!");
1351 setChild(i, NewChild);
1356 // Otherwise, we found a reference to a fragment. First, look up its
1357 // TreePattern record.
1358 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1360 // Verify that we are passing the right number of operands.
1361 if (Frag->getNumArgs() != Children.size()) {
1362 TP.error("'" + Op->getName() + "' fragment requires " +
1363 utostr(Frag->getNumArgs()) + " operands!");
1367 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1369 TreePredicateFn PredFn(Frag);
1370 if (!PredFn.isAlwaysTrue())
1371 FragTree->addPredicateFn(PredFn);
1373 // Resolve formal arguments to their actual value.
1374 if (Frag->getNumArgs()) {
1375 // Compute the map of formal to actual arguments.
1376 std::map<std::string, TreePatternNode*> ArgMap;
1377 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1378 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1380 FragTree->SubstituteFormalArguments(ArgMap);
1383 FragTree->setName(getName());
1384 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1385 FragTree->UpdateNodeType(i, getExtType(i), TP);
1387 // Transfer in the old predicates.
1388 for (const TreePredicateFn &Pred : getPredicateFns())
1389 FragTree->addPredicateFn(Pred);
1391 // Get a new copy of this fragment to stitch into here.
1392 //delete this; // FIXME: implement refcounting!
1394 // The fragment we inlined could have recursive inlining that is needed. See
1395 // if there are any pattern fragments in it and inline them as needed.
1396 return FragTree->InlinePatternFragments(TP);
1399 /// getImplicitType - Check to see if the specified record has an implicit
1400 /// type which should be applied to it. This will infer the type of register
1401 /// references from the register file information, for example.
1403 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1404 /// the F8RC register class argument in:
1406 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
1408 /// When Unnamed is false, return the type of a named DAG operand such as the
1409 /// GPR:$src operand above.
1411 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1415 // Check to see if this is a register operand.
1416 if (R->isSubClassOf("RegisterOperand")) {
1417 assert(ResNo == 0 && "Regoperand ref only has one result!");
1419 return EEVT::TypeSet(); // Unknown.
1420 Record *RegClass = R->getValueAsDef("RegClass");
1421 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1422 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1425 // Check to see if this is a register or a register class.
1426 if (R->isSubClassOf("RegisterClass")) {
1427 assert(ResNo == 0 && "Regclass ref only has one result!");
1428 // An unnamed register class represents itself as an i32 immediate, for
1429 // example on a COPY_TO_REGCLASS instruction.
1431 return EEVT::TypeSet(MVT::i32, TP);
1433 // In a named operand, the register class provides the possible set of
1436 return EEVT::TypeSet(); // Unknown.
1437 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1438 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1441 if (R->isSubClassOf("PatFrag")) {
1442 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1443 // Pattern fragment types will be resolved when they are inlined.
1444 return EEVT::TypeSet(); // Unknown.
1447 if (R->isSubClassOf("Register")) {
1448 assert(ResNo == 0 && "Registers only produce one result!");
1450 return EEVT::TypeSet(); // Unknown.
1451 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1452 return EEVT::TypeSet(T.getRegisterVTs(R));
1455 if (R->isSubClassOf("SubRegIndex")) {
1456 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1457 return EEVT::TypeSet(MVT::i32, TP);
1460 if (R->isSubClassOf("ValueType")) {
1461 assert(ResNo == 0 && "This node only has one result!");
1462 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1464 // (sext_inreg GPR:$src, i16)
1467 return EEVT::TypeSet(MVT::Other, TP);
1468 // With a name, the ValueType simply provides the type of the named
1471 // (sext_inreg i32:$src, i16)
1474 return EEVT::TypeSet(); // Unknown.
1475 return EEVT::TypeSet(getValueType(R), TP);
1478 if (R->isSubClassOf("CondCode")) {
1479 assert(ResNo == 0 && "This node only has one result!");
1480 // Using a CondCodeSDNode.
1481 return EEVT::TypeSet(MVT::Other, TP);
1484 if (R->isSubClassOf("ComplexPattern")) {
1485 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1487 return EEVT::TypeSet(); // Unknown.
1488 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1491 if (R->isSubClassOf("PointerLikeRegClass")) {
1492 assert(ResNo == 0 && "Regclass can only have one result!");
1493 return EEVT::TypeSet(MVT::iPTR, TP);
1496 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1497 R->getName() == "zero_reg") {
1499 return EEVT::TypeSet(); // Unknown.
1502 if (R->isSubClassOf("Operand"))
1503 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1505 TP.error("Unknown node flavor used in pattern: " + R->getName());
1506 return EEVT::TypeSet(MVT::Other, TP);
1510 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1511 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1512 const CodeGenIntrinsic *TreePatternNode::
1513 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1514 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1515 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1516 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1519 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
1520 return &CDP.getIntrinsicInfo(IID);
1523 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1524 /// return the ComplexPattern information, otherwise return null.
1525 const ComplexPattern *
1526 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1529 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1534 Rec = getOperator();
1536 if (!Rec->isSubClassOf("ComplexPattern"))
1538 return &CGP.getComplexPattern(Rec);
1541 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1542 // A ComplexPattern specifically declares how many results it fills in.
1543 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1544 return CP->getNumOperands();
1546 // If MIOperandInfo is specified, that gives the count.
1548 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1549 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1550 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1551 if (MIOps->getNumArgs())
1552 return MIOps->getNumArgs();
1556 // Otherwise there is just one result.
1560 /// NodeHasProperty - Return true if this node has the specified property.
1561 bool TreePatternNode::NodeHasProperty(SDNP Property,
1562 const CodeGenDAGPatterns &CGP) const {
1564 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1565 return CP->hasProperty(Property);
1569 Record *Operator = getOperator();
1570 if (!Operator->isSubClassOf("SDNode")) return false;
1572 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1578 /// TreeHasProperty - Return true if any node in this tree has the specified
1580 bool TreePatternNode::TreeHasProperty(SDNP Property,
1581 const CodeGenDAGPatterns &CGP) const {
1582 if (NodeHasProperty(Property, CGP))
1584 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1585 if (getChild(i)->TreeHasProperty(Property, CGP))
1590 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1591 /// commutative intrinsic.
1593 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1594 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1595 return Int->isCommutative;
1599 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1601 return N->getOperator()->isSubClassOf(Class);
1603 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1604 if (DI && DI->getDef()->isSubClassOf(Class))
1610 static void emitTooManyOperandsError(TreePattern &TP,
1614 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1615 " operands but expected only " + Twine(Expected) + "!");
1618 static void emitTooFewOperandsError(TreePattern &TP,
1621 TP.error("Instruction '" + InstName +
1622 "' expects more than the provided " + Twine(Actual) + " operands!");
1625 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1626 /// this node and its children in the tree. This returns true if it makes a
1627 /// change, false otherwise. If a type contradiction is found, flag an error.
1628 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1632 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1634 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1635 // If it's a regclass or something else known, include the type.
1636 bool MadeChange = false;
1637 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1638 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1640 !hasName(), TP), TP);
1644 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
1645 assert(Types.size() == 1 && "Invalid IntInit");
1647 // Int inits are always integers. :)
1648 bool MadeChange = Types[0].EnforceInteger(TP);
1650 if (!Types[0].isConcrete())
1653 MVT::SimpleValueType VT = getType(0);
1654 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1657 unsigned Size = MVT(VT).getSizeInBits();
1658 // Make sure that the value is representable for this type.
1659 if (Size >= 32) return MadeChange;
1661 // Check that the value doesn't use more bits than we have. It must either
1662 // be a sign- or zero-extended equivalent of the original.
1663 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1664 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1667 TP.error("Integer value '" + itostr(II->getValue()) +
1668 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1674 // special handling for set, which isn't really an SDNode.
1675 if (getOperator()->getName() == "set") {
1676 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1677 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1678 unsigned NC = getNumChildren();
1680 TreePatternNode *SetVal = getChild(NC-1);
1681 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1683 for (unsigned i = 0; i < NC-1; ++i) {
1684 TreePatternNode *Child = getChild(i);
1685 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1687 // Types of operands must match.
1688 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1689 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1694 if (getOperator()->getName() == "implicit") {
1695 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1697 bool MadeChange = false;
1698 for (unsigned i = 0; i < getNumChildren(); ++i)
1699 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1703 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1704 bool MadeChange = false;
1706 // Apply the result type to the node.
1707 unsigned NumRetVTs = Int->IS.RetVTs.size();
1708 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1710 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1711 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1713 if (getNumChildren() != NumParamVTs + 1) {
1714 TP.error("Intrinsic '" + Int->Name + "' expects " +
1715 utostr(NumParamVTs) + " operands, not " +
1716 utostr(getNumChildren() - 1) + " operands!");
1720 // Apply type info to the intrinsic ID.
1721 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1723 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1724 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1726 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1727 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1728 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1733 if (getOperator()->isSubClassOf("SDNode")) {
1734 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1736 // Check that the number of operands is sane. Negative operands -> varargs.
1737 if (NI.getNumOperands() >= 0 &&
1738 getNumChildren() != (unsigned)NI.getNumOperands()) {
1739 TP.error(getOperator()->getName() + " node requires exactly " +
1740 itostr(NI.getNumOperands()) + " operands!");
1744 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1745 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1746 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1750 if (getOperator()->isSubClassOf("Instruction")) {
1751 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1752 CodeGenInstruction &InstInfo =
1753 CDP.getTargetInfo().getInstruction(getOperator());
1755 bool MadeChange = false;
1757 // Apply the result types to the node, these come from the things in the
1758 // (outs) list of the instruction.
1759 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1760 Inst.getNumResults());
1761 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1762 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
1764 // If the instruction has implicit defs, we apply the first one as a result.
1765 // FIXME: This sucks, it should apply all implicit defs.
1766 if (!InstInfo.ImplicitDefs.empty()) {
1767 unsigned ResNo = NumResultsToAdd;
1769 // FIXME: Generalize to multiple possible types and multiple possible
1771 MVT::SimpleValueType VT =
1772 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1774 if (VT != MVT::Other)
1775 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1778 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1780 if (getOperator()->getName() == "INSERT_SUBREG") {
1781 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1782 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1783 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1784 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1785 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1788 unsigned NChild = getNumChildren();
1790 TP.error("REG_SEQUENCE requires at least 3 operands!");
1794 if (NChild % 2 == 0) {
1795 TP.error("REG_SEQUENCE requires an odd number of operands!");
1799 if (!isOperandClass(getChild(0), "RegisterClass")) {
1800 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1804 for (unsigned I = 1; I < NChild; I += 2) {
1805 TreePatternNode *SubIdxChild = getChild(I + 1);
1806 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1807 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1808 itostr(I + 1) + "!");
1814 unsigned ChildNo = 0;
1815 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1816 Record *OperandNode = Inst.getOperand(i);
1818 // If the instruction expects a predicate or optional def operand, we
1819 // codegen this by setting the operand to it's default value if it has a
1820 // non-empty DefaultOps field.
1821 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1822 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1825 // Verify that we didn't run out of provided operands.
1826 if (ChildNo >= getNumChildren()) {
1827 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
1831 TreePatternNode *Child = getChild(ChildNo++);
1832 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1834 // If the operand has sub-operands, they may be provided by distinct
1835 // child patterns, so attempt to match each sub-operand separately.
1836 if (OperandNode->isSubClassOf("Operand")) {
1837 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1838 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1839 // But don't do that if the whole operand is being provided by
1840 // a single ComplexPattern-related Operand.
1842 if (Child->getNumMIResults(CDP) < NumArgs) {
1843 // Match first sub-operand against the child we already have.
1844 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1846 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1848 // And the remaining sub-operands against subsequent children.
1849 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1850 if (ChildNo >= getNumChildren()) {
1851 emitTooFewOperandsError(TP, getOperator()->getName(),
1855 Child = getChild(ChildNo++);
1857 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1859 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1866 // If we didn't match by pieces above, attempt to match the whole
1868 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
1871 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
1872 emitTooManyOperandsError(TP, getOperator()->getName(),
1873 ChildNo, getNumChildren());
1877 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1878 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1882 if (getOperator()->isSubClassOf("ComplexPattern")) {
1883 bool MadeChange = false;
1885 for (unsigned i = 0; i < getNumChildren(); ++i)
1886 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1891 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1893 // Node transforms always take one operand.
1894 if (getNumChildren() != 1) {
1895 TP.error("Node transform '" + getOperator()->getName() +
1896 "' requires one operand!");
1900 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1903 // If either the output or input of the xform does not have exact
1904 // type info. We assume they must be the same. Otherwise, it is perfectly
1905 // legal to transform from one type to a completely different type.
1907 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1908 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1909 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1916 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1917 /// RHS of a commutative operation, not the on LHS.
1918 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1919 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1921 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
1927 /// canPatternMatch - If it is impossible for this pattern to match on this
1928 /// target, fill in Reason and return false. Otherwise, return true. This is
1929 /// used as a sanity check for .td files (to prevent people from writing stuff
1930 /// that can never possibly work), and to prevent the pattern permuter from
1931 /// generating stuff that is useless.
1932 bool TreePatternNode::canPatternMatch(std::string &Reason,
1933 const CodeGenDAGPatterns &CDP) {
1934 if (isLeaf()) return true;
1936 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1937 if (!getChild(i)->canPatternMatch(Reason, CDP))
1940 // If this is an intrinsic, handle cases that would make it not match. For
1941 // example, if an operand is required to be an immediate.
1942 if (getOperator()->isSubClassOf("Intrinsic")) {
1947 if (getOperator()->isSubClassOf("ComplexPattern"))
1950 // If this node is a commutative operator, check that the LHS isn't an
1952 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1953 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1954 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1955 // Scan all of the operands of the node and make sure that only the last one
1956 // is a constant node, unless the RHS also is.
1957 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1958 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1959 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1960 if (OnlyOnRHSOfCommutative(getChild(i))) {
1961 Reason="Immediate value must be on the RHS of commutative operators!";
1970 //===----------------------------------------------------------------------===//
1971 // TreePattern implementation
1974 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1975 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1976 isInputPattern(isInput), HasError(false) {
1977 for (Init *I : RawPat->getValues())
1978 Trees.push_back(ParseTreePattern(I, ""));
1981 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1982 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1983 isInputPattern(isInput), HasError(false) {
1984 Trees.push_back(ParseTreePattern(Pat, ""));
1987 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1988 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1989 isInputPattern(isInput), HasError(false) {
1990 Trees.push_back(Pat);
1993 void TreePattern::error(const Twine &Msg) {
1997 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2001 void TreePattern::ComputeNamedNodes() {
2002 for (TreePatternNode *Tree : Trees)
2003 ComputeNamedNodes(Tree);
2006 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2007 if (!N->getName().empty())
2008 NamedNodes[N->getName()].push_back(N);
2010 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2011 ComputeNamedNodes(N->getChild(i));
2015 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2016 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2017 Record *R = DI->getDef();
2019 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2020 // TreePatternNode of its own. For example:
2021 /// (foo GPR, imm) -> (foo GPR, (imm))
2022 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2023 return ParseTreePattern(
2024 DagInit::get(DI, "",
2025 std::vector<std::pair<Init*, std::string> >()),
2029 TreePatternNode *Res = new TreePatternNode(DI, 1);
2030 if (R->getName() == "node" && !OpName.empty()) {
2032 error("'node' argument requires a name to match with operand list");
2033 Args.push_back(OpName);
2036 Res->setName(OpName);
2040 // ?:$name or just $name.
2041 if (isa<UnsetInit>(TheInit)) {
2043 error("'?' argument requires a name to match with operand list");
2044 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2045 Args.push_back(OpName);
2046 Res->setName(OpName);
2050 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2051 if (!OpName.empty())
2052 error("Constant int argument should not have a name!");
2053 return new TreePatternNode(II, 1);
2056 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2057 // Turn this into an IntInit.
2058 Init *II = BI->convertInitializerTo(IntRecTy::get());
2059 if (!II || !isa<IntInit>(II))
2060 error("Bits value must be constants!");
2061 return ParseTreePattern(II, OpName);
2064 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2067 error("Pattern has unexpected init kind!");
2069 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2070 if (!OpDef) error("Pattern has unexpected operator type!");
2071 Record *Operator = OpDef->getDef();
2073 if (Operator->isSubClassOf("ValueType")) {
2074 // If the operator is a ValueType, then this must be "type cast" of a leaf
2076 if (Dag->getNumArgs() != 1)
2077 error("Type cast only takes one operand!");
2079 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
2081 // Apply the type cast.
2082 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2083 New->UpdateNodeType(0, getValueType(Operator), *this);
2085 if (!OpName.empty())
2086 error("ValueType cast should not have a name!");
2090 // Verify that this is something that makes sense for an operator.
2091 if (!Operator->isSubClassOf("PatFrag") &&
2092 !Operator->isSubClassOf("SDNode") &&
2093 !Operator->isSubClassOf("Instruction") &&
2094 !Operator->isSubClassOf("SDNodeXForm") &&
2095 !Operator->isSubClassOf("Intrinsic") &&
2096 !Operator->isSubClassOf("ComplexPattern") &&
2097 Operator->getName() != "set" &&
2098 Operator->getName() != "implicit")
2099 error("Unrecognized node '" + Operator->getName() + "'!");
2101 // Check to see if this is something that is illegal in an input pattern.
2102 if (isInputPattern) {
2103 if (Operator->isSubClassOf("Instruction") ||
2104 Operator->isSubClassOf("SDNodeXForm"))
2105 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2107 if (Operator->isSubClassOf("Intrinsic"))
2108 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2110 if (Operator->isSubClassOf("SDNode") &&
2111 Operator->getName() != "imm" &&
2112 Operator->getName() != "fpimm" &&
2113 Operator->getName() != "tglobaltlsaddr" &&
2114 Operator->getName() != "tconstpool" &&
2115 Operator->getName() != "tjumptable" &&
2116 Operator->getName() != "tframeindex" &&
2117 Operator->getName() != "texternalsym" &&
2118 Operator->getName() != "tblockaddress" &&
2119 Operator->getName() != "tglobaladdr" &&
2120 Operator->getName() != "bb" &&
2121 Operator->getName() != "vt" &&
2122 Operator->getName() != "mcsym")
2123 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2126 std::vector<TreePatternNode*> Children;
2128 // Parse all the operands.
2129 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2130 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
2132 // If the operator is an intrinsic, then this is just syntactic sugar for for
2133 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2134 // convert the intrinsic name to a number.
2135 if (Operator->isSubClassOf("Intrinsic")) {
2136 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2137 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2139 // If this intrinsic returns void, it must have side-effects and thus a
2141 if (Int.IS.RetVTs.empty())
2142 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2143 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2144 // Has side-effects, requires chain.
2145 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2146 else // Otherwise, no chain.
2147 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2149 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2150 Children.insert(Children.begin(), IIDNode);
2153 if (Operator->isSubClassOf("ComplexPattern")) {
2154 for (unsigned i = 0; i < Children.size(); ++i) {
2155 TreePatternNode *Child = Children[i];
2157 if (Child->getName().empty())
2158 error("All arguments to a ComplexPattern must be named");
2160 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2161 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2162 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2163 auto OperandId = std::make_pair(Operator, i);
2164 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2165 if (PrevOp != ComplexPatternOperands.end()) {
2166 if (PrevOp->getValue() != OperandId)
2167 error("All ComplexPattern operands must appear consistently: "
2168 "in the same order in just one ComplexPattern instance.");
2170 ComplexPatternOperands[Child->getName()] = OperandId;
2174 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2175 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2176 Result->setName(OpName);
2178 if (!Dag->getName().empty()) {
2179 assert(Result->getName().empty());
2180 Result->setName(Dag->getName());
2185 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2186 /// will never match in favor of something obvious that will. This is here
2187 /// strictly as a convenience to target authors because it allows them to write
2188 /// more type generic things and have useless type casts fold away.
2190 /// This returns true if any change is made.
2191 static bool SimplifyTree(TreePatternNode *&N) {
2195 // If we have a bitconvert with a resolved type and if the source and
2196 // destination types are the same, then the bitconvert is useless, remove it.
2197 if (N->getOperator()->getName() == "bitconvert" &&
2198 N->getExtType(0).isConcrete() &&
2199 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2200 N->getName().empty()) {
2206 // Walk all children.
2207 bool MadeChange = false;
2208 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2209 TreePatternNode *Child = N->getChild(i);
2210 MadeChange |= SimplifyTree(Child);
2211 N->setChild(i, Child);
2218 /// InferAllTypes - Infer/propagate as many types throughout the expression
2219 /// patterns as possible. Return true if all types are inferred, false
2220 /// otherwise. Flags an error if a type contradiction is found.
2222 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2223 if (NamedNodes.empty())
2224 ComputeNamedNodes();
2226 bool MadeChange = true;
2227 while (MadeChange) {
2229 for (TreePatternNode *Tree : Trees) {
2230 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2231 MadeChange |= SimplifyTree(Tree);
2234 // If there are constraints on our named nodes, apply them.
2235 for (auto &Entry : NamedNodes) {
2236 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2238 // If we have input named node types, propagate their types to the named
2241 if (!InNamedTypes->count(Entry.getKey())) {
2242 error("Node '" + std::string(Entry.getKey()) +
2243 "' in output pattern but not input pattern");
2247 const SmallVectorImpl<TreePatternNode*> &InNodes =
2248 InNamedTypes->find(Entry.getKey())->second;
2250 // The input types should be fully resolved by now.
2251 for (TreePatternNode *Node : Nodes) {
2252 // If this node is a register class, and it is the root of the pattern
2253 // then we're mapping something onto an input register. We allow
2254 // changing the type of the input register in this case. This allows
2255 // us to match things like:
2256 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2257 if (Node == Trees[0] && Node->isLeaf()) {
2258 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
2259 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2260 DI->getDef()->isSubClassOf("RegisterOperand")))
2264 assert(Node->getNumTypes() == 1 &&
2265 InNodes[0]->getNumTypes() == 1 &&
2266 "FIXME: cannot name multiple result nodes yet");
2267 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2272 // If there are multiple nodes with the same name, they must all have the
2274 if (Entry.second.size() > 1) {
2275 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2276 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2277 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2278 "FIXME: cannot name multiple result nodes yet");
2280 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2281 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2287 bool HasUnresolvedTypes = false;
2288 for (const TreePatternNode *Tree : Trees)
2289 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
2290 return !HasUnresolvedTypes;
2293 void TreePattern::print(raw_ostream &OS) const {
2294 OS << getRecord()->getName();
2295 if (!Args.empty()) {
2296 OS << "(" << Args[0];
2297 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2298 OS << ", " << Args[i];
2303 if (Trees.size() > 1)
2305 for (const TreePatternNode *Tree : Trees) {
2311 if (Trees.size() > 1)
2315 void TreePattern::dump() const { print(errs()); }
2317 //===----------------------------------------------------------------------===//
2318 // CodeGenDAGPatterns implementation
2321 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2322 Records(R), Target(R) {
2324 Intrinsics = LoadIntrinsics(Records, false);
2325 TgtIntrinsics = LoadIntrinsics(Records, true);
2327 ParseNodeTransforms();
2328 ParseComplexPatterns();
2329 ParsePatternFragments();
2330 ParseDefaultOperands();
2331 ParseInstructions();
2332 ParsePatternFragments(/*OutFrags*/true);
2335 // Generate variants. For example, commutative patterns can match
2336 // multiple ways. Add them to PatternsToMatch as well.
2339 // Infer instruction flags. For example, we can detect loads,
2340 // stores, and side effects in many cases by examining an
2341 // instruction's pattern.
2342 InferInstructionFlags();
2344 // Verify that instruction flags match the patterns.
2345 VerifyInstructionFlags();
2348 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2349 Record *N = Records.getDef(Name);
2350 if (!N || !N->isSubClassOf("SDNode"))
2351 PrintFatalError("Error getting SDNode '" + Name + "'!");
2356 // Parse all of the SDNode definitions for the target, populating SDNodes.
2357 void CodeGenDAGPatterns::ParseNodeInfo() {
2358 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2359 while (!Nodes.empty()) {
2360 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2364 // Get the builtin intrinsic nodes.
2365 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2366 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2367 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2370 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2371 /// map, and emit them to the file as functions.
2372 void CodeGenDAGPatterns::ParseNodeTransforms() {
2373 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2374 while (!Xforms.empty()) {
2375 Record *XFormNode = Xforms.back();
2376 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2377 std::string Code = XFormNode->getValueAsString("XFormFunction");
2378 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2384 void CodeGenDAGPatterns::ParseComplexPatterns() {
2385 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2386 while (!AMs.empty()) {
2387 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2393 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2394 /// file, building up the PatternFragments map. After we've collected them all,
2395 /// inline fragments together as necessary, so that there are no references left
2396 /// inside a pattern fragment to a pattern fragment.
2398 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2399 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2401 // First step, parse all of the fragments.
2402 for (Record *Frag : Fragments) {
2403 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2406 DagInit *Tree = Frag->getValueAsDag("Fragment");
2408 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2409 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
2412 // Validate the argument list, converting it to set, to discard duplicates.
2413 std::vector<std::string> &Args = P->getArgList();
2414 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2416 if (OperandsSet.count(""))
2417 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2419 // Parse the operands list.
2420 DagInit *OpsList = Frag->getValueAsDag("Operands");
2421 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2422 // Special cases: ops == outs == ins. Different names are used to
2423 // improve readability.
2425 (OpsOp->getDef()->getName() != "ops" &&
2426 OpsOp->getDef()->getName() != "outs" &&
2427 OpsOp->getDef()->getName() != "ins"))
2428 P->error("Operands list should start with '(ops ... '!");
2430 // Copy over the arguments.
2432 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2433 if (!isa<DefInit>(OpsList->getArg(j)) ||
2434 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2435 P->error("Operands list should all be 'node' values.");
2436 if (OpsList->getArgName(j).empty())
2437 P->error("Operands list should have names for each operand!");
2438 if (!OperandsSet.count(OpsList->getArgName(j)))
2439 P->error("'" + OpsList->getArgName(j) +
2440 "' does not occur in pattern or was multiply specified!");
2441 OperandsSet.erase(OpsList->getArgName(j));
2442 Args.push_back(OpsList->getArgName(j));
2445 if (!OperandsSet.empty())
2446 P->error("Operands list does not contain an entry for operand '" +
2447 *OperandsSet.begin() + "'!");
2449 // If there is a code init for this fragment, keep track of the fact that
2450 // this fragment uses it.
2451 TreePredicateFn PredFn(P);
2452 if (!PredFn.isAlwaysTrue())
2453 P->getOnlyTree()->addPredicateFn(PredFn);
2455 // If there is a node transformation corresponding to this, keep track of
2457 Record *Transform = Frag->getValueAsDef("OperandTransform");
2458 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2459 P->getOnlyTree()->setTransformFn(Transform);
2462 // Now that we've parsed all of the tree fragments, do a closure on them so
2463 // that there are not references to PatFrags left inside of them.
2464 for (Record *Frag : Fragments) {
2465 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2468 TreePattern &ThePat = *PatternFragments[Frag];
2469 ThePat.InlinePatternFragments();
2471 // Infer as many types as possible. Don't worry about it if we don't infer
2472 // all of them, some may depend on the inputs of the pattern.
2473 ThePat.InferAllTypes();
2474 ThePat.resetError();
2476 // If debugging, print out the pattern fragment result.
2477 DEBUG(ThePat.dump());
2481 void CodeGenDAGPatterns::ParseDefaultOperands() {
2482 std::vector<Record*> DefaultOps;
2483 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2485 // Find some SDNode.
2486 assert(!SDNodes.empty() && "No SDNodes parsed?");
2487 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2489 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2490 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
2492 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2493 // SomeSDnode so that we can parse this.
2494 std::vector<std::pair<Init*, std::string> > Ops;
2495 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2496 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2497 DefaultInfo->getArgName(op)));
2498 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
2500 // Create a TreePattern to parse this.
2501 TreePattern P(DefaultOps[i], DI, false, *this);
2502 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2504 // Copy the operands over into a DAGDefaultOperand.
2505 DAGDefaultOperand DefaultOpInfo;
2507 TreePatternNode *T = P.getTree(0);
2508 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2509 TreePatternNode *TPN = T->getChild(op);
2510 while (TPN->ApplyTypeConstraints(P, false))
2511 /* Resolve all types */;
2513 if (TPN->ContainsUnresolvedType()) {
2514 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2515 DefaultOps[i]->getName() +
2516 "' doesn't have a concrete type!");
2518 DefaultOpInfo.DefaultOps.push_back(TPN);
2521 // Insert it into the DefaultOperands map so we can find it later.
2522 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
2526 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2527 /// instruction input. Return true if this is a real use.
2528 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2529 std::map<std::string, TreePatternNode*> &InstInputs) {
2530 // No name -> not interesting.
2531 if (Pat->getName().empty()) {
2532 if (Pat->isLeaf()) {
2533 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2534 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2535 DI->getDef()->isSubClassOf("RegisterOperand")))
2536 I->error("Input " + DI->getDef()->getName() + " must be named!");
2542 if (Pat->isLeaf()) {
2543 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2544 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2547 Rec = Pat->getOperator();
2550 // SRCVALUE nodes are ignored.
2551 if (Rec->getName() == "srcvalue")
2554 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2560 if (Slot->isLeaf()) {
2561 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
2563 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2564 SlotRec = Slot->getOperator();
2567 // Ensure that the inputs agree if we've already seen this input.
2569 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2570 if (Slot->getExtTypes() != Pat->getExtTypes())
2571 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2575 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2576 /// part of "I", the instruction), computing the set of inputs and outputs of
2577 /// the pattern. Report errors if we see anything naughty.
2578 void CodeGenDAGPatterns::
2579 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2580 std::map<std::string, TreePatternNode*> &InstInputs,
2581 std::map<std::string, TreePatternNode*>&InstResults,
2582 std::vector<Record*> &InstImpResults) {
2583 if (Pat->isLeaf()) {
2584 bool isUse = HandleUse(I, Pat, InstInputs);
2585 if (!isUse && Pat->getTransformFn())
2586 I->error("Cannot specify a transform function for a non-input value!");
2590 if (Pat->getOperator()->getName() == "implicit") {
2591 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2592 TreePatternNode *Dest = Pat->getChild(i);
2593 if (!Dest->isLeaf())
2594 I->error("implicitly defined value should be a register!");
2596 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2597 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2598 I->error("implicitly defined value should be a register!");
2599 InstImpResults.push_back(Val->getDef());
2604 if (Pat->getOperator()->getName() != "set") {
2605 // If this is not a set, verify that the children nodes are not void typed,
2607 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2608 if (Pat->getChild(i)->getNumTypes() == 0)
2609 I->error("Cannot have void nodes inside of patterns!");
2610 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2614 // If this is a non-leaf node with no children, treat it basically as if
2615 // it were a leaf. This handles nodes like (imm).
2616 bool isUse = HandleUse(I, Pat, InstInputs);
2618 if (!isUse && Pat->getTransformFn())
2619 I->error("Cannot specify a transform function for a non-input value!");
2623 // Otherwise, this is a set, validate and collect instruction results.
2624 if (Pat->getNumChildren() == 0)
2625 I->error("set requires operands!");
2627 if (Pat->getTransformFn())
2628 I->error("Cannot specify a transform function on a set node!");
2630 // Check the set destinations.
2631 unsigned NumDests = Pat->getNumChildren()-1;
2632 for (unsigned i = 0; i != NumDests; ++i) {
2633 TreePatternNode *Dest = Pat->getChild(i);
2634 if (!Dest->isLeaf())
2635 I->error("set destination should be a register!");
2637 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2639 I->error("set destination should be a register!");
2643 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2644 Val->getDef()->isSubClassOf("ValueType") ||
2645 Val->getDef()->isSubClassOf("RegisterOperand") ||
2646 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2647 if (Dest->getName().empty())
2648 I->error("set destination must have a name!");
2649 if (InstResults.count(Dest->getName()))
2650 I->error("cannot set '" + Dest->getName() +"' multiple times");
2651 InstResults[Dest->getName()] = Dest;
2652 } else if (Val->getDef()->isSubClassOf("Register")) {
2653 InstImpResults.push_back(Val->getDef());
2655 I->error("set destination should be a register!");
2659 // Verify and collect info from the computation.
2660 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2661 InstInputs, InstResults, InstImpResults);
2664 //===----------------------------------------------------------------------===//
2665 // Instruction Analysis
2666 //===----------------------------------------------------------------------===//
2668 class InstAnalyzer {
2669 const CodeGenDAGPatterns &CDP;
2671 bool hasSideEffects;
2677 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2678 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2679 isBitcast(false), isVariadic(false) {}
2681 void Analyze(const TreePattern *Pat) {
2682 // Assume only the first tree is the pattern. The others are clobber nodes.
2683 AnalyzeNode(Pat->getTree(0));
2686 void Analyze(const PatternToMatch *Pat) {
2687 AnalyzeNode(Pat->getSrcPattern());
2691 bool IsNodeBitcast(const TreePatternNode *N) const {
2692 if (hasSideEffects || mayLoad || mayStore || isVariadic)
2695 if (N->getNumChildren() != 2)
2698 const TreePatternNode *N0 = N->getChild(0);
2699 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
2702 const TreePatternNode *N1 = N->getChild(1);
2705 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2708 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2709 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2711 return OpInfo.getEnumName() == "ISD::BITCAST";
2715 void AnalyzeNode(const TreePatternNode *N) {
2717 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
2718 Record *LeafRec = DI->getDef();
2719 // Handle ComplexPattern leaves.
2720 if (LeafRec->isSubClassOf("ComplexPattern")) {
2721 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2722 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2723 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2724 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2730 // Analyze children.
2731 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2732 AnalyzeNode(N->getChild(i));
2734 // Ignore set nodes, which are not SDNodes.
2735 if (N->getOperator()->getName() == "set") {
2736 isBitcast = IsNodeBitcast(N);
2740 // Notice properties of the node.
2741 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2742 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2743 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2744 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
2746 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2747 // If this is an intrinsic, analyze it.
2748 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2749 mayLoad = true;// These may load memory.
2751 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2752 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2754 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2755 // WriteMem intrinsics can have other strange effects.
2756 hasSideEffects = true;
2762 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2763 const InstAnalyzer &PatInfo,
2767 // Remember where InstInfo got its flags.
2768 if (InstInfo.hasUndefFlags())
2769 InstInfo.InferredFrom = PatDef;
2771 // Check explicitly set flags for consistency.
2772 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2773 !InstInfo.hasSideEffects_Unset) {
2774 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2775 // the pattern has no side effects. That could be useful for div/rem
2776 // instructions that may trap.
2777 if (!InstInfo.hasSideEffects) {
2779 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2780 Twine(InstInfo.hasSideEffects));
2784 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2786 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2787 Twine(InstInfo.mayStore));
2790 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2791 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2792 // Some targets translate immediates to loads.
2793 if (!InstInfo.mayLoad) {
2795 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2796 Twine(InstInfo.mayLoad));
2800 // Transfer inferred flags.
2801 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2802 InstInfo.mayStore |= PatInfo.mayStore;
2803 InstInfo.mayLoad |= PatInfo.mayLoad;
2805 // These flags are silently added without any verification.
2806 InstInfo.isBitcast |= PatInfo.isBitcast;
2808 // Don't infer isVariadic. This flag means something different on SDNodes and
2809 // instructions. For example, a CALL SDNode is variadic because it has the
2810 // call arguments as operands, but a CALL instruction is not variadic - it
2811 // has argument registers as implicit, not explicit uses.
2816 /// hasNullFragReference - Return true if the DAG has any reference to the
2817 /// null_frag operator.
2818 static bool hasNullFragReference(DagInit *DI) {
2819 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
2820 if (!OpDef) return false;
2821 Record *Operator = OpDef->getDef();
2823 // If this is the null fragment, return true.
2824 if (Operator->getName() == "null_frag") return true;
2825 // If any of the arguments reference the null fragment, return true.
2826 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2827 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
2828 if (Arg && hasNullFragReference(Arg))
2835 /// hasNullFragReference - Return true if any DAG in the list references
2836 /// the null_frag operator.
2837 static bool hasNullFragReference(ListInit *LI) {
2838 for (Init *I : LI->getValues()) {
2839 DagInit *DI = dyn_cast<DagInit>(I);
2840 assert(DI && "non-dag in an instruction Pattern list?!");
2841 if (hasNullFragReference(DI))
2847 /// Get all the instructions in a tree.
2849 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2852 if (Tree->getOperator()->isSubClassOf("Instruction"))
2853 Instrs.push_back(Tree->getOperator());
2854 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2855 getInstructionsInTree(Tree->getChild(i), Instrs);
2858 /// Check the class of a pattern leaf node against the instruction operand it
2860 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2865 // Allow direct value types to be used in instruction set patterns.
2866 // The type will be checked later.
2867 if (Leaf->isSubClassOf("ValueType"))
2870 // Patterns can also be ComplexPattern instances.
2871 if (Leaf->isSubClassOf("ComplexPattern"))
2877 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2878 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
2880 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
2882 // Parse the instruction.
2883 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2884 // Inline pattern fragments into it.
2885 I->InlinePatternFragments();
2887 // Infer as many types as possible. If we cannot infer all of them, we can
2888 // never do anything with this instruction pattern: report it to the user.
2889 if (!I->InferAllTypes())
2890 I->error("Could not infer all types in pattern!");
2892 // InstInputs - Keep track of all of the inputs of the instruction, along
2893 // with the record they are declared as.
2894 std::map<std::string, TreePatternNode*> InstInputs;
2896 // InstResults - Keep track of all the virtual registers that are 'set'
2897 // in the instruction, including what reg class they are.
2898 std::map<std::string, TreePatternNode*> InstResults;
2900 std::vector<Record*> InstImpResults;
2902 // Verify that the top-level forms in the instruction are of void type, and
2903 // fill in the InstResults map.
2904 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2905 TreePatternNode *Pat = I->getTree(j);
2906 if (Pat->getNumTypes() != 0)
2907 I->error("Top-level forms in instruction pattern should have"
2910 // Find inputs and outputs, and verify the structure of the uses/defs.
2911 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2915 // Now that we have inputs and outputs of the pattern, inspect the operands
2916 // list for the instruction. This determines the order that operands are
2917 // added to the machine instruction the node corresponds to.
2918 unsigned NumResults = InstResults.size();
2920 // Parse the operands list from the (ops) list, validating it.
2921 assert(I->getArgList().empty() && "Args list should still be empty here!");
2923 // Check that all of the results occur first in the list.
2924 std::vector<Record*> Results;
2925 SmallVector<TreePatternNode *, 2> ResNodes;
2926 for (unsigned i = 0; i != NumResults; ++i) {
2927 if (i == CGI.Operands.size())
2928 I->error("'" + InstResults.begin()->first +
2929 "' set but does not appear in operand list!");
2930 const std::string &OpName = CGI.Operands[i].Name;
2932 // Check that it exists in InstResults.
2933 TreePatternNode *RNode = InstResults[OpName];
2935 I->error("Operand $" + OpName + " does not exist in operand list!");
2937 ResNodes.push_back(RNode);
2939 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2941 I->error("Operand $" + OpName + " should be a set destination: all "
2942 "outputs must occur before inputs in operand list!");
2944 if (!checkOperandClass(CGI.Operands[i], R))
2945 I->error("Operand $" + OpName + " class mismatch!");
2947 // Remember the return type.
2948 Results.push_back(CGI.Operands[i].Rec);
2950 // Okay, this one checks out.
2951 InstResults.erase(OpName);
2954 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2955 // the copy while we're checking the inputs.
2956 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2958 std::vector<TreePatternNode*> ResultNodeOperands;
2959 std::vector<Record*> Operands;
2960 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2961 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2962 const std::string &OpName = Op.Name;
2964 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2966 if (!InstInputsCheck.count(OpName)) {
2967 // If this is an operand with a DefaultOps set filled in, we can ignore
2968 // this. When we codegen it, we will do so as always executed.
2969 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2970 // Does it have a non-empty DefaultOps field? If so, ignore this
2972 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2975 I->error("Operand $" + OpName +
2976 " does not appear in the instruction pattern");
2978 TreePatternNode *InVal = InstInputsCheck[OpName];
2979 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2981 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
2982 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2983 if (!checkOperandClass(Op, InRec))
2984 I->error("Operand $" + OpName + "'s register class disagrees"
2985 " between the operand and pattern");
2987 Operands.push_back(Op.Rec);
2989 // Construct the result for the dest-pattern operand list.
2990 TreePatternNode *OpNode = InVal->clone();
2992 // No predicate is useful on the result.
2993 OpNode->clearPredicateFns();
2995 // Promote the xform function to be an explicit node if set.
2996 if (Record *Xform = OpNode->getTransformFn()) {
2997 OpNode->setTransformFn(nullptr);
2998 std::vector<TreePatternNode*> Children;
2999 Children.push_back(OpNode);
3000 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3003 ResultNodeOperands.push_back(OpNode);
3006 if (!InstInputsCheck.empty())
3007 I->error("Input operand $" + InstInputsCheck.begin()->first +
3008 " occurs in pattern but not in operands list!");
3010 TreePatternNode *ResultPattern =
3011 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3012 GetNumNodeResults(I->getRecord(), *this));
3013 // Copy fully inferred output node types to instruction result pattern.
3014 for (unsigned i = 0; i != NumResults; ++i) {
3015 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3016 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3019 // Create and insert the instruction.
3020 // FIXME: InstImpResults should not be part of DAGInstruction.
3021 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3022 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3024 // Use a temporary tree pattern to infer all types and make sure that the
3025 // constructed result is correct. This depends on the instruction already
3026 // being inserted into the DAGInsts map.
3027 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3028 Temp.InferAllTypes(&I->getNamedNodesMap());
3030 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3031 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3033 return TheInsertedInst;
3036 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3037 /// any fragments involved. This populates the Instructions list with fully
3038 /// resolved instructions.
3039 void CodeGenDAGPatterns::ParseInstructions() {
3040 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3042 for (Record *Instr : Instrs) {
3043 ListInit *LI = nullptr;
3045 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3046 LI = Instr->getValueAsListInit("Pattern");
3048 // If there is no pattern, only collect minimal information about the
3049 // instruction for its operand list. We have to assume that there is one
3050 // result, as we have no detailed info. A pattern which references the
3051 // null_frag operator is as-if no pattern were specified. Normally this
3052 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3054 if (!LI || LI->empty() || hasNullFragReference(LI)) {
3055 std::vector<Record*> Results;
3056 std::vector<Record*> Operands;
3058 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3060 if (InstInfo.Operands.size() != 0) {
3061 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3062 Results.push_back(InstInfo.Operands[j].Rec);
3064 // The rest are inputs.
3065 for (unsigned j = InstInfo.Operands.NumDefs,
3066 e = InstInfo.Operands.size(); j < e; ++j)
3067 Operands.push_back(InstInfo.Operands[j].Rec);
3070 // Create and insert the instruction.
3071 std::vector<Record*> ImpResults;
3072 Instructions.insert(std::make_pair(Instr,
3073 DAGInstruction(nullptr, Results, Operands, ImpResults)));
3074 continue; // no pattern.
3077 CodeGenInstruction &CGI = Target.getInstruction(Instr);
3078 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3081 DEBUG(DI.getPattern()->dump());
3084 // If we can, convert the instructions to be patterns that are matched!
3085 for (auto &Entry : Instructions) {
3086 DAGInstruction &TheInst = Entry.second;
3087 TreePattern *I = TheInst.getPattern();
3088 if (!I) continue; // No pattern.
3090 // FIXME: Assume only the first tree is the pattern. The others are clobber
3092 TreePatternNode *Pattern = I->getTree(0);
3093 TreePatternNode *SrcPattern;
3094 if (Pattern->getOperator()->getName() == "set") {
3095 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3097 // Not a set (store or something?)
3098 SrcPattern = Pattern;
3101 Record *Instr = Entry.first;
3102 AddPatternToMatch(I,
3103 PatternToMatch(Instr,
3104 Instr->getValueAsListInit("Predicates"),
3106 TheInst.getResultPattern(),
3107 TheInst.getImpResults(),
3108 Instr->getValueAsInt("AddedComplexity"),
3114 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3116 static void FindNames(const TreePatternNode *P,
3117 std::map<std::string, NameRecord> &Names,
3118 TreePattern *PatternTop) {
3119 if (!P->getName().empty()) {
3120 NameRecord &Rec = Names[P->getName()];
3121 // If this is the first instance of the name, remember the node.
3122 if (Rec.second++ == 0)
3124 else if (Rec.first->getExtTypes() != P->getExtTypes())
3125 PatternTop->error("repetition of value: $" + P->getName() +
3126 " where different uses have different types!");
3130 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3131 FindNames(P->getChild(i), Names, PatternTop);
3135 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3136 const PatternToMatch &PTM) {
3137 // Do some sanity checking on the pattern we're about to match.
3139 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3140 PrintWarning(Pattern->getRecord()->getLoc(),
3141 Twine("Pattern can never match: ") + Reason);
3145 // If the source pattern's root is a complex pattern, that complex pattern
3146 // must specify the nodes it can potentially match.
3147 if (const ComplexPattern *CP =
3148 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3149 if (CP->getRootNodes().empty())
3150 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3154 // Find all of the named values in the input and output, ensure they have the
3156 std::map<std::string, NameRecord> SrcNames, DstNames;
3157 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3158 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3160 // Scan all of the named values in the destination pattern, rejecting them if
3161 // they don't exist in the input pattern.
3162 for (const auto &Entry : DstNames) {
3163 if (SrcNames[Entry.first].first == nullptr)
3164 Pattern->error("Pattern has input without matching name in output: $" +
3168 // Scan all of the named values in the source pattern, rejecting them if the
3169 // name isn't used in the dest, and isn't used to tie two values together.
3170 for (const auto &Entry : SrcNames)
3171 if (DstNames[Entry.first].first == nullptr &&
3172 SrcNames[Entry.first].second == 1)
3173 Pattern->error("Pattern has dead named input: $" + Entry.first);
3175 PatternsToMatch.push_back(PTM);
3180 void CodeGenDAGPatterns::InferInstructionFlags() {
3181 const std::vector<const CodeGenInstruction*> &Instructions =
3182 Target.getInstructionsByEnumValue();
3184 // First try to infer flags from the primary instruction pattern, if any.
3185 SmallVector<CodeGenInstruction*, 8> Revisit;
3186 unsigned Errors = 0;
3187 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3188 CodeGenInstruction &InstInfo =
3189 const_cast<CodeGenInstruction &>(*Instructions[i]);
3191 // Get the primary instruction pattern.
3192 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3194 if (InstInfo.hasUndefFlags())
3195 Revisit.push_back(&InstInfo);
3198 InstAnalyzer PatInfo(*this);
3199 PatInfo.Analyze(Pattern);
3200 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3203 // Second, look for single-instruction patterns defined outside the
3205 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3206 const PatternToMatch &PTM = *I;
3208 // We can only infer from single-instruction patterns, otherwise we won't
3209 // know which instruction should get the flags.
3210 SmallVector<Record*, 8> PatInstrs;
3211 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3212 if (PatInstrs.size() != 1)
3215 // Get the single instruction.
3216 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3218 // Only infer properties from the first pattern. We'll verify the others.
3219 if (InstInfo.InferredFrom)
3222 InstAnalyzer PatInfo(*this);
3223 PatInfo.Analyze(&PTM);
3224 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3228 PrintFatalError("pattern conflicts");
3230 // Revisit instructions with undefined flags and no pattern.
3231 if (Target.guessInstructionProperties()) {
3232 for (CodeGenInstruction *InstInfo : Revisit) {
3233 if (InstInfo->InferredFrom)
3235 // The mayLoad and mayStore flags default to false.
3236 // Conservatively assume hasSideEffects if it wasn't explicit.
3237 if (InstInfo->hasSideEffects_Unset)
3238 InstInfo->hasSideEffects = true;
3243 // Complain about any flags that are still undefined.
3244 for (CodeGenInstruction *InstInfo : Revisit) {
3245 if (InstInfo->InferredFrom)
3247 if (InstInfo->hasSideEffects_Unset)
3248 PrintError(InstInfo->TheDef->getLoc(),
3249 "Can't infer hasSideEffects from patterns");
3250 if (InstInfo->mayStore_Unset)
3251 PrintError(InstInfo->TheDef->getLoc(),
3252 "Can't infer mayStore from patterns");
3253 if (InstInfo->mayLoad_Unset)
3254 PrintError(InstInfo->TheDef->getLoc(),
3255 "Can't infer mayLoad from patterns");
3260 /// Verify instruction flags against pattern node properties.
3261 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3262 unsigned Errors = 0;
3263 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3264 const PatternToMatch &PTM = *I;
3265 SmallVector<Record*, 8> Instrs;
3266 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3270 // Count the number of instructions with each flag set.
3271 unsigned NumSideEffects = 0;
3272 unsigned NumStores = 0;
3273 unsigned NumLoads = 0;
3274 for (const Record *Instr : Instrs) {
3275 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3276 NumSideEffects += InstInfo.hasSideEffects;
3277 NumStores += InstInfo.mayStore;
3278 NumLoads += InstInfo.mayLoad;
3281 // Analyze the source pattern.
3282 InstAnalyzer PatInfo(*this);
3283 PatInfo.Analyze(&PTM);
3285 // Collect error messages.
3286 SmallVector<std::string, 4> Msgs;
3288 // Check for missing flags in the output.
3289 // Permit extra flags for now at least.
3290 if (PatInfo.hasSideEffects && !NumSideEffects)
3291 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3293 // Don't verify store flags on instructions with side effects. At least for
3294 // intrinsics, side effects implies mayStore.
3295 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3296 Msgs.push_back("pattern may store, but mayStore isn't set");
3298 // Similarly, mayStore implies mayLoad on intrinsics.
3299 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3300 Msgs.push_back("pattern may load, but mayLoad isn't set");
3302 // Print error messages.
3307 for (const std::string &Msg : Msgs)
3308 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
3309 (Instrs.size() == 1 ?
3310 "instruction" : "output instructions"));
3311 // Provide the location of the relevant instruction definitions.
3312 for (const Record *Instr : Instrs) {
3313 if (Instr != PTM.getSrcRecord())
3314 PrintError(Instr->getLoc(), "defined here");
3315 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3316 if (InstInfo.InferredFrom &&
3317 InstInfo.InferredFrom != InstInfo.TheDef &&
3318 InstInfo.InferredFrom != PTM.getSrcRecord())
3319 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3323 PrintFatalError("Errors in DAG patterns");
3326 /// Given a pattern result with an unresolved type, see if we can find one
3327 /// instruction with an unresolved result type. Force this result type to an
3328 /// arbitrary element if it's possible types to converge results.
3329 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3333 // Analyze children.
3334 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3335 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3338 if (!N->getOperator()->isSubClassOf("Instruction"))
3341 // If this type is already concrete or completely unknown we can't do
3343 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3344 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3347 // Otherwise, force its type to the first possibility (an arbitrary choice).
3348 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3355 void CodeGenDAGPatterns::ParsePatterns() {
3356 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3358 for (Record *CurPattern : Patterns) {
3359 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3361 // If the pattern references the null_frag, there's nothing to do.
3362 if (hasNullFragReference(Tree))
3365 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3367 // Inline pattern fragments into it.
3368 Pattern->InlinePatternFragments();
3370 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3371 if (LI->empty()) continue; // no pattern.
3373 // Parse the instruction.
3374 TreePattern Result(CurPattern, LI, false, *this);
3376 // Inline pattern fragments into it.
3377 Result.InlinePatternFragments();
3379 if (Result.getNumTrees() != 1)
3380 Result.error("Cannot handle instructions producing instructions "
3381 "with temporaries yet!");
3383 bool IterateInference;
3384 bool InferredAllPatternTypes, InferredAllResultTypes;
3386 // Infer as many types as possible. If we cannot infer all of them, we
3387 // can never do anything with this pattern: report it to the user.
3388 InferredAllPatternTypes =
3389 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3391 // Infer as many types as possible. If we cannot infer all of them, we
3392 // can never do anything with this pattern: report it to the user.
3393 InferredAllResultTypes =
3394 Result.InferAllTypes(&Pattern->getNamedNodesMap());
3396 IterateInference = false;
3398 // Apply the type of the result to the source pattern. This helps us
3399 // resolve cases where the input type is known to be a pointer type (which
3400 // is considered resolved), but the result knows it needs to be 32- or
3401 // 64-bits. Infer the other way for good measure.
3402 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3403 Pattern->getTree(0)->getNumTypes());
3405 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3406 i, Result.getTree(0)->getExtType(i), Result);
3407 IterateInference |= Result.getTree(0)->UpdateNodeType(
3408 i, Pattern->getTree(0)->getExtType(i), Result);
3411 // If our iteration has converged and the input pattern's types are fully
3412 // resolved but the result pattern is not fully resolved, we may have a
3413 // situation where we have two instructions in the result pattern and
3414 // the instructions require a common register class, but don't care about
3415 // what actual MVT is used. This is actually a bug in our modelling:
3416 // output patterns should have register classes, not MVTs.
3418 // In any case, to handle this, we just go through and disambiguate some
3419 // arbitrary types to the result pattern's nodes.
3420 if (!IterateInference && InferredAllPatternTypes &&
3421 !InferredAllResultTypes)
3423 ForceArbitraryInstResultType(Result.getTree(0), Result);
3424 } while (IterateInference);
3426 // Verify that we inferred enough types that we can do something with the
3427 // pattern and result. If these fire the user has to add type casts.
3428 if (!InferredAllPatternTypes)
3429 Pattern->error("Could not infer all types in pattern!");
3430 if (!InferredAllResultTypes) {
3432 Result.error("Could not infer all types in pattern result!");
3435 // Validate that the input pattern is correct.
3436 std::map<std::string, TreePatternNode*> InstInputs;
3437 std::map<std::string, TreePatternNode*> InstResults;
3438 std::vector<Record*> InstImpResults;
3439 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3440 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3441 InstInputs, InstResults,
3444 // Promote the xform function to be an explicit node if set.
3445 TreePatternNode *DstPattern = Result.getOnlyTree();
3446 std::vector<TreePatternNode*> ResultNodeOperands;
3447 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3448 TreePatternNode *OpNode = DstPattern->getChild(ii);
3449 if (Record *Xform = OpNode->getTransformFn()) {
3450 OpNode->setTransformFn(nullptr);
3451 std::vector<TreePatternNode*> Children;
3452 Children.push_back(OpNode);
3453 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3455 ResultNodeOperands.push_back(OpNode);
3457 DstPattern = Result.getOnlyTree();
3458 if (!DstPattern->isLeaf())
3459 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3461 DstPattern->getNumTypes());
3463 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3464 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3466 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
3467 Temp.InferAllTypes();
3470 AddPatternToMatch(Pattern,
3471 PatternToMatch(CurPattern,
3472 CurPattern->getValueAsListInit("Predicates"),
3473 Pattern->getTree(0),
3474 Temp.getOnlyTree(), InstImpResults,
3475 CurPattern->getValueAsInt("AddedComplexity"),
3476 CurPattern->getID()));
3480 /// CombineChildVariants - Given a bunch of permutations of each child of the
3481 /// 'operator' node, put them together in all possible ways.
3482 static void CombineChildVariants(TreePatternNode *Orig,
3483 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3484 std::vector<TreePatternNode*> &OutVariants,
3485 CodeGenDAGPatterns &CDP,
3486 const MultipleUseVarSet &DepVars) {
3487 // Make sure that each operand has at least one variant to choose from.
3488 for (const auto &Variants : ChildVariants)
3489 if (Variants.empty())
3492 // The end result is an all-pairs construction of the resultant pattern.
3493 std::vector<unsigned> Idxs;
3494 Idxs.resize(ChildVariants.size());
3498 DEBUG(if (!Idxs.empty()) {
3499 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3500 for (unsigned Idx : Idxs) {
3501 errs() << Idx << " ";
3506 // Create the variant and add it to the output list.
3507 std::vector<TreePatternNode*> NewChildren;
3508 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3509 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3510 auto R = llvm::make_unique<TreePatternNode>(
3511 Orig->getOperator(), NewChildren, Orig->getNumTypes());
3513 // Copy over properties.
3514 R->setName(Orig->getName());
3515 R->setPredicateFns(Orig->getPredicateFns());
3516 R->setTransformFn(Orig->getTransformFn());
3517 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3518 R->setType(i, Orig->getExtType(i));
3520 // If this pattern cannot match, do not include it as a variant.
3521 std::string ErrString;
3522 // Scan to see if this pattern has already been emitted. We can get
3523 // duplication due to things like commuting:
3524 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3525 // which are the same pattern. Ignore the dups.
3526 if (R->canPatternMatch(ErrString, CDP) &&
3527 std::none_of(OutVariants.begin(), OutVariants.end(),
3528 [&](TreePatternNode *Variant) {
3529 return R->isIsomorphicTo(Variant, DepVars);
3531 OutVariants.push_back(R.release());
3533 // Increment indices to the next permutation by incrementing the
3534 // indices from last index backward, e.g., generate the sequence
3535 // [0, 0], [0, 1], [1, 0], [1, 1].
3537 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3538 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3543 NotDone = (IdxsIdx >= 0);
3547 /// CombineChildVariants - A helper function for binary operators.
3549 static void CombineChildVariants(TreePatternNode *Orig,
3550 const std::vector<TreePatternNode*> &LHS,
3551 const std::vector<TreePatternNode*> &RHS,
3552 std::vector<TreePatternNode*> &OutVariants,
3553 CodeGenDAGPatterns &CDP,
3554 const MultipleUseVarSet &DepVars) {
3555 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3556 ChildVariants.push_back(LHS);
3557 ChildVariants.push_back(RHS);
3558 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3562 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3563 std::vector<TreePatternNode *> &Children) {
3564 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3565 Record *Operator = N->getOperator();
3567 // Only permit raw nodes.
3568 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3569 N->getTransformFn()) {
3570 Children.push_back(N);
3574 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3575 Children.push_back(N->getChild(0));
3577 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3579 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3580 Children.push_back(N->getChild(1));
3582 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3585 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3586 /// the (potentially recursive) pattern by using algebraic laws.
3588 static void GenerateVariantsOf(TreePatternNode *N,
3589 std::vector<TreePatternNode*> &OutVariants,
3590 CodeGenDAGPatterns &CDP,
3591 const MultipleUseVarSet &DepVars) {
3592 // We cannot permute leaves or ComplexPattern uses.
3593 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
3594 OutVariants.push_back(N);
3598 // Look up interesting info about the node.
3599 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3601 // If this node is associative, re-associate.
3602 if (NodeInfo.hasProperty(SDNPAssociative)) {
3603 // Re-associate by pulling together all of the linked operators
3604 std::vector<TreePatternNode*> MaximalChildren;
3605 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3607 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3609 if (MaximalChildren.size() == 3) {
3610 // Find the variants of all of our maximal children.
3611 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3612 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3613 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3614 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3616 // There are only two ways we can permute the tree:
3617 // (A op B) op C and A op (B op C)
3618 // Within these forms, we can also permute A/B/C.
3620 // Generate legal pair permutations of A/B/C.
3621 std::vector<TreePatternNode*> ABVariants;
3622 std::vector<TreePatternNode*> BAVariants;
3623 std::vector<TreePatternNode*> ACVariants;
3624 std::vector<TreePatternNode*> CAVariants;
3625 std::vector<TreePatternNode*> BCVariants;
3626 std::vector<TreePatternNode*> CBVariants;
3627 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3628 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3629 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3630 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3631 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3632 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3634 // Combine those into the result: (x op x) op x
3635 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3636 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3637 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3638 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3639 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3640 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3642 // Combine those into the result: x op (x op x)
3643 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3644 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3645 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3646 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3647 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3648 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3653 // Compute permutations of all children.
3654 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3655 ChildVariants.resize(N->getNumChildren());
3656 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3657 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3659 // Build all permutations based on how the children were formed.
3660 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3662 // If this node is commutative, consider the commuted order.
3663 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3664 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3665 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3666 "Commutative but doesn't have 2 children!");
3667 // Don't count children which are actually register references.
3669 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3670 TreePatternNode *Child = N->getChild(i);
3671 if (Child->isLeaf())
3672 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
3673 Record *RR = DI->getDef();
3674 if (RR->isSubClassOf("Register"))
3679 // Consider the commuted order.
3680 if (isCommIntrinsic) {
3681 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3682 // operands are the commutative operands, and there might be more operands
3685 "Commutative intrinsic should have at least 3 children!");
3686 std::vector<std::vector<TreePatternNode*> > Variants;
3687 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3688 Variants.push_back(ChildVariants[2]);
3689 Variants.push_back(ChildVariants[1]);
3690 for (unsigned i = 3; i != NC; ++i)
3691 Variants.push_back(ChildVariants[i]);
3692 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3694 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3695 OutVariants, CDP, DepVars);
3700 // GenerateVariants - Generate variants. For example, commutative patterns can
3701 // match multiple ways. Add them to PatternsToMatch as well.
3702 void CodeGenDAGPatterns::GenerateVariants() {
3703 DEBUG(errs() << "Generating instruction variants.\n");
3705 // Loop over all of the patterns we've collected, checking to see if we can
3706 // generate variants of the instruction, through the exploitation of
3707 // identities. This permits the target to provide aggressive matching without
3708 // the .td file having to contain tons of variants of instructions.
3710 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3711 // intentionally do not reconsider these. Any variants of added patterns have
3712 // already been added.
3714 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3715 MultipleUseVarSet DepVars;
3716 std::vector<TreePatternNode*> Variants;
3717 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3718 DEBUG(errs() << "Dependent/multiply used variables: ");
3719 DEBUG(DumpDepVars(DepVars));
3720 DEBUG(errs() << "\n");
3721 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3724 assert(!Variants.empty() && "Must create at least original variant!");
3725 Variants.erase(Variants.begin()); // Remove the original pattern.
3727 if (Variants.empty()) // No variants for this pattern.
3730 DEBUG(errs() << "FOUND VARIANTS OF: ";
3731 PatternsToMatch[i].getSrcPattern()->dump();
3734 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3735 TreePatternNode *Variant = Variants[v];
3737 DEBUG(errs() << " VAR#" << v << ": ";
3741 // Scan to see if an instruction or explicit pattern already matches this.
3742 bool AlreadyExists = false;
3743 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3744 // Skip if the top level predicates do not match.
3745 if (PatternsToMatch[i].getPredicates() !=
3746 PatternsToMatch[p].getPredicates())
3748 // Check to see if this variant already exists.
3749 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3751 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3752 AlreadyExists = true;
3756 // If we already have it, ignore the variant.
3757 if (AlreadyExists) continue;
3759 // Otherwise, add it to the list of patterns we have.
3760 PatternsToMatch.emplace_back(
3761 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3762 Variant, PatternsToMatch[i].getDstPattern(),
3763 PatternsToMatch[i].getDstRegs(),
3764 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
3767 DEBUG(errs() << "\n");