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();
485 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
488 // If the scalar type is known, filter out vector types whose element types
490 if (!VTOperand.isConcrete())
493 MVT::SimpleValueType VT = VTOperand.getConcrete();
495 TypeSet InputSet(*this);
497 // Filter out all the types which don't have the right element type.
498 for (unsigned i = 0; i != TypeVec.size(); ++i) {
499 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
500 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
501 TypeVec.erase(TypeVec.begin()+i--);
506 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
507 TP.error("Type inference contradiction found, forcing '" +
508 InputSet.getName() + "' to have a vector element");
514 /// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
515 /// vector type specified by VTOperand.
516 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
521 // "This" must be a vector and "VTOperand" must be a vector.
522 bool MadeChange = false;
523 MadeChange |= EnforceVector(TP);
524 MadeChange |= VTOperand.EnforceVector(TP);
526 // If one side is known to be integer or known to be FP but the other side has
527 // no information, get at least the type integrality info in there.
528 if (!hasFloatingPointTypes())
529 MadeChange |= VTOperand.EnforceInteger(TP);
530 else if (!hasIntegerTypes())
531 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
532 if (!VTOperand.hasFloatingPointTypes())
533 MadeChange |= EnforceInteger(TP);
534 else if (!VTOperand.hasIntegerTypes())
535 MadeChange |= EnforceFloatingPoint(TP);
537 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
538 "Should have a type list now");
540 // If we know the vector type, it forces the scalar types to agree.
541 // Also force one vector to have more elements than the other.
543 MVT IVT = getConcrete();
544 unsigned NumElems = IVT.getVectorNumElements();
545 IVT = IVT.getVectorElementType();
547 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
548 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
550 // Only keep types that have less elements than VTOperand.
551 TypeSet InputSet(VTOperand);
553 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
554 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
555 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
556 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
560 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
561 TP.error("Type inference contradiction found, forcing '" +
562 InputSet.getName() + "' to have less vector elements than '" +
566 } else if (VTOperand.isConcrete()) {
567 MVT IVT = VTOperand.getConcrete();
568 unsigned NumElems = IVT.getVectorNumElements();
569 IVT = IVT.getVectorElementType();
571 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
572 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
574 // Only keep types that have more elements than 'this'.
575 TypeSet InputSet(*this);
577 for (unsigned i = 0; i != TypeVec.size(); ++i) {
578 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
579 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
580 TypeVec.erase(TypeVec.begin()+i--);
584 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
585 TP.error("Type inference contradiction found, forcing '" +
586 InputSet.getName() + "' to have more vector elements than '" +
587 VTOperand.getName() + "'");
595 /// EnforceVectorSameNumElts - 'this' is now constrained to
596 /// be a vector with same num elements as VTOperand.
597 bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
602 // "This" must be a vector and "VTOperand" must be a vector.
603 bool MadeChange = false;
604 MadeChange |= EnforceVector(TP);
605 MadeChange |= VTOperand.EnforceVector(TP);
607 // If we know one of the vector types, it forces the other type to agree.
609 MVT IVT = getConcrete();
610 unsigned NumElems = IVT.getVectorNumElements();
612 // Only keep types that have same elements as VTOperand.
613 TypeSet InputSet(VTOperand);
615 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
616 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
617 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
618 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
622 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
623 TP.error("Type inference contradiction found, forcing '" +
624 InputSet.getName() + "' to have same number elements as '" +
628 } else if (VTOperand.isConcrete()) {
629 MVT IVT = VTOperand.getConcrete();
630 unsigned NumElems = IVT.getVectorNumElements();
632 // Only keep types that have same elements as 'this'.
633 TypeSet InputSet(*this);
635 for (unsigned i = 0; i != TypeVec.size(); ++i) {
636 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
637 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
638 TypeVec.erase(TypeVec.begin()+i--);
642 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
643 TP.error("Type inference contradiction found, forcing '" +
644 InputSet.getName() + "' to have same number elements than '" +
645 VTOperand.getName() + "'");
653 //===----------------------------------------------------------------------===//
654 // Helpers for working with extended types.
656 /// Dependent variable map for CodeGenDAGPattern variant generation
657 typedef std::map<std::string, int> DepVarMap;
659 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
661 if (isa<DefInit>(N->getLeafValue()))
662 DepMap[N->getName()]++;
664 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
665 FindDepVarsOf(N->getChild(i), DepMap);
669 /// Find dependent variables within child patterns
670 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
672 FindDepVarsOf(N, depcounts);
673 for (const std::pair<std::string, int> &Pair : depcounts) {
675 DepVars.insert(Pair.first);
680 /// Dump the dependent variable set:
681 static void DumpDepVars(MultipleUseVarSet &DepVars) {
682 if (DepVars.empty()) {
683 DEBUG(errs() << "<empty set>");
685 DEBUG(errs() << "[ ");
686 for (const std::string &DepVar : DepVars) {
687 DEBUG(errs() << DepVar << " ");
689 DEBUG(errs() << "]");
695 //===----------------------------------------------------------------------===//
696 // TreePredicateFn Implementation
697 //===----------------------------------------------------------------------===//
699 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
700 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
701 assert((getPredCode().empty() || getImmCode().empty()) &&
702 ".td file corrupt: can't have a node predicate *and* an imm predicate");
705 std::string TreePredicateFn::getPredCode() const {
706 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
709 std::string TreePredicateFn::getImmCode() const {
710 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
714 /// isAlwaysTrue - Return true if this is a noop predicate.
715 bool TreePredicateFn::isAlwaysTrue() const {
716 return getPredCode().empty() && getImmCode().empty();
719 /// Return the name to use in the generated code to reference this, this is
720 /// "Predicate_foo" if from a pattern fragment "foo".
721 std::string TreePredicateFn::getFnName() const {
722 return "Predicate_" + PatFragRec->getRecord()->getName();
725 /// getCodeToRunOnSDNode - Return the code for the function body that
726 /// evaluates this predicate. The argument is expected to be in "Node",
727 /// not N. This handles casting and conversion to a concrete node type as
729 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
730 // Handle immediate predicates first.
731 std::string ImmCode = getImmCode();
732 if (!ImmCode.empty()) {
734 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
735 return Result + ImmCode;
738 // Handle arbitrary node predicates.
739 assert(!getPredCode().empty() && "Don't have any predicate code!");
740 std::string ClassName;
741 if (PatFragRec->getOnlyTree()->isLeaf())
742 ClassName = "SDNode";
744 Record *Op = PatFragRec->getOnlyTree()->getOperator();
745 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
748 if (ClassName == "SDNode")
749 Result = " SDNode *N = Node;\n";
751 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
753 return Result + getPredCode();
756 //===----------------------------------------------------------------------===//
757 // PatternToMatch implementation
761 /// getPatternSize - Return the 'size' of this pattern. We want to match large
762 /// patterns before small ones. This is used to determine the size of a
764 static unsigned getPatternSize(const TreePatternNode *P,
765 const CodeGenDAGPatterns &CGP) {
766 unsigned Size = 3; // The node itself.
767 // If the root node is a ConstantSDNode, increases its size.
768 // e.g. (set R32:$dst, 0).
769 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
772 // FIXME: This is a hack to statically increase the priority of patterns
773 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
774 // Later we can allow complexity / cost for each pattern to be (optionally)
775 // specified. To get best possible pattern match we'll need to dynamically
776 // calculate the complexity of all patterns a dag can potentially map to.
777 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
779 Size += AM->getNumOperands() * 3;
781 // We don't want to count any children twice, so return early.
785 // If this node has some predicate function that must match, it adds to the
786 // complexity of this node.
787 if (!P->getPredicateFns().empty())
790 // Count children in the count if they are also nodes.
791 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
792 TreePatternNode *Child = P->getChild(i);
793 if (!Child->isLeaf() && Child->getNumTypes() &&
794 Child->getType(0) != MVT::Other)
795 Size += getPatternSize(Child, CGP);
796 else if (Child->isLeaf()) {
797 if (isa<IntInit>(Child->getLeafValue()))
798 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
799 else if (Child->getComplexPatternInfo(CGP))
800 Size += getPatternSize(Child, CGP);
801 else if (!Child->getPredicateFns().empty())
809 /// Compute the complexity metric for the input pattern. This roughly
810 /// corresponds to the number of nodes that are covered.
812 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
813 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
817 /// getPredicateCheck - Return a single string containing all of this
818 /// pattern's predicates concatenated with "&&" operators.
820 std::string PatternToMatch::getPredicateCheck() const {
821 std::string PredicateCheck;
822 for (Init *I : Predicates->getValues()) {
823 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
824 Record *Def = Pred->getDef();
825 if (!Def->isSubClassOf("Predicate")) {
829 llvm_unreachable("Unknown predicate type!");
831 if (!PredicateCheck.empty())
832 PredicateCheck += " && ";
833 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
837 return PredicateCheck;
840 //===----------------------------------------------------------------------===//
841 // SDTypeConstraint implementation
844 SDTypeConstraint::SDTypeConstraint(Record *R) {
845 OperandNo = R->getValueAsInt("OperandNum");
847 if (R->isSubClassOf("SDTCisVT")) {
848 ConstraintType = SDTCisVT;
849 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
850 if (x.SDTCisVT_Info.VT == MVT::isVoid)
851 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
853 } else if (R->isSubClassOf("SDTCisPtrTy")) {
854 ConstraintType = SDTCisPtrTy;
855 } else if (R->isSubClassOf("SDTCisInt")) {
856 ConstraintType = SDTCisInt;
857 } else if (R->isSubClassOf("SDTCisFP")) {
858 ConstraintType = SDTCisFP;
859 } else if (R->isSubClassOf("SDTCisVec")) {
860 ConstraintType = SDTCisVec;
861 } else if (R->isSubClassOf("SDTCisSameAs")) {
862 ConstraintType = SDTCisSameAs;
863 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
864 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
865 ConstraintType = SDTCisVTSmallerThanOp;
866 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
867 R->getValueAsInt("OtherOperandNum");
868 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
869 ConstraintType = SDTCisOpSmallerThanOp;
870 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
871 R->getValueAsInt("BigOperandNum");
872 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
873 ConstraintType = SDTCisEltOfVec;
874 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
875 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
876 ConstraintType = SDTCisSubVecOfVec;
877 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
878 R->getValueAsInt("OtherOpNum");
879 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
880 ConstraintType = SDTCVecEltisVT;
881 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
882 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
883 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
884 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
885 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
886 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
887 "as SDTCVecEltisVT");
888 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
889 ConstraintType = SDTCisSameNumEltsAs;
890 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
891 R->getValueAsInt("OtherOperandNum");
893 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
897 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
898 /// N, and the result number in ResNo.
899 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
900 const SDNodeInfo &NodeInfo,
902 unsigned NumResults = NodeInfo.getNumResults();
903 if (OpNo < NumResults) {
910 if (OpNo >= N->getNumChildren()) {
912 raw_string_ostream OS(S);
913 OS << "Invalid operand number in type constraint "
914 << (OpNo+NumResults) << " ";
916 PrintFatalError(OS.str());
919 return N->getChild(OpNo);
922 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
923 /// constraint to the nodes operands. This returns true if it makes a
924 /// change, false otherwise. If a type contradiction is found, flag an error.
925 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
926 const SDNodeInfo &NodeInfo,
927 TreePattern &TP) const {
931 unsigned ResNo = 0; // The result number being referenced.
932 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
934 switch (ConstraintType) {
936 // Operand must be a particular type.
937 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
939 // Operand must be same as target pointer type.
940 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
942 // Require it to be one of the legal integer VTs.
943 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
945 // Require it to be one of the legal fp VTs.
946 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
948 // Require it to be one of the legal vector VTs.
949 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
952 TreePatternNode *OtherNode =
953 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
954 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
955 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
957 case SDTCisVTSmallerThanOp: {
958 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
959 // have an integer type that is smaller than the VT.
960 if (!NodeToApply->isLeaf() ||
961 !isa<DefInit>(NodeToApply->getLeafValue()) ||
962 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
963 ->isSubClassOf("ValueType")) {
964 TP.error(N->getOperator()->getName() + " expects a VT operand!");
967 MVT::SimpleValueType VT =
968 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
970 EEVT::TypeSet TypeListTmp(VT, TP);
973 TreePatternNode *OtherNode =
974 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
977 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
979 case SDTCisOpSmallerThanOp: {
981 TreePatternNode *BigOperand =
982 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
984 return NodeToApply->getExtType(ResNo).
985 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
987 case SDTCisEltOfVec: {
989 TreePatternNode *VecOperand =
990 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
993 // Filter vector types out of VecOperand that don't have the right element
995 return VecOperand->getExtType(VResNo).
996 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
998 case SDTCisSubVecOfVec: {
1000 TreePatternNode *BigVecOperand =
1001 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1004 // Filter vector types out of BigVecOperand that don't have the
1005 // right subvector type.
1006 return BigVecOperand->getExtType(VResNo).
1007 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1009 case SDTCVecEltisVT: {
1010 return NodeToApply->getExtType(ResNo).
1011 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1013 case SDTCisSameNumEltsAs: {
1014 unsigned OResNo = 0;
1015 TreePatternNode *OtherNode =
1016 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1017 N, NodeInfo, OResNo);
1018 return OtherNode->getExtType(OResNo).
1019 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1022 llvm_unreachable("Invalid ConstraintType!");
1025 // Update the node type to match an instruction operand or result as specified
1026 // in the ins or outs lists on the instruction definition. Return true if the
1027 // type was actually changed.
1028 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1031 // The 'unknown' operand indicates that types should be inferred from the
1033 if (Operand->isSubClassOf("unknown_class"))
1036 // The Operand class specifies a type directly.
1037 if (Operand->isSubClassOf("Operand"))
1038 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1041 // PointerLikeRegClass has a type that is determined at runtime.
1042 if (Operand->isSubClassOf("PointerLikeRegClass"))
1043 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1045 // Both RegisterClass and RegisterOperand operands derive their types from a
1046 // register class def.
1047 Record *RC = nullptr;
1048 if (Operand->isSubClassOf("RegisterClass"))
1050 else if (Operand->isSubClassOf("RegisterOperand"))
1051 RC = Operand->getValueAsDef("RegClass");
1053 assert(RC && "Unknown operand type");
1054 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1055 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1059 //===----------------------------------------------------------------------===//
1060 // SDNodeInfo implementation
1062 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1063 EnumName = R->getValueAsString("Opcode");
1064 SDClassName = R->getValueAsString("SDClass");
1065 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1066 NumResults = TypeProfile->getValueAsInt("NumResults");
1067 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1069 // Parse the properties.
1071 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1072 if (Property->getName() == "SDNPCommutative") {
1073 Properties |= 1 << SDNPCommutative;
1074 } else if (Property->getName() == "SDNPAssociative") {
1075 Properties |= 1 << SDNPAssociative;
1076 } else if (Property->getName() == "SDNPHasChain") {
1077 Properties |= 1 << SDNPHasChain;
1078 } else if (Property->getName() == "SDNPOutGlue") {
1079 Properties |= 1 << SDNPOutGlue;
1080 } else if (Property->getName() == "SDNPInGlue") {
1081 Properties |= 1 << SDNPInGlue;
1082 } else if (Property->getName() == "SDNPOptInGlue") {
1083 Properties |= 1 << SDNPOptInGlue;
1084 } else if (Property->getName() == "SDNPMayStore") {
1085 Properties |= 1 << SDNPMayStore;
1086 } else if (Property->getName() == "SDNPMayLoad") {
1087 Properties |= 1 << SDNPMayLoad;
1088 } else if (Property->getName() == "SDNPSideEffect") {
1089 Properties |= 1 << SDNPSideEffect;
1090 } else if (Property->getName() == "SDNPMemOperand") {
1091 Properties |= 1 << SDNPMemOperand;
1092 } else if (Property->getName() == "SDNPVariadic") {
1093 Properties |= 1 << SDNPVariadic;
1095 PrintFatalError("Unknown SD Node property '" +
1096 Property->getName() + "' on node '" +
1097 R->getName() + "'!");
1102 // Parse the type constraints.
1103 std::vector<Record*> ConstraintList =
1104 TypeProfile->getValueAsListOfDefs("Constraints");
1105 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1108 /// getKnownType - If the type constraints on this node imply a fixed type
1109 /// (e.g. all stores return void, etc), then return it as an
1110 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1111 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1112 unsigned NumResults = getNumResults();
1113 assert(NumResults <= 1 &&
1114 "We only work with nodes with zero or one result so far!");
1115 assert(ResNo == 0 && "Only handles single result nodes so far");
1117 for (const SDTypeConstraint &Constraint : TypeConstraints) {
1118 // Make sure that this applies to the correct node result.
1119 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1122 switch (Constraint.ConstraintType) {
1124 case SDTypeConstraint::SDTCisVT:
1125 return Constraint.x.SDTCisVT_Info.VT;
1126 case SDTypeConstraint::SDTCisPtrTy:
1133 //===----------------------------------------------------------------------===//
1134 // TreePatternNode implementation
1137 TreePatternNode::~TreePatternNode() {
1138 #if 0 // FIXME: implement refcounted tree nodes!
1139 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1144 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1145 if (Operator->getName() == "set" ||
1146 Operator->getName() == "implicit")
1147 return 0; // All return nothing.
1149 if (Operator->isSubClassOf("Intrinsic"))
1150 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1152 if (Operator->isSubClassOf("SDNode"))
1153 return CDP.getSDNodeInfo(Operator).getNumResults();
1155 if (Operator->isSubClassOf("PatFrag")) {
1156 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1157 // the forward reference case where one pattern fragment references another
1158 // before it is processed.
1159 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1160 return PFRec->getOnlyTree()->getNumTypes();
1162 // Get the result tree.
1163 DagInit *Tree = Operator->getValueAsDag("Fragment");
1164 Record *Op = nullptr;
1166 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1168 assert(Op && "Invalid Fragment");
1169 return GetNumNodeResults(Op, CDP);
1172 if (Operator->isSubClassOf("Instruction")) {
1173 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1175 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1177 // Subtract any defaulted outputs.
1178 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1179 Record *OperandNode = InstInfo.Operands[i].Rec;
1181 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1182 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1186 // Add on one implicit def if it has a resolvable type.
1187 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1189 return NumDefsToAdd;
1192 if (Operator->isSubClassOf("SDNodeXForm"))
1193 return 1; // FIXME: Generalize SDNodeXForm
1195 if (Operator->isSubClassOf("ValueType"))
1196 return 1; // A type-cast of one result.
1198 if (Operator->isSubClassOf("ComplexPattern"))
1202 PrintFatalError("Unhandled node in GetNumNodeResults");
1205 void TreePatternNode::print(raw_ostream &OS) const {
1207 OS << *getLeafValue();
1209 OS << '(' << getOperator()->getName();
1211 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1212 OS << ':' << getExtType(i).getName();
1215 if (getNumChildren() != 0) {
1217 getChild(0)->print(OS);
1218 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1220 getChild(i)->print(OS);
1226 for (const TreePredicateFn &Pred : PredicateFns)
1227 OS << "<<P:" << Pred.getFnName() << ">>";
1229 OS << "<<X:" << TransformFn->getName() << ">>";
1230 if (!getName().empty())
1231 OS << ":$" << getName();
1234 void TreePatternNode::dump() const {
1238 /// isIsomorphicTo - Return true if this node is recursively
1239 /// isomorphic to the specified node. For this comparison, the node's
1240 /// entire state is considered. The assigned name is ignored, since
1241 /// nodes with differing names are considered isomorphic. However, if
1242 /// the assigned name is present in the dependent variable set, then
1243 /// the assigned name is considered significant and the node is
1244 /// isomorphic if the names match.
1245 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1246 const MultipleUseVarSet &DepVars) const {
1247 if (N == this) return true;
1248 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1249 getPredicateFns() != N->getPredicateFns() ||
1250 getTransformFn() != N->getTransformFn())
1254 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1255 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1256 return ((DI->getDef() == NDI->getDef())
1257 && (DepVars.find(getName()) == DepVars.end()
1258 || getName() == N->getName()));
1261 return getLeafValue() == N->getLeafValue();
1264 if (N->getOperator() != getOperator() ||
1265 N->getNumChildren() != getNumChildren()) return false;
1266 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1267 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1272 /// clone - Make a copy of this tree and all of its children.
1274 TreePatternNode *TreePatternNode::clone() const {
1275 TreePatternNode *New;
1277 New = new TreePatternNode(getLeafValue(), getNumTypes());
1279 std::vector<TreePatternNode*> CChildren;
1280 CChildren.reserve(Children.size());
1281 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1282 CChildren.push_back(getChild(i)->clone());
1283 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1285 New->setName(getName());
1287 New->setPredicateFns(getPredicateFns());
1288 New->setTransformFn(getTransformFn());
1292 /// RemoveAllTypes - Recursively strip all the types of this tree.
1293 void TreePatternNode::RemoveAllTypes() {
1294 // Reset to unknown type.
1295 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
1296 if (isLeaf()) return;
1297 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1298 getChild(i)->RemoveAllTypes();
1302 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1303 /// with actual values specified by ArgMap.
1304 void TreePatternNode::
1305 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1306 if (isLeaf()) return;
1308 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1309 TreePatternNode *Child = getChild(i);
1310 if (Child->isLeaf()) {
1311 Init *Val = Child->getLeafValue();
1312 // Note that, when substituting into an output pattern, Val might be an
1314 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1315 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1316 // We found a use of a formal argument, replace it with its value.
1317 TreePatternNode *NewChild = ArgMap[Child->getName()];
1318 assert(NewChild && "Couldn't find formal argument!");
1319 assert((Child->getPredicateFns().empty() ||
1320 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1321 "Non-empty child predicate clobbered!");
1322 setChild(i, NewChild);
1325 getChild(i)->SubstituteFormalArguments(ArgMap);
1331 /// InlinePatternFragments - If this pattern refers to any pattern
1332 /// fragments, inline them into place, giving us a pattern without any
1333 /// PatFrag references.
1334 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1339 return this; // nothing to do.
1340 Record *Op = getOperator();
1342 if (!Op->isSubClassOf("PatFrag")) {
1343 // Just recursively inline children nodes.
1344 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1345 TreePatternNode *Child = getChild(i);
1346 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1348 assert((Child->getPredicateFns().empty() ||
1349 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1350 "Non-empty child predicate clobbered!");
1352 setChild(i, NewChild);
1357 // Otherwise, we found a reference to a fragment. First, look up its
1358 // TreePattern record.
1359 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1361 // Verify that we are passing the right number of operands.
1362 if (Frag->getNumArgs() != Children.size()) {
1363 TP.error("'" + Op->getName() + "' fragment requires " +
1364 utostr(Frag->getNumArgs()) + " operands!");
1368 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1370 TreePredicateFn PredFn(Frag);
1371 if (!PredFn.isAlwaysTrue())
1372 FragTree->addPredicateFn(PredFn);
1374 // Resolve formal arguments to their actual value.
1375 if (Frag->getNumArgs()) {
1376 // Compute the map of formal to actual arguments.
1377 std::map<std::string, TreePatternNode*> ArgMap;
1378 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1379 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1381 FragTree->SubstituteFormalArguments(ArgMap);
1384 FragTree->setName(getName());
1385 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1386 FragTree->UpdateNodeType(i, getExtType(i), TP);
1388 // Transfer in the old predicates.
1389 for (const TreePredicateFn &Pred : getPredicateFns())
1390 FragTree->addPredicateFn(Pred);
1392 // Get a new copy of this fragment to stitch into here.
1393 //delete this; // FIXME: implement refcounting!
1395 // The fragment we inlined could have recursive inlining that is needed. See
1396 // if there are any pattern fragments in it and inline them as needed.
1397 return FragTree->InlinePatternFragments(TP);
1400 /// getImplicitType - Check to see if the specified record has an implicit
1401 /// type which should be applied to it. This will infer the type of register
1402 /// references from the register file information, for example.
1404 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1405 /// the F8RC register class argument in:
1407 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
1409 /// When Unnamed is false, return the type of a named DAG operand such as the
1410 /// GPR:$src operand above.
1412 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1416 // Check to see if this is a register operand.
1417 if (R->isSubClassOf("RegisterOperand")) {
1418 assert(ResNo == 0 && "Regoperand ref only has one result!");
1420 return EEVT::TypeSet(); // Unknown.
1421 Record *RegClass = R->getValueAsDef("RegClass");
1422 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1423 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1426 // Check to see if this is a register or a register class.
1427 if (R->isSubClassOf("RegisterClass")) {
1428 assert(ResNo == 0 && "Regclass ref only has one result!");
1429 // An unnamed register class represents itself as an i32 immediate, for
1430 // example on a COPY_TO_REGCLASS instruction.
1432 return EEVT::TypeSet(MVT::i32, TP);
1434 // In a named operand, the register class provides the possible set of
1437 return EEVT::TypeSet(); // Unknown.
1438 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1439 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1442 if (R->isSubClassOf("PatFrag")) {
1443 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1444 // Pattern fragment types will be resolved when they are inlined.
1445 return EEVT::TypeSet(); // Unknown.
1448 if (R->isSubClassOf("Register")) {
1449 assert(ResNo == 0 && "Registers only produce one result!");
1451 return EEVT::TypeSet(); // Unknown.
1452 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1453 return EEVT::TypeSet(T.getRegisterVTs(R));
1456 if (R->isSubClassOf("SubRegIndex")) {
1457 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1458 return EEVT::TypeSet(MVT::i32, TP);
1461 if (R->isSubClassOf("ValueType")) {
1462 assert(ResNo == 0 && "This node only has one result!");
1463 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1465 // (sext_inreg GPR:$src, i16)
1468 return EEVT::TypeSet(MVT::Other, TP);
1469 // With a name, the ValueType simply provides the type of the named
1472 // (sext_inreg i32:$src, i16)
1475 return EEVT::TypeSet(); // Unknown.
1476 return EEVT::TypeSet(getValueType(R), TP);
1479 if (R->isSubClassOf("CondCode")) {
1480 assert(ResNo == 0 && "This node only has one result!");
1481 // Using a CondCodeSDNode.
1482 return EEVT::TypeSet(MVT::Other, TP);
1485 if (R->isSubClassOf("ComplexPattern")) {
1486 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1488 return EEVT::TypeSet(); // Unknown.
1489 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1492 if (R->isSubClassOf("PointerLikeRegClass")) {
1493 assert(ResNo == 0 && "Regclass can only have one result!");
1494 return EEVT::TypeSet(MVT::iPTR, TP);
1497 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1498 R->getName() == "zero_reg") {
1500 return EEVT::TypeSet(); // Unknown.
1503 if (R->isSubClassOf("Operand"))
1504 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1506 TP.error("Unknown node flavor used in pattern: " + R->getName());
1507 return EEVT::TypeSet(MVT::Other, TP);
1511 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1512 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1513 const CodeGenIntrinsic *TreePatternNode::
1514 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1515 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1516 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1517 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1520 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
1521 return &CDP.getIntrinsicInfo(IID);
1524 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1525 /// return the ComplexPattern information, otherwise return null.
1526 const ComplexPattern *
1527 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1530 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1535 Rec = getOperator();
1537 if (!Rec->isSubClassOf("ComplexPattern"))
1539 return &CGP.getComplexPattern(Rec);
1542 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1543 // A ComplexPattern specifically declares how many results it fills in.
1544 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1545 return CP->getNumOperands();
1547 // If MIOperandInfo is specified, that gives the count.
1549 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1550 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1551 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1552 if (MIOps->getNumArgs())
1553 return MIOps->getNumArgs();
1557 // Otherwise there is just one result.
1561 /// NodeHasProperty - Return true if this node has the specified property.
1562 bool TreePatternNode::NodeHasProperty(SDNP Property,
1563 const CodeGenDAGPatterns &CGP) const {
1565 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1566 return CP->hasProperty(Property);
1570 Record *Operator = getOperator();
1571 if (!Operator->isSubClassOf("SDNode")) return false;
1573 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1579 /// TreeHasProperty - Return true if any node in this tree has the specified
1581 bool TreePatternNode::TreeHasProperty(SDNP Property,
1582 const CodeGenDAGPatterns &CGP) const {
1583 if (NodeHasProperty(Property, CGP))
1585 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1586 if (getChild(i)->TreeHasProperty(Property, CGP))
1591 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1592 /// commutative intrinsic.
1594 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1595 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1596 return Int->isCommutative;
1600 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1602 return N->getOperator()->isSubClassOf(Class);
1604 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1605 if (DI && DI->getDef()->isSubClassOf(Class))
1611 static void emitTooManyOperandsError(TreePattern &TP,
1615 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1616 " operands but expected only " + Twine(Expected) + "!");
1619 static void emitTooFewOperandsError(TreePattern &TP,
1622 TP.error("Instruction '" + InstName +
1623 "' expects more than the provided " + Twine(Actual) + " operands!");
1626 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1627 /// this node and its children in the tree. This returns true if it makes a
1628 /// change, false otherwise. If a type contradiction is found, flag an error.
1629 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1633 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1635 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1636 // If it's a regclass or something else known, include the type.
1637 bool MadeChange = false;
1638 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1639 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1641 !hasName(), TP), TP);
1645 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
1646 assert(Types.size() == 1 && "Invalid IntInit");
1648 // Int inits are always integers. :)
1649 bool MadeChange = Types[0].EnforceInteger(TP);
1651 if (!Types[0].isConcrete())
1654 MVT::SimpleValueType VT = getType(0);
1655 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1658 unsigned Size = MVT(VT).getSizeInBits();
1659 // Make sure that the value is representable for this type.
1660 if (Size >= 32) return MadeChange;
1662 // Check that the value doesn't use more bits than we have. It must either
1663 // be a sign- or zero-extended equivalent of the original.
1664 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1665 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1668 TP.error("Integer value '" + itostr(II->getValue()) +
1669 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1675 // special handling for set, which isn't really an SDNode.
1676 if (getOperator()->getName() == "set") {
1677 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1678 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1679 unsigned NC = getNumChildren();
1681 TreePatternNode *SetVal = getChild(NC-1);
1682 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1684 for (unsigned i = 0; i < NC-1; ++i) {
1685 TreePatternNode *Child = getChild(i);
1686 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1688 // Types of operands must match.
1689 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1690 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1695 if (getOperator()->getName() == "implicit") {
1696 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1698 bool MadeChange = false;
1699 for (unsigned i = 0; i < getNumChildren(); ++i)
1700 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1704 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1705 bool MadeChange = false;
1707 // Apply the result type to the node.
1708 unsigned NumRetVTs = Int->IS.RetVTs.size();
1709 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1711 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1712 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1714 if (getNumChildren() != NumParamVTs + 1) {
1715 TP.error("Intrinsic '" + Int->Name + "' expects " +
1716 utostr(NumParamVTs) + " operands, not " +
1717 utostr(getNumChildren() - 1) + " operands!");
1721 // Apply type info to the intrinsic ID.
1722 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1724 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1725 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1727 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1728 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1729 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1734 if (getOperator()->isSubClassOf("SDNode")) {
1735 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1737 // Check that the number of operands is sane. Negative operands -> varargs.
1738 if (NI.getNumOperands() >= 0 &&
1739 getNumChildren() != (unsigned)NI.getNumOperands()) {
1740 TP.error(getOperator()->getName() + " node requires exactly " +
1741 itostr(NI.getNumOperands()) + " operands!");
1745 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1746 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1747 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1751 if (getOperator()->isSubClassOf("Instruction")) {
1752 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1753 CodeGenInstruction &InstInfo =
1754 CDP.getTargetInfo().getInstruction(getOperator());
1756 bool MadeChange = false;
1758 // Apply the result types to the node, these come from the things in the
1759 // (outs) list of the instruction.
1760 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1761 Inst.getNumResults());
1762 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1763 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
1765 // If the instruction has implicit defs, we apply the first one as a result.
1766 // FIXME: This sucks, it should apply all implicit defs.
1767 if (!InstInfo.ImplicitDefs.empty()) {
1768 unsigned ResNo = NumResultsToAdd;
1770 // FIXME: Generalize to multiple possible types and multiple possible
1772 MVT::SimpleValueType VT =
1773 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1775 if (VT != MVT::Other)
1776 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1779 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1781 if (getOperator()->getName() == "INSERT_SUBREG") {
1782 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1783 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1784 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1785 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1786 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1789 unsigned NChild = getNumChildren();
1791 TP.error("REG_SEQUENCE requires at least 3 operands!");
1795 if (NChild % 2 == 0) {
1796 TP.error("REG_SEQUENCE requires an odd number of operands!");
1800 if (!isOperandClass(getChild(0), "RegisterClass")) {
1801 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1805 for (unsigned I = 1; I < NChild; I += 2) {
1806 TreePatternNode *SubIdxChild = getChild(I + 1);
1807 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1808 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1809 itostr(I + 1) + "!");
1815 unsigned ChildNo = 0;
1816 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1817 Record *OperandNode = Inst.getOperand(i);
1819 // If the instruction expects a predicate or optional def operand, we
1820 // codegen this by setting the operand to it's default value if it has a
1821 // non-empty DefaultOps field.
1822 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1823 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1826 // Verify that we didn't run out of provided operands.
1827 if (ChildNo >= getNumChildren()) {
1828 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
1832 TreePatternNode *Child = getChild(ChildNo++);
1833 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1835 // If the operand has sub-operands, they may be provided by distinct
1836 // child patterns, so attempt to match each sub-operand separately.
1837 if (OperandNode->isSubClassOf("Operand")) {
1838 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1839 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1840 // But don't do that if the whole operand is being provided by
1841 // a single ComplexPattern-related Operand.
1843 if (Child->getNumMIResults(CDP) < NumArgs) {
1844 // Match first sub-operand against the child we already have.
1845 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1847 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1849 // And the remaining sub-operands against subsequent children.
1850 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1851 if (ChildNo >= getNumChildren()) {
1852 emitTooFewOperandsError(TP, getOperator()->getName(),
1856 Child = getChild(ChildNo++);
1858 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1860 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1867 // If we didn't match by pieces above, attempt to match the whole
1869 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
1872 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
1873 emitTooManyOperandsError(TP, getOperator()->getName(),
1874 ChildNo, getNumChildren());
1878 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1879 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1883 if (getOperator()->isSubClassOf("ComplexPattern")) {
1884 bool MadeChange = false;
1886 for (unsigned i = 0; i < getNumChildren(); ++i)
1887 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1892 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1894 // Node transforms always take one operand.
1895 if (getNumChildren() != 1) {
1896 TP.error("Node transform '" + getOperator()->getName() +
1897 "' requires one operand!");
1901 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1904 // If either the output or input of the xform does not have exact
1905 // type info. We assume they must be the same. Otherwise, it is perfectly
1906 // legal to transform from one type to a completely different type.
1908 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1909 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1910 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1917 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1918 /// RHS of a commutative operation, not the on LHS.
1919 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1920 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1922 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
1928 /// canPatternMatch - If it is impossible for this pattern to match on this
1929 /// target, fill in Reason and return false. Otherwise, return true. This is
1930 /// used as a sanity check for .td files (to prevent people from writing stuff
1931 /// that can never possibly work), and to prevent the pattern permuter from
1932 /// generating stuff that is useless.
1933 bool TreePatternNode::canPatternMatch(std::string &Reason,
1934 const CodeGenDAGPatterns &CDP) {
1935 if (isLeaf()) return true;
1937 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1938 if (!getChild(i)->canPatternMatch(Reason, CDP))
1941 // If this is an intrinsic, handle cases that would make it not match. For
1942 // example, if an operand is required to be an immediate.
1943 if (getOperator()->isSubClassOf("Intrinsic")) {
1948 if (getOperator()->isSubClassOf("ComplexPattern"))
1951 // If this node is a commutative operator, check that the LHS isn't an
1953 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1954 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1955 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1956 // Scan all of the operands of the node and make sure that only the last one
1957 // is a constant node, unless the RHS also is.
1958 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1959 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1960 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1961 if (OnlyOnRHSOfCommutative(getChild(i))) {
1962 Reason="Immediate value must be on the RHS of commutative operators!";
1971 //===----------------------------------------------------------------------===//
1972 // TreePattern implementation
1975 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1976 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1977 isInputPattern(isInput), HasError(false) {
1978 for (Init *I : RawPat->getValues())
1979 Trees.push_back(ParseTreePattern(I, ""));
1982 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1983 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1984 isInputPattern(isInput), HasError(false) {
1985 Trees.push_back(ParseTreePattern(Pat, ""));
1988 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1989 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1990 isInputPattern(isInput), HasError(false) {
1991 Trees.push_back(Pat);
1994 void TreePattern::error(const Twine &Msg) {
1998 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2002 void TreePattern::ComputeNamedNodes() {
2003 for (TreePatternNode *Tree : Trees)
2004 ComputeNamedNodes(Tree);
2007 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2008 if (!N->getName().empty())
2009 NamedNodes[N->getName()].push_back(N);
2011 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2012 ComputeNamedNodes(N->getChild(i));
2016 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2017 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2018 Record *R = DI->getDef();
2020 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2021 // TreePatternNode of its own. For example:
2022 /// (foo GPR, imm) -> (foo GPR, (imm))
2023 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2024 return ParseTreePattern(
2025 DagInit::get(DI, "",
2026 std::vector<std::pair<Init*, std::string> >()),
2030 TreePatternNode *Res = new TreePatternNode(DI, 1);
2031 if (R->getName() == "node" && !OpName.empty()) {
2033 error("'node' argument requires a name to match with operand list");
2034 Args.push_back(OpName);
2037 Res->setName(OpName);
2041 // ?:$name or just $name.
2042 if (isa<UnsetInit>(TheInit)) {
2044 error("'?' argument requires a name to match with operand list");
2045 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2046 Args.push_back(OpName);
2047 Res->setName(OpName);
2051 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2052 if (!OpName.empty())
2053 error("Constant int argument should not have a name!");
2054 return new TreePatternNode(II, 1);
2057 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2058 // Turn this into an IntInit.
2059 Init *II = BI->convertInitializerTo(IntRecTy::get());
2060 if (!II || !isa<IntInit>(II))
2061 error("Bits value must be constants!");
2062 return ParseTreePattern(II, OpName);
2065 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2068 error("Pattern has unexpected init kind!");
2070 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2071 if (!OpDef) error("Pattern has unexpected operator type!");
2072 Record *Operator = OpDef->getDef();
2074 if (Operator->isSubClassOf("ValueType")) {
2075 // If the operator is a ValueType, then this must be "type cast" of a leaf
2077 if (Dag->getNumArgs() != 1)
2078 error("Type cast only takes one operand!");
2080 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
2082 // Apply the type cast.
2083 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2084 New->UpdateNodeType(0, getValueType(Operator), *this);
2086 if (!OpName.empty())
2087 error("ValueType cast should not have a name!");
2091 // Verify that this is something that makes sense for an operator.
2092 if (!Operator->isSubClassOf("PatFrag") &&
2093 !Operator->isSubClassOf("SDNode") &&
2094 !Operator->isSubClassOf("Instruction") &&
2095 !Operator->isSubClassOf("SDNodeXForm") &&
2096 !Operator->isSubClassOf("Intrinsic") &&
2097 !Operator->isSubClassOf("ComplexPattern") &&
2098 Operator->getName() != "set" &&
2099 Operator->getName() != "implicit")
2100 error("Unrecognized node '" + Operator->getName() + "'!");
2102 // Check to see if this is something that is illegal in an input pattern.
2103 if (isInputPattern) {
2104 if (Operator->isSubClassOf("Instruction") ||
2105 Operator->isSubClassOf("SDNodeXForm"))
2106 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2108 if (Operator->isSubClassOf("Intrinsic"))
2109 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2111 if (Operator->isSubClassOf("SDNode") &&
2112 Operator->getName() != "imm" &&
2113 Operator->getName() != "fpimm" &&
2114 Operator->getName() != "tglobaltlsaddr" &&
2115 Operator->getName() != "tconstpool" &&
2116 Operator->getName() != "tjumptable" &&
2117 Operator->getName() != "tframeindex" &&
2118 Operator->getName() != "texternalsym" &&
2119 Operator->getName() != "tblockaddress" &&
2120 Operator->getName() != "tglobaladdr" &&
2121 Operator->getName() != "bb" &&
2122 Operator->getName() != "vt" &&
2123 Operator->getName() != "mcsym")
2124 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2127 std::vector<TreePatternNode*> Children;
2129 // Parse all the operands.
2130 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2131 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
2133 // If the operator is an intrinsic, then this is just syntactic sugar for for
2134 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2135 // convert the intrinsic name to a number.
2136 if (Operator->isSubClassOf("Intrinsic")) {
2137 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2138 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2140 // If this intrinsic returns void, it must have side-effects and thus a
2142 if (Int.IS.RetVTs.empty())
2143 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2144 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2145 // Has side-effects, requires chain.
2146 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2147 else // Otherwise, no chain.
2148 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2150 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2151 Children.insert(Children.begin(), IIDNode);
2154 if (Operator->isSubClassOf("ComplexPattern")) {
2155 for (unsigned i = 0; i < Children.size(); ++i) {
2156 TreePatternNode *Child = Children[i];
2158 if (Child->getName().empty())
2159 error("All arguments to a ComplexPattern must be named");
2161 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2162 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2163 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2164 auto OperandId = std::make_pair(Operator, i);
2165 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2166 if (PrevOp != ComplexPatternOperands.end()) {
2167 if (PrevOp->getValue() != OperandId)
2168 error("All ComplexPattern operands must appear consistently: "
2169 "in the same order in just one ComplexPattern instance.");
2171 ComplexPatternOperands[Child->getName()] = OperandId;
2175 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2176 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2177 Result->setName(OpName);
2179 if (!Dag->getName().empty()) {
2180 assert(Result->getName().empty());
2181 Result->setName(Dag->getName());
2186 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2187 /// will never match in favor of something obvious that will. This is here
2188 /// strictly as a convenience to target authors because it allows them to write
2189 /// more type generic things and have useless type casts fold away.
2191 /// This returns true if any change is made.
2192 static bool SimplifyTree(TreePatternNode *&N) {
2196 // If we have a bitconvert with a resolved type and if the source and
2197 // destination types are the same, then the bitconvert is useless, remove it.
2198 if (N->getOperator()->getName() == "bitconvert" &&
2199 N->getExtType(0).isConcrete() &&
2200 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2201 N->getName().empty()) {
2207 // Walk all children.
2208 bool MadeChange = false;
2209 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2210 TreePatternNode *Child = N->getChild(i);
2211 MadeChange |= SimplifyTree(Child);
2212 N->setChild(i, Child);
2219 /// InferAllTypes - Infer/propagate as many types throughout the expression
2220 /// patterns as possible. Return true if all types are inferred, false
2221 /// otherwise. Flags an error if a type contradiction is found.
2223 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2224 if (NamedNodes.empty())
2225 ComputeNamedNodes();
2227 bool MadeChange = true;
2228 while (MadeChange) {
2230 for (TreePatternNode *Tree : Trees) {
2231 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2232 MadeChange |= SimplifyTree(Tree);
2235 // If there are constraints on our named nodes, apply them.
2236 for (auto &Entry : NamedNodes) {
2237 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2239 // If we have input named node types, propagate their types to the named
2242 if (!InNamedTypes->count(Entry.getKey())) {
2243 error("Node '" + std::string(Entry.getKey()) +
2244 "' in output pattern but not input pattern");
2248 const SmallVectorImpl<TreePatternNode*> &InNodes =
2249 InNamedTypes->find(Entry.getKey())->second;
2251 // The input types should be fully resolved by now.
2252 for (TreePatternNode *Node : Nodes) {
2253 // If this node is a register class, and it is the root of the pattern
2254 // then we're mapping something onto an input register. We allow
2255 // changing the type of the input register in this case. This allows
2256 // us to match things like:
2257 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2258 if (Node == Trees[0] && Node->isLeaf()) {
2259 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
2260 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2261 DI->getDef()->isSubClassOf("RegisterOperand")))
2265 assert(Node->getNumTypes() == 1 &&
2266 InNodes[0]->getNumTypes() == 1 &&
2267 "FIXME: cannot name multiple result nodes yet");
2268 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2273 // If there are multiple nodes with the same name, they must all have the
2275 if (Entry.second.size() > 1) {
2276 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2277 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2278 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2279 "FIXME: cannot name multiple result nodes yet");
2281 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2282 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2288 bool HasUnresolvedTypes = false;
2289 for (const TreePatternNode *Tree : Trees)
2290 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
2291 return !HasUnresolvedTypes;
2294 void TreePattern::print(raw_ostream &OS) const {
2295 OS << getRecord()->getName();
2296 if (!Args.empty()) {
2297 OS << "(" << Args[0];
2298 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2299 OS << ", " << Args[i];
2304 if (Trees.size() > 1)
2306 for (const TreePatternNode *Tree : Trees) {
2312 if (Trees.size() > 1)
2316 void TreePattern::dump() const { print(errs()); }
2318 //===----------------------------------------------------------------------===//
2319 // CodeGenDAGPatterns implementation
2322 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2323 Records(R), Target(R) {
2325 Intrinsics = LoadIntrinsics(Records, false);
2326 TgtIntrinsics = LoadIntrinsics(Records, true);
2328 ParseNodeTransforms();
2329 ParseComplexPatterns();
2330 ParsePatternFragments();
2331 ParseDefaultOperands();
2332 ParseInstructions();
2333 ParsePatternFragments(/*OutFrags*/true);
2336 // Generate variants. For example, commutative patterns can match
2337 // multiple ways. Add them to PatternsToMatch as well.
2340 // Infer instruction flags. For example, we can detect loads,
2341 // stores, and side effects in many cases by examining an
2342 // instruction's pattern.
2343 InferInstructionFlags();
2345 // Verify that instruction flags match the patterns.
2346 VerifyInstructionFlags();
2349 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2350 Record *N = Records.getDef(Name);
2351 if (!N || !N->isSubClassOf("SDNode"))
2352 PrintFatalError("Error getting SDNode '" + Name + "'!");
2357 // Parse all of the SDNode definitions for the target, populating SDNodes.
2358 void CodeGenDAGPatterns::ParseNodeInfo() {
2359 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2360 while (!Nodes.empty()) {
2361 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2365 // Get the builtin intrinsic nodes.
2366 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2367 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2368 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2371 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2372 /// map, and emit them to the file as functions.
2373 void CodeGenDAGPatterns::ParseNodeTransforms() {
2374 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2375 while (!Xforms.empty()) {
2376 Record *XFormNode = Xforms.back();
2377 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2378 std::string Code = XFormNode->getValueAsString("XFormFunction");
2379 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2385 void CodeGenDAGPatterns::ParseComplexPatterns() {
2386 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2387 while (!AMs.empty()) {
2388 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2394 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2395 /// file, building up the PatternFragments map. After we've collected them all,
2396 /// inline fragments together as necessary, so that there are no references left
2397 /// inside a pattern fragment to a pattern fragment.
2399 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2400 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2402 // First step, parse all of the fragments.
2403 for (Record *Frag : Fragments) {
2404 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2407 DagInit *Tree = Frag->getValueAsDag("Fragment");
2409 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2410 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
2413 // Validate the argument list, converting it to set, to discard duplicates.
2414 std::vector<std::string> &Args = P->getArgList();
2415 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2417 if (OperandsSet.count(""))
2418 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2420 // Parse the operands list.
2421 DagInit *OpsList = Frag->getValueAsDag("Operands");
2422 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2423 // Special cases: ops == outs == ins. Different names are used to
2424 // improve readability.
2426 (OpsOp->getDef()->getName() != "ops" &&
2427 OpsOp->getDef()->getName() != "outs" &&
2428 OpsOp->getDef()->getName() != "ins"))
2429 P->error("Operands list should start with '(ops ... '!");
2431 // Copy over the arguments.
2433 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2434 if (!isa<DefInit>(OpsList->getArg(j)) ||
2435 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2436 P->error("Operands list should all be 'node' values.");
2437 if (OpsList->getArgName(j).empty())
2438 P->error("Operands list should have names for each operand!");
2439 if (!OperandsSet.count(OpsList->getArgName(j)))
2440 P->error("'" + OpsList->getArgName(j) +
2441 "' does not occur in pattern or was multiply specified!");
2442 OperandsSet.erase(OpsList->getArgName(j));
2443 Args.push_back(OpsList->getArgName(j));
2446 if (!OperandsSet.empty())
2447 P->error("Operands list does not contain an entry for operand '" +
2448 *OperandsSet.begin() + "'!");
2450 // If there is a code init for this fragment, keep track of the fact that
2451 // this fragment uses it.
2452 TreePredicateFn PredFn(P);
2453 if (!PredFn.isAlwaysTrue())
2454 P->getOnlyTree()->addPredicateFn(PredFn);
2456 // If there is a node transformation corresponding to this, keep track of
2458 Record *Transform = Frag->getValueAsDef("OperandTransform");
2459 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2460 P->getOnlyTree()->setTransformFn(Transform);
2463 // Now that we've parsed all of the tree fragments, do a closure on them so
2464 // that there are not references to PatFrags left inside of them.
2465 for (Record *Frag : Fragments) {
2466 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2469 TreePattern &ThePat = *PatternFragments[Frag];
2470 ThePat.InlinePatternFragments();
2472 // Infer as many types as possible. Don't worry about it if we don't infer
2473 // all of them, some may depend on the inputs of the pattern.
2474 ThePat.InferAllTypes();
2475 ThePat.resetError();
2477 // If debugging, print out the pattern fragment result.
2478 DEBUG(ThePat.dump());
2482 void CodeGenDAGPatterns::ParseDefaultOperands() {
2483 std::vector<Record*> DefaultOps;
2484 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2486 // Find some SDNode.
2487 assert(!SDNodes.empty() && "No SDNodes parsed?");
2488 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2490 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2491 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
2493 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2494 // SomeSDnode so that we can parse this.
2495 std::vector<std::pair<Init*, std::string> > Ops;
2496 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2497 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2498 DefaultInfo->getArgName(op)));
2499 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
2501 // Create a TreePattern to parse this.
2502 TreePattern P(DefaultOps[i], DI, false, *this);
2503 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2505 // Copy the operands over into a DAGDefaultOperand.
2506 DAGDefaultOperand DefaultOpInfo;
2508 TreePatternNode *T = P.getTree(0);
2509 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2510 TreePatternNode *TPN = T->getChild(op);
2511 while (TPN->ApplyTypeConstraints(P, false))
2512 /* Resolve all types */;
2514 if (TPN->ContainsUnresolvedType()) {
2515 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2516 DefaultOps[i]->getName() +
2517 "' doesn't have a concrete type!");
2519 DefaultOpInfo.DefaultOps.push_back(TPN);
2522 // Insert it into the DefaultOperands map so we can find it later.
2523 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
2527 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2528 /// instruction input. Return true if this is a real use.
2529 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2530 std::map<std::string, TreePatternNode*> &InstInputs) {
2531 // No name -> not interesting.
2532 if (Pat->getName().empty()) {
2533 if (Pat->isLeaf()) {
2534 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2535 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2536 DI->getDef()->isSubClassOf("RegisterOperand")))
2537 I->error("Input " + DI->getDef()->getName() + " must be named!");
2543 if (Pat->isLeaf()) {
2544 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2545 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2548 Rec = Pat->getOperator();
2551 // SRCVALUE nodes are ignored.
2552 if (Rec->getName() == "srcvalue")
2555 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2561 if (Slot->isLeaf()) {
2562 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
2564 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2565 SlotRec = Slot->getOperator();
2568 // Ensure that the inputs agree if we've already seen this input.
2570 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2571 if (Slot->getExtTypes() != Pat->getExtTypes())
2572 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2576 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2577 /// part of "I", the instruction), computing the set of inputs and outputs of
2578 /// the pattern. Report errors if we see anything naughty.
2579 void CodeGenDAGPatterns::
2580 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2581 std::map<std::string, TreePatternNode*> &InstInputs,
2582 std::map<std::string, TreePatternNode*>&InstResults,
2583 std::vector<Record*> &InstImpResults) {
2584 if (Pat->isLeaf()) {
2585 bool isUse = HandleUse(I, Pat, InstInputs);
2586 if (!isUse && Pat->getTransformFn())
2587 I->error("Cannot specify a transform function for a non-input value!");
2591 if (Pat->getOperator()->getName() == "implicit") {
2592 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2593 TreePatternNode *Dest = Pat->getChild(i);
2594 if (!Dest->isLeaf())
2595 I->error("implicitly defined value should be a register!");
2597 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2598 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2599 I->error("implicitly defined value should be a register!");
2600 InstImpResults.push_back(Val->getDef());
2605 if (Pat->getOperator()->getName() != "set") {
2606 // If this is not a set, verify that the children nodes are not void typed,
2608 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2609 if (Pat->getChild(i)->getNumTypes() == 0)
2610 I->error("Cannot have void nodes inside of patterns!");
2611 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2615 // If this is a non-leaf node with no children, treat it basically as if
2616 // it were a leaf. This handles nodes like (imm).
2617 bool isUse = HandleUse(I, Pat, InstInputs);
2619 if (!isUse && Pat->getTransformFn())
2620 I->error("Cannot specify a transform function for a non-input value!");
2624 // Otherwise, this is a set, validate and collect instruction results.
2625 if (Pat->getNumChildren() == 0)
2626 I->error("set requires operands!");
2628 if (Pat->getTransformFn())
2629 I->error("Cannot specify a transform function on a set node!");
2631 // Check the set destinations.
2632 unsigned NumDests = Pat->getNumChildren()-1;
2633 for (unsigned i = 0; i != NumDests; ++i) {
2634 TreePatternNode *Dest = Pat->getChild(i);
2635 if (!Dest->isLeaf())
2636 I->error("set destination should be a register!");
2638 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2640 I->error("set destination should be a register!");
2644 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2645 Val->getDef()->isSubClassOf("ValueType") ||
2646 Val->getDef()->isSubClassOf("RegisterOperand") ||
2647 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2648 if (Dest->getName().empty())
2649 I->error("set destination must have a name!");
2650 if (InstResults.count(Dest->getName()))
2651 I->error("cannot set '" + Dest->getName() +"' multiple times");
2652 InstResults[Dest->getName()] = Dest;
2653 } else if (Val->getDef()->isSubClassOf("Register")) {
2654 InstImpResults.push_back(Val->getDef());
2656 I->error("set destination should be a register!");
2660 // Verify and collect info from the computation.
2661 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2662 InstInputs, InstResults, InstImpResults);
2665 //===----------------------------------------------------------------------===//
2666 // Instruction Analysis
2667 //===----------------------------------------------------------------------===//
2669 class InstAnalyzer {
2670 const CodeGenDAGPatterns &CDP;
2672 bool hasSideEffects;
2678 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2679 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2680 isBitcast(false), isVariadic(false) {}
2682 void Analyze(const TreePattern *Pat) {
2683 // Assume only the first tree is the pattern. The others are clobber nodes.
2684 AnalyzeNode(Pat->getTree(0));
2687 void Analyze(const PatternToMatch *Pat) {
2688 AnalyzeNode(Pat->getSrcPattern());
2692 bool IsNodeBitcast(const TreePatternNode *N) const {
2693 if (hasSideEffects || mayLoad || mayStore || isVariadic)
2696 if (N->getNumChildren() != 2)
2699 const TreePatternNode *N0 = N->getChild(0);
2700 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
2703 const TreePatternNode *N1 = N->getChild(1);
2706 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2709 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2710 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2712 return OpInfo.getEnumName() == "ISD::BITCAST";
2716 void AnalyzeNode(const TreePatternNode *N) {
2718 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
2719 Record *LeafRec = DI->getDef();
2720 // Handle ComplexPattern leaves.
2721 if (LeafRec->isSubClassOf("ComplexPattern")) {
2722 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2723 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2724 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2725 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2731 // Analyze children.
2732 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2733 AnalyzeNode(N->getChild(i));
2735 // Ignore set nodes, which are not SDNodes.
2736 if (N->getOperator()->getName() == "set") {
2737 isBitcast = IsNodeBitcast(N);
2741 // Notice properties of the node.
2742 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2743 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2744 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2745 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
2747 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2748 // If this is an intrinsic, analyze it.
2749 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2750 mayLoad = true;// These may load memory.
2752 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2753 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2755 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2756 // WriteMem intrinsics can have other strange effects.
2757 hasSideEffects = true;
2763 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2764 const InstAnalyzer &PatInfo,
2768 // Remember where InstInfo got its flags.
2769 if (InstInfo.hasUndefFlags())
2770 InstInfo.InferredFrom = PatDef;
2772 // Check explicitly set flags for consistency.
2773 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2774 !InstInfo.hasSideEffects_Unset) {
2775 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2776 // the pattern has no side effects. That could be useful for div/rem
2777 // instructions that may trap.
2778 if (!InstInfo.hasSideEffects) {
2780 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2781 Twine(InstInfo.hasSideEffects));
2785 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2787 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2788 Twine(InstInfo.mayStore));
2791 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2792 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2793 // Some targets translate immediates to loads.
2794 if (!InstInfo.mayLoad) {
2796 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2797 Twine(InstInfo.mayLoad));
2801 // Transfer inferred flags.
2802 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2803 InstInfo.mayStore |= PatInfo.mayStore;
2804 InstInfo.mayLoad |= PatInfo.mayLoad;
2806 // These flags are silently added without any verification.
2807 InstInfo.isBitcast |= PatInfo.isBitcast;
2809 // Don't infer isVariadic. This flag means something different on SDNodes and
2810 // instructions. For example, a CALL SDNode is variadic because it has the
2811 // call arguments as operands, but a CALL instruction is not variadic - it
2812 // has argument registers as implicit, not explicit uses.
2817 /// hasNullFragReference - Return true if the DAG has any reference to the
2818 /// null_frag operator.
2819 static bool hasNullFragReference(DagInit *DI) {
2820 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
2821 if (!OpDef) return false;
2822 Record *Operator = OpDef->getDef();
2824 // If this is the null fragment, return true.
2825 if (Operator->getName() == "null_frag") return true;
2826 // If any of the arguments reference the null fragment, return true.
2827 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2828 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
2829 if (Arg && hasNullFragReference(Arg))
2836 /// hasNullFragReference - Return true if any DAG in the list references
2837 /// the null_frag operator.
2838 static bool hasNullFragReference(ListInit *LI) {
2839 for (Init *I : LI->getValues()) {
2840 DagInit *DI = dyn_cast<DagInit>(I);
2841 assert(DI && "non-dag in an instruction Pattern list?!");
2842 if (hasNullFragReference(DI))
2848 /// Get all the instructions in a tree.
2850 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2853 if (Tree->getOperator()->isSubClassOf("Instruction"))
2854 Instrs.push_back(Tree->getOperator());
2855 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2856 getInstructionsInTree(Tree->getChild(i), Instrs);
2859 /// Check the class of a pattern leaf node against the instruction operand it
2861 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2866 // Allow direct value types to be used in instruction set patterns.
2867 // The type will be checked later.
2868 if (Leaf->isSubClassOf("ValueType"))
2871 // Patterns can also be ComplexPattern instances.
2872 if (Leaf->isSubClassOf("ComplexPattern"))
2878 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2879 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
2881 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
2883 // Parse the instruction.
2884 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2885 // Inline pattern fragments into it.
2886 I->InlinePatternFragments();
2888 // Infer as many types as possible. If we cannot infer all of them, we can
2889 // never do anything with this instruction pattern: report it to the user.
2890 if (!I->InferAllTypes())
2891 I->error("Could not infer all types in pattern!");
2893 // InstInputs - Keep track of all of the inputs of the instruction, along
2894 // with the record they are declared as.
2895 std::map<std::string, TreePatternNode*> InstInputs;
2897 // InstResults - Keep track of all the virtual registers that are 'set'
2898 // in the instruction, including what reg class they are.
2899 std::map<std::string, TreePatternNode*> InstResults;
2901 std::vector<Record*> InstImpResults;
2903 // Verify that the top-level forms in the instruction are of void type, and
2904 // fill in the InstResults map.
2905 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2906 TreePatternNode *Pat = I->getTree(j);
2907 if (Pat->getNumTypes() != 0)
2908 I->error("Top-level forms in instruction pattern should have"
2911 // Find inputs and outputs, and verify the structure of the uses/defs.
2912 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2916 // Now that we have inputs and outputs of the pattern, inspect the operands
2917 // list for the instruction. This determines the order that operands are
2918 // added to the machine instruction the node corresponds to.
2919 unsigned NumResults = InstResults.size();
2921 // Parse the operands list from the (ops) list, validating it.
2922 assert(I->getArgList().empty() && "Args list should still be empty here!");
2924 // Check that all of the results occur first in the list.
2925 std::vector<Record*> Results;
2926 SmallVector<TreePatternNode *, 2> ResNodes;
2927 for (unsigned i = 0; i != NumResults; ++i) {
2928 if (i == CGI.Operands.size())
2929 I->error("'" + InstResults.begin()->first +
2930 "' set but does not appear in operand list!");
2931 const std::string &OpName = CGI.Operands[i].Name;
2933 // Check that it exists in InstResults.
2934 TreePatternNode *RNode = InstResults[OpName];
2936 I->error("Operand $" + OpName + " does not exist in operand list!");
2938 ResNodes.push_back(RNode);
2940 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2942 I->error("Operand $" + OpName + " should be a set destination: all "
2943 "outputs must occur before inputs in operand list!");
2945 if (!checkOperandClass(CGI.Operands[i], R))
2946 I->error("Operand $" + OpName + " class mismatch!");
2948 // Remember the return type.
2949 Results.push_back(CGI.Operands[i].Rec);
2951 // Okay, this one checks out.
2952 InstResults.erase(OpName);
2955 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2956 // the copy while we're checking the inputs.
2957 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2959 std::vector<TreePatternNode*> ResultNodeOperands;
2960 std::vector<Record*> Operands;
2961 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2962 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2963 const std::string &OpName = Op.Name;
2965 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2967 if (!InstInputsCheck.count(OpName)) {
2968 // If this is an operand with a DefaultOps set filled in, we can ignore
2969 // this. When we codegen it, we will do so as always executed.
2970 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2971 // Does it have a non-empty DefaultOps field? If so, ignore this
2973 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2976 I->error("Operand $" + OpName +
2977 " does not appear in the instruction pattern");
2979 TreePatternNode *InVal = InstInputsCheck[OpName];
2980 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2982 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
2983 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2984 if (!checkOperandClass(Op, InRec))
2985 I->error("Operand $" + OpName + "'s register class disagrees"
2986 " between the operand and pattern");
2988 Operands.push_back(Op.Rec);
2990 // Construct the result for the dest-pattern operand list.
2991 TreePatternNode *OpNode = InVal->clone();
2993 // No predicate is useful on the result.
2994 OpNode->clearPredicateFns();
2996 // Promote the xform function to be an explicit node if set.
2997 if (Record *Xform = OpNode->getTransformFn()) {
2998 OpNode->setTransformFn(nullptr);
2999 std::vector<TreePatternNode*> Children;
3000 Children.push_back(OpNode);
3001 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3004 ResultNodeOperands.push_back(OpNode);
3007 if (!InstInputsCheck.empty())
3008 I->error("Input operand $" + InstInputsCheck.begin()->first +
3009 " occurs in pattern but not in operands list!");
3011 TreePatternNode *ResultPattern =
3012 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3013 GetNumNodeResults(I->getRecord(), *this));
3014 // Copy fully inferred output node types to instruction result pattern.
3015 for (unsigned i = 0; i != NumResults; ++i) {
3016 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3017 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3020 // Create and insert the instruction.
3021 // FIXME: InstImpResults should not be part of DAGInstruction.
3022 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3023 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3025 // Use a temporary tree pattern to infer all types and make sure that the
3026 // constructed result is correct. This depends on the instruction already
3027 // being inserted into the DAGInsts map.
3028 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3029 Temp.InferAllTypes(&I->getNamedNodesMap());
3031 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3032 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3034 return TheInsertedInst;
3037 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3038 /// any fragments involved. This populates the Instructions list with fully
3039 /// resolved instructions.
3040 void CodeGenDAGPatterns::ParseInstructions() {
3041 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3043 for (Record *Instr : Instrs) {
3044 ListInit *LI = nullptr;
3046 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3047 LI = Instr->getValueAsListInit("Pattern");
3049 // If there is no pattern, only collect minimal information about the
3050 // instruction for its operand list. We have to assume that there is one
3051 // result, as we have no detailed info. A pattern which references the
3052 // null_frag operator is as-if no pattern were specified. Normally this
3053 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3055 if (!LI || LI->empty() || hasNullFragReference(LI)) {
3056 std::vector<Record*> Results;
3057 std::vector<Record*> Operands;
3059 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3061 if (InstInfo.Operands.size() != 0) {
3062 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3063 Results.push_back(InstInfo.Operands[j].Rec);
3065 // The rest are inputs.
3066 for (unsigned j = InstInfo.Operands.NumDefs,
3067 e = InstInfo.Operands.size(); j < e; ++j)
3068 Operands.push_back(InstInfo.Operands[j].Rec);
3071 // Create and insert the instruction.
3072 std::vector<Record*> ImpResults;
3073 Instructions.insert(std::make_pair(Instr,
3074 DAGInstruction(nullptr, Results, Operands, ImpResults)));
3075 continue; // no pattern.
3078 CodeGenInstruction &CGI = Target.getInstruction(Instr);
3079 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3082 DEBUG(DI.getPattern()->dump());
3085 // If we can, convert the instructions to be patterns that are matched!
3086 for (auto &Entry : Instructions) {
3087 DAGInstruction &TheInst = Entry.second;
3088 TreePattern *I = TheInst.getPattern();
3089 if (!I) continue; // No pattern.
3091 // FIXME: Assume only the first tree is the pattern. The others are clobber
3093 TreePatternNode *Pattern = I->getTree(0);
3094 TreePatternNode *SrcPattern;
3095 if (Pattern->getOperator()->getName() == "set") {
3096 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3098 // Not a set (store or something?)
3099 SrcPattern = Pattern;
3102 Record *Instr = Entry.first;
3103 AddPatternToMatch(I,
3104 PatternToMatch(Instr,
3105 Instr->getValueAsListInit("Predicates"),
3107 TheInst.getResultPattern(),
3108 TheInst.getImpResults(),
3109 Instr->getValueAsInt("AddedComplexity"),
3115 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3117 static void FindNames(const TreePatternNode *P,
3118 std::map<std::string, NameRecord> &Names,
3119 TreePattern *PatternTop) {
3120 if (!P->getName().empty()) {
3121 NameRecord &Rec = Names[P->getName()];
3122 // If this is the first instance of the name, remember the node.
3123 if (Rec.second++ == 0)
3125 else if (Rec.first->getExtTypes() != P->getExtTypes())
3126 PatternTop->error("repetition of value: $" + P->getName() +
3127 " where different uses have different types!");
3131 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3132 FindNames(P->getChild(i), Names, PatternTop);
3136 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3137 const PatternToMatch &PTM) {
3138 // Do some sanity checking on the pattern we're about to match.
3140 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3141 PrintWarning(Pattern->getRecord()->getLoc(),
3142 Twine("Pattern can never match: ") + Reason);
3146 // If the source pattern's root is a complex pattern, that complex pattern
3147 // must specify the nodes it can potentially match.
3148 if (const ComplexPattern *CP =
3149 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3150 if (CP->getRootNodes().empty())
3151 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3155 // Find all of the named values in the input and output, ensure they have the
3157 std::map<std::string, NameRecord> SrcNames, DstNames;
3158 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3159 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3161 // Scan all of the named values in the destination pattern, rejecting them if
3162 // they don't exist in the input pattern.
3163 for (const auto &Entry : DstNames) {
3164 if (SrcNames[Entry.first].first == nullptr)
3165 Pattern->error("Pattern has input without matching name in output: $" +
3169 // Scan all of the named values in the source pattern, rejecting them if the
3170 // name isn't used in the dest, and isn't used to tie two values together.
3171 for (const auto &Entry : SrcNames)
3172 if (DstNames[Entry.first].first == nullptr &&
3173 SrcNames[Entry.first].second == 1)
3174 Pattern->error("Pattern has dead named input: $" + Entry.first);
3176 PatternsToMatch.push_back(PTM);
3181 void CodeGenDAGPatterns::InferInstructionFlags() {
3182 const std::vector<const CodeGenInstruction*> &Instructions =
3183 Target.getInstructionsByEnumValue();
3185 // First try to infer flags from the primary instruction pattern, if any.
3186 SmallVector<CodeGenInstruction*, 8> Revisit;
3187 unsigned Errors = 0;
3188 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3189 CodeGenInstruction &InstInfo =
3190 const_cast<CodeGenInstruction &>(*Instructions[i]);
3192 // Get the primary instruction pattern.
3193 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3195 if (InstInfo.hasUndefFlags())
3196 Revisit.push_back(&InstInfo);
3199 InstAnalyzer PatInfo(*this);
3200 PatInfo.Analyze(Pattern);
3201 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3204 // Second, look for single-instruction patterns defined outside the
3206 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3207 const PatternToMatch &PTM = *I;
3209 // We can only infer from single-instruction patterns, otherwise we won't
3210 // know which instruction should get the flags.
3211 SmallVector<Record*, 8> PatInstrs;
3212 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3213 if (PatInstrs.size() != 1)
3216 // Get the single instruction.
3217 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3219 // Only infer properties from the first pattern. We'll verify the others.
3220 if (InstInfo.InferredFrom)
3223 InstAnalyzer PatInfo(*this);
3224 PatInfo.Analyze(&PTM);
3225 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3229 PrintFatalError("pattern conflicts");
3231 // Revisit instructions with undefined flags and no pattern.
3232 if (Target.guessInstructionProperties()) {
3233 for (CodeGenInstruction *InstInfo : Revisit) {
3234 if (InstInfo->InferredFrom)
3236 // The mayLoad and mayStore flags default to false.
3237 // Conservatively assume hasSideEffects if it wasn't explicit.
3238 if (InstInfo->hasSideEffects_Unset)
3239 InstInfo->hasSideEffects = true;
3244 // Complain about any flags that are still undefined.
3245 for (CodeGenInstruction *InstInfo : Revisit) {
3246 if (InstInfo->InferredFrom)
3248 if (InstInfo->hasSideEffects_Unset)
3249 PrintError(InstInfo->TheDef->getLoc(),
3250 "Can't infer hasSideEffects from patterns");
3251 if (InstInfo->mayStore_Unset)
3252 PrintError(InstInfo->TheDef->getLoc(),
3253 "Can't infer mayStore from patterns");
3254 if (InstInfo->mayLoad_Unset)
3255 PrintError(InstInfo->TheDef->getLoc(),
3256 "Can't infer mayLoad from patterns");
3261 /// Verify instruction flags against pattern node properties.
3262 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3263 unsigned Errors = 0;
3264 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3265 const PatternToMatch &PTM = *I;
3266 SmallVector<Record*, 8> Instrs;
3267 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3271 // Count the number of instructions with each flag set.
3272 unsigned NumSideEffects = 0;
3273 unsigned NumStores = 0;
3274 unsigned NumLoads = 0;
3275 for (const Record *Instr : Instrs) {
3276 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3277 NumSideEffects += InstInfo.hasSideEffects;
3278 NumStores += InstInfo.mayStore;
3279 NumLoads += InstInfo.mayLoad;
3282 // Analyze the source pattern.
3283 InstAnalyzer PatInfo(*this);
3284 PatInfo.Analyze(&PTM);
3286 // Collect error messages.
3287 SmallVector<std::string, 4> Msgs;
3289 // Check for missing flags in the output.
3290 // Permit extra flags for now at least.
3291 if (PatInfo.hasSideEffects && !NumSideEffects)
3292 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3294 // Don't verify store flags on instructions with side effects. At least for
3295 // intrinsics, side effects implies mayStore.
3296 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3297 Msgs.push_back("pattern may store, but mayStore isn't set");
3299 // Similarly, mayStore implies mayLoad on intrinsics.
3300 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3301 Msgs.push_back("pattern may load, but mayLoad isn't set");
3303 // Print error messages.
3308 for (const std::string &Msg : Msgs)
3309 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
3310 (Instrs.size() == 1 ?
3311 "instruction" : "output instructions"));
3312 // Provide the location of the relevant instruction definitions.
3313 for (const Record *Instr : Instrs) {
3314 if (Instr != PTM.getSrcRecord())
3315 PrintError(Instr->getLoc(), "defined here");
3316 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3317 if (InstInfo.InferredFrom &&
3318 InstInfo.InferredFrom != InstInfo.TheDef &&
3319 InstInfo.InferredFrom != PTM.getSrcRecord())
3320 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3324 PrintFatalError("Errors in DAG patterns");
3327 /// Given a pattern result with an unresolved type, see if we can find one
3328 /// instruction with an unresolved result type. Force this result type to an
3329 /// arbitrary element if it's possible types to converge results.
3330 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3334 // Analyze children.
3335 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3336 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3339 if (!N->getOperator()->isSubClassOf("Instruction"))
3342 // If this type is already concrete or completely unknown we can't do
3344 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3345 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3348 // Otherwise, force its type to the first possibility (an arbitrary choice).
3349 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3356 void CodeGenDAGPatterns::ParsePatterns() {
3357 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3359 for (Record *CurPattern : Patterns) {
3360 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3362 // If the pattern references the null_frag, there's nothing to do.
3363 if (hasNullFragReference(Tree))
3366 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3368 // Inline pattern fragments into it.
3369 Pattern->InlinePatternFragments();
3371 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3372 if (LI->empty()) continue; // no pattern.
3374 // Parse the instruction.
3375 TreePattern Result(CurPattern, LI, false, *this);
3377 // Inline pattern fragments into it.
3378 Result.InlinePatternFragments();
3380 if (Result.getNumTrees() != 1)
3381 Result.error("Cannot handle instructions producing instructions "
3382 "with temporaries yet!");
3384 bool IterateInference;
3385 bool InferredAllPatternTypes, InferredAllResultTypes;
3387 // Infer as many types as possible. If we cannot infer all of them, we
3388 // can never do anything with this pattern: report it to the user.
3389 InferredAllPatternTypes =
3390 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3392 // Infer as many types as possible. If we cannot infer all of them, we
3393 // can never do anything with this pattern: report it to the user.
3394 InferredAllResultTypes =
3395 Result.InferAllTypes(&Pattern->getNamedNodesMap());
3397 IterateInference = false;
3399 // Apply the type of the result to the source pattern. This helps us
3400 // resolve cases where the input type is known to be a pointer type (which
3401 // is considered resolved), but the result knows it needs to be 32- or
3402 // 64-bits. Infer the other way for good measure.
3403 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3404 Pattern->getTree(0)->getNumTypes());
3406 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3407 i, Result.getTree(0)->getExtType(i), Result);
3408 IterateInference |= Result.getTree(0)->UpdateNodeType(
3409 i, Pattern->getTree(0)->getExtType(i), Result);
3412 // If our iteration has converged and the input pattern's types are fully
3413 // resolved but the result pattern is not fully resolved, we may have a
3414 // situation where we have two instructions in the result pattern and
3415 // the instructions require a common register class, but don't care about
3416 // what actual MVT is used. This is actually a bug in our modelling:
3417 // output patterns should have register classes, not MVTs.
3419 // In any case, to handle this, we just go through and disambiguate some
3420 // arbitrary types to the result pattern's nodes.
3421 if (!IterateInference && InferredAllPatternTypes &&
3422 !InferredAllResultTypes)
3424 ForceArbitraryInstResultType(Result.getTree(0), Result);
3425 } while (IterateInference);
3427 // Verify that we inferred enough types that we can do something with the
3428 // pattern and result. If these fire the user has to add type casts.
3429 if (!InferredAllPatternTypes)
3430 Pattern->error("Could not infer all types in pattern!");
3431 if (!InferredAllResultTypes) {
3433 Result.error("Could not infer all types in pattern result!");
3436 // Validate that the input pattern is correct.
3437 std::map<std::string, TreePatternNode*> InstInputs;
3438 std::map<std::string, TreePatternNode*> InstResults;
3439 std::vector<Record*> InstImpResults;
3440 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3441 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3442 InstInputs, InstResults,
3445 // Promote the xform function to be an explicit node if set.
3446 TreePatternNode *DstPattern = Result.getOnlyTree();
3447 std::vector<TreePatternNode*> ResultNodeOperands;
3448 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3449 TreePatternNode *OpNode = DstPattern->getChild(ii);
3450 if (Record *Xform = OpNode->getTransformFn()) {
3451 OpNode->setTransformFn(nullptr);
3452 std::vector<TreePatternNode*> Children;
3453 Children.push_back(OpNode);
3454 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3456 ResultNodeOperands.push_back(OpNode);
3458 DstPattern = Result.getOnlyTree();
3459 if (!DstPattern->isLeaf())
3460 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3462 DstPattern->getNumTypes());
3464 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3465 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3467 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
3468 Temp.InferAllTypes();
3471 AddPatternToMatch(Pattern,
3472 PatternToMatch(CurPattern,
3473 CurPattern->getValueAsListInit("Predicates"),
3474 Pattern->getTree(0),
3475 Temp.getOnlyTree(), InstImpResults,
3476 CurPattern->getValueAsInt("AddedComplexity"),
3477 CurPattern->getID()));
3481 /// CombineChildVariants - Given a bunch of permutations of each child of the
3482 /// 'operator' node, put them together in all possible ways.
3483 static void CombineChildVariants(TreePatternNode *Orig,
3484 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3485 std::vector<TreePatternNode*> &OutVariants,
3486 CodeGenDAGPatterns &CDP,
3487 const MultipleUseVarSet &DepVars) {
3488 // Make sure that each operand has at least one variant to choose from.
3489 for (const auto &Variants : ChildVariants)
3490 if (Variants.empty())
3493 // The end result is an all-pairs construction of the resultant pattern.
3494 std::vector<unsigned> Idxs;
3495 Idxs.resize(ChildVariants.size());
3499 DEBUG(if (!Idxs.empty()) {
3500 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3501 for (unsigned Idx : Idxs) {
3502 errs() << Idx << " ";
3507 // Create the variant and add it to the output list.
3508 std::vector<TreePatternNode*> NewChildren;
3509 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3510 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3511 auto R = llvm::make_unique<TreePatternNode>(
3512 Orig->getOperator(), NewChildren, Orig->getNumTypes());
3514 // Copy over properties.
3515 R->setName(Orig->getName());
3516 R->setPredicateFns(Orig->getPredicateFns());
3517 R->setTransformFn(Orig->getTransformFn());
3518 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3519 R->setType(i, Orig->getExtType(i));
3521 // If this pattern cannot match, do not include it as a variant.
3522 std::string ErrString;
3523 // Scan to see if this pattern has already been emitted. We can get
3524 // duplication due to things like commuting:
3525 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3526 // which are the same pattern. Ignore the dups.
3527 if (R->canPatternMatch(ErrString, CDP) &&
3528 std::none_of(OutVariants.begin(), OutVariants.end(),
3529 [&](TreePatternNode *Variant) {
3530 return R->isIsomorphicTo(Variant, DepVars);
3532 OutVariants.push_back(R.release());
3534 // Increment indices to the next permutation by incrementing the
3535 // indices from last index backward, e.g., generate the sequence
3536 // [0, 0], [0, 1], [1, 0], [1, 1].
3538 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3539 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3544 NotDone = (IdxsIdx >= 0);
3548 /// CombineChildVariants - A helper function for binary operators.
3550 static void CombineChildVariants(TreePatternNode *Orig,
3551 const std::vector<TreePatternNode*> &LHS,
3552 const std::vector<TreePatternNode*> &RHS,
3553 std::vector<TreePatternNode*> &OutVariants,
3554 CodeGenDAGPatterns &CDP,
3555 const MultipleUseVarSet &DepVars) {
3556 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3557 ChildVariants.push_back(LHS);
3558 ChildVariants.push_back(RHS);
3559 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3563 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3564 std::vector<TreePatternNode *> &Children) {
3565 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3566 Record *Operator = N->getOperator();
3568 // Only permit raw nodes.
3569 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3570 N->getTransformFn()) {
3571 Children.push_back(N);
3575 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3576 Children.push_back(N->getChild(0));
3578 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3580 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3581 Children.push_back(N->getChild(1));
3583 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3586 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3587 /// the (potentially recursive) pattern by using algebraic laws.
3589 static void GenerateVariantsOf(TreePatternNode *N,
3590 std::vector<TreePatternNode*> &OutVariants,
3591 CodeGenDAGPatterns &CDP,
3592 const MultipleUseVarSet &DepVars) {
3593 // We cannot permute leaves or ComplexPattern uses.
3594 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
3595 OutVariants.push_back(N);
3599 // Look up interesting info about the node.
3600 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3602 // If this node is associative, re-associate.
3603 if (NodeInfo.hasProperty(SDNPAssociative)) {
3604 // Re-associate by pulling together all of the linked operators
3605 std::vector<TreePatternNode*> MaximalChildren;
3606 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3608 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3610 if (MaximalChildren.size() == 3) {
3611 // Find the variants of all of our maximal children.
3612 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3613 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3614 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3615 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3617 // There are only two ways we can permute the tree:
3618 // (A op B) op C and A op (B op C)
3619 // Within these forms, we can also permute A/B/C.
3621 // Generate legal pair permutations of A/B/C.
3622 std::vector<TreePatternNode*> ABVariants;
3623 std::vector<TreePatternNode*> BAVariants;
3624 std::vector<TreePatternNode*> ACVariants;
3625 std::vector<TreePatternNode*> CAVariants;
3626 std::vector<TreePatternNode*> BCVariants;
3627 std::vector<TreePatternNode*> CBVariants;
3628 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3629 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3630 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3631 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3632 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3633 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3635 // Combine those into the result: (x op x) op x
3636 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3637 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3638 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3639 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3640 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3641 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3643 // Combine those into the result: x op (x op x)
3644 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3645 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3646 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3647 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3648 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3649 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3654 // Compute permutations of all children.
3655 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3656 ChildVariants.resize(N->getNumChildren());
3657 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3658 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3660 // Build all permutations based on how the children were formed.
3661 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3663 // If this node is commutative, consider the commuted order.
3664 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3665 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3666 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3667 "Commutative but doesn't have 2 children!");
3668 // Don't count children which are actually register references.
3670 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3671 TreePatternNode *Child = N->getChild(i);
3672 if (Child->isLeaf())
3673 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
3674 Record *RR = DI->getDef();
3675 if (RR->isSubClassOf("Register"))
3680 // Consider the commuted order.
3681 if (isCommIntrinsic) {
3682 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3683 // operands are the commutative operands, and there might be more operands
3686 "Commutative intrinsic should have at least 3 children!");
3687 std::vector<std::vector<TreePatternNode*> > Variants;
3688 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3689 Variants.push_back(ChildVariants[2]);
3690 Variants.push_back(ChildVariants[1]);
3691 for (unsigned i = 3; i != NC; ++i)
3692 Variants.push_back(ChildVariants[i]);
3693 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3695 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3696 OutVariants, CDP, DepVars);
3701 // GenerateVariants - Generate variants. For example, commutative patterns can
3702 // match multiple ways. Add them to PatternsToMatch as well.
3703 void CodeGenDAGPatterns::GenerateVariants() {
3704 DEBUG(errs() << "Generating instruction variants.\n");
3706 // Loop over all of the patterns we've collected, checking to see if we can
3707 // generate variants of the instruction, through the exploitation of
3708 // identities. This permits the target to provide aggressive matching without
3709 // the .td file having to contain tons of variants of instructions.
3711 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3712 // intentionally do not reconsider these. Any variants of added patterns have
3713 // already been added.
3715 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3716 MultipleUseVarSet DepVars;
3717 std::vector<TreePatternNode*> Variants;
3718 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3719 DEBUG(errs() << "Dependent/multiply used variables: ");
3720 DEBUG(DumpDepVars(DepVars));
3721 DEBUG(errs() << "\n");
3722 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3725 assert(!Variants.empty() && "Must create at least original variant!");
3726 Variants.erase(Variants.begin()); // Remove the original pattern.
3728 if (Variants.empty()) // No variants for this pattern.
3731 DEBUG(errs() << "FOUND VARIANTS OF: ";
3732 PatternsToMatch[i].getSrcPattern()->dump();
3735 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3736 TreePatternNode *Variant = Variants[v];
3738 DEBUG(errs() << " VAR#" << v << ": ";
3742 // Scan to see if an instruction or explicit pattern already matches this.
3743 bool AlreadyExists = false;
3744 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3745 // Skip if the top level predicates do not match.
3746 if (PatternsToMatch[i].getPredicates() !=
3747 PatternsToMatch[p].getPredicates())
3749 // Check to see if this variant already exists.
3750 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3752 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3753 AlreadyExists = true;
3757 // If we already have it, ignore the variant.
3758 if (AlreadyExists) continue;
3760 // Otherwise, add it to the list of patterns we have.
3761 PatternsToMatch.emplace_back(
3762 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3763 Variant, PatternsToMatch[i].getDstPattern(),
3764 PatternsToMatch[i].getDstRegs(),
3765 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
3768 DEBUG(errs() << "\n");