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) {
198 TypeVec[0] = InVT.TypeVec[0];
205 // If this is a type list and the RHS is a typelist as well, eliminate entries
206 // from this list that aren't in the other one.
207 bool MadeChange = false;
208 TypeSet InputSet(*this);
210 for (unsigned i = 0; i != TypeVec.size(); ++i) {
211 if (std::find(InVT.TypeVec.begin(), InVT.TypeVec.end(), TypeVec[i]) !=
215 TypeVec.erase(TypeVec.begin()+i--);
219 // If we removed all of our types, we have a type contradiction.
220 if (!TypeVec.empty())
223 // FIXME: Really want an SMLoc here!
224 TP.error("Type inference contradiction found, merging '" +
225 InVT.getName() + "' into '" + InputSet.getName() + "'");
229 /// EnforceInteger - Remove all non-integer types from this set.
230 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
233 // If we know nothing, then get the full set.
235 return FillWithPossibleTypes(TP, isInteger, "integer");
237 if (!hasFloatingPointTypes())
240 TypeSet InputSet(*this);
242 // Filter out all the fp types.
243 for (unsigned i = 0; i != TypeVec.size(); ++i)
244 if (!isInteger(TypeVec[i]))
245 TypeVec.erase(TypeVec.begin()+i--);
247 if (TypeVec.empty()) {
248 TP.error("Type inference contradiction found, '" +
249 InputSet.getName() + "' needs to be integer");
255 /// EnforceFloatingPoint - Remove all integer types from this set.
256 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
259 // If we know nothing, then get the full set.
261 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
263 if (!hasIntegerTypes())
266 TypeSet InputSet(*this);
268 // Filter out all the fp types.
269 for (unsigned i = 0; i != TypeVec.size(); ++i)
270 if (!isFloatingPoint(TypeVec[i]))
271 TypeVec.erase(TypeVec.begin()+i--);
273 if (TypeVec.empty()) {
274 TP.error("Type inference contradiction found, '" +
275 InputSet.getName() + "' needs to be floating point");
281 /// EnforceScalar - Remove all vector types from this.
282 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
286 // If we know nothing, then get the full set.
288 return FillWithPossibleTypes(TP, isScalar, "scalar");
290 if (!hasVectorTypes())
293 TypeSet InputSet(*this);
295 // Filter out all the vector types.
296 for (unsigned i = 0; i != TypeVec.size(); ++i)
297 if (!isScalar(TypeVec[i]))
298 TypeVec.erase(TypeVec.begin()+i--);
300 if (TypeVec.empty()) {
301 TP.error("Type inference contradiction found, '" +
302 InputSet.getName() + "' needs to be scalar");
308 /// EnforceVector - Remove all vector types from this.
309 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
313 // If we know nothing, then get the full set.
315 return FillWithPossibleTypes(TP, isVector, "vector");
317 TypeSet InputSet(*this);
318 bool MadeChange = false;
320 // Filter out all the scalar types.
321 for (unsigned i = 0; i != TypeVec.size(); ++i)
322 if (!isVector(TypeVec[i])) {
323 TypeVec.erase(TypeVec.begin()+i--);
327 if (TypeVec.empty()) {
328 TP.error("Type inference contradiction found, '" +
329 InputSet.getName() + "' needs to be a vector");
337 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
338 /// this should be based on the element type. Update this and other based on
339 /// this information.
340 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
344 // Both operands must be integer or FP, but we don't care which.
345 bool MadeChange = false;
347 if (isCompletelyUnknown())
348 MadeChange = FillWithPossibleTypes(TP);
350 if (Other.isCompletelyUnknown())
351 MadeChange = Other.FillWithPossibleTypes(TP);
353 // If one side is known to be integer or known to be FP but the other side has
354 // no information, get at least the type integrality info in there.
355 if (!hasFloatingPointTypes())
356 MadeChange |= Other.EnforceInteger(TP);
357 else if (!hasIntegerTypes())
358 MadeChange |= Other.EnforceFloatingPoint(TP);
359 if (!Other.hasFloatingPointTypes())
360 MadeChange |= EnforceInteger(TP);
361 else if (!Other.hasIntegerTypes())
362 MadeChange |= EnforceFloatingPoint(TP);
364 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
365 "Should have a type list now");
367 // If one contains vectors but the other doesn't pull vectors out.
368 if (!hasVectorTypes())
369 MadeChange |= Other.EnforceScalar(TP);
370 else if (!hasScalarTypes())
371 MadeChange |= Other.EnforceVector(TP);
372 if (!Other.hasVectorTypes())
373 MadeChange |= EnforceScalar(TP);
374 else if (!Other.hasScalarTypes())
375 MadeChange |= EnforceVector(TP);
377 // This code does not currently handle nodes which have multiple types,
378 // where some types are integer, and some are fp. Assert that this is not
380 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
381 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
382 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
387 // Okay, find the smallest type from current set and remove anything the
388 // same or smaller from the other set. We need to ensure that the scalar
389 // type size is smaller than the scalar size of the smallest type. For
390 // vectors, we also need to make sure that the total size is no larger than
391 // the size of the smallest type.
392 TypeSet InputSet(Other);
393 MVT Smallest = TypeVec[0];
394 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
395 MVT OtherVT = Other.TypeVec[i];
396 // Don't compare vector and non-vector types.
397 if (OtherVT.isVector() != Smallest.isVector())
399 // The getSizeInBits() check here is only needed for vectors, but is
400 // a subset of the scalar check for scalars so no need to qualify.
401 if (OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
402 OtherVT.getSizeInBits() < Smallest.getSizeInBits()) {
403 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
408 if (Other.TypeVec.empty()) {
409 TP.error("Type inference contradiction found, '" + InputSet.getName() +
410 "' has nothing larger than '" + getName() +"'!");
414 // Okay, find the largest type from the other set and remove anything the
415 // same or smaller from the current set. We need to ensure that the scalar
416 // type size is larger than the scalar size of the largest type. For
417 // vectors, we also need to make sure that the total size is no smaller than
418 // the size of the largest type.
419 InputSet = TypeSet(*this);
420 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
421 for (unsigned i = 0; i != TypeVec.size(); ++i) {
422 MVT OtherVT = TypeVec[i];
423 // Don't compare vector and non-vector types.
424 if (OtherVT.isVector() != Largest.isVector())
426 // The getSizeInBits() check here is only needed for vectors, but is
427 // a subset of the scalar check for scalars so no need to qualify.
428 if (OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
429 OtherVT.getSizeInBits() > Largest.getSizeInBits()) {
430 TypeVec.erase(TypeVec.begin()+i--);
435 if (TypeVec.empty()) {
436 TP.error("Type inference contradiction found, '" + InputSet.getName() +
437 "' has nothing smaller than '" + Other.getName() +"'!");
444 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
445 /// whose element is specified by VTOperand.
446 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
448 bool MadeChange = false;
450 MadeChange |= EnforceVector(TP);
452 TypeSet InputSet(*this);
454 // Filter out all the types which don't have the right element type.
455 for (unsigned i = 0; i != TypeVec.size(); ++i) {
456 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
457 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
458 TypeVec.erase(TypeVec.begin()+i--);
463 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
464 TP.error("Type inference contradiction found, forcing '" +
465 InputSet.getName() + "' to have a vector element");
472 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
473 /// whose element is specified by VTOperand.
474 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
479 // "This" must be a vector and "VTOperand" must be a scalar.
480 bool MadeChange = false;
481 MadeChange |= EnforceVector(TP);
482 MadeChange |= VTOperand.EnforceScalar(TP);
484 // If we know the vector type, it forces the scalar to agree.
486 MVT IVT = getConcrete();
487 IVT = IVT.getVectorElementType();
489 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
492 // If the scalar type is known, filter out vector types whose element types
494 if (!VTOperand.isConcrete())
497 MVT::SimpleValueType VT = VTOperand.getConcrete();
499 TypeSet InputSet(*this);
501 // Filter out all the types which don't have the right element type.
502 for (unsigned i = 0; i != TypeVec.size(); ++i) {
503 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
504 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
505 TypeVec.erase(TypeVec.begin()+i--);
510 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
511 TP.error("Type inference contradiction found, forcing '" +
512 InputSet.getName() + "' to have a vector element");
518 /// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
519 /// vector type specified by VTOperand.
520 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
525 // "This" must be a vector and "VTOperand" must be a vector.
526 bool MadeChange = false;
527 MadeChange |= EnforceVector(TP);
528 MadeChange |= VTOperand.EnforceVector(TP);
530 // If one side is known to be integer or known to be FP but the other side has
531 // no information, get at least the type integrality info in there.
532 if (!hasFloatingPointTypes())
533 MadeChange |= VTOperand.EnforceInteger(TP);
534 else if (!hasIntegerTypes())
535 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
536 if (!VTOperand.hasFloatingPointTypes())
537 MadeChange |= EnforceInteger(TP);
538 else if (!VTOperand.hasIntegerTypes())
539 MadeChange |= EnforceFloatingPoint(TP);
541 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
542 "Should have a type list now");
544 // If we know the vector type, it forces the scalar types to agree.
545 // Also force one vector to have more elements than the other.
547 MVT IVT = getConcrete();
548 unsigned NumElems = IVT.getVectorNumElements();
549 IVT = IVT.getVectorElementType();
551 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
552 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
554 // Only keep types that have less elements than VTOperand.
555 TypeSet InputSet(VTOperand);
557 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
558 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
559 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
560 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
564 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
565 TP.error("Type inference contradiction found, forcing '" +
566 InputSet.getName() + "' to have less vector elements than '" +
570 } else if (VTOperand.isConcrete()) {
571 MVT IVT = VTOperand.getConcrete();
572 unsigned NumElems = IVT.getVectorNumElements();
573 IVT = IVT.getVectorElementType();
575 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
576 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
578 // Only keep types that have more elements than 'this'.
579 TypeSet InputSet(*this);
581 for (unsigned i = 0; i != TypeVec.size(); ++i) {
582 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
583 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
584 TypeVec.erase(TypeVec.begin()+i--);
588 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
589 TP.error("Type inference contradiction found, forcing '" +
590 InputSet.getName() + "' to have more vector elements than '" +
591 VTOperand.getName() + "'");
599 /// EnforceVectorSameNumElts - 'this' is now constrained to
600 /// be a vector with same num elements as VTOperand.
601 bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
606 // "This" must be a vector and "VTOperand" must be a vector.
607 bool MadeChange = false;
608 MadeChange |= EnforceVector(TP);
609 MadeChange |= VTOperand.EnforceVector(TP);
611 // If we know one of the vector types, it forces the other type to agree.
613 MVT IVT = getConcrete();
614 unsigned NumElems = IVT.getVectorNumElements();
616 // Only keep types that have same elements as VTOperand.
617 TypeSet InputSet(VTOperand);
619 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
620 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
621 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
622 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
626 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
627 TP.error("Type inference contradiction found, forcing '" +
628 InputSet.getName() + "' to have same number elements as '" +
632 } else if (VTOperand.isConcrete()) {
633 MVT IVT = VTOperand.getConcrete();
634 unsigned NumElems = IVT.getVectorNumElements();
636 // Only keep types that have same elements as 'this'.
637 TypeSet InputSet(*this);
639 for (unsigned i = 0; i != TypeVec.size(); ++i) {
640 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
641 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
642 TypeVec.erase(TypeVec.begin()+i--);
646 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
647 TP.error("Type inference contradiction found, forcing '" +
648 InputSet.getName() + "' to have same number elements than '" +
649 VTOperand.getName() + "'");
657 //===----------------------------------------------------------------------===//
658 // Helpers for working with extended types.
660 /// Dependent variable map for CodeGenDAGPattern variant generation
661 typedef std::map<std::string, int> DepVarMap;
663 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
665 if (isa<DefInit>(N->getLeafValue()))
666 DepMap[N->getName()]++;
668 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
669 FindDepVarsOf(N->getChild(i), DepMap);
673 /// Find dependent variables within child patterns
674 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
676 FindDepVarsOf(N, depcounts);
677 for (const std::pair<std::string, int> &Pair : depcounts) {
679 DepVars.insert(Pair.first);
684 /// Dump the dependent variable set:
685 static void DumpDepVars(MultipleUseVarSet &DepVars) {
686 if (DepVars.empty()) {
687 DEBUG(errs() << "<empty set>");
689 DEBUG(errs() << "[ ");
690 for (const std::string &DepVar : DepVars) {
691 DEBUG(errs() << DepVar << " ");
693 DEBUG(errs() << "]");
699 //===----------------------------------------------------------------------===//
700 // TreePredicateFn Implementation
701 //===----------------------------------------------------------------------===//
703 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
704 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
705 assert((getPredCode().empty() || getImmCode().empty()) &&
706 ".td file corrupt: can't have a node predicate *and* an imm predicate");
709 std::string TreePredicateFn::getPredCode() const {
710 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
713 std::string TreePredicateFn::getImmCode() const {
714 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
718 /// isAlwaysTrue - Return true if this is a noop predicate.
719 bool TreePredicateFn::isAlwaysTrue() const {
720 return getPredCode().empty() && getImmCode().empty();
723 /// Return the name to use in the generated code to reference this, this is
724 /// "Predicate_foo" if from a pattern fragment "foo".
725 std::string TreePredicateFn::getFnName() const {
726 return "Predicate_" + PatFragRec->getRecord()->getName();
729 /// getCodeToRunOnSDNode - Return the code for the function body that
730 /// evaluates this predicate. The argument is expected to be in "Node",
731 /// not N. This handles casting and conversion to a concrete node type as
733 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
734 // Handle immediate predicates first.
735 std::string ImmCode = getImmCode();
736 if (!ImmCode.empty()) {
738 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
739 return Result + ImmCode;
742 // Handle arbitrary node predicates.
743 assert(!getPredCode().empty() && "Don't have any predicate code!");
744 std::string ClassName;
745 if (PatFragRec->getOnlyTree()->isLeaf())
746 ClassName = "SDNode";
748 Record *Op = PatFragRec->getOnlyTree()->getOperator();
749 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
752 if (ClassName == "SDNode")
753 Result = " SDNode *N = Node;\n";
755 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
757 return Result + getPredCode();
760 //===----------------------------------------------------------------------===//
761 // PatternToMatch implementation
765 /// getPatternSize - Return the 'size' of this pattern. We want to match large
766 /// patterns before small ones. This is used to determine the size of a
768 static unsigned getPatternSize(const TreePatternNode *P,
769 const CodeGenDAGPatterns &CGP) {
770 unsigned Size = 3; // The node itself.
771 // If the root node is a ConstantSDNode, increases its size.
772 // e.g. (set R32:$dst, 0).
773 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
776 // FIXME: This is a hack to statically increase the priority of patterns
777 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
778 // Later we can allow complexity / cost for each pattern to be (optionally)
779 // specified. To get best possible pattern match we'll need to dynamically
780 // calculate the complexity of all patterns a dag can potentially map to.
781 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
783 Size += AM->getNumOperands() * 3;
785 // We don't want to count any children twice, so return early.
789 // If this node has some predicate function that must match, it adds to the
790 // complexity of this node.
791 if (!P->getPredicateFns().empty())
794 // Count children in the count if they are also nodes.
795 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
796 TreePatternNode *Child = P->getChild(i);
797 if (!Child->isLeaf() && Child->getNumTypes() &&
798 Child->getType(0) != MVT::Other)
799 Size += getPatternSize(Child, CGP);
800 else if (Child->isLeaf()) {
801 if (isa<IntInit>(Child->getLeafValue()))
802 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
803 else if (Child->getComplexPatternInfo(CGP))
804 Size += getPatternSize(Child, CGP);
805 else if (!Child->getPredicateFns().empty())
813 /// Compute the complexity metric for the input pattern. This roughly
814 /// corresponds to the number of nodes that are covered.
816 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
817 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
821 /// getPredicateCheck - Return a single string containing all of this
822 /// pattern's predicates concatenated with "&&" operators.
824 std::string PatternToMatch::getPredicateCheck() const {
825 std::string PredicateCheck;
826 for (Init *I : Predicates->getValues()) {
827 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
828 Record *Def = Pred->getDef();
829 if (!Def->isSubClassOf("Predicate")) {
833 llvm_unreachable("Unknown predicate type!");
835 if (!PredicateCheck.empty())
836 PredicateCheck += " && ";
837 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
841 return PredicateCheck;
844 //===----------------------------------------------------------------------===//
845 // SDTypeConstraint implementation
848 SDTypeConstraint::SDTypeConstraint(Record *R) {
849 OperandNo = R->getValueAsInt("OperandNum");
851 if (R->isSubClassOf("SDTCisVT")) {
852 ConstraintType = SDTCisVT;
853 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
854 if (x.SDTCisVT_Info.VT == MVT::isVoid)
855 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
857 } else if (R->isSubClassOf("SDTCisPtrTy")) {
858 ConstraintType = SDTCisPtrTy;
859 } else if (R->isSubClassOf("SDTCisInt")) {
860 ConstraintType = SDTCisInt;
861 } else if (R->isSubClassOf("SDTCisFP")) {
862 ConstraintType = SDTCisFP;
863 } else if (R->isSubClassOf("SDTCisVec")) {
864 ConstraintType = SDTCisVec;
865 } else if (R->isSubClassOf("SDTCisSameAs")) {
866 ConstraintType = SDTCisSameAs;
867 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
868 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
869 ConstraintType = SDTCisVTSmallerThanOp;
870 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
871 R->getValueAsInt("OtherOperandNum");
872 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
873 ConstraintType = SDTCisOpSmallerThanOp;
874 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
875 R->getValueAsInt("BigOperandNum");
876 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
877 ConstraintType = SDTCisEltOfVec;
878 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
879 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
880 ConstraintType = SDTCisSubVecOfVec;
881 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
882 R->getValueAsInt("OtherOpNum");
883 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
884 ConstraintType = SDTCVecEltisVT;
885 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
886 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
887 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
888 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
889 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
890 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
891 "as SDTCVecEltisVT");
892 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
893 ConstraintType = SDTCisSameNumEltsAs;
894 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
895 R->getValueAsInt("OtherOperandNum");
897 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
901 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
902 /// N, and the result number in ResNo.
903 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
904 const SDNodeInfo &NodeInfo,
906 unsigned NumResults = NodeInfo.getNumResults();
907 if (OpNo < NumResults) {
914 if (OpNo >= N->getNumChildren()) {
916 raw_string_ostream OS(S);
917 OS << "Invalid operand number in type constraint "
918 << (OpNo+NumResults) << " ";
920 PrintFatalError(OS.str());
923 return N->getChild(OpNo);
926 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
927 /// constraint to the nodes operands. This returns true if it makes a
928 /// change, false otherwise. If a type contradiction is found, flag an error.
929 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
930 const SDNodeInfo &NodeInfo,
931 TreePattern &TP) const {
935 unsigned ResNo = 0; // The result number being referenced.
936 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
938 switch (ConstraintType) {
940 // Operand must be a particular type.
941 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
943 // Operand must be same as target pointer type.
944 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
946 // Require it to be one of the legal integer VTs.
947 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
949 // Require it to be one of the legal fp VTs.
950 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
952 // Require it to be one of the legal vector VTs.
953 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
956 TreePatternNode *OtherNode =
957 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
958 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
959 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
961 case SDTCisVTSmallerThanOp: {
962 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
963 // have an integer type that is smaller than the VT.
964 if (!NodeToApply->isLeaf() ||
965 !isa<DefInit>(NodeToApply->getLeafValue()) ||
966 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
967 ->isSubClassOf("ValueType")) {
968 TP.error(N->getOperator()->getName() + " expects a VT operand!");
971 MVT::SimpleValueType VT =
972 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
974 EEVT::TypeSet TypeListTmp(VT, TP);
977 TreePatternNode *OtherNode =
978 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
981 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
983 case SDTCisOpSmallerThanOp: {
985 TreePatternNode *BigOperand =
986 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
988 return NodeToApply->getExtType(ResNo).
989 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
991 case SDTCisEltOfVec: {
993 TreePatternNode *VecOperand =
994 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
997 // Filter vector types out of VecOperand that don't have the right element
999 return VecOperand->getExtType(VResNo).
1000 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
1002 case SDTCisSubVecOfVec: {
1003 unsigned VResNo = 0;
1004 TreePatternNode *BigVecOperand =
1005 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1008 // Filter vector types out of BigVecOperand that don't have the
1009 // right subvector type.
1010 return BigVecOperand->getExtType(VResNo).
1011 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1013 case SDTCVecEltisVT: {
1014 return NodeToApply->getExtType(ResNo).
1015 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1017 case SDTCisSameNumEltsAs: {
1018 unsigned OResNo = 0;
1019 TreePatternNode *OtherNode =
1020 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1021 N, NodeInfo, OResNo);
1022 return OtherNode->getExtType(OResNo).
1023 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1026 llvm_unreachable("Invalid ConstraintType!");
1029 // Update the node type to match an instruction operand or result as specified
1030 // in the ins or outs lists on the instruction definition. Return true if the
1031 // type was actually changed.
1032 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1035 // The 'unknown' operand indicates that types should be inferred from the
1037 if (Operand->isSubClassOf("unknown_class"))
1040 // The Operand class specifies a type directly.
1041 if (Operand->isSubClassOf("Operand"))
1042 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1045 // PointerLikeRegClass has a type that is determined at runtime.
1046 if (Operand->isSubClassOf("PointerLikeRegClass"))
1047 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1049 // Both RegisterClass and RegisterOperand operands derive their types from a
1050 // register class def.
1051 Record *RC = nullptr;
1052 if (Operand->isSubClassOf("RegisterClass"))
1054 else if (Operand->isSubClassOf("RegisterOperand"))
1055 RC = Operand->getValueAsDef("RegClass");
1057 assert(RC && "Unknown operand type");
1058 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1059 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1063 //===----------------------------------------------------------------------===//
1064 // SDNodeInfo implementation
1066 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1067 EnumName = R->getValueAsString("Opcode");
1068 SDClassName = R->getValueAsString("SDClass");
1069 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1070 NumResults = TypeProfile->getValueAsInt("NumResults");
1071 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1073 // Parse the properties.
1075 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1076 if (Property->getName() == "SDNPCommutative") {
1077 Properties |= 1 << SDNPCommutative;
1078 } else if (Property->getName() == "SDNPAssociative") {
1079 Properties |= 1 << SDNPAssociative;
1080 } else if (Property->getName() == "SDNPHasChain") {
1081 Properties |= 1 << SDNPHasChain;
1082 } else if (Property->getName() == "SDNPOutGlue") {
1083 Properties |= 1 << SDNPOutGlue;
1084 } else if (Property->getName() == "SDNPInGlue") {
1085 Properties |= 1 << SDNPInGlue;
1086 } else if (Property->getName() == "SDNPOptInGlue") {
1087 Properties |= 1 << SDNPOptInGlue;
1088 } else if (Property->getName() == "SDNPMayStore") {
1089 Properties |= 1 << SDNPMayStore;
1090 } else if (Property->getName() == "SDNPMayLoad") {
1091 Properties |= 1 << SDNPMayLoad;
1092 } else if (Property->getName() == "SDNPSideEffect") {
1093 Properties |= 1 << SDNPSideEffect;
1094 } else if (Property->getName() == "SDNPMemOperand") {
1095 Properties |= 1 << SDNPMemOperand;
1096 } else if (Property->getName() == "SDNPVariadic") {
1097 Properties |= 1 << SDNPVariadic;
1099 PrintFatalError("Unknown SD Node property '" +
1100 Property->getName() + "' on node '" +
1101 R->getName() + "'!");
1106 // Parse the type constraints.
1107 std::vector<Record*> ConstraintList =
1108 TypeProfile->getValueAsListOfDefs("Constraints");
1109 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1112 /// getKnownType - If the type constraints on this node imply a fixed type
1113 /// (e.g. all stores return void, etc), then return it as an
1114 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1115 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1116 unsigned NumResults = getNumResults();
1117 assert(NumResults <= 1 &&
1118 "We only work with nodes with zero or one result so far!");
1119 assert(ResNo == 0 && "Only handles single result nodes so far");
1121 for (const SDTypeConstraint &Constraint : TypeConstraints) {
1122 // Make sure that this applies to the correct node result.
1123 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1126 switch (Constraint.ConstraintType) {
1128 case SDTypeConstraint::SDTCisVT:
1129 return Constraint.x.SDTCisVT_Info.VT;
1130 case SDTypeConstraint::SDTCisPtrTy:
1137 //===----------------------------------------------------------------------===//
1138 // TreePatternNode implementation
1141 TreePatternNode::~TreePatternNode() {
1142 #if 0 // FIXME: implement refcounted tree nodes!
1143 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1148 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1149 if (Operator->getName() == "set" ||
1150 Operator->getName() == "implicit")
1151 return 0; // All return nothing.
1153 if (Operator->isSubClassOf("Intrinsic"))
1154 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1156 if (Operator->isSubClassOf("SDNode"))
1157 return CDP.getSDNodeInfo(Operator).getNumResults();
1159 if (Operator->isSubClassOf("PatFrag")) {
1160 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1161 // the forward reference case where one pattern fragment references another
1162 // before it is processed.
1163 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1164 return PFRec->getOnlyTree()->getNumTypes();
1166 // Get the result tree.
1167 DagInit *Tree = Operator->getValueAsDag("Fragment");
1168 Record *Op = nullptr;
1170 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1172 assert(Op && "Invalid Fragment");
1173 return GetNumNodeResults(Op, CDP);
1176 if (Operator->isSubClassOf("Instruction")) {
1177 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1179 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1181 // Subtract any defaulted outputs.
1182 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1183 Record *OperandNode = InstInfo.Operands[i].Rec;
1185 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1186 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1190 // Add on one implicit def if it has a resolvable type.
1191 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1193 return NumDefsToAdd;
1196 if (Operator->isSubClassOf("SDNodeXForm"))
1197 return 1; // FIXME: Generalize SDNodeXForm
1199 if (Operator->isSubClassOf("ValueType"))
1200 return 1; // A type-cast of one result.
1202 if (Operator->isSubClassOf("ComplexPattern"))
1206 PrintFatalError("Unhandled node in GetNumNodeResults");
1209 void TreePatternNode::print(raw_ostream &OS) const {
1211 OS << *getLeafValue();
1213 OS << '(' << getOperator()->getName();
1215 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1216 OS << ':' << getExtType(i).getName();
1219 if (getNumChildren() != 0) {
1221 getChild(0)->print(OS);
1222 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1224 getChild(i)->print(OS);
1230 for (const TreePredicateFn &Pred : PredicateFns)
1231 OS << "<<P:" << Pred.getFnName() << ">>";
1233 OS << "<<X:" << TransformFn->getName() << ">>";
1234 if (!getName().empty())
1235 OS << ":$" << getName();
1238 void TreePatternNode::dump() const {
1242 /// isIsomorphicTo - Return true if this node is recursively
1243 /// isomorphic to the specified node. For this comparison, the node's
1244 /// entire state is considered. The assigned name is ignored, since
1245 /// nodes with differing names are considered isomorphic. However, if
1246 /// the assigned name is present in the dependent variable set, then
1247 /// the assigned name is considered significant and the node is
1248 /// isomorphic if the names match.
1249 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1250 const MultipleUseVarSet &DepVars) const {
1251 if (N == this) return true;
1252 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1253 getPredicateFns() != N->getPredicateFns() ||
1254 getTransformFn() != N->getTransformFn())
1258 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1259 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1260 return ((DI->getDef() == NDI->getDef())
1261 && (DepVars.find(getName()) == DepVars.end()
1262 || getName() == N->getName()));
1265 return getLeafValue() == N->getLeafValue();
1268 if (N->getOperator() != getOperator() ||
1269 N->getNumChildren() != getNumChildren()) return false;
1270 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1271 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1276 /// clone - Make a copy of this tree and all of its children.
1278 TreePatternNode *TreePatternNode::clone() const {
1279 TreePatternNode *New;
1281 New = new TreePatternNode(getLeafValue(), getNumTypes());
1283 std::vector<TreePatternNode*> CChildren;
1284 CChildren.reserve(Children.size());
1285 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1286 CChildren.push_back(getChild(i)->clone());
1287 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1289 New->setName(getName());
1291 New->setPredicateFns(getPredicateFns());
1292 New->setTransformFn(getTransformFn());
1296 /// RemoveAllTypes - Recursively strip all the types of this tree.
1297 void TreePatternNode::RemoveAllTypes() {
1298 // Reset to unknown type.
1299 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
1300 if (isLeaf()) return;
1301 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1302 getChild(i)->RemoveAllTypes();
1306 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1307 /// with actual values specified by ArgMap.
1308 void TreePatternNode::
1309 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1310 if (isLeaf()) return;
1312 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1313 TreePatternNode *Child = getChild(i);
1314 if (Child->isLeaf()) {
1315 Init *Val = Child->getLeafValue();
1316 // Note that, when substituting into an output pattern, Val might be an
1318 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1319 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1320 // We found a use of a formal argument, replace it with its value.
1321 TreePatternNode *NewChild = ArgMap[Child->getName()];
1322 assert(NewChild && "Couldn't find formal argument!");
1323 assert((Child->getPredicateFns().empty() ||
1324 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1325 "Non-empty child predicate clobbered!");
1326 setChild(i, NewChild);
1329 getChild(i)->SubstituteFormalArguments(ArgMap);
1335 /// InlinePatternFragments - If this pattern refers to any pattern
1336 /// fragments, inline them into place, giving us a pattern without any
1337 /// PatFrag references.
1338 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1343 return this; // nothing to do.
1344 Record *Op = getOperator();
1346 if (!Op->isSubClassOf("PatFrag")) {
1347 // Just recursively inline children nodes.
1348 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1349 TreePatternNode *Child = getChild(i);
1350 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1352 assert((Child->getPredicateFns().empty() ||
1353 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1354 "Non-empty child predicate clobbered!");
1356 setChild(i, NewChild);
1361 // Otherwise, we found a reference to a fragment. First, look up its
1362 // TreePattern record.
1363 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1365 // Verify that we are passing the right number of operands.
1366 if (Frag->getNumArgs() != Children.size()) {
1367 TP.error("'" + Op->getName() + "' fragment requires " +
1368 utostr(Frag->getNumArgs()) + " operands!");
1372 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1374 TreePredicateFn PredFn(Frag);
1375 if (!PredFn.isAlwaysTrue())
1376 FragTree->addPredicateFn(PredFn);
1378 // Resolve formal arguments to their actual value.
1379 if (Frag->getNumArgs()) {
1380 // Compute the map of formal to actual arguments.
1381 std::map<std::string, TreePatternNode*> ArgMap;
1382 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1383 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1385 FragTree->SubstituteFormalArguments(ArgMap);
1388 FragTree->setName(getName());
1389 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1390 FragTree->UpdateNodeType(i, getExtType(i), TP);
1392 // Transfer in the old predicates.
1393 for (const TreePredicateFn &Pred : getPredicateFns())
1394 FragTree->addPredicateFn(Pred);
1396 // Get a new copy of this fragment to stitch into here.
1397 //delete this; // FIXME: implement refcounting!
1399 // The fragment we inlined could have recursive inlining that is needed. See
1400 // if there are any pattern fragments in it and inline them as needed.
1401 return FragTree->InlinePatternFragments(TP);
1404 /// getImplicitType - Check to see if the specified record has an implicit
1405 /// type which should be applied to it. This will infer the type of register
1406 /// references from the register file information, for example.
1408 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1409 /// the F8RC register class argument in:
1411 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
1413 /// When Unnamed is false, return the type of a named DAG operand such as the
1414 /// GPR:$src operand above.
1416 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1420 // Check to see if this is a register operand.
1421 if (R->isSubClassOf("RegisterOperand")) {
1422 assert(ResNo == 0 && "Regoperand ref only has one result!");
1424 return EEVT::TypeSet(); // Unknown.
1425 Record *RegClass = R->getValueAsDef("RegClass");
1426 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1427 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1430 // Check to see if this is a register or a register class.
1431 if (R->isSubClassOf("RegisterClass")) {
1432 assert(ResNo == 0 && "Regclass ref only has one result!");
1433 // An unnamed register class represents itself as an i32 immediate, for
1434 // example on a COPY_TO_REGCLASS instruction.
1436 return EEVT::TypeSet(MVT::i32, TP);
1438 // In a named operand, the register class provides the possible set of
1441 return EEVT::TypeSet(); // Unknown.
1442 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1443 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1446 if (R->isSubClassOf("PatFrag")) {
1447 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1448 // Pattern fragment types will be resolved when they are inlined.
1449 return EEVT::TypeSet(); // Unknown.
1452 if (R->isSubClassOf("Register")) {
1453 assert(ResNo == 0 && "Registers only produce one result!");
1455 return EEVT::TypeSet(); // Unknown.
1456 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1457 return EEVT::TypeSet(T.getRegisterVTs(R));
1460 if (R->isSubClassOf("SubRegIndex")) {
1461 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1462 return EEVT::TypeSet(MVT::i32, TP);
1465 if (R->isSubClassOf("ValueType")) {
1466 assert(ResNo == 0 && "This node only has one result!");
1467 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1469 // (sext_inreg GPR:$src, i16)
1472 return EEVT::TypeSet(MVT::Other, TP);
1473 // With a name, the ValueType simply provides the type of the named
1476 // (sext_inreg i32:$src, i16)
1479 return EEVT::TypeSet(); // Unknown.
1480 return EEVT::TypeSet(getValueType(R), TP);
1483 if (R->isSubClassOf("CondCode")) {
1484 assert(ResNo == 0 && "This node only has one result!");
1485 // Using a CondCodeSDNode.
1486 return EEVT::TypeSet(MVT::Other, TP);
1489 if (R->isSubClassOf("ComplexPattern")) {
1490 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1492 return EEVT::TypeSet(); // Unknown.
1493 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1496 if (R->isSubClassOf("PointerLikeRegClass")) {
1497 assert(ResNo == 0 && "Regclass can only have one result!");
1498 return EEVT::TypeSet(MVT::iPTR, TP);
1501 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1502 R->getName() == "zero_reg") {
1504 return EEVT::TypeSet(); // Unknown.
1507 if (R->isSubClassOf("Operand"))
1508 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1510 TP.error("Unknown node flavor used in pattern: " + R->getName());
1511 return EEVT::TypeSet(MVT::Other, TP);
1515 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1516 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1517 const CodeGenIntrinsic *TreePatternNode::
1518 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1519 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1520 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1521 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1524 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
1525 return &CDP.getIntrinsicInfo(IID);
1528 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1529 /// return the ComplexPattern information, otherwise return null.
1530 const ComplexPattern *
1531 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1534 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1539 Rec = getOperator();
1541 if (!Rec->isSubClassOf("ComplexPattern"))
1543 return &CGP.getComplexPattern(Rec);
1546 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1547 // A ComplexPattern specifically declares how many results it fills in.
1548 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1549 return CP->getNumOperands();
1551 // If MIOperandInfo is specified, that gives the count.
1553 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1554 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1555 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1556 if (MIOps->getNumArgs())
1557 return MIOps->getNumArgs();
1561 // Otherwise there is just one result.
1565 /// NodeHasProperty - Return true if this node has the specified property.
1566 bool TreePatternNode::NodeHasProperty(SDNP Property,
1567 const CodeGenDAGPatterns &CGP) const {
1569 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1570 return CP->hasProperty(Property);
1574 Record *Operator = getOperator();
1575 if (!Operator->isSubClassOf("SDNode")) return false;
1577 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1583 /// TreeHasProperty - Return true if any node in this tree has the specified
1585 bool TreePatternNode::TreeHasProperty(SDNP Property,
1586 const CodeGenDAGPatterns &CGP) const {
1587 if (NodeHasProperty(Property, CGP))
1589 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1590 if (getChild(i)->TreeHasProperty(Property, CGP))
1595 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1596 /// commutative intrinsic.
1598 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1599 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1600 return Int->isCommutative;
1604 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1606 return N->getOperator()->isSubClassOf(Class);
1608 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1609 if (DI && DI->getDef()->isSubClassOf(Class))
1615 static void emitTooManyOperandsError(TreePattern &TP,
1619 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1620 " operands but expected only " + Twine(Expected) + "!");
1623 static void emitTooFewOperandsError(TreePattern &TP,
1626 TP.error("Instruction '" + InstName +
1627 "' expects more than the provided " + Twine(Actual) + " operands!");
1630 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1631 /// this node and its children in the tree. This returns true if it makes a
1632 /// change, false otherwise. If a type contradiction is found, flag an error.
1633 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1637 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1639 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1640 // If it's a regclass or something else known, include the type.
1641 bool MadeChange = false;
1642 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1643 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1645 !hasName(), TP), TP);
1649 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
1650 assert(Types.size() == 1 && "Invalid IntInit");
1652 // Int inits are always integers. :)
1653 bool MadeChange = Types[0].EnforceInteger(TP);
1655 if (!Types[0].isConcrete())
1658 MVT::SimpleValueType VT = getType(0);
1659 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1662 unsigned Size = MVT(VT).getSizeInBits();
1663 // Make sure that the value is representable for this type.
1664 if (Size >= 32) return MadeChange;
1666 // Check that the value doesn't use more bits than we have. It must either
1667 // be a sign- or zero-extended equivalent of the original.
1668 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1669 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1672 TP.error("Integer value '" + itostr(II->getValue()) +
1673 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1679 // special handling for set, which isn't really an SDNode.
1680 if (getOperator()->getName() == "set") {
1681 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1682 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1683 unsigned NC = getNumChildren();
1685 TreePatternNode *SetVal = getChild(NC-1);
1686 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1688 for (unsigned i = 0; i < NC-1; ++i) {
1689 TreePatternNode *Child = getChild(i);
1690 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1692 // Types of operands must match.
1693 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1694 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1699 if (getOperator()->getName() == "implicit") {
1700 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1702 bool MadeChange = false;
1703 for (unsigned i = 0; i < getNumChildren(); ++i)
1704 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1708 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1709 bool MadeChange = false;
1711 // Apply the result type to the node.
1712 unsigned NumRetVTs = Int->IS.RetVTs.size();
1713 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1715 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1716 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1718 if (getNumChildren() != NumParamVTs + 1) {
1719 TP.error("Intrinsic '" + Int->Name + "' expects " +
1720 utostr(NumParamVTs) + " operands, not " +
1721 utostr(getNumChildren() - 1) + " operands!");
1725 // Apply type info to the intrinsic ID.
1726 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1728 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1729 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1731 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1732 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1733 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1738 if (getOperator()->isSubClassOf("SDNode")) {
1739 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1741 // Check that the number of operands is sane. Negative operands -> varargs.
1742 if (NI.getNumOperands() >= 0 &&
1743 getNumChildren() != (unsigned)NI.getNumOperands()) {
1744 TP.error(getOperator()->getName() + " node requires exactly " +
1745 itostr(NI.getNumOperands()) + " operands!");
1749 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1750 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1751 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1755 if (getOperator()->isSubClassOf("Instruction")) {
1756 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1757 CodeGenInstruction &InstInfo =
1758 CDP.getTargetInfo().getInstruction(getOperator());
1760 bool MadeChange = false;
1762 // Apply the result types to the node, these come from the things in the
1763 // (outs) list of the instruction.
1764 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1765 Inst.getNumResults());
1766 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1767 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
1769 // If the instruction has implicit defs, we apply the first one as a result.
1770 // FIXME: This sucks, it should apply all implicit defs.
1771 if (!InstInfo.ImplicitDefs.empty()) {
1772 unsigned ResNo = NumResultsToAdd;
1774 // FIXME: Generalize to multiple possible types and multiple possible
1776 MVT::SimpleValueType VT =
1777 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1779 if (VT != MVT::Other)
1780 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1783 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1785 if (getOperator()->getName() == "INSERT_SUBREG") {
1786 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1787 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1788 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1789 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1790 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1793 unsigned NChild = getNumChildren();
1795 TP.error("REG_SEQUENCE requires at least 3 operands!");
1799 if (NChild % 2 == 0) {
1800 TP.error("REG_SEQUENCE requires an odd number of operands!");
1804 if (!isOperandClass(getChild(0), "RegisterClass")) {
1805 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1809 for (unsigned I = 1; I < NChild; I += 2) {
1810 TreePatternNode *SubIdxChild = getChild(I + 1);
1811 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1812 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1813 itostr(I + 1) + "!");
1819 unsigned ChildNo = 0;
1820 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1821 Record *OperandNode = Inst.getOperand(i);
1823 // If the instruction expects a predicate or optional def operand, we
1824 // codegen this by setting the operand to it's default value if it has a
1825 // non-empty DefaultOps field.
1826 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1827 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1830 // Verify that we didn't run out of provided operands.
1831 if (ChildNo >= getNumChildren()) {
1832 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
1836 TreePatternNode *Child = getChild(ChildNo++);
1837 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1839 // If the operand has sub-operands, they may be provided by distinct
1840 // child patterns, so attempt to match each sub-operand separately.
1841 if (OperandNode->isSubClassOf("Operand")) {
1842 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1843 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1844 // But don't do that if the whole operand is being provided by
1845 // a single ComplexPattern-related Operand.
1847 if (Child->getNumMIResults(CDP) < NumArgs) {
1848 // Match first sub-operand against the child we already have.
1849 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1851 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1853 // And the remaining sub-operands against subsequent children.
1854 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1855 if (ChildNo >= getNumChildren()) {
1856 emitTooFewOperandsError(TP, getOperator()->getName(),
1860 Child = getChild(ChildNo++);
1862 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1864 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1871 // If we didn't match by pieces above, attempt to match the whole
1873 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
1876 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
1877 emitTooManyOperandsError(TP, getOperator()->getName(),
1878 ChildNo, getNumChildren());
1882 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1883 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1887 if (getOperator()->isSubClassOf("ComplexPattern")) {
1888 bool MadeChange = false;
1890 for (unsigned i = 0; i < getNumChildren(); ++i)
1891 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1896 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1898 // Node transforms always take one operand.
1899 if (getNumChildren() != 1) {
1900 TP.error("Node transform '" + getOperator()->getName() +
1901 "' requires one operand!");
1905 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1908 // If either the output or input of the xform does not have exact
1909 // type info. We assume they must be the same. Otherwise, it is perfectly
1910 // legal to transform from one type to a completely different type.
1912 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1913 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1914 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1921 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1922 /// RHS of a commutative operation, not the on LHS.
1923 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1924 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1926 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
1932 /// canPatternMatch - If it is impossible for this pattern to match on this
1933 /// target, fill in Reason and return false. Otherwise, return true. This is
1934 /// used as a sanity check for .td files (to prevent people from writing stuff
1935 /// that can never possibly work), and to prevent the pattern permuter from
1936 /// generating stuff that is useless.
1937 bool TreePatternNode::canPatternMatch(std::string &Reason,
1938 const CodeGenDAGPatterns &CDP) {
1939 if (isLeaf()) return true;
1941 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1942 if (!getChild(i)->canPatternMatch(Reason, CDP))
1945 // If this is an intrinsic, handle cases that would make it not match. For
1946 // example, if an operand is required to be an immediate.
1947 if (getOperator()->isSubClassOf("Intrinsic")) {
1952 if (getOperator()->isSubClassOf("ComplexPattern"))
1955 // If this node is a commutative operator, check that the LHS isn't an
1957 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1958 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1959 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1960 // Scan all of the operands of the node and make sure that only the last one
1961 // is a constant node, unless the RHS also is.
1962 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1963 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1964 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1965 if (OnlyOnRHSOfCommutative(getChild(i))) {
1966 Reason="Immediate value must be on the RHS of commutative operators!";
1975 //===----------------------------------------------------------------------===//
1976 // TreePattern implementation
1979 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1980 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1981 isInputPattern(isInput), HasError(false) {
1982 for (Init *I : RawPat->getValues())
1983 Trees.push_back(ParseTreePattern(I, ""));
1986 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1987 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1988 isInputPattern(isInput), HasError(false) {
1989 Trees.push_back(ParseTreePattern(Pat, ""));
1992 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1993 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1994 isInputPattern(isInput), HasError(false) {
1995 Trees.push_back(Pat);
1998 void TreePattern::error(const Twine &Msg) {
2002 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2006 void TreePattern::ComputeNamedNodes() {
2007 for (TreePatternNode *Tree : Trees)
2008 ComputeNamedNodes(Tree);
2011 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2012 if (!N->getName().empty())
2013 NamedNodes[N->getName()].push_back(N);
2015 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2016 ComputeNamedNodes(N->getChild(i));
2020 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2021 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2022 Record *R = DI->getDef();
2024 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2025 // TreePatternNode of its own. For example:
2026 /// (foo GPR, imm) -> (foo GPR, (imm))
2027 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2028 return ParseTreePattern(
2029 DagInit::get(DI, "",
2030 std::vector<std::pair<Init*, std::string> >()),
2034 TreePatternNode *Res = new TreePatternNode(DI, 1);
2035 if (R->getName() == "node" && !OpName.empty()) {
2037 error("'node' argument requires a name to match with operand list");
2038 Args.push_back(OpName);
2041 Res->setName(OpName);
2045 // ?:$name or just $name.
2046 if (isa<UnsetInit>(TheInit)) {
2048 error("'?' argument requires a name to match with operand list");
2049 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2050 Args.push_back(OpName);
2051 Res->setName(OpName);
2055 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2056 if (!OpName.empty())
2057 error("Constant int argument should not have a name!");
2058 return new TreePatternNode(II, 1);
2061 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2062 // Turn this into an IntInit.
2063 Init *II = BI->convertInitializerTo(IntRecTy::get());
2064 if (!II || !isa<IntInit>(II))
2065 error("Bits value must be constants!");
2066 return ParseTreePattern(II, OpName);
2069 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2072 error("Pattern has unexpected init kind!");
2074 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2075 if (!OpDef) error("Pattern has unexpected operator type!");
2076 Record *Operator = OpDef->getDef();
2078 if (Operator->isSubClassOf("ValueType")) {
2079 // If the operator is a ValueType, then this must be "type cast" of a leaf
2081 if (Dag->getNumArgs() != 1)
2082 error("Type cast only takes one operand!");
2084 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
2086 // Apply the type cast.
2087 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2088 New->UpdateNodeType(0, getValueType(Operator), *this);
2090 if (!OpName.empty())
2091 error("ValueType cast should not have a name!");
2095 // Verify that this is something that makes sense for an operator.
2096 if (!Operator->isSubClassOf("PatFrag") &&
2097 !Operator->isSubClassOf("SDNode") &&
2098 !Operator->isSubClassOf("Instruction") &&
2099 !Operator->isSubClassOf("SDNodeXForm") &&
2100 !Operator->isSubClassOf("Intrinsic") &&
2101 !Operator->isSubClassOf("ComplexPattern") &&
2102 Operator->getName() != "set" &&
2103 Operator->getName() != "implicit")
2104 error("Unrecognized node '" + Operator->getName() + "'!");
2106 // Check to see if this is something that is illegal in an input pattern.
2107 if (isInputPattern) {
2108 if (Operator->isSubClassOf("Instruction") ||
2109 Operator->isSubClassOf("SDNodeXForm"))
2110 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2112 if (Operator->isSubClassOf("Intrinsic"))
2113 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2115 if (Operator->isSubClassOf("SDNode") &&
2116 Operator->getName() != "imm" &&
2117 Operator->getName() != "fpimm" &&
2118 Operator->getName() != "tglobaltlsaddr" &&
2119 Operator->getName() != "tconstpool" &&
2120 Operator->getName() != "tjumptable" &&
2121 Operator->getName() != "tframeindex" &&
2122 Operator->getName() != "texternalsym" &&
2123 Operator->getName() != "tblockaddress" &&
2124 Operator->getName() != "tglobaladdr" &&
2125 Operator->getName() != "bb" &&
2126 Operator->getName() != "vt" &&
2127 Operator->getName() != "mcsym")
2128 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2131 std::vector<TreePatternNode*> Children;
2133 // Parse all the operands.
2134 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2135 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
2137 // If the operator is an intrinsic, then this is just syntactic sugar for for
2138 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2139 // convert the intrinsic name to a number.
2140 if (Operator->isSubClassOf("Intrinsic")) {
2141 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2142 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2144 // If this intrinsic returns void, it must have side-effects and thus a
2146 if (Int.IS.RetVTs.empty())
2147 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2148 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2149 // Has side-effects, requires chain.
2150 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2151 else // Otherwise, no chain.
2152 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2154 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2155 Children.insert(Children.begin(), IIDNode);
2158 if (Operator->isSubClassOf("ComplexPattern")) {
2159 for (unsigned i = 0; i < Children.size(); ++i) {
2160 TreePatternNode *Child = Children[i];
2162 if (Child->getName().empty())
2163 error("All arguments to a ComplexPattern must be named");
2165 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2166 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2167 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2168 auto OperandId = std::make_pair(Operator, i);
2169 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2170 if (PrevOp != ComplexPatternOperands.end()) {
2171 if (PrevOp->getValue() != OperandId)
2172 error("All ComplexPattern operands must appear consistently: "
2173 "in the same order in just one ComplexPattern instance.");
2175 ComplexPatternOperands[Child->getName()] = OperandId;
2179 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2180 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2181 Result->setName(OpName);
2183 if (!Dag->getName().empty()) {
2184 assert(Result->getName().empty());
2185 Result->setName(Dag->getName());
2190 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2191 /// will never match in favor of something obvious that will. This is here
2192 /// strictly as a convenience to target authors because it allows them to write
2193 /// more type generic things and have useless type casts fold away.
2195 /// This returns true if any change is made.
2196 static bool SimplifyTree(TreePatternNode *&N) {
2200 // If we have a bitconvert with a resolved type and if the source and
2201 // destination types are the same, then the bitconvert is useless, remove it.
2202 if (N->getOperator()->getName() == "bitconvert" &&
2203 N->getExtType(0).isConcrete() &&
2204 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2205 N->getName().empty()) {
2211 // Walk all children.
2212 bool MadeChange = false;
2213 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2214 TreePatternNode *Child = N->getChild(i);
2215 MadeChange |= SimplifyTree(Child);
2216 N->setChild(i, Child);
2223 /// InferAllTypes - Infer/propagate as many types throughout the expression
2224 /// patterns as possible. Return true if all types are inferred, false
2225 /// otherwise. Flags an error if a type contradiction is found.
2227 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2228 if (NamedNodes.empty())
2229 ComputeNamedNodes();
2231 bool MadeChange = true;
2232 while (MadeChange) {
2234 for (TreePatternNode *Tree : Trees) {
2235 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2236 MadeChange |= SimplifyTree(Tree);
2239 // If there are constraints on our named nodes, apply them.
2240 for (auto &Entry : NamedNodes) {
2241 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2243 // If we have input named node types, propagate their types to the named
2246 if (!InNamedTypes->count(Entry.getKey())) {
2247 error("Node '" + std::string(Entry.getKey()) +
2248 "' in output pattern but not input pattern");
2252 const SmallVectorImpl<TreePatternNode*> &InNodes =
2253 InNamedTypes->find(Entry.getKey())->second;
2255 // The input types should be fully resolved by now.
2256 for (TreePatternNode *Node : Nodes) {
2257 // If this node is a register class, and it is the root of the pattern
2258 // then we're mapping something onto an input register. We allow
2259 // changing the type of the input register in this case. This allows
2260 // us to match things like:
2261 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2262 if (Node == Trees[0] && Node->isLeaf()) {
2263 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
2264 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2265 DI->getDef()->isSubClassOf("RegisterOperand")))
2269 assert(Node->getNumTypes() == 1 &&
2270 InNodes[0]->getNumTypes() == 1 &&
2271 "FIXME: cannot name multiple result nodes yet");
2272 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2277 // If there are multiple nodes with the same name, they must all have the
2279 if (Entry.second.size() > 1) {
2280 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2281 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2282 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2283 "FIXME: cannot name multiple result nodes yet");
2285 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2286 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2292 bool HasUnresolvedTypes = false;
2293 for (const TreePatternNode *Tree : Trees)
2294 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
2295 return !HasUnresolvedTypes;
2298 void TreePattern::print(raw_ostream &OS) const {
2299 OS << getRecord()->getName();
2300 if (!Args.empty()) {
2301 OS << "(" << Args[0];
2302 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2303 OS << ", " << Args[i];
2308 if (Trees.size() > 1)
2310 for (const TreePatternNode *Tree : Trees) {
2316 if (Trees.size() > 1)
2320 void TreePattern::dump() const { print(errs()); }
2322 //===----------------------------------------------------------------------===//
2323 // CodeGenDAGPatterns implementation
2326 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2327 Records(R), Target(R) {
2329 Intrinsics = LoadIntrinsics(Records, false);
2330 TgtIntrinsics = LoadIntrinsics(Records, true);
2332 ParseNodeTransforms();
2333 ParseComplexPatterns();
2334 ParsePatternFragments();
2335 ParseDefaultOperands();
2336 ParseInstructions();
2337 ParsePatternFragments(/*OutFrags*/true);
2340 // Generate variants. For example, commutative patterns can match
2341 // multiple ways. Add them to PatternsToMatch as well.
2344 // Infer instruction flags. For example, we can detect loads,
2345 // stores, and side effects in many cases by examining an
2346 // instruction's pattern.
2347 InferInstructionFlags();
2349 // Verify that instruction flags match the patterns.
2350 VerifyInstructionFlags();
2353 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2354 Record *N = Records.getDef(Name);
2355 if (!N || !N->isSubClassOf("SDNode"))
2356 PrintFatalError("Error getting SDNode '" + Name + "'!");
2361 // Parse all of the SDNode definitions for the target, populating SDNodes.
2362 void CodeGenDAGPatterns::ParseNodeInfo() {
2363 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2364 while (!Nodes.empty()) {
2365 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2369 // Get the builtin intrinsic nodes.
2370 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2371 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2372 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2375 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2376 /// map, and emit them to the file as functions.
2377 void CodeGenDAGPatterns::ParseNodeTransforms() {
2378 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2379 while (!Xforms.empty()) {
2380 Record *XFormNode = Xforms.back();
2381 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2382 std::string Code = XFormNode->getValueAsString("XFormFunction");
2383 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2389 void CodeGenDAGPatterns::ParseComplexPatterns() {
2390 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2391 while (!AMs.empty()) {
2392 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2398 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2399 /// file, building up the PatternFragments map. After we've collected them all,
2400 /// inline fragments together as necessary, so that there are no references left
2401 /// inside a pattern fragment to a pattern fragment.
2403 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2404 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2406 // First step, parse all of the fragments.
2407 for (Record *Frag : Fragments) {
2408 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2411 DagInit *Tree = Frag->getValueAsDag("Fragment");
2413 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2414 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
2417 // Validate the argument list, converting it to set, to discard duplicates.
2418 std::vector<std::string> &Args = P->getArgList();
2419 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2421 if (OperandsSet.count(""))
2422 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2424 // Parse the operands list.
2425 DagInit *OpsList = Frag->getValueAsDag("Operands");
2426 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2427 // Special cases: ops == outs == ins. Different names are used to
2428 // improve readability.
2430 (OpsOp->getDef()->getName() != "ops" &&
2431 OpsOp->getDef()->getName() != "outs" &&
2432 OpsOp->getDef()->getName() != "ins"))
2433 P->error("Operands list should start with '(ops ... '!");
2435 // Copy over the arguments.
2437 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2438 if (!isa<DefInit>(OpsList->getArg(j)) ||
2439 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2440 P->error("Operands list should all be 'node' values.");
2441 if (OpsList->getArgName(j).empty())
2442 P->error("Operands list should have names for each operand!");
2443 if (!OperandsSet.count(OpsList->getArgName(j)))
2444 P->error("'" + OpsList->getArgName(j) +
2445 "' does not occur in pattern or was multiply specified!");
2446 OperandsSet.erase(OpsList->getArgName(j));
2447 Args.push_back(OpsList->getArgName(j));
2450 if (!OperandsSet.empty())
2451 P->error("Operands list does not contain an entry for operand '" +
2452 *OperandsSet.begin() + "'!");
2454 // If there is a code init for this fragment, keep track of the fact that
2455 // this fragment uses it.
2456 TreePredicateFn PredFn(P);
2457 if (!PredFn.isAlwaysTrue())
2458 P->getOnlyTree()->addPredicateFn(PredFn);
2460 // If there is a node transformation corresponding to this, keep track of
2462 Record *Transform = Frag->getValueAsDef("OperandTransform");
2463 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2464 P->getOnlyTree()->setTransformFn(Transform);
2467 // Now that we've parsed all of the tree fragments, do a closure on them so
2468 // that there are not references to PatFrags left inside of them.
2469 for (Record *Frag : Fragments) {
2470 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2473 TreePattern &ThePat = *PatternFragments[Frag];
2474 ThePat.InlinePatternFragments();
2476 // Infer as many types as possible. Don't worry about it if we don't infer
2477 // all of them, some may depend on the inputs of the pattern.
2478 ThePat.InferAllTypes();
2479 ThePat.resetError();
2481 // If debugging, print out the pattern fragment result.
2482 DEBUG(ThePat.dump());
2486 void CodeGenDAGPatterns::ParseDefaultOperands() {
2487 std::vector<Record*> DefaultOps;
2488 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2490 // Find some SDNode.
2491 assert(!SDNodes.empty() && "No SDNodes parsed?");
2492 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2494 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2495 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
2497 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2498 // SomeSDnode so that we can parse this.
2499 std::vector<std::pair<Init*, std::string> > Ops;
2500 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2501 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2502 DefaultInfo->getArgName(op)));
2503 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
2505 // Create a TreePattern to parse this.
2506 TreePattern P(DefaultOps[i], DI, false, *this);
2507 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2509 // Copy the operands over into a DAGDefaultOperand.
2510 DAGDefaultOperand DefaultOpInfo;
2512 TreePatternNode *T = P.getTree(0);
2513 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2514 TreePatternNode *TPN = T->getChild(op);
2515 while (TPN->ApplyTypeConstraints(P, false))
2516 /* Resolve all types */;
2518 if (TPN->ContainsUnresolvedType()) {
2519 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2520 DefaultOps[i]->getName() +
2521 "' doesn't have a concrete type!");
2523 DefaultOpInfo.DefaultOps.push_back(TPN);
2526 // Insert it into the DefaultOperands map so we can find it later.
2527 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
2531 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2532 /// instruction input. Return true if this is a real use.
2533 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2534 std::map<std::string, TreePatternNode*> &InstInputs) {
2535 // No name -> not interesting.
2536 if (Pat->getName().empty()) {
2537 if (Pat->isLeaf()) {
2538 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2539 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2540 DI->getDef()->isSubClassOf("RegisterOperand")))
2541 I->error("Input " + DI->getDef()->getName() + " must be named!");
2547 if (Pat->isLeaf()) {
2548 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2549 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2552 Rec = Pat->getOperator();
2555 // SRCVALUE nodes are ignored.
2556 if (Rec->getName() == "srcvalue")
2559 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2565 if (Slot->isLeaf()) {
2566 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
2568 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2569 SlotRec = Slot->getOperator();
2572 // Ensure that the inputs agree if we've already seen this input.
2574 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2575 if (Slot->getExtTypes() != Pat->getExtTypes())
2576 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2580 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2581 /// part of "I", the instruction), computing the set of inputs and outputs of
2582 /// the pattern. Report errors if we see anything naughty.
2583 void CodeGenDAGPatterns::
2584 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2585 std::map<std::string, TreePatternNode*> &InstInputs,
2586 std::map<std::string, TreePatternNode*>&InstResults,
2587 std::vector<Record*> &InstImpResults) {
2588 if (Pat->isLeaf()) {
2589 bool isUse = HandleUse(I, Pat, InstInputs);
2590 if (!isUse && Pat->getTransformFn())
2591 I->error("Cannot specify a transform function for a non-input value!");
2595 if (Pat->getOperator()->getName() == "implicit") {
2596 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2597 TreePatternNode *Dest = Pat->getChild(i);
2598 if (!Dest->isLeaf())
2599 I->error("implicitly defined value should be a register!");
2601 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2602 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2603 I->error("implicitly defined value should be a register!");
2604 InstImpResults.push_back(Val->getDef());
2609 if (Pat->getOperator()->getName() != "set") {
2610 // If this is not a set, verify that the children nodes are not void typed,
2612 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2613 if (Pat->getChild(i)->getNumTypes() == 0)
2614 I->error("Cannot have void nodes inside of patterns!");
2615 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2619 // If this is a non-leaf node with no children, treat it basically as if
2620 // it were a leaf. This handles nodes like (imm).
2621 bool isUse = HandleUse(I, Pat, InstInputs);
2623 if (!isUse && Pat->getTransformFn())
2624 I->error("Cannot specify a transform function for a non-input value!");
2628 // Otherwise, this is a set, validate and collect instruction results.
2629 if (Pat->getNumChildren() == 0)
2630 I->error("set requires operands!");
2632 if (Pat->getTransformFn())
2633 I->error("Cannot specify a transform function on a set node!");
2635 // Check the set destinations.
2636 unsigned NumDests = Pat->getNumChildren()-1;
2637 for (unsigned i = 0; i != NumDests; ++i) {
2638 TreePatternNode *Dest = Pat->getChild(i);
2639 if (!Dest->isLeaf())
2640 I->error("set destination should be a register!");
2642 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2644 I->error("set destination should be a register!");
2648 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2649 Val->getDef()->isSubClassOf("ValueType") ||
2650 Val->getDef()->isSubClassOf("RegisterOperand") ||
2651 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2652 if (Dest->getName().empty())
2653 I->error("set destination must have a name!");
2654 if (InstResults.count(Dest->getName()))
2655 I->error("cannot set '" + Dest->getName() +"' multiple times");
2656 InstResults[Dest->getName()] = Dest;
2657 } else if (Val->getDef()->isSubClassOf("Register")) {
2658 InstImpResults.push_back(Val->getDef());
2660 I->error("set destination should be a register!");
2664 // Verify and collect info from the computation.
2665 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2666 InstInputs, InstResults, InstImpResults);
2669 //===----------------------------------------------------------------------===//
2670 // Instruction Analysis
2671 //===----------------------------------------------------------------------===//
2673 class InstAnalyzer {
2674 const CodeGenDAGPatterns &CDP;
2676 bool hasSideEffects;
2682 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2683 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2684 isBitcast(false), isVariadic(false) {}
2686 void Analyze(const TreePattern *Pat) {
2687 // Assume only the first tree is the pattern. The others are clobber nodes.
2688 AnalyzeNode(Pat->getTree(0));
2691 void Analyze(const PatternToMatch *Pat) {
2692 AnalyzeNode(Pat->getSrcPattern());
2696 bool IsNodeBitcast(const TreePatternNode *N) const {
2697 if (hasSideEffects || mayLoad || mayStore || isVariadic)
2700 if (N->getNumChildren() != 2)
2703 const TreePatternNode *N0 = N->getChild(0);
2704 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
2707 const TreePatternNode *N1 = N->getChild(1);
2710 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2713 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2714 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2716 return OpInfo.getEnumName() == "ISD::BITCAST";
2720 void AnalyzeNode(const TreePatternNode *N) {
2722 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
2723 Record *LeafRec = DI->getDef();
2724 // Handle ComplexPattern leaves.
2725 if (LeafRec->isSubClassOf("ComplexPattern")) {
2726 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2727 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2728 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2729 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2735 // Analyze children.
2736 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2737 AnalyzeNode(N->getChild(i));
2739 // Ignore set nodes, which are not SDNodes.
2740 if (N->getOperator()->getName() == "set") {
2741 isBitcast = IsNodeBitcast(N);
2745 // Notice properties of the node.
2746 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2747 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2748 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2749 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
2751 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2752 // If this is an intrinsic, analyze it.
2753 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2754 mayLoad = true;// These may load memory.
2756 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2757 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2759 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2760 // WriteMem intrinsics can have other strange effects.
2761 hasSideEffects = true;
2767 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2768 const InstAnalyzer &PatInfo,
2772 // Remember where InstInfo got its flags.
2773 if (InstInfo.hasUndefFlags())
2774 InstInfo.InferredFrom = PatDef;
2776 // Check explicitly set flags for consistency.
2777 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2778 !InstInfo.hasSideEffects_Unset) {
2779 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2780 // the pattern has no side effects. That could be useful for div/rem
2781 // instructions that may trap.
2782 if (!InstInfo.hasSideEffects) {
2784 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2785 Twine(InstInfo.hasSideEffects));
2789 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2791 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2792 Twine(InstInfo.mayStore));
2795 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2796 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2797 // Some targets translate immediates to loads.
2798 if (!InstInfo.mayLoad) {
2800 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2801 Twine(InstInfo.mayLoad));
2805 // Transfer inferred flags.
2806 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2807 InstInfo.mayStore |= PatInfo.mayStore;
2808 InstInfo.mayLoad |= PatInfo.mayLoad;
2810 // These flags are silently added without any verification.
2811 InstInfo.isBitcast |= PatInfo.isBitcast;
2813 // Don't infer isVariadic. This flag means something different on SDNodes and
2814 // instructions. For example, a CALL SDNode is variadic because it has the
2815 // call arguments as operands, but a CALL instruction is not variadic - it
2816 // has argument registers as implicit, not explicit uses.
2821 /// hasNullFragReference - Return true if the DAG has any reference to the
2822 /// null_frag operator.
2823 static bool hasNullFragReference(DagInit *DI) {
2824 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
2825 if (!OpDef) return false;
2826 Record *Operator = OpDef->getDef();
2828 // If this is the null fragment, return true.
2829 if (Operator->getName() == "null_frag") return true;
2830 // If any of the arguments reference the null fragment, return true.
2831 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2832 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
2833 if (Arg && hasNullFragReference(Arg))
2840 /// hasNullFragReference - Return true if any DAG in the list references
2841 /// the null_frag operator.
2842 static bool hasNullFragReference(ListInit *LI) {
2843 for (Init *I : LI->getValues()) {
2844 DagInit *DI = dyn_cast<DagInit>(I);
2845 assert(DI && "non-dag in an instruction Pattern list?!");
2846 if (hasNullFragReference(DI))
2852 /// Get all the instructions in a tree.
2854 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2857 if (Tree->getOperator()->isSubClassOf("Instruction"))
2858 Instrs.push_back(Tree->getOperator());
2859 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2860 getInstructionsInTree(Tree->getChild(i), Instrs);
2863 /// Check the class of a pattern leaf node against the instruction operand it
2865 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2870 // Allow direct value types to be used in instruction set patterns.
2871 // The type will be checked later.
2872 if (Leaf->isSubClassOf("ValueType"))
2875 // Patterns can also be ComplexPattern instances.
2876 if (Leaf->isSubClassOf("ComplexPattern"))
2882 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2883 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
2885 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
2887 // Parse the instruction.
2888 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2889 // Inline pattern fragments into it.
2890 I->InlinePatternFragments();
2892 // Infer as many types as possible. If we cannot infer all of them, we can
2893 // never do anything with this instruction pattern: report it to the user.
2894 if (!I->InferAllTypes())
2895 I->error("Could not infer all types in pattern!");
2897 // InstInputs - Keep track of all of the inputs of the instruction, along
2898 // with the record they are declared as.
2899 std::map<std::string, TreePatternNode*> InstInputs;
2901 // InstResults - Keep track of all the virtual registers that are 'set'
2902 // in the instruction, including what reg class they are.
2903 std::map<std::string, TreePatternNode*> InstResults;
2905 std::vector<Record*> InstImpResults;
2907 // Verify that the top-level forms in the instruction are of void type, and
2908 // fill in the InstResults map.
2909 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2910 TreePatternNode *Pat = I->getTree(j);
2911 if (Pat->getNumTypes() != 0)
2912 I->error("Top-level forms in instruction pattern should have"
2915 // Find inputs and outputs, and verify the structure of the uses/defs.
2916 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2920 // Now that we have inputs and outputs of the pattern, inspect the operands
2921 // list for the instruction. This determines the order that operands are
2922 // added to the machine instruction the node corresponds to.
2923 unsigned NumResults = InstResults.size();
2925 // Parse the operands list from the (ops) list, validating it.
2926 assert(I->getArgList().empty() && "Args list should still be empty here!");
2928 // Check that all of the results occur first in the list.
2929 std::vector<Record*> Results;
2930 SmallVector<TreePatternNode *, 2> ResNodes;
2931 for (unsigned i = 0; i != NumResults; ++i) {
2932 if (i == CGI.Operands.size())
2933 I->error("'" + InstResults.begin()->first +
2934 "' set but does not appear in operand list!");
2935 const std::string &OpName = CGI.Operands[i].Name;
2937 // Check that it exists in InstResults.
2938 TreePatternNode *RNode = InstResults[OpName];
2940 I->error("Operand $" + OpName + " does not exist in operand list!");
2942 ResNodes.push_back(RNode);
2944 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2946 I->error("Operand $" + OpName + " should be a set destination: all "
2947 "outputs must occur before inputs in operand list!");
2949 if (!checkOperandClass(CGI.Operands[i], R))
2950 I->error("Operand $" + OpName + " class mismatch!");
2952 // Remember the return type.
2953 Results.push_back(CGI.Operands[i].Rec);
2955 // Okay, this one checks out.
2956 InstResults.erase(OpName);
2959 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2960 // the copy while we're checking the inputs.
2961 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2963 std::vector<TreePatternNode*> ResultNodeOperands;
2964 std::vector<Record*> Operands;
2965 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2966 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2967 const std::string &OpName = Op.Name;
2969 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2971 if (!InstInputsCheck.count(OpName)) {
2972 // If this is an operand with a DefaultOps set filled in, we can ignore
2973 // this. When we codegen it, we will do so as always executed.
2974 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2975 // Does it have a non-empty DefaultOps field? If so, ignore this
2977 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2980 I->error("Operand $" + OpName +
2981 " does not appear in the instruction pattern");
2983 TreePatternNode *InVal = InstInputsCheck[OpName];
2984 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2986 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
2987 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2988 if (!checkOperandClass(Op, InRec))
2989 I->error("Operand $" + OpName + "'s register class disagrees"
2990 " between the operand and pattern");
2992 Operands.push_back(Op.Rec);
2994 // Construct the result for the dest-pattern operand list.
2995 TreePatternNode *OpNode = InVal->clone();
2997 // No predicate is useful on the result.
2998 OpNode->clearPredicateFns();
3000 // Promote the xform function to be an explicit node if set.
3001 if (Record *Xform = OpNode->getTransformFn()) {
3002 OpNode->setTransformFn(nullptr);
3003 std::vector<TreePatternNode*> Children;
3004 Children.push_back(OpNode);
3005 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3008 ResultNodeOperands.push_back(OpNode);
3011 if (!InstInputsCheck.empty())
3012 I->error("Input operand $" + InstInputsCheck.begin()->first +
3013 " occurs in pattern but not in operands list!");
3015 TreePatternNode *ResultPattern =
3016 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3017 GetNumNodeResults(I->getRecord(), *this));
3018 // Copy fully inferred output node types to instruction result pattern.
3019 for (unsigned i = 0; i != NumResults; ++i) {
3020 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3021 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3024 // Create and insert the instruction.
3025 // FIXME: InstImpResults should not be part of DAGInstruction.
3026 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3027 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3029 // Use a temporary tree pattern to infer all types and make sure that the
3030 // constructed result is correct. This depends on the instruction already
3031 // being inserted into the DAGInsts map.
3032 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3033 Temp.InferAllTypes(&I->getNamedNodesMap());
3035 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3036 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3038 return TheInsertedInst;
3041 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3042 /// any fragments involved. This populates the Instructions list with fully
3043 /// resolved instructions.
3044 void CodeGenDAGPatterns::ParseInstructions() {
3045 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3047 for (Record *Instr : Instrs) {
3048 ListInit *LI = nullptr;
3050 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3051 LI = Instr->getValueAsListInit("Pattern");
3053 // If there is no pattern, only collect minimal information about the
3054 // instruction for its operand list. We have to assume that there is one
3055 // result, as we have no detailed info. A pattern which references the
3056 // null_frag operator is as-if no pattern were specified. Normally this
3057 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3059 if (!LI || LI->empty() || hasNullFragReference(LI)) {
3060 std::vector<Record*> Results;
3061 std::vector<Record*> Operands;
3063 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3065 if (InstInfo.Operands.size() != 0) {
3066 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3067 Results.push_back(InstInfo.Operands[j].Rec);
3069 // The rest are inputs.
3070 for (unsigned j = InstInfo.Operands.NumDefs,
3071 e = InstInfo.Operands.size(); j < e; ++j)
3072 Operands.push_back(InstInfo.Operands[j].Rec);
3075 // Create and insert the instruction.
3076 std::vector<Record*> ImpResults;
3077 Instructions.insert(std::make_pair(Instr,
3078 DAGInstruction(nullptr, Results, Operands, ImpResults)));
3079 continue; // no pattern.
3082 CodeGenInstruction &CGI = Target.getInstruction(Instr);
3083 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3086 DEBUG(DI.getPattern()->dump());
3089 // If we can, convert the instructions to be patterns that are matched!
3090 for (auto &Entry : Instructions) {
3091 DAGInstruction &TheInst = Entry.second;
3092 TreePattern *I = TheInst.getPattern();
3093 if (!I) continue; // No pattern.
3095 // FIXME: Assume only the first tree is the pattern. The others are clobber
3097 TreePatternNode *Pattern = I->getTree(0);
3098 TreePatternNode *SrcPattern;
3099 if (Pattern->getOperator()->getName() == "set") {
3100 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3102 // Not a set (store or something?)
3103 SrcPattern = Pattern;
3106 Record *Instr = Entry.first;
3107 AddPatternToMatch(I,
3108 PatternToMatch(Instr,
3109 Instr->getValueAsListInit("Predicates"),
3111 TheInst.getResultPattern(),
3112 TheInst.getImpResults(),
3113 Instr->getValueAsInt("AddedComplexity"),
3119 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3121 static void FindNames(const TreePatternNode *P,
3122 std::map<std::string, NameRecord> &Names,
3123 TreePattern *PatternTop) {
3124 if (!P->getName().empty()) {
3125 NameRecord &Rec = Names[P->getName()];
3126 // If this is the first instance of the name, remember the node.
3127 if (Rec.second++ == 0)
3129 else if (Rec.first->getExtTypes() != P->getExtTypes())
3130 PatternTop->error("repetition of value: $" + P->getName() +
3131 " where different uses have different types!");
3135 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3136 FindNames(P->getChild(i), Names, PatternTop);
3140 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3141 const PatternToMatch &PTM) {
3142 // Do some sanity checking on the pattern we're about to match.
3144 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3145 PrintWarning(Pattern->getRecord()->getLoc(),
3146 Twine("Pattern can never match: ") + Reason);
3150 // If the source pattern's root is a complex pattern, that complex pattern
3151 // must specify the nodes it can potentially match.
3152 if (const ComplexPattern *CP =
3153 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3154 if (CP->getRootNodes().empty())
3155 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3159 // Find all of the named values in the input and output, ensure they have the
3161 std::map<std::string, NameRecord> SrcNames, DstNames;
3162 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3163 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3165 // Scan all of the named values in the destination pattern, rejecting them if
3166 // they don't exist in the input pattern.
3167 for (const auto &Entry : DstNames) {
3168 if (SrcNames[Entry.first].first == nullptr)
3169 Pattern->error("Pattern has input without matching name in output: $" +
3173 // Scan all of the named values in the source pattern, rejecting them if the
3174 // name isn't used in the dest, and isn't used to tie two values together.
3175 for (const auto &Entry : SrcNames)
3176 if (DstNames[Entry.first].first == nullptr &&
3177 SrcNames[Entry.first].second == 1)
3178 Pattern->error("Pattern has dead named input: $" + Entry.first);
3180 PatternsToMatch.push_back(PTM);
3185 void CodeGenDAGPatterns::InferInstructionFlags() {
3186 const std::vector<const CodeGenInstruction*> &Instructions =
3187 Target.getInstructionsByEnumValue();
3189 // First try to infer flags from the primary instruction pattern, if any.
3190 SmallVector<CodeGenInstruction*, 8> Revisit;
3191 unsigned Errors = 0;
3192 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3193 CodeGenInstruction &InstInfo =
3194 const_cast<CodeGenInstruction &>(*Instructions[i]);
3196 // Get the primary instruction pattern.
3197 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3199 if (InstInfo.hasUndefFlags())
3200 Revisit.push_back(&InstInfo);
3203 InstAnalyzer PatInfo(*this);
3204 PatInfo.Analyze(Pattern);
3205 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3208 // Second, look for single-instruction patterns defined outside the
3210 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3211 const PatternToMatch &PTM = *I;
3213 // We can only infer from single-instruction patterns, otherwise we won't
3214 // know which instruction should get the flags.
3215 SmallVector<Record*, 8> PatInstrs;
3216 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3217 if (PatInstrs.size() != 1)
3220 // Get the single instruction.
3221 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3223 // Only infer properties from the first pattern. We'll verify the others.
3224 if (InstInfo.InferredFrom)
3227 InstAnalyzer PatInfo(*this);
3228 PatInfo.Analyze(&PTM);
3229 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3233 PrintFatalError("pattern conflicts");
3235 // Revisit instructions with undefined flags and no pattern.
3236 if (Target.guessInstructionProperties()) {
3237 for (CodeGenInstruction *InstInfo : Revisit) {
3238 if (InstInfo->InferredFrom)
3240 // The mayLoad and mayStore flags default to false.
3241 // Conservatively assume hasSideEffects if it wasn't explicit.
3242 if (InstInfo->hasSideEffects_Unset)
3243 InstInfo->hasSideEffects = true;
3248 // Complain about any flags that are still undefined.
3249 for (CodeGenInstruction *InstInfo : Revisit) {
3250 if (InstInfo->InferredFrom)
3252 if (InstInfo->hasSideEffects_Unset)
3253 PrintError(InstInfo->TheDef->getLoc(),
3254 "Can't infer hasSideEffects from patterns");
3255 if (InstInfo->mayStore_Unset)
3256 PrintError(InstInfo->TheDef->getLoc(),
3257 "Can't infer mayStore from patterns");
3258 if (InstInfo->mayLoad_Unset)
3259 PrintError(InstInfo->TheDef->getLoc(),
3260 "Can't infer mayLoad from patterns");
3265 /// Verify instruction flags against pattern node properties.
3266 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3267 unsigned Errors = 0;
3268 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3269 const PatternToMatch &PTM = *I;
3270 SmallVector<Record*, 8> Instrs;
3271 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3275 // Count the number of instructions with each flag set.
3276 unsigned NumSideEffects = 0;
3277 unsigned NumStores = 0;
3278 unsigned NumLoads = 0;
3279 for (const Record *Instr : Instrs) {
3280 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3281 NumSideEffects += InstInfo.hasSideEffects;
3282 NumStores += InstInfo.mayStore;
3283 NumLoads += InstInfo.mayLoad;
3286 // Analyze the source pattern.
3287 InstAnalyzer PatInfo(*this);
3288 PatInfo.Analyze(&PTM);
3290 // Collect error messages.
3291 SmallVector<std::string, 4> Msgs;
3293 // Check for missing flags in the output.
3294 // Permit extra flags for now at least.
3295 if (PatInfo.hasSideEffects && !NumSideEffects)
3296 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3298 // Don't verify store flags on instructions with side effects. At least for
3299 // intrinsics, side effects implies mayStore.
3300 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3301 Msgs.push_back("pattern may store, but mayStore isn't set");
3303 // Similarly, mayStore implies mayLoad on intrinsics.
3304 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3305 Msgs.push_back("pattern may load, but mayLoad isn't set");
3307 // Print error messages.
3312 for (const std::string &Msg : Msgs)
3313 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
3314 (Instrs.size() == 1 ?
3315 "instruction" : "output instructions"));
3316 // Provide the location of the relevant instruction definitions.
3317 for (const Record *Instr : Instrs) {
3318 if (Instr != PTM.getSrcRecord())
3319 PrintError(Instr->getLoc(), "defined here");
3320 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3321 if (InstInfo.InferredFrom &&
3322 InstInfo.InferredFrom != InstInfo.TheDef &&
3323 InstInfo.InferredFrom != PTM.getSrcRecord())
3324 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3328 PrintFatalError("Errors in DAG patterns");
3331 /// Given a pattern result with an unresolved type, see if we can find one
3332 /// instruction with an unresolved result type. Force this result type to an
3333 /// arbitrary element if it's possible types to converge results.
3334 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3338 // Analyze children.
3339 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3340 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3343 if (!N->getOperator()->isSubClassOf("Instruction"))
3346 // If this type is already concrete or completely unknown we can't do
3348 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3349 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3352 // Otherwise, force its type to the first possibility (an arbitrary choice).
3353 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3360 void CodeGenDAGPatterns::ParsePatterns() {
3361 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3363 for (Record *CurPattern : Patterns) {
3364 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3366 // If the pattern references the null_frag, there's nothing to do.
3367 if (hasNullFragReference(Tree))
3370 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3372 // Inline pattern fragments into it.
3373 Pattern->InlinePatternFragments();
3375 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3376 if (LI->empty()) continue; // no pattern.
3378 // Parse the instruction.
3379 TreePattern Result(CurPattern, LI, false, *this);
3381 // Inline pattern fragments into it.
3382 Result.InlinePatternFragments();
3384 if (Result.getNumTrees() != 1)
3385 Result.error("Cannot handle instructions producing instructions "
3386 "with temporaries yet!");
3388 bool IterateInference;
3389 bool InferredAllPatternTypes, InferredAllResultTypes;
3391 // Infer as many types as possible. If we cannot infer all of them, we
3392 // can never do anything with this pattern: report it to the user.
3393 InferredAllPatternTypes =
3394 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3396 // Infer as many types as possible. If we cannot infer all of them, we
3397 // can never do anything with this pattern: report it to the user.
3398 InferredAllResultTypes =
3399 Result.InferAllTypes(&Pattern->getNamedNodesMap());
3401 IterateInference = false;
3403 // Apply the type of the result to the source pattern. This helps us
3404 // resolve cases where the input type is known to be a pointer type (which
3405 // is considered resolved), but the result knows it needs to be 32- or
3406 // 64-bits. Infer the other way for good measure.
3407 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3408 Pattern->getTree(0)->getNumTypes());
3410 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3411 i, Result.getTree(0)->getExtType(i), Result);
3412 IterateInference |= Result.getTree(0)->UpdateNodeType(
3413 i, Pattern->getTree(0)->getExtType(i), Result);
3416 // If our iteration has converged and the input pattern's types are fully
3417 // resolved but the result pattern is not fully resolved, we may have a
3418 // situation where we have two instructions in the result pattern and
3419 // the instructions require a common register class, but don't care about
3420 // what actual MVT is used. This is actually a bug in our modelling:
3421 // output patterns should have register classes, not MVTs.
3423 // In any case, to handle this, we just go through and disambiguate some
3424 // arbitrary types to the result pattern's nodes.
3425 if (!IterateInference && InferredAllPatternTypes &&
3426 !InferredAllResultTypes)
3428 ForceArbitraryInstResultType(Result.getTree(0), Result);
3429 } while (IterateInference);
3431 // Verify that we inferred enough types that we can do something with the
3432 // pattern and result. If these fire the user has to add type casts.
3433 if (!InferredAllPatternTypes)
3434 Pattern->error("Could not infer all types in pattern!");
3435 if (!InferredAllResultTypes) {
3437 Result.error("Could not infer all types in pattern result!");
3440 // Validate that the input pattern is correct.
3441 std::map<std::string, TreePatternNode*> InstInputs;
3442 std::map<std::string, TreePatternNode*> InstResults;
3443 std::vector<Record*> InstImpResults;
3444 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3445 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3446 InstInputs, InstResults,
3449 // Promote the xform function to be an explicit node if set.
3450 TreePatternNode *DstPattern = Result.getOnlyTree();
3451 std::vector<TreePatternNode*> ResultNodeOperands;
3452 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3453 TreePatternNode *OpNode = DstPattern->getChild(ii);
3454 if (Record *Xform = OpNode->getTransformFn()) {
3455 OpNode->setTransformFn(nullptr);
3456 std::vector<TreePatternNode*> Children;
3457 Children.push_back(OpNode);
3458 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3460 ResultNodeOperands.push_back(OpNode);
3462 DstPattern = Result.getOnlyTree();
3463 if (!DstPattern->isLeaf())
3464 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3466 DstPattern->getNumTypes());
3468 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3469 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3471 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
3472 Temp.InferAllTypes();
3475 AddPatternToMatch(Pattern,
3476 PatternToMatch(CurPattern,
3477 CurPattern->getValueAsListInit("Predicates"),
3478 Pattern->getTree(0),
3479 Temp.getOnlyTree(), InstImpResults,
3480 CurPattern->getValueAsInt("AddedComplexity"),
3481 CurPattern->getID()));
3485 /// CombineChildVariants - Given a bunch of permutations of each child of the
3486 /// 'operator' node, put them together in all possible ways.
3487 static void CombineChildVariants(TreePatternNode *Orig,
3488 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3489 std::vector<TreePatternNode*> &OutVariants,
3490 CodeGenDAGPatterns &CDP,
3491 const MultipleUseVarSet &DepVars) {
3492 // Make sure that each operand has at least one variant to choose from.
3493 for (const auto &Variants : ChildVariants)
3494 if (Variants.empty())
3497 // The end result is an all-pairs construction of the resultant pattern.
3498 std::vector<unsigned> Idxs;
3499 Idxs.resize(ChildVariants.size());
3503 DEBUG(if (!Idxs.empty()) {
3504 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3505 for (unsigned Idx : Idxs) {
3506 errs() << Idx << " ";
3511 // Create the variant and add it to the output list.
3512 std::vector<TreePatternNode*> NewChildren;
3513 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3514 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3515 auto R = llvm::make_unique<TreePatternNode>(
3516 Orig->getOperator(), NewChildren, Orig->getNumTypes());
3518 // Copy over properties.
3519 R->setName(Orig->getName());
3520 R->setPredicateFns(Orig->getPredicateFns());
3521 R->setTransformFn(Orig->getTransformFn());
3522 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3523 R->setType(i, Orig->getExtType(i));
3525 // If this pattern cannot match, do not include it as a variant.
3526 std::string ErrString;
3527 // Scan to see if this pattern has already been emitted. We can get
3528 // duplication due to things like commuting:
3529 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3530 // which are the same pattern. Ignore the dups.
3531 if (R->canPatternMatch(ErrString, CDP) &&
3532 std::none_of(OutVariants.begin(), OutVariants.end(),
3533 [&](TreePatternNode *Variant) {
3534 return R->isIsomorphicTo(Variant, DepVars);
3536 OutVariants.push_back(R.release());
3538 // Increment indices to the next permutation by incrementing the
3539 // indices from last index backward, e.g., generate the sequence
3540 // [0, 0], [0, 1], [1, 0], [1, 1].
3542 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3543 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3548 NotDone = (IdxsIdx >= 0);
3552 /// CombineChildVariants - A helper function for binary operators.
3554 static void CombineChildVariants(TreePatternNode *Orig,
3555 const std::vector<TreePatternNode*> &LHS,
3556 const std::vector<TreePatternNode*> &RHS,
3557 std::vector<TreePatternNode*> &OutVariants,
3558 CodeGenDAGPatterns &CDP,
3559 const MultipleUseVarSet &DepVars) {
3560 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3561 ChildVariants.push_back(LHS);
3562 ChildVariants.push_back(RHS);
3563 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3567 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3568 std::vector<TreePatternNode *> &Children) {
3569 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3570 Record *Operator = N->getOperator();
3572 // Only permit raw nodes.
3573 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3574 N->getTransformFn()) {
3575 Children.push_back(N);
3579 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3580 Children.push_back(N->getChild(0));
3582 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3584 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3585 Children.push_back(N->getChild(1));
3587 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3590 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3591 /// the (potentially recursive) pattern by using algebraic laws.
3593 static void GenerateVariantsOf(TreePatternNode *N,
3594 std::vector<TreePatternNode*> &OutVariants,
3595 CodeGenDAGPatterns &CDP,
3596 const MultipleUseVarSet &DepVars) {
3597 // We cannot permute leaves or ComplexPattern uses.
3598 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
3599 OutVariants.push_back(N);
3603 // Look up interesting info about the node.
3604 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3606 // If this node is associative, re-associate.
3607 if (NodeInfo.hasProperty(SDNPAssociative)) {
3608 // Re-associate by pulling together all of the linked operators
3609 std::vector<TreePatternNode*> MaximalChildren;
3610 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3612 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3614 if (MaximalChildren.size() == 3) {
3615 // Find the variants of all of our maximal children.
3616 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3617 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3618 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3619 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3621 // There are only two ways we can permute the tree:
3622 // (A op B) op C and A op (B op C)
3623 // Within these forms, we can also permute A/B/C.
3625 // Generate legal pair permutations of A/B/C.
3626 std::vector<TreePatternNode*> ABVariants;
3627 std::vector<TreePatternNode*> BAVariants;
3628 std::vector<TreePatternNode*> ACVariants;
3629 std::vector<TreePatternNode*> CAVariants;
3630 std::vector<TreePatternNode*> BCVariants;
3631 std::vector<TreePatternNode*> CBVariants;
3632 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3633 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3634 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3635 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3636 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3637 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3639 // Combine those into the result: (x op x) op x
3640 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3641 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3642 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3643 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3644 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3645 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3647 // Combine those into the result: x op (x op x)
3648 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3649 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3650 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3651 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3652 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3653 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3658 // Compute permutations of all children.
3659 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3660 ChildVariants.resize(N->getNumChildren());
3661 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3662 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3664 // Build all permutations based on how the children were formed.
3665 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3667 // If this node is commutative, consider the commuted order.
3668 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3669 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3670 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3671 "Commutative but doesn't have 2 children!");
3672 // Don't count children which are actually register references.
3674 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3675 TreePatternNode *Child = N->getChild(i);
3676 if (Child->isLeaf())
3677 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
3678 Record *RR = DI->getDef();
3679 if (RR->isSubClassOf("Register"))
3684 // Consider the commuted order.
3685 if (isCommIntrinsic) {
3686 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3687 // operands are the commutative operands, and there might be more operands
3690 "Commutative intrinsic should have at least 3 children!");
3691 std::vector<std::vector<TreePatternNode*> > Variants;
3692 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3693 Variants.push_back(ChildVariants[2]);
3694 Variants.push_back(ChildVariants[1]);
3695 for (unsigned i = 3; i != NC; ++i)
3696 Variants.push_back(ChildVariants[i]);
3697 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3699 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3700 OutVariants, CDP, DepVars);
3705 // GenerateVariants - Generate variants. For example, commutative patterns can
3706 // match multiple ways. Add them to PatternsToMatch as well.
3707 void CodeGenDAGPatterns::GenerateVariants() {
3708 DEBUG(errs() << "Generating instruction variants.\n");
3710 // Loop over all of the patterns we've collected, checking to see if we can
3711 // generate variants of the instruction, through the exploitation of
3712 // identities. This permits the target to provide aggressive matching without
3713 // the .td file having to contain tons of variants of instructions.
3715 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3716 // intentionally do not reconsider these. Any variants of added patterns have
3717 // already been added.
3719 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3720 MultipleUseVarSet DepVars;
3721 std::vector<TreePatternNode*> Variants;
3722 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3723 DEBUG(errs() << "Dependent/multiply used variables: ");
3724 DEBUG(DumpDepVars(DepVars));
3725 DEBUG(errs() << "\n");
3726 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3729 assert(!Variants.empty() && "Must create at least original variant!");
3730 Variants.erase(Variants.begin()); // Remove the original pattern.
3732 if (Variants.empty()) // No variants for this pattern.
3735 DEBUG(errs() << "FOUND VARIANTS OF: ";
3736 PatternsToMatch[i].getSrcPattern()->dump();
3739 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3740 TreePatternNode *Variant = Variants[v];
3742 DEBUG(errs() << " VAR#" << v << ": ";
3746 // Scan to see if an instruction or explicit pattern already matches this.
3747 bool AlreadyExists = false;
3748 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3749 // Skip if the top level predicates do not match.
3750 if (PatternsToMatch[i].getPredicates() !=
3751 PatternsToMatch[p].getPredicates())
3753 // Check to see if this variant already exists.
3754 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3756 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3757 AlreadyExists = true;
3761 // If we already have it, ignore the variant.
3762 if (AlreadyExists) continue;
3764 // Otherwise, add it to the list of patterns we have.
3765 PatternsToMatch.emplace_back(
3766 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3767 Variant, PatternsToMatch[i].getDstPattern(),
3768 PatternsToMatch[i].getDstRegs(),
3769 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
3772 DEBUG(errs() << "\n");