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 bool MadeChange = false;
207 TypeSet InputSet(*this);
209 for (unsigned i = 0; i != TypeVec.size(); ++i) {
210 if (std::find(InVT.TypeVec.begin(), InVT.TypeVec.end(), TypeVec[i]) !=
214 TypeVec.erase(TypeVec.begin()+i--);
218 // If we removed all of our types, we have a type contradiction.
219 if (!TypeVec.empty())
222 // FIXME: Really want an SMLoc here!
223 TP.error("Type inference contradiction found, merging '" +
224 InVT.getName() + "' into '" + InputSet.getName() + "'");
228 /// EnforceInteger - Remove all non-integer types from this set.
229 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
232 // If we know nothing, then get the full set.
234 return FillWithPossibleTypes(TP, isInteger, "integer");
236 if (!hasFloatingPointTypes())
239 TypeSet InputSet(*this);
241 // Filter out all the fp types.
242 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
243 std::not1(std::ptr_fun(isInteger))),
246 if (TypeVec.empty()) {
247 TP.error("Type inference contradiction found, '" +
248 InputSet.getName() + "' needs to be integer");
254 /// EnforceFloatingPoint - Remove all integer types from this set.
255 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
258 // If we know nothing, then get the full set.
260 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
262 if (!hasIntegerTypes())
265 TypeSet InputSet(*this);
267 // Filter out all the integer types.
268 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
269 std::not1(std::ptr_fun(isFloatingPoint))),
272 if (TypeVec.empty()) {
273 TP.error("Type inference contradiction found, '" +
274 InputSet.getName() + "' needs to be floating point");
280 /// EnforceScalar - Remove all vector types from this.
281 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
285 // If we know nothing, then get the full set.
287 return FillWithPossibleTypes(TP, isScalar, "scalar");
289 if (!hasVectorTypes())
292 TypeSet InputSet(*this);
294 // Filter out all the vector types.
295 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
296 std::not1(std::ptr_fun(isScalar))),
299 if (TypeVec.empty()) {
300 TP.error("Type inference contradiction found, '" +
301 InputSet.getName() + "' needs to be scalar");
307 /// EnforceVector - Remove all vector types from this.
308 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
312 // If we know nothing, then get the full set.
314 return FillWithPossibleTypes(TP, isVector, "vector");
316 TypeSet InputSet(*this);
317 bool MadeChange = false;
319 // Filter out all the scalar types.
320 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
321 std::not1(std::ptr_fun(isVector))),
324 if (TypeVec.empty()) {
325 TP.error("Type inference contradiction found, '" +
326 InputSet.getName() + "' needs to be a vector");
334 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
335 /// this should be based on the element type. Update this and other based on
336 /// this information.
337 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
341 // Both operands must be integer or FP, but we don't care which.
342 bool MadeChange = false;
344 if (isCompletelyUnknown())
345 MadeChange = FillWithPossibleTypes(TP);
347 if (Other.isCompletelyUnknown())
348 MadeChange = Other.FillWithPossibleTypes(TP);
350 // If one side is known to be integer or known to be FP but the other side has
351 // no information, get at least the type integrality info in there.
352 if (!hasFloatingPointTypes())
353 MadeChange |= Other.EnforceInteger(TP);
354 else if (!hasIntegerTypes())
355 MadeChange |= Other.EnforceFloatingPoint(TP);
356 if (!Other.hasFloatingPointTypes())
357 MadeChange |= EnforceInteger(TP);
358 else if (!Other.hasIntegerTypes())
359 MadeChange |= EnforceFloatingPoint(TP);
361 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
362 "Should have a type list now");
364 // If one contains vectors but the other doesn't pull vectors out.
365 if (!hasVectorTypes())
366 MadeChange |= Other.EnforceScalar(TP);
367 else if (!hasScalarTypes())
368 MadeChange |= Other.EnforceVector(TP);
369 if (!Other.hasVectorTypes())
370 MadeChange |= EnforceScalar(TP);
371 else if (!Other.hasScalarTypes())
372 MadeChange |= EnforceVector(TP);
374 // This code does not currently handle nodes which have multiple types,
375 // where some types are integer, and some are fp. Assert that this is not
377 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
378 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
379 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
384 // Okay, find the smallest type from current set and remove anything the
385 // same or smaller from the other set. We need to ensure that the scalar
386 // type size is smaller than the scalar size of the smallest type. For
387 // vectors, we also need to make sure that the total size is no larger than
388 // the size of the smallest type.
389 TypeSet InputSet(Other);
390 MVT Smallest = TypeVec[0];
391 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
392 MVT OtherVT = Other.TypeVec[i];
393 // Don't compare vector and non-vector types.
394 if (OtherVT.isVector() != Smallest.isVector())
396 // The getSizeInBits() check here is only needed for vectors, but is
397 // a subset of the scalar check for scalars so no need to qualify.
398 if (OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
399 OtherVT.getSizeInBits() < Smallest.getSizeInBits()) {
400 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
405 if (Other.TypeVec.empty()) {
406 TP.error("Type inference contradiction found, '" + InputSet.getName() +
407 "' has nothing larger than '" + getName() +"'!");
411 // Okay, find the largest type from the other set and remove anything the
412 // same or smaller from the current set. We need to ensure that the scalar
413 // type size is larger than the scalar size of the largest type. For
414 // vectors, we also need to make sure that the total size is no smaller than
415 // the size of the largest type.
416 InputSet = TypeSet(*this);
417 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
418 for (unsigned i = 0; i != TypeVec.size(); ++i) {
419 MVT OtherVT = TypeVec[i];
420 // Don't compare vector and non-vector types.
421 if (OtherVT.isVector() != Largest.isVector())
423 // The getSizeInBits() check here is only needed for vectors, but is
424 // a subset of the scalar check for scalars so no need to qualify.
425 if (OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
426 OtherVT.getSizeInBits() > Largest.getSizeInBits()) {
427 TypeVec.erase(TypeVec.begin()+i--);
432 if (TypeVec.empty()) {
433 TP.error("Type inference contradiction found, '" + InputSet.getName() +
434 "' has nothing smaller than '" + Other.getName() +"'!");
441 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
442 /// whose element is specified by VTOperand.
443 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
445 bool MadeChange = false;
447 MadeChange |= EnforceVector(TP);
449 TypeSet InputSet(*this);
451 // Filter out all the types which don't have the right element type.
452 for (unsigned i = 0; i != TypeVec.size(); ++i) {
453 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
454 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
455 TypeVec.erase(TypeVec.begin()+i--);
460 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
461 TP.error("Type inference contradiction found, forcing '" +
462 InputSet.getName() + "' to have a vector element");
469 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
470 /// whose element is specified by VTOperand.
471 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
476 // "This" must be a vector and "VTOperand" must be a scalar.
477 bool MadeChange = false;
478 MadeChange |= EnforceVector(TP);
479 MadeChange |= VTOperand.EnforceScalar(TP);
481 // If we know the vector type, it forces the scalar to agree.
483 MVT IVT = getConcrete();
484 IVT = IVT.getVectorElementType();
486 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
489 // If the scalar type is known, filter out vector types whose element types
491 if (!VTOperand.isConcrete())
494 MVT::SimpleValueType VT = VTOperand.getConcrete();
496 TypeSet InputSet(*this);
498 // Filter out all the types which don't have the right element type.
499 for (unsigned i = 0; i != TypeVec.size(); ++i) {
500 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
501 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
502 TypeVec.erase(TypeVec.begin()+i--);
507 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
508 TP.error("Type inference contradiction found, forcing '" +
509 InputSet.getName() + "' to have a vector element");
515 /// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
516 /// vector type specified by VTOperand.
517 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
522 // "This" must be a vector and "VTOperand" must be a vector.
523 bool MadeChange = false;
524 MadeChange |= EnforceVector(TP);
525 MadeChange |= VTOperand.EnforceVector(TP);
527 // If one side is known to be integer or known to be FP but the other side has
528 // no information, get at least the type integrality info in there.
529 if (!hasFloatingPointTypes())
530 MadeChange |= VTOperand.EnforceInteger(TP);
531 else if (!hasIntegerTypes())
532 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
533 if (!VTOperand.hasFloatingPointTypes())
534 MadeChange |= EnforceInteger(TP);
535 else if (!VTOperand.hasIntegerTypes())
536 MadeChange |= EnforceFloatingPoint(TP);
538 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
539 "Should have a type list now");
541 // If we know the vector type, it forces the scalar types to agree.
542 // Also force one vector to have more elements than the other.
544 MVT IVT = getConcrete();
545 unsigned NumElems = IVT.getVectorNumElements();
546 IVT = IVT.getVectorElementType();
548 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
549 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
551 // Only keep types that have less elements than VTOperand.
552 TypeSet InputSet(VTOperand);
554 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
555 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
556 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
557 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
561 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
562 TP.error("Type inference contradiction found, forcing '" +
563 InputSet.getName() + "' to have less vector elements than '" +
567 } else if (VTOperand.isConcrete()) {
568 MVT IVT = VTOperand.getConcrete();
569 unsigned NumElems = IVT.getVectorNumElements();
570 IVT = IVT.getVectorElementType();
572 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
573 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
575 // Only keep types that have more elements than 'this'.
576 TypeSet InputSet(*this);
578 for (unsigned i = 0; i != TypeVec.size(); ++i) {
579 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
580 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
581 TypeVec.erase(TypeVec.begin()+i--);
585 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
586 TP.error("Type inference contradiction found, forcing '" +
587 InputSet.getName() + "' to have more vector elements than '" +
588 VTOperand.getName() + "'");
596 /// EnforceVectorSameNumElts - 'this' is now constrained to
597 /// be a vector with same num elements as VTOperand.
598 bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
603 // "This" must be a vector and "VTOperand" must be a vector.
604 bool MadeChange = false;
605 MadeChange |= EnforceVector(TP);
606 MadeChange |= VTOperand.EnforceVector(TP);
608 // If we know one of the vector types, it forces the other type to agree.
610 MVT IVT = getConcrete();
611 unsigned NumElems = IVT.getVectorNumElements();
613 // Only keep types that have same elements as VTOperand.
614 TypeSet InputSet(VTOperand);
616 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
617 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
618 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
619 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
623 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
624 TP.error("Type inference contradiction found, forcing '" +
625 InputSet.getName() + "' to have same number elements as '" +
629 } else if (VTOperand.isConcrete()) {
630 MVT IVT = VTOperand.getConcrete();
631 unsigned NumElems = IVT.getVectorNumElements();
633 // Only keep types that have same elements as 'this'.
634 TypeSet InputSet(*this);
636 for (unsigned i = 0; i != TypeVec.size(); ++i) {
637 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
638 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
639 TypeVec.erase(TypeVec.begin()+i--);
643 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
644 TP.error("Type inference contradiction found, forcing '" +
645 InputSet.getName() + "' to have same number elements than '" +
646 VTOperand.getName() + "'");
654 //===----------------------------------------------------------------------===//
655 // Helpers for working with extended types.
657 /// Dependent variable map for CodeGenDAGPattern variant generation
658 typedef std::map<std::string, int> DepVarMap;
660 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
662 if (isa<DefInit>(N->getLeafValue()))
663 DepMap[N->getName()]++;
665 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
666 FindDepVarsOf(N->getChild(i), DepMap);
670 /// Find dependent variables within child patterns
671 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
673 FindDepVarsOf(N, depcounts);
674 for (const std::pair<std::string, int> &Pair : depcounts) {
676 DepVars.insert(Pair.first);
681 /// Dump the dependent variable set:
682 static void DumpDepVars(MultipleUseVarSet &DepVars) {
683 if (DepVars.empty()) {
684 DEBUG(errs() << "<empty set>");
686 DEBUG(errs() << "[ ");
687 for (const std::string &DepVar : DepVars) {
688 DEBUG(errs() << DepVar << " ");
690 DEBUG(errs() << "]");
696 //===----------------------------------------------------------------------===//
697 // TreePredicateFn Implementation
698 //===----------------------------------------------------------------------===//
700 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
701 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
702 assert((getPredCode().empty() || getImmCode().empty()) &&
703 ".td file corrupt: can't have a node predicate *and* an imm predicate");
706 std::string TreePredicateFn::getPredCode() const {
707 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
710 std::string TreePredicateFn::getImmCode() const {
711 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
715 /// isAlwaysTrue - Return true if this is a noop predicate.
716 bool TreePredicateFn::isAlwaysTrue() const {
717 return getPredCode().empty() && getImmCode().empty();
720 /// Return the name to use in the generated code to reference this, this is
721 /// "Predicate_foo" if from a pattern fragment "foo".
722 std::string TreePredicateFn::getFnName() const {
723 return "Predicate_" + PatFragRec->getRecord()->getName();
726 /// getCodeToRunOnSDNode - Return the code for the function body that
727 /// evaluates this predicate. The argument is expected to be in "Node",
728 /// not N. This handles casting and conversion to a concrete node type as
730 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
731 // Handle immediate predicates first.
732 std::string ImmCode = getImmCode();
733 if (!ImmCode.empty()) {
735 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
736 return Result + ImmCode;
739 // Handle arbitrary node predicates.
740 assert(!getPredCode().empty() && "Don't have any predicate code!");
741 std::string ClassName;
742 if (PatFragRec->getOnlyTree()->isLeaf())
743 ClassName = "SDNode";
745 Record *Op = PatFragRec->getOnlyTree()->getOperator();
746 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
749 if (ClassName == "SDNode")
750 Result = " SDNode *N = Node;\n";
752 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
754 return Result + getPredCode();
757 //===----------------------------------------------------------------------===//
758 // PatternToMatch implementation
762 /// getPatternSize - Return the 'size' of this pattern. We want to match large
763 /// patterns before small ones. This is used to determine the size of a
765 static unsigned getPatternSize(const TreePatternNode *P,
766 const CodeGenDAGPatterns &CGP) {
767 unsigned Size = 3; // The node itself.
768 // If the root node is a ConstantSDNode, increases its size.
769 // e.g. (set R32:$dst, 0).
770 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
773 // FIXME: This is a hack to statically increase the priority of patterns
774 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
775 // Later we can allow complexity / cost for each pattern to be (optionally)
776 // specified. To get best possible pattern match we'll need to dynamically
777 // calculate the complexity of all patterns a dag can potentially map to.
778 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
780 Size += AM->getNumOperands() * 3;
782 // We don't want to count any children twice, so return early.
786 // If this node has some predicate function that must match, it adds to the
787 // complexity of this node.
788 if (!P->getPredicateFns().empty())
791 // Count children in the count if they are also nodes.
792 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
793 TreePatternNode *Child = P->getChild(i);
794 if (!Child->isLeaf() && Child->getNumTypes() &&
795 Child->getType(0) != MVT::Other)
796 Size += getPatternSize(Child, CGP);
797 else if (Child->isLeaf()) {
798 if (isa<IntInit>(Child->getLeafValue()))
799 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
800 else if (Child->getComplexPatternInfo(CGP))
801 Size += getPatternSize(Child, CGP);
802 else if (!Child->getPredicateFns().empty())
810 /// Compute the complexity metric for the input pattern. This roughly
811 /// corresponds to the number of nodes that are covered.
813 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
814 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
818 /// getPredicateCheck - Return a single string containing all of this
819 /// pattern's predicates concatenated with "&&" operators.
821 std::string PatternToMatch::getPredicateCheck() const {
822 std::string PredicateCheck;
823 for (Init *I : Predicates->getValues()) {
824 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
825 Record *Def = Pred->getDef();
826 if (!Def->isSubClassOf("Predicate")) {
830 llvm_unreachable("Unknown predicate type!");
832 if (!PredicateCheck.empty())
833 PredicateCheck += " && ";
834 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
838 return PredicateCheck;
841 //===----------------------------------------------------------------------===//
842 // SDTypeConstraint implementation
845 SDTypeConstraint::SDTypeConstraint(Record *R) {
846 OperandNo = R->getValueAsInt("OperandNum");
848 if (R->isSubClassOf("SDTCisVT")) {
849 ConstraintType = SDTCisVT;
850 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
851 if (x.SDTCisVT_Info.VT == MVT::isVoid)
852 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
854 } else if (R->isSubClassOf("SDTCisPtrTy")) {
855 ConstraintType = SDTCisPtrTy;
856 } else if (R->isSubClassOf("SDTCisInt")) {
857 ConstraintType = SDTCisInt;
858 } else if (R->isSubClassOf("SDTCisFP")) {
859 ConstraintType = SDTCisFP;
860 } else if (R->isSubClassOf("SDTCisVec")) {
861 ConstraintType = SDTCisVec;
862 } else if (R->isSubClassOf("SDTCisSameAs")) {
863 ConstraintType = SDTCisSameAs;
864 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
865 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
866 ConstraintType = SDTCisVTSmallerThanOp;
867 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
868 R->getValueAsInt("OtherOperandNum");
869 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
870 ConstraintType = SDTCisOpSmallerThanOp;
871 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
872 R->getValueAsInt("BigOperandNum");
873 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
874 ConstraintType = SDTCisEltOfVec;
875 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
876 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
877 ConstraintType = SDTCisSubVecOfVec;
878 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
879 R->getValueAsInt("OtherOpNum");
880 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
881 ConstraintType = SDTCVecEltisVT;
882 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
883 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
884 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
885 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
886 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
887 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
888 "as SDTCVecEltisVT");
889 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
890 ConstraintType = SDTCisSameNumEltsAs;
891 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
892 R->getValueAsInt("OtherOperandNum");
894 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
898 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
899 /// N, and the result number in ResNo.
900 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
901 const SDNodeInfo &NodeInfo,
903 unsigned NumResults = NodeInfo.getNumResults();
904 if (OpNo < NumResults) {
911 if (OpNo >= N->getNumChildren()) {
913 raw_string_ostream OS(S);
914 OS << "Invalid operand number in type constraint "
915 << (OpNo+NumResults) << " ";
917 PrintFatalError(OS.str());
920 return N->getChild(OpNo);
923 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
924 /// constraint to the nodes operands. This returns true if it makes a
925 /// change, false otherwise. If a type contradiction is found, flag an error.
926 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
927 const SDNodeInfo &NodeInfo,
928 TreePattern &TP) const {
932 unsigned ResNo = 0; // The result number being referenced.
933 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
935 switch (ConstraintType) {
937 // Operand must be a particular type.
938 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
940 // Operand must be same as target pointer type.
941 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
943 // Require it to be one of the legal integer VTs.
944 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
946 // Require it to be one of the legal fp VTs.
947 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
949 // Require it to be one of the legal vector VTs.
950 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
953 TreePatternNode *OtherNode =
954 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
955 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
956 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
958 case SDTCisVTSmallerThanOp: {
959 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
960 // have an integer type that is smaller than the VT.
961 if (!NodeToApply->isLeaf() ||
962 !isa<DefInit>(NodeToApply->getLeafValue()) ||
963 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
964 ->isSubClassOf("ValueType")) {
965 TP.error(N->getOperator()->getName() + " expects a VT operand!");
968 MVT::SimpleValueType VT =
969 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
971 EEVT::TypeSet TypeListTmp(VT, TP);
974 TreePatternNode *OtherNode =
975 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
978 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
980 case SDTCisOpSmallerThanOp: {
982 TreePatternNode *BigOperand =
983 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
985 return NodeToApply->getExtType(ResNo).
986 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
988 case SDTCisEltOfVec: {
990 TreePatternNode *VecOperand =
991 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
994 // Filter vector types out of VecOperand that don't have the right element
996 return VecOperand->getExtType(VResNo).
997 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
999 case SDTCisSubVecOfVec: {
1000 unsigned VResNo = 0;
1001 TreePatternNode *BigVecOperand =
1002 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1005 // Filter vector types out of BigVecOperand that don't have the
1006 // right subvector type.
1007 return BigVecOperand->getExtType(VResNo).
1008 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1010 case SDTCVecEltisVT: {
1011 return NodeToApply->getExtType(ResNo).
1012 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1014 case SDTCisSameNumEltsAs: {
1015 unsigned OResNo = 0;
1016 TreePatternNode *OtherNode =
1017 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1018 N, NodeInfo, OResNo);
1019 return OtherNode->getExtType(OResNo).
1020 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1023 llvm_unreachable("Invalid ConstraintType!");
1026 // Update the node type to match an instruction operand or result as specified
1027 // in the ins or outs lists on the instruction definition. Return true if the
1028 // type was actually changed.
1029 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1032 // The 'unknown' operand indicates that types should be inferred from the
1034 if (Operand->isSubClassOf("unknown_class"))
1037 // The Operand class specifies a type directly.
1038 if (Operand->isSubClassOf("Operand"))
1039 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1042 // PointerLikeRegClass has a type that is determined at runtime.
1043 if (Operand->isSubClassOf("PointerLikeRegClass"))
1044 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1046 // Both RegisterClass and RegisterOperand operands derive their types from a
1047 // register class def.
1048 Record *RC = nullptr;
1049 if (Operand->isSubClassOf("RegisterClass"))
1051 else if (Operand->isSubClassOf("RegisterOperand"))
1052 RC = Operand->getValueAsDef("RegClass");
1054 assert(RC && "Unknown operand type");
1055 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1056 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1060 //===----------------------------------------------------------------------===//
1061 // SDNodeInfo implementation
1063 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1064 EnumName = R->getValueAsString("Opcode");
1065 SDClassName = R->getValueAsString("SDClass");
1066 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1067 NumResults = TypeProfile->getValueAsInt("NumResults");
1068 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1070 // Parse the properties.
1072 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1073 if (Property->getName() == "SDNPCommutative") {
1074 Properties |= 1 << SDNPCommutative;
1075 } else if (Property->getName() == "SDNPAssociative") {
1076 Properties |= 1 << SDNPAssociative;
1077 } else if (Property->getName() == "SDNPHasChain") {
1078 Properties |= 1 << SDNPHasChain;
1079 } else if (Property->getName() == "SDNPOutGlue") {
1080 Properties |= 1 << SDNPOutGlue;
1081 } else if (Property->getName() == "SDNPInGlue") {
1082 Properties |= 1 << SDNPInGlue;
1083 } else if (Property->getName() == "SDNPOptInGlue") {
1084 Properties |= 1 << SDNPOptInGlue;
1085 } else if (Property->getName() == "SDNPMayStore") {
1086 Properties |= 1 << SDNPMayStore;
1087 } else if (Property->getName() == "SDNPMayLoad") {
1088 Properties |= 1 << SDNPMayLoad;
1089 } else if (Property->getName() == "SDNPSideEffect") {
1090 Properties |= 1 << SDNPSideEffect;
1091 } else if (Property->getName() == "SDNPMemOperand") {
1092 Properties |= 1 << SDNPMemOperand;
1093 } else if (Property->getName() == "SDNPVariadic") {
1094 Properties |= 1 << SDNPVariadic;
1096 PrintFatalError("Unknown SD Node property '" +
1097 Property->getName() + "' on node '" +
1098 R->getName() + "'!");
1103 // Parse the type constraints.
1104 std::vector<Record*> ConstraintList =
1105 TypeProfile->getValueAsListOfDefs("Constraints");
1106 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1109 /// getKnownType - If the type constraints on this node imply a fixed type
1110 /// (e.g. all stores return void, etc), then return it as an
1111 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1112 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1113 unsigned NumResults = getNumResults();
1114 assert(NumResults <= 1 &&
1115 "We only work with nodes with zero or one result so far!");
1116 assert(ResNo == 0 && "Only handles single result nodes so far");
1118 for (const SDTypeConstraint &Constraint : TypeConstraints) {
1119 // Make sure that this applies to the correct node result.
1120 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1123 switch (Constraint.ConstraintType) {
1125 case SDTypeConstraint::SDTCisVT:
1126 return Constraint.x.SDTCisVT_Info.VT;
1127 case SDTypeConstraint::SDTCisPtrTy:
1134 //===----------------------------------------------------------------------===//
1135 // TreePatternNode implementation
1138 TreePatternNode::~TreePatternNode() {
1139 #if 0 // FIXME: implement refcounted tree nodes!
1140 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1145 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1146 if (Operator->getName() == "set" ||
1147 Operator->getName() == "implicit")
1148 return 0; // All return nothing.
1150 if (Operator->isSubClassOf("Intrinsic"))
1151 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1153 if (Operator->isSubClassOf("SDNode"))
1154 return CDP.getSDNodeInfo(Operator).getNumResults();
1156 if (Operator->isSubClassOf("PatFrag")) {
1157 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1158 // the forward reference case where one pattern fragment references another
1159 // before it is processed.
1160 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1161 return PFRec->getOnlyTree()->getNumTypes();
1163 // Get the result tree.
1164 DagInit *Tree = Operator->getValueAsDag("Fragment");
1165 Record *Op = nullptr;
1167 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1169 assert(Op && "Invalid Fragment");
1170 return GetNumNodeResults(Op, CDP);
1173 if (Operator->isSubClassOf("Instruction")) {
1174 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1176 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1178 // Subtract any defaulted outputs.
1179 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1180 Record *OperandNode = InstInfo.Operands[i].Rec;
1182 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1183 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1187 // Add on one implicit def if it has a resolvable type.
1188 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1190 return NumDefsToAdd;
1193 if (Operator->isSubClassOf("SDNodeXForm"))
1194 return 1; // FIXME: Generalize SDNodeXForm
1196 if (Operator->isSubClassOf("ValueType"))
1197 return 1; // A type-cast of one result.
1199 if (Operator->isSubClassOf("ComplexPattern"))
1203 PrintFatalError("Unhandled node in GetNumNodeResults");
1206 void TreePatternNode::print(raw_ostream &OS) const {
1208 OS << *getLeafValue();
1210 OS << '(' << getOperator()->getName();
1212 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1213 OS << ':' << getExtType(i).getName();
1216 if (getNumChildren() != 0) {
1218 getChild(0)->print(OS);
1219 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1221 getChild(i)->print(OS);
1227 for (const TreePredicateFn &Pred : PredicateFns)
1228 OS << "<<P:" << Pred.getFnName() << ">>";
1230 OS << "<<X:" << TransformFn->getName() << ">>";
1231 if (!getName().empty())
1232 OS << ":$" << getName();
1235 void TreePatternNode::dump() const {
1239 /// isIsomorphicTo - Return true if this node is recursively
1240 /// isomorphic to the specified node. For this comparison, the node's
1241 /// entire state is considered. The assigned name is ignored, since
1242 /// nodes with differing names are considered isomorphic. However, if
1243 /// the assigned name is present in the dependent variable set, then
1244 /// the assigned name is considered significant and the node is
1245 /// isomorphic if the names match.
1246 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1247 const MultipleUseVarSet &DepVars) const {
1248 if (N == this) return true;
1249 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1250 getPredicateFns() != N->getPredicateFns() ||
1251 getTransformFn() != N->getTransformFn())
1255 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1256 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1257 return ((DI->getDef() == NDI->getDef())
1258 && (DepVars.find(getName()) == DepVars.end()
1259 || getName() == N->getName()));
1262 return getLeafValue() == N->getLeafValue();
1265 if (N->getOperator() != getOperator() ||
1266 N->getNumChildren() != getNumChildren()) return false;
1267 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1268 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1273 /// clone - Make a copy of this tree and all of its children.
1275 TreePatternNode *TreePatternNode::clone() const {
1276 TreePatternNode *New;
1278 New = new TreePatternNode(getLeafValue(), getNumTypes());
1280 std::vector<TreePatternNode*> CChildren;
1281 CChildren.reserve(Children.size());
1282 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1283 CChildren.push_back(getChild(i)->clone());
1284 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1286 New->setName(getName());
1288 New->setPredicateFns(getPredicateFns());
1289 New->setTransformFn(getTransformFn());
1293 /// RemoveAllTypes - Recursively strip all the types of this tree.
1294 void TreePatternNode::RemoveAllTypes() {
1295 // Reset to unknown type.
1296 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
1297 if (isLeaf()) return;
1298 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1299 getChild(i)->RemoveAllTypes();
1303 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1304 /// with actual values specified by ArgMap.
1305 void TreePatternNode::
1306 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1307 if (isLeaf()) return;
1309 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1310 TreePatternNode *Child = getChild(i);
1311 if (Child->isLeaf()) {
1312 Init *Val = Child->getLeafValue();
1313 // Note that, when substituting into an output pattern, Val might be an
1315 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1316 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1317 // We found a use of a formal argument, replace it with its value.
1318 TreePatternNode *NewChild = ArgMap[Child->getName()];
1319 assert(NewChild && "Couldn't find formal argument!");
1320 assert((Child->getPredicateFns().empty() ||
1321 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1322 "Non-empty child predicate clobbered!");
1323 setChild(i, NewChild);
1326 getChild(i)->SubstituteFormalArguments(ArgMap);
1332 /// InlinePatternFragments - If this pattern refers to any pattern
1333 /// fragments, inline them into place, giving us a pattern without any
1334 /// PatFrag references.
1335 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1340 return this; // nothing to do.
1341 Record *Op = getOperator();
1343 if (!Op->isSubClassOf("PatFrag")) {
1344 // Just recursively inline children nodes.
1345 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1346 TreePatternNode *Child = getChild(i);
1347 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1349 assert((Child->getPredicateFns().empty() ||
1350 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1351 "Non-empty child predicate clobbered!");
1353 setChild(i, NewChild);
1358 // Otherwise, we found a reference to a fragment. First, look up its
1359 // TreePattern record.
1360 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1362 // Verify that we are passing the right number of operands.
1363 if (Frag->getNumArgs() != Children.size()) {
1364 TP.error("'" + Op->getName() + "' fragment requires " +
1365 utostr(Frag->getNumArgs()) + " operands!");
1369 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1371 TreePredicateFn PredFn(Frag);
1372 if (!PredFn.isAlwaysTrue())
1373 FragTree->addPredicateFn(PredFn);
1375 // Resolve formal arguments to their actual value.
1376 if (Frag->getNumArgs()) {
1377 // Compute the map of formal to actual arguments.
1378 std::map<std::string, TreePatternNode*> ArgMap;
1379 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1380 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1382 FragTree->SubstituteFormalArguments(ArgMap);
1385 FragTree->setName(getName());
1386 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1387 FragTree->UpdateNodeType(i, getExtType(i), TP);
1389 // Transfer in the old predicates.
1390 for (const TreePredicateFn &Pred : getPredicateFns())
1391 FragTree->addPredicateFn(Pred);
1393 // Get a new copy of this fragment to stitch into here.
1394 //delete this; // FIXME: implement refcounting!
1396 // The fragment we inlined could have recursive inlining that is needed. See
1397 // if there are any pattern fragments in it and inline them as needed.
1398 return FragTree->InlinePatternFragments(TP);
1401 /// getImplicitType - Check to see if the specified record has an implicit
1402 /// type which should be applied to it. This will infer the type of register
1403 /// references from the register file information, for example.
1405 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1406 /// the F8RC register class argument in:
1408 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
1410 /// When Unnamed is false, return the type of a named DAG operand such as the
1411 /// GPR:$src operand above.
1413 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1417 // Check to see if this is a register operand.
1418 if (R->isSubClassOf("RegisterOperand")) {
1419 assert(ResNo == 0 && "Regoperand ref only has one result!");
1421 return EEVT::TypeSet(); // Unknown.
1422 Record *RegClass = R->getValueAsDef("RegClass");
1423 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1424 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1427 // Check to see if this is a register or a register class.
1428 if (R->isSubClassOf("RegisterClass")) {
1429 assert(ResNo == 0 && "Regclass ref only has one result!");
1430 // An unnamed register class represents itself as an i32 immediate, for
1431 // example on a COPY_TO_REGCLASS instruction.
1433 return EEVT::TypeSet(MVT::i32, TP);
1435 // In a named operand, the register class provides the possible set of
1438 return EEVT::TypeSet(); // Unknown.
1439 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1440 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1443 if (R->isSubClassOf("PatFrag")) {
1444 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1445 // Pattern fragment types will be resolved when they are inlined.
1446 return EEVT::TypeSet(); // Unknown.
1449 if (R->isSubClassOf("Register")) {
1450 assert(ResNo == 0 && "Registers only produce one result!");
1452 return EEVT::TypeSet(); // Unknown.
1453 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1454 return EEVT::TypeSet(T.getRegisterVTs(R));
1457 if (R->isSubClassOf("SubRegIndex")) {
1458 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1459 return EEVT::TypeSet(MVT::i32, TP);
1462 if (R->isSubClassOf("ValueType")) {
1463 assert(ResNo == 0 && "This node only has one result!");
1464 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1466 // (sext_inreg GPR:$src, i16)
1469 return EEVT::TypeSet(MVT::Other, TP);
1470 // With a name, the ValueType simply provides the type of the named
1473 // (sext_inreg i32:$src, i16)
1476 return EEVT::TypeSet(); // Unknown.
1477 return EEVT::TypeSet(getValueType(R), TP);
1480 if (R->isSubClassOf("CondCode")) {
1481 assert(ResNo == 0 && "This node only has one result!");
1482 // Using a CondCodeSDNode.
1483 return EEVT::TypeSet(MVT::Other, TP);
1486 if (R->isSubClassOf("ComplexPattern")) {
1487 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1489 return EEVT::TypeSet(); // Unknown.
1490 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1493 if (R->isSubClassOf("PointerLikeRegClass")) {
1494 assert(ResNo == 0 && "Regclass can only have one result!");
1495 return EEVT::TypeSet(MVT::iPTR, TP);
1498 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1499 R->getName() == "zero_reg") {
1501 return EEVT::TypeSet(); // Unknown.
1504 if (R->isSubClassOf("Operand"))
1505 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1507 TP.error("Unknown node flavor used in pattern: " + R->getName());
1508 return EEVT::TypeSet(MVT::Other, TP);
1512 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1513 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1514 const CodeGenIntrinsic *TreePatternNode::
1515 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1516 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1517 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1518 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1521 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
1522 return &CDP.getIntrinsicInfo(IID);
1525 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1526 /// return the ComplexPattern information, otherwise return null.
1527 const ComplexPattern *
1528 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1531 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1536 Rec = getOperator();
1538 if (!Rec->isSubClassOf("ComplexPattern"))
1540 return &CGP.getComplexPattern(Rec);
1543 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1544 // A ComplexPattern specifically declares how many results it fills in.
1545 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1546 return CP->getNumOperands();
1548 // If MIOperandInfo is specified, that gives the count.
1550 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1551 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1552 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1553 if (MIOps->getNumArgs())
1554 return MIOps->getNumArgs();
1558 // Otherwise there is just one result.
1562 /// NodeHasProperty - Return true if this node has the specified property.
1563 bool TreePatternNode::NodeHasProperty(SDNP Property,
1564 const CodeGenDAGPatterns &CGP) const {
1566 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1567 return CP->hasProperty(Property);
1571 Record *Operator = getOperator();
1572 if (!Operator->isSubClassOf("SDNode")) return false;
1574 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1580 /// TreeHasProperty - Return true if any node in this tree has the specified
1582 bool TreePatternNode::TreeHasProperty(SDNP Property,
1583 const CodeGenDAGPatterns &CGP) const {
1584 if (NodeHasProperty(Property, CGP))
1586 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1587 if (getChild(i)->TreeHasProperty(Property, CGP))
1592 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1593 /// commutative intrinsic.
1595 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1596 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1597 return Int->isCommutative;
1601 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1603 return N->getOperator()->isSubClassOf(Class);
1605 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1606 if (DI && DI->getDef()->isSubClassOf(Class))
1612 static void emitTooManyOperandsError(TreePattern &TP,
1616 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1617 " operands but expected only " + Twine(Expected) + "!");
1620 static void emitTooFewOperandsError(TreePattern &TP,
1623 TP.error("Instruction '" + InstName +
1624 "' expects more than the provided " + Twine(Actual) + " operands!");
1627 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1628 /// this node and its children in the tree. This returns true if it makes a
1629 /// change, false otherwise. If a type contradiction is found, flag an error.
1630 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1634 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1636 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1637 // If it's a regclass or something else known, include the type.
1638 bool MadeChange = false;
1639 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1640 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1642 !hasName(), TP), TP);
1646 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
1647 assert(Types.size() == 1 && "Invalid IntInit");
1649 // Int inits are always integers. :)
1650 bool MadeChange = Types[0].EnforceInteger(TP);
1652 if (!Types[0].isConcrete())
1655 MVT::SimpleValueType VT = getType(0);
1656 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1659 unsigned Size = MVT(VT).getSizeInBits();
1660 // Make sure that the value is representable for this type.
1661 if (Size >= 32) return MadeChange;
1663 // Check that the value doesn't use more bits than we have. It must either
1664 // be a sign- or zero-extended equivalent of the original.
1665 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1666 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1669 TP.error("Integer value '" + itostr(II->getValue()) +
1670 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1676 // special handling for set, which isn't really an SDNode.
1677 if (getOperator()->getName() == "set") {
1678 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1679 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1680 unsigned NC = getNumChildren();
1682 TreePatternNode *SetVal = getChild(NC-1);
1683 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1685 for (unsigned i = 0; i < NC-1; ++i) {
1686 TreePatternNode *Child = getChild(i);
1687 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1689 // Types of operands must match.
1690 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1691 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1696 if (getOperator()->getName() == "implicit") {
1697 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1699 bool MadeChange = false;
1700 for (unsigned i = 0; i < getNumChildren(); ++i)
1701 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1705 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1706 bool MadeChange = false;
1708 // Apply the result type to the node.
1709 unsigned NumRetVTs = Int->IS.RetVTs.size();
1710 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1712 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1713 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1715 if (getNumChildren() != NumParamVTs + 1) {
1716 TP.error("Intrinsic '" + Int->Name + "' expects " +
1717 utostr(NumParamVTs) + " operands, not " +
1718 utostr(getNumChildren() - 1) + " operands!");
1722 // Apply type info to the intrinsic ID.
1723 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1725 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1726 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1728 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1729 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1730 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1735 if (getOperator()->isSubClassOf("SDNode")) {
1736 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1738 // Check that the number of operands is sane. Negative operands -> varargs.
1739 if (NI.getNumOperands() >= 0 &&
1740 getNumChildren() != (unsigned)NI.getNumOperands()) {
1741 TP.error(getOperator()->getName() + " node requires exactly " +
1742 itostr(NI.getNumOperands()) + " operands!");
1746 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1747 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1748 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1752 if (getOperator()->isSubClassOf("Instruction")) {
1753 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1754 CodeGenInstruction &InstInfo =
1755 CDP.getTargetInfo().getInstruction(getOperator());
1757 bool MadeChange = false;
1759 // Apply the result types to the node, these come from the things in the
1760 // (outs) list of the instruction.
1761 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1762 Inst.getNumResults());
1763 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1764 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
1766 // If the instruction has implicit defs, we apply the first one as a result.
1767 // FIXME: This sucks, it should apply all implicit defs.
1768 if (!InstInfo.ImplicitDefs.empty()) {
1769 unsigned ResNo = NumResultsToAdd;
1771 // FIXME: Generalize to multiple possible types and multiple possible
1773 MVT::SimpleValueType VT =
1774 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1776 if (VT != MVT::Other)
1777 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1780 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1782 if (getOperator()->getName() == "INSERT_SUBREG") {
1783 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1784 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1785 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1786 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1787 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1790 unsigned NChild = getNumChildren();
1792 TP.error("REG_SEQUENCE requires at least 3 operands!");
1796 if (NChild % 2 == 0) {
1797 TP.error("REG_SEQUENCE requires an odd number of operands!");
1801 if (!isOperandClass(getChild(0), "RegisterClass")) {
1802 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1806 for (unsigned I = 1; I < NChild; I += 2) {
1807 TreePatternNode *SubIdxChild = getChild(I + 1);
1808 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1809 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1810 itostr(I + 1) + "!");
1816 unsigned ChildNo = 0;
1817 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1818 Record *OperandNode = Inst.getOperand(i);
1820 // If the instruction expects a predicate or optional def operand, we
1821 // codegen this by setting the operand to it's default value if it has a
1822 // non-empty DefaultOps field.
1823 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1824 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1827 // Verify that we didn't run out of provided operands.
1828 if (ChildNo >= getNumChildren()) {
1829 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
1833 TreePatternNode *Child = getChild(ChildNo++);
1834 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1836 // If the operand has sub-operands, they may be provided by distinct
1837 // child patterns, so attempt to match each sub-operand separately.
1838 if (OperandNode->isSubClassOf("Operand")) {
1839 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1840 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1841 // But don't do that if the whole operand is being provided by
1842 // a single ComplexPattern-related Operand.
1844 if (Child->getNumMIResults(CDP) < NumArgs) {
1845 // Match first sub-operand against the child we already have.
1846 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1848 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1850 // And the remaining sub-operands against subsequent children.
1851 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1852 if (ChildNo >= getNumChildren()) {
1853 emitTooFewOperandsError(TP, getOperator()->getName(),
1857 Child = getChild(ChildNo++);
1859 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1861 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1868 // If we didn't match by pieces above, attempt to match the whole
1870 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
1873 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
1874 emitTooManyOperandsError(TP, getOperator()->getName(),
1875 ChildNo, getNumChildren());
1879 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1880 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1884 if (getOperator()->isSubClassOf("ComplexPattern")) {
1885 bool MadeChange = false;
1887 for (unsigned i = 0; i < getNumChildren(); ++i)
1888 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1893 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1895 // Node transforms always take one operand.
1896 if (getNumChildren() != 1) {
1897 TP.error("Node transform '" + getOperator()->getName() +
1898 "' requires one operand!");
1902 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1905 // If either the output or input of the xform does not have exact
1906 // type info. We assume they must be the same. Otherwise, it is perfectly
1907 // legal to transform from one type to a completely different type.
1909 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1910 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1911 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1918 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1919 /// RHS of a commutative operation, not the on LHS.
1920 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1921 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1923 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
1929 /// canPatternMatch - If it is impossible for this pattern to match on this
1930 /// target, fill in Reason and return false. Otherwise, return true. This is
1931 /// used as a sanity check for .td files (to prevent people from writing stuff
1932 /// that can never possibly work), and to prevent the pattern permuter from
1933 /// generating stuff that is useless.
1934 bool TreePatternNode::canPatternMatch(std::string &Reason,
1935 const CodeGenDAGPatterns &CDP) {
1936 if (isLeaf()) return true;
1938 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1939 if (!getChild(i)->canPatternMatch(Reason, CDP))
1942 // If this is an intrinsic, handle cases that would make it not match. For
1943 // example, if an operand is required to be an immediate.
1944 if (getOperator()->isSubClassOf("Intrinsic")) {
1949 if (getOperator()->isSubClassOf("ComplexPattern"))
1952 // If this node is a commutative operator, check that the LHS isn't an
1954 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1955 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1956 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1957 // Scan all of the operands of the node and make sure that only the last one
1958 // is a constant node, unless the RHS also is.
1959 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1960 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1961 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1962 if (OnlyOnRHSOfCommutative(getChild(i))) {
1963 Reason="Immediate value must be on the RHS of commutative operators!";
1972 //===----------------------------------------------------------------------===//
1973 // TreePattern implementation
1976 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1977 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1978 isInputPattern(isInput), HasError(false) {
1979 for (Init *I : RawPat->getValues())
1980 Trees.push_back(ParseTreePattern(I, ""));
1983 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1984 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1985 isInputPattern(isInput), HasError(false) {
1986 Trees.push_back(ParseTreePattern(Pat, ""));
1989 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1990 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1991 isInputPattern(isInput), HasError(false) {
1992 Trees.push_back(Pat);
1995 void TreePattern::error(const Twine &Msg) {
1999 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2003 void TreePattern::ComputeNamedNodes() {
2004 for (TreePatternNode *Tree : Trees)
2005 ComputeNamedNodes(Tree);
2008 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2009 if (!N->getName().empty())
2010 NamedNodes[N->getName()].push_back(N);
2012 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2013 ComputeNamedNodes(N->getChild(i));
2017 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2018 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2019 Record *R = DI->getDef();
2021 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2022 // TreePatternNode of its own. For example:
2023 /// (foo GPR, imm) -> (foo GPR, (imm))
2024 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2025 return ParseTreePattern(
2026 DagInit::get(DI, "",
2027 std::vector<std::pair<Init*, std::string> >()),
2031 TreePatternNode *Res = new TreePatternNode(DI, 1);
2032 if (R->getName() == "node" && !OpName.empty()) {
2034 error("'node' argument requires a name to match with operand list");
2035 Args.push_back(OpName);
2038 Res->setName(OpName);
2042 // ?:$name or just $name.
2043 if (isa<UnsetInit>(TheInit)) {
2045 error("'?' argument requires a name to match with operand list");
2046 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2047 Args.push_back(OpName);
2048 Res->setName(OpName);
2052 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2053 if (!OpName.empty())
2054 error("Constant int argument should not have a name!");
2055 return new TreePatternNode(II, 1);
2058 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2059 // Turn this into an IntInit.
2060 Init *II = BI->convertInitializerTo(IntRecTy::get());
2061 if (!II || !isa<IntInit>(II))
2062 error("Bits value must be constants!");
2063 return ParseTreePattern(II, OpName);
2066 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2069 error("Pattern has unexpected init kind!");
2071 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2072 if (!OpDef) error("Pattern has unexpected operator type!");
2073 Record *Operator = OpDef->getDef();
2075 if (Operator->isSubClassOf("ValueType")) {
2076 // If the operator is a ValueType, then this must be "type cast" of a leaf
2078 if (Dag->getNumArgs() != 1)
2079 error("Type cast only takes one operand!");
2081 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
2083 // Apply the type cast.
2084 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2085 New->UpdateNodeType(0, getValueType(Operator), *this);
2087 if (!OpName.empty())
2088 error("ValueType cast should not have a name!");
2092 // Verify that this is something that makes sense for an operator.
2093 if (!Operator->isSubClassOf("PatFrag") &&
2094 !Operator->isSubClassOf("SDNode") &&
2095 !Operator->isSubClassOf("Instruction") &&
2096 !Operator->isSubClassOf("SDNodeXForm") &&
2097 !Operator->isSubClassOf("Intrinsic") &&
2098 !Operator->isSubClassOf("ComplexPattern") &&
2099 Operator->getName() != "set" &&
2100 Operator->getName() != "implicit")
2101 error("Unrecognized node '" + Operator->getName() + "'!");
2103 // Check to see if this is something that is illegal in an input pattern.
2104 if (isInputPattern) {
2105 if (Operator->isSubClassOf("Instruction") ||
2106 Operator->isSubClassOf("SDNodeXForm"))
2107 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2109 if (Operator->isSubClassOf("Intrinsic"))
2110 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2112 if (Operator->isSubClassOf("SDNode") &&
2113 Operator->getName() != "imm" &&
2114 Operator->getName() != "fpimm" &&
2115 Operator->getName() != "tglobaltlsaddr" &&
2116 Operator->getName() != "tconstpool" &&
2117 Operator->getName() != "tjumptable" &&
2118 Operator->getName() != "tframeindex" &&
2119 Operator->getName() != "texternalsym" &&
2120 Operator->getName() != "tblockaddress" &&
2121 Operator->getName() != "tglobaladdr" &&
2122 Operator->getName() != "bb" &&
2123 Operator->getName() != "vt" &&
2124 Operator->getName() != "mcsym")
2125 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2128 std::vector<TreePatternNode*> Children;
2130 // Parse all the operands.
2131 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2132 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
2134 // If the operator is an intrinsic, then this is just syntactic sugar for for
2135 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2136 // convert the intrinsic name to a number.
2137 if (Operator->isSubClassOf("Intrinsic")) {
2138 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2139 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2141 // If this intrinsic returns void, it must have side-effects and thus a
2143 if (Int.IS.RetVTs.empty())
2144 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2145 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2146 // Has side-effects, requires chain.
2147 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2148 else // Otherwise, no chain.
2149 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2151 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2152 Children.insert(Children.begin(), IIDNode);
2155 if (Operator->isSubClassOf("ComplexPattern")) {
2156 for (unsigned i = 0; i < Children.size(); ++i) {
2157 TreePatternNode *Child = Children[i];
2159 if (Child->getName().empty())
2160 error("All arguments to a ComplexPattern must be named");
2162 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2163 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2164 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2165 auto OperandId = std::make_pair(Operator, i);
2166 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2167 if (PrevOp != ComplexPatternOperands.end()) {
2168 if (PrevOp->getValue() != OperandId)
2169 error("All ComplexPattern operands must appear consistently: "
2170 "in the same order in just one ComplexPattern instance.");
2172 ComplexPatternOperands[Child->getName()] = OperandId;
2176 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2177 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2178 Result->setName(OpName);
2180 if (!Dag->getName().empty()) {
2181 assert(Result->getName().empty());
2182 Result->setName(Dag->getName());
2187 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2188 /// will never match in favor of something obvious that will. This is here
2189 /// strictly as a convenience to target authors because it allows them to write
2190 /// more type generic things and have useless type casts fold away.
2192 /// This returns true if any change is made.
2193 static bool SimplifyTree(TreePatternNode *&N) {
2197 // If we have a bitconvert with a resolved type and if the source and
2198 // destination types are the same, then the bitconvert is useless, remove it.
2199 if (N->getOperator()->getName() == "bitconvert" &&
2200 N->getExtType(0).isConcrete() &&
2201 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2202 N->getName().empty()) {
2208 // Walk all children.
2209 bool MadeChange = false;
2210 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2211 TreePatternNode *Child = N->getChild(i);
2212 MadeChange |= SimplifyTree(Child);
2213 N->setChild(i, Child);
2220 /// InferAllTypes - Infer/propagate as many types throughout the expression
2221 /// patterns as possible. Return true if all types are inferred, false
2222 /// otherwise. Flags an error if a type contradiction is found.
2224 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2225 if (NamedNodes.empty())
2226 ComputeNamedNodes();
2228 bool MadeChange = true;
2229 while (MadeChange) {
2231 for (TreePatternNode *Tree : Trees) {
2232 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2233 MadeChange |= SimplifyTree(Tree);
2236 // If there are constraints on our named nodes, apply them.
2237 for (auto &Entry : NamedNodes) {
2238 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2240 // If we have input named node types, propagate their types to the named
2243 if (!InNamedTypes->count(Entry.getKey())) {
2244 error("Node '" + std::string(Entry.getKey()) +
2245 "' in output pattern but not input pattern");
2249 const SmallVectorImpl<TreePatternNode*> &InNodes =
2250 InNamedTypes->find(Entry.getKey())->second;
2252 // The input types should be fully resolved by now.
2253 for (TreePatternNode *Node : Nodes) {
2254 // If this node is a register class, and it is the root of the pattern
2255 // then we're mapping something onto an input register. We allow
2256 // changing the type of the input register in this case. This allows
2257 // us to match things like:
2258 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2259 if (Node == Trees[0] && Node->isLeaf()) {
2260 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
2261 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2262 DI->getDef()->isSubClassOf("RegisterOperand")))
2266 assert(Node->getNumTypes() == 1 &&
2267 InNodes[0]->getNumTypes() == 1 &&
2268 "FIXME: cannot name multiple result nodes yet");
2269 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2274 // If there are multiple nodes with the same name, they must all have the
2276 if (Entry.second.size() > 1) {
2277 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2278 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2279 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2280 "FIXME: cannot name multiple result nodes yet");
2282 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2283 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2289 bool HasUnresolvedTypes = false;
2290 for (const TreePatternNode *Tree : Trees)
2291 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
2292 return !HasUnresolvedTypes;
2295 void TreePattern::print(raw_ostream &OS) const {
2296 OS << getRecord()->getName();
2297 if (!Args.empty()) {
2298 OS << "(" << Args[0];
2299 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2300 OS << ", " << Args[i];
2305 if (Trees.size() > 1)
2307 for (const TreePatternNode *Tree : Trees) {
2313 if (Trees.size() > 1)
2317 void TreePattern::dump() const { print(errs()); }
2319 //===----------------------------------------------------------------------===//
2320 // CodeGenDAGPatterns implementation
2323 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2324 Records(R), Target(R) {
2326 Intrinsics = LoadIntrinsics(Records, false);
2327 TgtIntrinsics = LoadIntrinsics(Records, true);
2329 ParseNodeTransforms();
2330 ParseComplexPatterns();
2331 ParsePatternFragments();
2332 ParseDefaultOperands();
2333 ParseInstructions();
2334 ParsePatternFragments(/*OutFrags*/true);
2337 // Generate variants. For example, commutative patterns can match
2338 // multiple ways. Add them to PatternsToMatch as well.
2341 // Infer instruction flags. For example, we can detect loads,
2342 // stores, and side effects in many cases by examining an
2343 // instruction's pattern.
2344 InferInstructionFlags();
2346 // Verify that instruction flags match the patterns.
2347 VerifyInstructionFlags();
2350 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2351 Record *N = Records.getDef(Name);
2352 if (!N || !N->isSubClassOf("SDNode"))
2353 PrintFatalError("Error getting SDNode '" + Name + "'!");
2358 // Parse all of the SDNode definitions for the target, populating SDNodes.
2359 void CodeGenDAGPatterns::ParseNodeInfo() {
2360 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2361 while (!Nodes.empty()) {
2362 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2366 // Get the builtin intrinsic nodes.
2367 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2368 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2369 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2372 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2373 /// map, and emit them to the file as functions.
2374 void CodeGenDAGPatterns::ParseNodeTransforms() {
2375 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2376 while (!Xforms.empty()) {
2377 Record *XFormNode = Xforms.back();
2378 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2379 std::string Code = XFormNode->getValueAsString("XFormFunction");
2380 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2386 void CodeGenDAGPatterns::ParseComplexPatterns() {
2387 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2388 while (!AMs.empty()) {
2389 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2395 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2396 /// file, building up the PatternFragments map. After we've collected them all,
2397 /// inline fragments together as necessary, so that there are no references left
2398 /// inside a pattern fragment to a pattern fragment.
2400 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2401 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2403 // First step, parse all of the fragments.
2404 for (Record *Frag : Fragments) {
2405 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2408 DagInit *Tree = Frag->getValueAsDag("Fragment");
2410 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2411 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
2414 // Validate the argument list, converting it to set, to discard duplicates.
2415 std::vector<std::string> &Args = P->getArgList();
2416 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2418 if (OperandsSet.count(""))
2419 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2421 // Parse the operands list.
2422 DagInit *OpsList = Frag->getValueAsDag("Operands");
2423 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2424 // Special cases: ops == outs == ins. Different names are used to
2425 // improve readability.
2427 (OpsOp->getDef()->getName() != "ops" &&
2428 OpsOp->getDef()->getName() != "outs" &&
2429 OpsOp->getDef()->getName() != "ins"))
2430 P->error("Operands list should start with '(ops ... '!");
2432 // Copy over the arguments.
2434 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2435 if (!isa<DefInit>(OpsList->getArg(j)) ||
2436 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2437 P->error("Operands list should all be 'node' values.");
2438 if (OpsList->getArgName(j).empty())
2439 P->error("Operands list should have names for each operand!");
2440 if (!OperandsSet.count(OpsList->getArgName(j)))
2441 P->error("'" + OpsList->getArgName(j) +
2442 "' does not occur in pattern or was multiply specified!");
2443 OperandsSet.erase(OpsList->getArgName(j));
2444 Args.push_back(OpsList->getArgName(j));
2447 if (!OperandsSet.empty())
2448 P->error("Operands list does not contain an entry for operand '" +
2449 *OperandsSet.begin() + "'!");
2451 // If there is a code init for this fragment, keep track of the fact that
2452 // this fragment uses it.
2453 TreePredicateFn PredFn(P);
2454 if (!PredFn.isAlwaysTrue())
2455 P->getOnlyTree()->addPredicateFn(PredFn);
2457 // If there is a node transformation corresponding to this, keep track of
2459 Record *Transform = Frag->getValueAsDef("OperandTransform");
2460 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2461 P->getOnlyTree()->setTransformFn(Transform);
2464 // Now that we've parsed all of the tree fragments, do a closure on them so
2465 // that there are not references to PatFrags left inside of them.
2466 for (Record *Frag : Fragments) {
2467 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2470 TreePattern &ThePat = *PatternFragments[Frag];
2471 ThePat.InlinePatternFragments();
2473 // Infer as many types as possible. Don't worry about it if we don't infer
2474 // all of them, some may depend on the inputs of the pattern.
2475 ThePat.InferAllTypes();
2476 ThePat.resetError();
2478 // If debugging, print out the pattern fragment result.
2479 DEBUG(ThePat.dump());
2483 void CodeGenDAGPatterns::ParseDefaultOperands() {
2484 std::vector<Record*> DefaultOps;
2485 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2487 // Find some SDNode.
2488 assert(!SDNodes.empty() && "No SDNodes parsed?");
2489 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2491 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2492 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
2494 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2495 // SomeSDnode so that we can parse this.
2496 std::vector<std::pair<Init*, std::string> > Ops;
2497 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2498 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2499 DefaultInfo->getArgName(op)));
2500 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
2502 // Create a TreePattern to parse this.
2503 TreePattern P(DefaultOps[i], DI, false, *this);
2504 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2506 // Copy the operands over into a DAGDefaultOperand.
2507 DAGDefaultOperand DefaultOpInfo;
2509 TreePatternNode *T = P.getTree(0);
2510 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2511 TreePatternNode *TPN = T->getChild(op);
2512 while (TPN->ApplyTypeConstraints(P, false))
2513 /* Resolve all types */;
2515 if (TPN->ContainsUnresolvedType()) {
2516 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2517 DefaultOps[i]->getName() +
2518 "' doesn't have a concrete type!");
2520 DefaultOpInfo.DefaultOps.push_back(TPN);
2523 // Insert it into the DefaultOperands map so we can find it later.
2524 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
2528 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2529 /// instruction input. Return true if this is a real use.
2530 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2531 std::map<std::string, TreePatternNode*> &InstInputs) {
2532 // No name -> not interesting.
2533 if (Pat->getName().empty()) {
2534 if (Pat->isLeaf()) {
2535 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2536 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2537 DI->getDef()->isSubClassOf("RegisterOperand")))
2538 I->error("Input " + DI->getDef()->getName() + " must be named!");
2544 if (Pat->isLeaf()) {
2545 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2546 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2549 Rec = Pat->getOperator();
2552 // SRCVALUE nodes are ignored.
2553 if (Rec->getName() == "srcvalue")
2556 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2562 if (Slot->isLeaf()) {
2563 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
2565 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2566 SlotRec = Slot->getOperator();
2569 // Ensure that the inputs agree if we've already seen this input.
2571 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2572 if (Slot->getExtTypes() != Pat->getExtTypes())
2573 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2577 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2578 /// part of "I", the instruction), computing the set of inputs and outputs of
2579 /// the pattern. Report errors if we see anything naughty.
2580 void CodeGenDAGPatterns::
2581 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2582 std::map<std::string, TreePatternNode*> &InstInputs,
2583 std::map<std::string, TreePatternNode*>&InstResults,
2584 std::vector<Record*> &InstImpResults) {
2585 if (Pat->isLeaf()) {
2586 bool isUse = HandleUse(I, Pat, InstInputs);
2587 if (!isUse && Pat->getTransformFn())
2588 I->error("Cannot specify a transform function for a non-input value!");
2592 if (Pat->getOperator()->getName() == "implicit") {
2593 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2594 TreePatternNode *Dest = Pat->getChild(i);
2595 if (!Dest->isLeaf())
2596 I->error("implicitly defined value should be a register!");
2598 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2599 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2600 I->error("implicitly defined value should be a register!");
2601 InstImpResults.push_back(Val->getDef());
2606 if (Pat->getOperator()->getName() != "set") {
2607 // If this is not a set, verify that the children nodes are not void typed,
2609 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2610 if (Pat->getChild(i)->getNumTypes() == 0)
2611 I->error("Cannot have void nodes inside of patterns!");
2612 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2616 // If this is a non-leaf node with no children, treat it basically as if
2617 // it were a leaf. This handles nodes like (imm).
2618 bool isUse = HandleUse(I, Pat, InstInputs);
2620 if (!isUse && Pat->getTransformFn())
2621 I->error("Cannot specify a transform function for a non-input value!");
2625 // Otherwise, this is a set, validate and collect instruction results.
2626 if (Pat->getNumChildren() == 0)
2627 I->error("set requires operands!");
2629 if (Pat->getTransformFn())
2630 I->error("Cannot specify a transform function on a set node!");
2632 // Check the set destinations.
2633 unsigned NumDests = Pat->getNumChildren()-1;
2634 for (unsigned i = 0; i != NumDests; ++i) {
2635 TreePatternNode *Dest = Pat->getChild(i);
2636 if (!Dest->isLeaf())
2637 I->error("set destination should be a register!");
2639 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2641 I->error("set destination should be a register!");
2645 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2646 Val->getDef()->isSubClassOf("ValueType") ||
2647 Val->getDef()->isSubClassOf("RegisterOperand") ||
2648 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2649 if (Dest->getName().empty())
2650 I->error("set destination must have a name!");
2651 if (InstResults.count(Dest->getName()))
2652 I->error("cannot set '" + Dest->getName() +"' multiple times");
2653 InstResults[Dest->getName()] = Dest;
2654 } else if (Val->getDef()->isSubClassOf("Register")) {
2655 InstImpResults.push_back(Val->getDef());
2657 I->error("set destination should be a register!");
2661 // Verify and collect info from the computation.
2662 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2663 InstInputs, InstResults, InstImpResults);
2666 //===----------------------------------------------------------------------===//
2667 // Instruction Analysis
2668 //===----------------------------------------------------------------------===//
2670 class InstAnalyzer {
2671 const CodeGenDAGPatterns &CDP;
2673 bool hasSideEffects;
2679 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2680 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2681 isBitcast(false), isVariadic(false) {}
2683 void Analyze(const TreePattern *Pat) {
2684 // Assume only the first tree is the pattern. The others are clobber nodes.
2685 AnalyzeNode(Pat->getTree(0));
2688 void Analyze(const PatternToMatch *Pat) {
2689 AnalyzeNode(Pat->getSrcPattern());
2693 bool IsNodeBitcast(const TreePatternNode *N) const {
2694 if (hasSideEffects || mayLoad || mayStore || isVariadic)
2697 if (N->getNumChildren() != 2)
2700 const TreePatternNode *N0 = N->getChild(0);
2701 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
2704 const TreePatternNode *N1 = N->getChild(1);
2707 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2710 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2711 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2713 return OpInfo.getEnumName() == "ISD::BITCAST";
2717 void AnalyzeNode(const TreePatternNode *N) {
2719 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
2720 Record *LeafRec = DI->getDef();
2721 // Handle ComplexPattern leaves.
2722 if (LeafRec->isSubClassOf("ComplexPattern")) {
2723 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2724 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2725 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2726 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2732 // Analyze children.
2733 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2734 AnalyzeNode(N->getChild(i));
2736 // Ignore set nodes, which are not SDNodes.
2737 if (N->getOperator()->getName() == "set") {
2738 isBitcast = IsNodeBitcast(N);
2742 // Notice properties of the node.
2743 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2744 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2745 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2746 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
2748 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2749 // If this is an intrinsic, analyze it.
2750 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2751 mayLoad = true;// These may load memory.
2753 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2754 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2756 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2757 // WriteMem intrinsics can have other strange effects.
2758 hasSideEffects = true;
2764 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2765 const InstAnalyzer &PatInfo,
2769 // Remember where InstInfo got its flags.
2770 if (InstInfo.hasUndefFlags())
2771 InstInfo.InferredFrom = PatDef;
2773 // Check explicitly set flags for consistency.
2774 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2775 !InstInfo.hasSideEffects_Unset) {
2776 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2777 // the pattern has no side effects. That could be useful for div/rem
2778 // instructions that may trap.
2779 if (!InstInfo.hasSideEffects) {
2781 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2782 Twine(InstInfo.hasSideEffects));
2786 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2788 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2789 Twine(InstInfo.mayStore));
2792 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2793 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2794 // Some targets translate immediates to loads.
2795 if (!InstInfo.mayLoad) {
2797 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2798 Twine(InstInfo.mayLoad));
2802 // Transfer inferred flags.
2803 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2804 InstInfo.mayStore |= PatInfo.mayStore;
2805 InstInfo.mayLoad |= PatInfo.mayLoad;
2807 // These flags are silently added without any verification.
2808 InstInfo.isBitcast |= PatInfo.isBitcast;
2810 // Don't infer isVariadic. This flag means something different on SDNodes and
2811 // instructions. For example, a CALL SDNode is variadic because it has the
2812 // call arguments as operands, but a CALL instruction is not variadic - it
2813 // has argument registers as implicit, not explicit uses.
2818 /// hasNullFragReference - Return true if the DAG has any reference to the
2819 /// null_frag operator.
2820 static bool hasNullFragReference(DagInit *DI) {
2821 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
2822 if (!OpDef) return false;
2823 Record *Operator = OpDef->getDef();
2825 // If this is the null fragment, return true.
2826 if (Operator->getName() == "null_frag") return true;
2827 // If any of the arguments reference the null fragment, return true.
2828 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2829 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
2830 if (Arg && hasNullFragReference(Arg))
2837 /// hasNullFragReference - Return true if any DAG in the list references
2838 /// the null_frag operator.
2839 static bool hasNullFragReference(ListInit *LI) {
2840 for (Init *I : LI->getValues()) {
2841 DagInit *DI = dyn_cast<DagInit>(I);
2842 assert(DI && "non-dag in an instruction Pattern list?!");
2843 if (hasNullFragReference(DI))
2849 /// Get all the instructions in a tree.
2851 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2854 if (Tree->getOperator()->isSubClassOf("Instruction"))
2855 Instrs.push_back(Tree->getOperator());
2856 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2857 getInstructionsInTree(Tree->getChild(i), Instrs);
2860 /// Check the class of a pattern leaf node against the instruction operand it
2862 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2867 // Allow direct value types to be used in instruction set patterns.
2868 // The type will be checked later.
2869 if (Leaf->isSubClassOf("ValueType"))
2872 // Patterns can also be ComplexPattern instances.
2873 if (Leaf->isSubClassOf("ComplexPattern"))
2879 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2880 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
2882 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
2884 // Parse the instruction.
2885 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2886 // Inline pattern fragments into it.
2887 I->InlinePatternFragments();
2889 // Infer as many types as possible. If we cannot infer all of them, we can
2890 // never do anything with this instruction pattern: report it to the user.
2891 if (!I->InferAllTypes())
2892 I->error("Could not infer all types in pattern!");
2894 // InstInputs - Keep track of all of the inputs of the instruction, along
2895 // with the record they are declared as.
2896 std::map<std::string, TreePatternNode*> InstInputs;
2898 // InstResults - Keep track of all the virtual registers that are 'set'
2899 // in the instruction, including what reg class they are.
2900 std::map<std::string, TreePatternNode*> InstResults;
2902 std::vector<Record*> InstImpResults;
2904 // Verify that the top-level forms in the instruction are of void type, and
2905 // fill in the InstResults map.
2906 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2907 TreePatternNode *Pat = I->getTree(j);
2908 if (Pat->getNumTypes() != 0)
2909 I->error("Top-level forms in instruction pattern should have"
2912 // Find inputs and outputs, and verify the structure of the uses/defs.
2913 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2917 // Now that we have inputs and outputs of the pattern, inspect the operands
2918 // list for the instruction. This determines the order that operands are
2919 // added to the machine instruction the node corresponds to.
2920 unsigned NumResults = InstResults.size();
2922 // Parse the operands list from the (ops) list, validating it.
2923 assert(I->getArgList().empty() && "Args list should still be empty here!");
2925 // Check that all of the results occur first in the list.
2926 std::vector<Record*> Results;
2927 SmallVector<TreePatternNode *, 2> ResNodes;
2928 for (unsigned i = 0; i != NumResults; ++i) {
2929 if (i == CGI.Operands.size())
2930 I->error("'" + InstResults.begin()->first +
2931 "' set but does not appear in operand list!");
2932 const std::string &OpName = CGI.Operands[i].Name;
2934 // Check that it exists in InstResults.
2935 TreePatternNode *RNode = InstResults[OpName];
2937 I->error("Operand $" + OpName + " does not exist in operand list!");
2939 ResNodes.push_back(RNode);
2941 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2943 I->error("Operand $" + OpName + " should be a set destination: all "
2944 "outputs must occur before inputs in operand list!");
2946 if (!checkOperandClass(CGI.Operands[i], R))
2947 I->error("Operand $" + OpName + " class mismatch!");
2949 // Remember the return type.
2950 Results.push_back(CGI.Operands[i].Rec);
2952 // Okay, this one checks out.
2953 InstResults.erase(OpName);
2956 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2957 // the copy while we're checking the inputs.
2958 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2960 std::vector<TreePatternNode*> ResultNodeOperands;
2961 std::vector<Record*> Operands;
2962 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2963 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2964 const std::string &OpName = Op.Name;
2966 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2968 if (!InstInputsCheck.count(OpName)) {
2969 // If this is an operand with a DefaultOps set filled in, we can ignore
2970 // this. When we codegen it, we will do so as always executed.
2971 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2972 // Does it have a non-empty DefaultOps field? If so, ignore this
2974 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2977 I->error("Operand $" + OpName +
2978 " does not appear in the instruction pattern");
2980 TreePatternNode *InVal = InstInputsCheck[OpName];
2981 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2983 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
2984 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2985 if (!checkOperandClass(Op, InRec))
2986 I->error("Operand $" + OpName + "'s register class disagrees"
2987 " between the operand and pattern");
2989 Operands.push_back(Op.Rec);
2991 // Construct the result for the dest-pattern operand list.
2992 TreePatternNode *OpNode = InVal->clone();
2994 // No predicate is useful on the result.
2995 OpNode->clearPredicateFns();
2997 // Promote the xform function to be an explicit node if set.
2998 if (Record *Xform = OpNode->getTransformFn()) {
2999 OpNode->setTransformFn(nullptr);
3000 std::vector<TreePatternNode*> Children;
3001 Children.push_back(OpNode);
3002 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3005 ResultNodeOperands.push_back(OpNode);
3008 if (!InstInputsCheck.empty())
3009 I->error("Input operand $" + InstInputsCheck.begin()->first +
3010 " occurs in pattern but not in operands list!");
3012 TreePatternNode *ResultPattern =
3013 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3014 GetNumNodeResults(I->getRecord(), *this));
3015 // Copy fully inferred output node types to instruction result pattern.
3016 for (unsigned i = 0; i != NumResults; ++i) {
3017 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3018 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3021 // Create and insert the instruction.
3022 // FIXME: InstImpResults should not be part of DAGInstruction.
3023 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3024 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3026 // Use a temporary tree pattern to infer all types and make sure that the
3027 // constructed result is correct. This depends on the instruction already
3028 // being inserted into the DAGInsts map.
3029 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3030 Temp.InferAllTypes(&I->getNamedNodesMap());
3032 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3033 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3035 return TheInsertedInst;
3038 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3039 /// any fragments involved. This populates the Instructions list with fully
3040 /// resolved instructions.
3041 void CodeGenDAGPatterns::ParseInstructions() {
3042 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3044 for (Record *Instr : Instrs) {
3045 ListInit *LI = nullptr;
3047 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3048 LI = Instr->getValueAsListInit("Pattern");
3050 // If there is no pattern, only collect minimal information about the
3051 // instruction for its operand list. We have to assume that there is one
3052 // result, as we have no detailed info. A pattern which references the
3053 // null_frag operator is as-if no pattern were specified. Normally this
3054 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3056 if (!LI || LI->empty() || hasNullFragReference(LI)) {
3057 std::vector<Record*> Results;
3058 std::vector<Record*> Operands;
3060 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3062 if (InstInfo.Operands.size() != 0) {
3063 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3064 Results.push_back(InstInfo.Operands[j].Rec);
3066 // The rest are inputs.
3067 for (unsigned j = InstInfo.Operands.NumDefs,
3068 e = InstInfo.Operands.size(); j < e; ++j)
3069 Operands.push_back(InstInfo.Operands[j].Rec);
3072 // Create and insert the instruction.
3073 std::vector<Record*> ImpResults;
3074 Instructions.insert(std::make_pair(Instr,
3075 DAGInstruction(nullptr, Results, Operands, ImpResults)));
3076 continue; // no pattern.
3079 CodeGenInstruction &CGI = Target.getInstruction(Instr);
3080 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3083 DEBUG(DI.getPattern()->dump());
3086 // If we can, convert the instructions to be patterns that are matched!
3087 for (auto &Entry : Instructions) {
3088 DAGInstruction &TheInst = Entry.second;
3089 TreePattern *I = TheInst.getPattern();
3090 if (!I) continue; // No pattern.
3092 // FIXME: Assume only the first tree is the pattern. The others are clobber
3094 TreePatternNode *Pattern = I->getTree(0);
3095 TreePatternNode *SrcPattern;
3096 if (Pattern->getOperator()->getName() == "set") {
3097 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3099 // Not a set (store or something?)
3100 SrcPattern = Pattern;
3103 Record *Instr = Entry.first;
3104 AddPatternToMatch(I,
3105 PatternToMatch(Instr,
3106 Instr->getValueAsListInit("Predicates"),
3108 TheInst.getResultPattern(),
3109 TheInst.getImpResults(),
3110 Instr->getValueAsInt("AddedComplexity"),
3116 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3118 static void FindNames(const TreePatternNode *P,
3119 std::map<std::string, NameRecord> &Names,
3120 TreePattern *PatternTop) {
3121 if (!P->getName().empty()) {
3122 NameRecord &Rec = Names[P->getName()];
3123 // If this is the first instance of the name, remember the node.
3124 if (Rec.second++ == 0)
3126 else if (Rec.first->getExtTypes() != P->getExtTypes())
3127 PatternTop->error("repetition of value: $" + P->getName() +
3128 " where different uses have different types!");
3132 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3133 FindNames(P->getChild(i), Names, PatternTop);
3137 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3138 const PatternToMatch &PTM) {
3139 // Do some sanity checking on the pattern we're about to match.
3141 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3142 PrintWarning(Pattern->getRecord()->getLoc(),
3143 Twine("Pattern can never match: ") + Reason);
3147 // If the source pattern's root is a complex pattern, that complex pattern
3148 // must specify the nodes it can potentially match.
3149 if (const ComplexPattern *CP =
3150 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3151 if (CP->getRootNodes().empty())
3152 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3156 // Find all of the named values in the input and output, ensure they have the
3158 std::map<std::string, NameRecord> SrcNames, DstNames;
3159 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3160 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3162 // Scan all of the named values in the destination pattern, rejecting them if
3163 // they don't exist in the input pattern.
3164 for (const auto &Entry : DstNames) {
3165 if (SrcNames[Entry.first].first == nullptr)
3166 Pattern->error("Pattern has input without matching name in output: $" +
3170 // Scan all of the named values in the source pattern, rejecting them if the
3171 // name isn't used in the dest, and isn't used to tie two values together.
3172 for (const auto &Entry : SrcNames)
3173 if (DstNames[Entry.first].first == nullptr &&
3174 SrcNames[Entry.first].second == 1)
3175 Pattern->error("Pattern has dead named input: $" + Entry.first);
3177 PatternsToMatch.push_back(PTM);
3182 void CodeGenDAGPatterns::InferInstructionFlags() {
3183 const std::vector<const CodeGenInstruction*> &Instructions =
3184 Target.getInstructionsByEnumValue();
3186 // First try to infer flags from the primary instruction pattern, if any.
3187 SmallVector<CodeGenInstruction*, 8> Revisit;
3188 unsigned Errors = 0;
3189 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3190 CodeGenInstruction &InstInfo =
3191 const_cast<CodeGenInstruction &>(*Instructions[i]);
3193 // Get the primary instruction pattern.
3194 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3196 if (InstInfo.hasUndefFlags())
3197 Revisit.push_back(&InstInfo);
3200 InstAnalyzer PatInfo(*this);
3201 PatInfo.Analyze(Pattern);
3202 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3205 // Second, look for single-instruction patterns defined outside the
3207 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3208 const PatternToMatch &PTM = *I;
3210 // We can only infer from single-instruction patterns, otherwise we won't
3211 // know which instruction should get the flags.
3212 SmallVector<Record*, 8> PatInstrs;
3213 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3214 if (PatInstrs.size() != 1)
3217 // Get the single instruction.
3218 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3220 // Only infer properties from the first pattern. We'll verify the others.
3221 if (InstInfo.InferredFrom)
3224 InstAnalyzer PatInfo(*this);
3225 PatInfo.Analyze(&PTM);
3226 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3230 PrintFatalError("pattern conflicts");
3232 // Revisit instructions with undefined flags and no pattern.
3233 if (Target.guessInstructionProperties()) {
3234 for (CodeGenInstruction *InstInfo : Revisit) {
3235 if (InstInfo->InferredFrom)
3237 // The mayLoad and mayStore flags default to false.
3238 // Conservatively assume hasSideEffects if it wasn't explicit.
3239 if (InstInfo->hasSideEffects_Unset)
3240 InstInfo->hasSideEffects = true;
3245 // Complain about any flags that are still undefined.
3246 for (CodeGenInstruction *InstInfo : Revisit) {
3247 if (InstInfo->InferredFrom)
3249 if (InstInfo->hasSideEffects_Unset)
3250 PrintError(InstInfo->TheDef->getLoc(),
3251 "Can't infer hasSideEffects from patterns");
3252 if (InstInfo->mayStore_Unset)
3253 PrintError(InstInfo->TheDef->getLoc(),
3254 "Can't infer mayStore from patterns");
3255 if (InstInfo->mayLoad_Unset)
3256 PrintError(InstInfo->TheDef->getLoc(),
3257 "Can't infer mayLoad from patterns");
3262 /// Verify instruction flags against pattern node properties.
3263 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3264 unsigned Errors = 0;
3265 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3266 const PatternToMatch &PTM = *I;
3267 SmallVector<Record*, 8> Instrs;
3268 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3272 // Count the number of instructions with each flag set.
3273 unsigned NumSideEffects = 0;
3274 unsigned NumStores = 0;
3275 unsigned NumLoads = 0;
3276 for (const Record *Instr : Instrs) {
3277 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3278 NumSideEffects += InstInfo.hasSideEffects;
3279 NumStores += InstInfo.mayStore;
3280 NumLoads += InstInfo.mayLoad;
3283 // Analyze the source pattern.
3284 InstAnalyzer PatInfo(*this);
3285 PatInfo.Analyze(&PTM);
3287 // Collect error messages.
3288 SmallVector<std::string, 4> Msgs;
3290 // Check for missing flags in the output.
3291 // Permit extra flags for now at least.
3292 if (PatInfo.hasSideEffects && !NumSideEffects)
3293 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3295 // Don't verify store flags on instructions with side effects. At least for
3296 // intrinsics, side effects implies mayStore.
3297 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3298 Msgs.push_back("pattern may store, but mayStore isn't set");
3300 // Similarly, mayStore implies mayLoad on intrinsics.
3301 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3302 Msgs.push_back("pattern may load, but mayLoad isn't set");
3304 // Print error messages.
3309 for (const std::string &Msg : Msgs)
3310 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
3311 (Instrs.size() == 1 ?
3312 "instruction" : "output instructions"));
3313 // Provide the location of the relevant instruction definitions.
3314 for (const Record *Instr : Instrs) {
3315 if (Instr != PTM.getSrcRecord())
3316 PrintError(Instr->getLoc(), "defined here");
3317 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3318 if (InstInfo.InferredFrom &&
3319 InstInfo.InferredFrom != InstInfo.TheDef &&
3320 InstInfo.InferredFrom != PTM.getSrcRecord())
3321 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3325 PrintFatalError("Errors in DAG patterns");
3328 /// Given a pattern result with an unresolved type, see if we can find one
3329 /// instruction with an unresolved result type. Force this result type to an
3330 /// arbitrary element if it's possible types to converge results.
3331 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3335 // Analyze children.
3336 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3337 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3340 if (!N->getOperator()->isSubClassOf("Instruction"))
3343 // If this type is already concrete or completely unknown we can't do
3345 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3346 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3349 // Otherwise, force its type to the first possibility (an arbitrary choice).
3350 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3357 void CodeGenDAGPatterns::ParsePatterns() {
3358 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3360 for (Record *CurPattern : Patterns) {
3361 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3363 // If the pattern references the null_frag, there's nothing to do.
3364 if (hasNullFragReference(Tree))
3367 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3369 // Inline pattern fragments into it.
3370 Pattern->InlinePatternFragments();
3372 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3373 if (LI->empty()) continue; // no pattern.
3375 // Parse the instruction.
3376 TreePattern Result(CurPattern, LI, false, *this);
3378 // Inline pattern fragments into it.
3379 Result.InlinePatternFragments();
3381 if (Result.getNumTrees() != 1)
3382 Result.error("Cannot handle instructions producing instructions "
3383 "with temporaries yet!");
3385 bool IterateInference;
3386 bool InferredAllPatternTypes, InferredAllResultTypes;
3388 // Infer as many types as possible. If we cannot infer all of them, we
3389 // can never do anything with this pattern: report it to the user.
3390 InferredAllPatternTypes =
3391 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3393 // Infer as many types as possible. If we cannot infer all of them, we
3394 // can never do anything with this pattern: report it to the user.
3395 InferredAllResultTypes =
3396 Result.InferAllTypes(&Pattern->getNamedNodesMap());
3398 IterateInference = false;
3400 // Apply the type of the result to the source pattern. This helps us
3401 // resolve cases where the input type is known to be a pointer type (which
3402 // is considered resolved), but the result knows it needs to be 32- or
3403 // 64-bits. Infer the other way for good measure.
3404 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3405 Pattern->getTree(0)->getNumTypes());
3407 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3408 i, Result.getTree(0)->getExtType(i), Result);
3409 IterateInference |= Result.getTree(0)->UpdateNodeType(
3410 i, Pattern->getTree(0)->getExtType(i), Result);
3413 // If our iteration has converged and the input pattern's types are fully
3414 // resolved but the result pattern is not fully resolved, we may have a
3415 // situation where we have two instructions in the result pattern and
3416 // the instructions require a common register class, but don't care about
3417 // what actual MVT is used. This is actually a bug in our modelling:
3418 // output patterns should have register classes, not MVTs.
3420 // In any case, to handle this, we just go through and disambiguate some
3421 // arbitrary types to the result pattern's nodes.
3422 if (!IterateInference && InferredAllPatternTypes &&
3423 !InferredAllResultTypes)
3425 ForceArbitraryInstResultType(Result.getTree(0), Result);
3426 } while (IterateInference);
3428 // Verify that we inferred enough types that we can do something with the
3429 // pattern and result. If these fire the user has to add type casts.
3430 if (!InferredAllPatternTypes)
3431 Pattern->error("Could not infer all types in pattern!");
3432 if (!InferredAllResultTypes) {
3434 Result.error("Could not infer all types in pattern result!");
3437 // Validate that the input pattern is correct.
3438 std::map<std::string, TreePatternNode*> InstInputs;
3439 std::map<std::string, TreePatternNode*> InstResults;
3440 std::vector<Record*> InstImpResults;
3441 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3442 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3443 InstInputs, InstResults,
3446 // Promote the xform function to be an explicit node if set.
3447 TreePatternNode *DstPattern = Result.getOnlyTree();
3448 std::vector<TreePatternNode*> ResultNodeOperands;
3449 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3450 TreePatternNode *OpNode = DstPattern->getChild(ii);
3451 if (Record *Xform = OpNode->getTransformFn()) {
3452 OpNode->setTransformFn(nullptr);
3453 std::vector<TreePatternNode*> Children;
3454 Children.push_back(OpNode);
3455 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3457 ResultNodeOperands.push_back(OpNode);
3459 DstPattern = Result.getOnlyTree();
3460 if (!DstPattern->isLeaf())
3461 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3463 DstPattern->getNumTypes());
3465 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3466 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3468 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
3469 Temp.InferAllTypes();
3472 AddPatternToMatch(Pattern,
3473 PatternToMatch(CurPattern,
3474 CurPattern->getValueAsListInit("Predicates"),
3475 Pattern->getTree(0),
3476 Temp.getOnlyTree(), InstImpResults,
3477 CurPattern->getValueAsInt("AddedComplexity"),
3478 CurPattern->getID()));
3482 /// CombineChildVariants - Given a bunch of permutations of each child of the
3483 /// 'operator' node, put them together in all possible ways.
3484 static void CombineChildVariants(TreePatternNode *Orig,
3485 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3486 std::vector<TreePatternNode*> &OutVariants,
3487 CodeGenDAGPatterns &CDP,
3488 const MultipleUseVarSet &DepVars) {
3489 // Make sure that each operand has at least one variant to choose from.
3490 for (const auto &Variants : ChildVariants)
3491 if (Variants.empty())
3494 // The end result is an all-pairs construction of the resultant pattern.
3495 std::vector<unsigned> Idxs;
3496 Idxs.resize(ChildVariants.size());
3500 DEBUG(if (!Idxs.empty()) {
3501 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3502 for (unsigned Idx : Idxs) {
3503 errs() << Idx << " ";
3508 // Create the variant and add it to the output list.
3509 std::vector<TreePatternNode*> NewChildren;
3510 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3511 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3512 auto R = llvm::make_unique<TreePatternNode>(
3513 Orig->getOperator(), NewChildren, Orig->getNumTypes());
3515 // Copy over properties.
3516 R->setName(Orig->getName());
3517 R->setPredicateFns(Orig->getPredicateFns());
3518 R->setTransformFn(Orig->getTransformFn());
3519 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3520 R->setType(i, Orig->getExtType(i));
3522 // If this pattern cannot match, do not include it as a variant.
3523 std::string ErrString;
3524 // Scan to see if this pattern has already been emitted. We can get
3525 // duplication due to things like commuting:
3526 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3527 // which are the same pattern. Ignore the dups.
3528 if (R->canPatternMatch(ErrString, CDP) &&
3529 std::none_of(OutVariants.begin(), OutVariants.end(),
3530 [&](TreePatternNode *Variant) {
3531 return R->isIsomorphicTo(Variant, DepVars);
3533 OutVariants.push_back(R.release());
3535 // Increment indices to the next permutation by incrementing the
3536 // indices from last index backward, e.g., generate the sequence
3537 // [0, 0], [0, 1], [1, 0], [1, 1].
3539 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3540 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3545 NotDone = (IdxsIdx >= 0);
3549 /// CombineChildVariants - A helper function for binary operators.
3551 static void CombineChildVariants(TreePatternNode *Orig,
3552 const std::vector<TreePatternNode*> &LHS,
3553 const std::vector<TreePatternNode*> &RHS,
3554 std::vector<TreePatternNode*> &OutVariants,
3555 CodeGenDAGPatterns &CDP,
3556 const MultipleUseVarSet &DepVars) {
3557 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3558 ChildVariants.push_back(LHS);
3559 ChildVariants.push_back(RHS);
3560 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3564 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3565 std::vector<TreePatternNode *> &Children) {
3566 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3567 Record *Operator = N->getOperator();
3569 // Only permit raw nodes.
3570 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3571 N->getTransformFn()) {
3572 Children.push_back(N);
3576 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3577 Children.push_back(N->getChild(0));
3579 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3581 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3582 Children.push_back(N->getChild(1));
3584 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3587 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3588 /// the (potentially recursive) pattern by using algebraic laws.
3590 static void GenerateVariantsOf(TreePatternNode *N,
3591 std::vector<TreePatternNode*> &OutVariants,
3592 CodeGenDAGPatterns &CDP,
3593 const MultipleUseVarSet &DepVars) {
3594 // We cannot permute leaves or ComplexPattern uses.
3595 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
3596 OutVariants.push_back(N);
3600 // Look up interesting info about the node.
3601 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3603 // If this node is associative, re-associate.
3604 if (NodeInfo.hasProperty(SDNPAssociative)) {
3605 // Re-associate by pulling together all of the linked operators
3606 std::vector<TreePatternNode*> MaximalChildren;
3607 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3609 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3611 if (MaximalChildren.size() == 3) {
3612 // Find the variants of all of our maximal children.
3613 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3614 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3615 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3616 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3618 // There are only two ways we can permute the tree:
3619 // (A op B) op C and A op (B op C)
3620 // Within these forms, we can also permute A/B/C.
3622 // Generate legal pair permutations of A/B/C.
3623 std::vector<TreePatternNode*> ABVariants;
3624 std::vector<TreePatternNode*> BAVariants;
3625 std::vector<TreePatternNode*> ACVariants;
3626 std::vector<TreePatternNode*> CAVariants;
3627 std::vector<TreePatternNode*> BCVariants;
3628 std::vector<TreePatternNode*> CBVariants;
3629 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3630 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3631 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3632 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3633 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3634 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3636 // Combine those into the result: (x op x) op x
3637 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3638 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3639 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3640 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3641 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3642 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3644 // Combine those into the result: x op (x op x)
3645 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3646 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3647 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3648 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3649 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3650 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3655 // Compute permutations of all children.
3656 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3657 ChildVariants.resize(N->getNumChildren());
3658 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3659 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3661 // Build all permutations based on how the children were formed.
3662 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3664 // If this node is commutative, consider the commuted order.
3665 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3666 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3667 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3668 "Commutative but doesn't have 2 children!");
3669 // Don't count children which are actually register references.
3671 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3672 TreePatternNode *Child = N->getChild(i);
3673 if (Child->isLeaf())
3674 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
3675 Record *RR = DI->getDef();
3676 if (RR->isSubClassOf("Register"))
3681 // Consider the commuted order.
3682 if (isCommIntrinsic) {
3683 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3684 // operands are the commutative operands, and there might be more operands
3687 "Commutative intrinsic should have at least 3 children!");
3688 std::vector<std::vector<TreePatternNode*> > Variants;
3689 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3690 Variants.push_back(ChildVariants[2]);
3691 Variants.push_back(ChildVariants[1]);
3692 for (unsigned i = 3; i != NC; ++i)
3693 Variants.push_back(ChildVariants[i]);
3694 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3696 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3697 OutVariants, CDP, DepVars);
3702 // GenerateVariants - Generate variants. For example, commutative patterns can
3703 // match multiple ways. Add them to PatternsToMatch as well.
3704 void CodeGenDAGPatterns::GenerateVariants() {
3705 DEBUG(errs() << "Generating instruction variants.\n");
3707 // Loop over all of the patterns we've collected, checking to see if we can
3708 // generate variants of the instruction, through the exploitation of
3709 // identities. This permits the target to provide aggressive matching without
3710 // the .td file having to contain tons of variants of instructions.
3712 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3713 // intentionally do not reconsider these. Any variants of added patterns have
3714 // already been added.
3716 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3717 MultipleUseVarSet DepVars;
3718 std::vector<TreePatternNode*> Variants;
3719 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3720 DEBUG(errs() << "Dependent/multiply used variables: ");
3721 DEBUG(DumpDepVars(DepVars));
3722 DEBUG(errs() << "\n");
3723 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3726 assert(!Variants.empty() && "Must create at least original variant!");
3727 Variants.erase(Variants.begin()); // Remove the original pattern.
3729 if (Variants.empty()) // No variants for this pattern.
3732 DEBUG(errs() << "FOUND VARIANTS OF: ";
3733 PatternsToMatch[i].getSrcPattern()->dump();
3736 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3737 TreePatternNode *Variant = Variants[v];
3739 DEBUG(errs() << " VAR#" << v << ": ";
3743 // Scan to see if an instruction or explicit pattern already matches this.
3744 bool AlreadyExists = false;
3745 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3746 // Skip if the top level predicates do not match.
3747 if (PatternsToMatch[i].getPredicates() !=
3748 PatternsToMatch[p].getPredicates())
3750 // Check to see if this variant already exists.
3751 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3753 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3754 AlreadyExists = true;
3758 // If we already have it, ignore the variant.
3759 if (AlreadyExists) continue;
3761 // Otherwise, add it to the list of patterns we have.
3762 PatternsToMatch.emplace_back(
3763 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3764 Variant, PatternsToMatch[i].getDstPattern(),
3765 PatternsToMatch[i].getDstRegs(),
3766 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
3769 DEBUG(errs() << "\n");