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/SmallString.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/TableGen/Error.h"
23 #include "llvm/TableGen/Record.h"
29 #define DEBUG_TYPE "dag-patterns"
31 //===----------------------------------------------------------------------===//
32 // EEVT::TypeSet Implementation
33 //===----------------------------------------------------------------------===//
35 static inline bool isInteger(MVT::SimpleValueType VT) {
36 return MVT(VT).isInteger();
38 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
39 return MVT(VT).isFloatingPoint();
41 static inline bool isVector(MVT::SimpleValueType VT) {
42 return MVT(VT).isVector();
44 static inline bool isScalar(MVT::SimpleValueType VT) {
45 return !MVT(VT).isVector();
48 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
51 else if (VT == MVT::fAny)
52 EnforceFloatingPoint(TP);
53 else if (VT == MVT::vAny)
56 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
57 VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!");
58 TypeVec.push_back(VT);
63 EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
64 assert(!VTList.empty() && "empty list?");
65 TypeVec.append(VTList.begin(), VTList.end());
68 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
69 VTList[0] != MVT::fAny);
71 // Verify no duplicates.
72 array_pod_sort(TypeVec.begin(), TypeVec.end());
73 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
76 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
77 /// on completely unknown type sets.
78 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
79 bool (*Pred)(MVT::SimpleValueType),
80 const char *PredicateName) {
81 assert(isCompletelyUnknown());
82 ArrayRef<MVT::SimpleValueType> LegalTypes =
83 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
88 for (MVT::SimpleValueType VT : LegalTypes)
89 if (!Pred || Pred(VT))
90 TypeVec.push_back(VT);
92 // If we have nothing that matches the predicate, bail out.
93 if (TypeVec.empty()) {
94 TP.error("Type inference contradiction found, no " +
95 std::string(PredicateName) + " types found");
98 // No need to sort with one element.
99 if (TypeVec.size() == 1) return true;
101 // Remove duplicates.
102 array_pod_sort(TypeVec.begin(), TypeVec.end());
103 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
108 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
109 /// integer value type.
110 bool EEVT::TypeSet::hasIntegerTypes() const {
111 return any_of(TypeVec, isInteger);
114 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
115 /// a floating point value type.
116 bool EEVT::TypeSet::hasFloatingPointTypes() const {
117 return any_of(TypeVec, isFloatingPoint);
120 /// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
121 bool EEVT::TypeSet::hasScalarTypes() const {
122 return any_of(TypeVec, isScalar);
125 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
127 bool EEVT::TypeSet::hasVectorTypes() const {
128 return any_of(TypeVec, isVector);
132 std::string EEVT::TypeSet::getName() const {
133 if (TypeVec.empty()) return "<empty>";
137 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
138 std::string VTName = llvm::getEnumName(TypeVec[i]);
139 // Strip off MVT:: prefix if present.
140 if (VTName.substr(0,5) == "MVT::")
141 VTName = VTName.substr(5);
142 if (i) Result += ':';
146 if (TypeVec.size() == 1)
148 return "{" + Result + "}";
151 /// MergeInTypeInfo - This merges in type information from the specified
152 /// argument. If 'this' changes, it returns true. If the two types are
153 /// contradictory (e.g. merge f32 into i32) then this flags an error.
154 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
155 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
158 if (isCompletelyUnknown()) {
163 assert(!TypeVec.empty() && !InVT.TypeVec.empty() && "No unknowns");
165 // Handle the abstract cases, seeing if we can resolve them better.
166 switch (TypeVec[0]) {
170 if (InVT.hasIntegerTypes()) {
171 EEVT::TypeSet InCopy(InVT);
172 InCopy.EnforceInteger(TP);
173 InCopy.EnforceScalar(TP);
175 if (InCopy.isConcrete()) {
176 // If the RHS has one integer type, upgrade iPTR to i32.
177 TypeVec[0] = InVT.TypeVec[0];
181 // If the input has multiple scalar integers, this doesn't add any info.
182 if (!InCopy.isCompletelyUnknown())
188 // If the input constraint is iAny/iPTR and this is an integer type list,
189 // remove non-integer types from the list.
190 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
192 bool MadeChange = EnforceInteger(TP);
194 // If we're merging in iPTR/iPTRAny and the node currently has a list of
195 // multiple different integer types, replace them with a single iPTR.
196 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
197 TypeVec.size() != 1) {
198 TypeVec.assign(1, 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 TypeSet InputSet(*this);
210 std::set_intersection(InputSet.TypeVec.begin(), InputSet.TypeVec.end(),
211 InVT.TypeVec.begin(), InVT.TypeVec.end(),
212 std::back_inserter(TypeVec));
214 // If the intersection is the same size as the original set then we're done.
215 if (TypeVec.size() == InputSet.TypeVec.size())
218 // If we removed all of our types, we have a type contradiction.
219 if (!TypeVec.empty())
222 // FIXME: Really want an SMLoc here!
223 TP.error("Type inference contradiction found, merging '" +
224 InVT.getName() + "' into '" + InputSet.getName() + "'");
228 /// EnforceInteger - Remove all non-integer types from this set.
229 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
232 // If we know nothing, then get the full set.
234 return FillWithPossibleTypes(TP, isInteger, "integer");
236 if (!hasFloatingPointTypes())
239 TypeSet InputSet(*this);
241 // Filter out all the fp types.
242 TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isInteger))),
245 if (TypeVec.empty()) {
246 TP.error("Type inference contradiction found, '" +
247 InputSet.getName() + "' needs to be integer");
253 /// EnforceFloatingPoint - Remove all integer types from this set.
254 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
257 // If we know nothing, then get the full set.
259 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
261 if (!hasIntegerTypes())
264 TypeSet InputSet(*this);
266 // Filter out all the integer types.
267 TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isFloatingPoint))),
270 if (TypeVec.empty()) {
271 TP.error("Type inference contradiction found, '" +
272 InputSet.getName() + "' needs to be floating point");
278 /// EnforceScalar - Remove all vector types from this.
279 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
283 // If we know nothing, then get the full set.
285 return FillWithPossibleTypes(TP, isScalar, "scalar");
287 if (!hasVectorTypes())
290 TypeSet InputSet(*this);
292 // Filter out all the vector types.
293 TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isScalar))),
296 if (TypeVec.empty()) {
297 TP.error("Type inference contradiction found, '" +
298 InputSet.getName() + "' needs to be scalar");
304 /// EnforceVector - Remove all vector types from this.
305 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
309 // If we know nothing, then get the full set.
311 return FillWithPossibleTypes(TP, isVector, "vector");
313 TypeSet InputSet(*this);
314 bool MadeChange = false;
316 // Filter out all the scalar types.
317 TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isVector))),
320 if (TypeVec.empty()) {
321 TP.error("Type inference contradiction found, '" +
322 InputSet.getName() + "' needs to be a vector");
330 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
331 /// this should be based on the element type. Update this and other based on
332 /// this information.
333 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
337 // Both operands must be integer or FP, but we don't care which.
338 bool MadeChange = false;
340 if (isCompletelyUnknown())
341 MadeChange = FillWithPossibleTypes(TP);
343 if (Other.isCompletelyUnknown())
344 MadeChange = Other.FillWithPossibleTypes(TP);
346 // If one side is known to be integer or known to be FP but the other side has
347 // no information, get at least the type integrality info in there.
348 if (!hasFloatingPointTypes())
349 MadeChange |= Other.EnforceInteger(TP);
350 else if (!hasIntegerTypes())
351 MadeChange |= Other.EnforceFloatingPoint(TP);
352 if (!Other.hasFloatingPointTypes())
353 MadeChange |= EnforceInteger(TP);
354 else if (!Other.hasIntegerTypes())
355 MadeChange |= EnforceFloatingPoint(TP);
357 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
358 "Should have a type list now");
360 // If one contains vectors but the other doesn't pull vectors out.
361 if (!hasVectorTypes())
362 MadeChange |= Other.EnforceScalar(TP);
363 else if (!hasScalarTypes())
364 MadeChange |= Other.EnforceVector(TP);
365 if (!Other.hasVectorTypes())
366 MadeChange |= EnforceScalar(TP);
367 else if (!Other.hasScalarTypes())
368 MadeChange |= EnforceVector(TP);
370 // This code does not currently handle nodes which have multiple types,
371 // where some types are integer, and some are fp. Assert that this is not
373 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
374 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
375 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
380 // Okay, find the smallest type from current set and remove anything the
381 // same or smaller from the other set. We need to ensure that the scalar
382 // type size is smaller than the scalar size of the smallest type. For
383 // vectors, we also need to make sure that the total size is no larger than
384 // the size of the smallest type.
386 TypeSet InputSet(Other);
387 MVT Smallest = *std::min_element(TypeVec.begin(), TypeVec.end(),
389 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
390 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
391 A.getSizeInBits() < B.getSizeInBits());
394 auto I = remove_if(Other.TypeVec, [Smallest](MVT OtherVT) {
395 // Don't compare vector and non-vector types.
396 if (OtherVT.isVector() != Smallest.isVector())
398 // The getSizeInBits() check here is only needed for vectors, but is
399 // a subset of the scalar check for scalars so no need to qualify.
400 return OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
401 OtherVT.getSizeInBits() < Smallest.getSizeInBits();
403 MadeChange |= I != Other.TypeVec.end(); // If we're about to remove types.
404 Other.TypeVec.erase(I, Other.TypeVec.end());
406 if (Other.TypeVec.empty()) {
407 TP.error("Type inference contradiction found, '" + InputSet.getName() +
408 "' has nothing larger than '" + getName() +"'!");
413 // Okay, find the largest type from the other set and remove anything the
414 // same or smaller from the current set. We need to ensure that the scalar
415 // type size is larger than the scalar size of the largest type. For
416 // vectors, we also need to make sure that the total size is no smaller than
417 // the size of the largest type.
419 TypeSet InputSet(*this);
420 MVT Largest = *std::max_element(Other.TypeVec.begin(), Other.TypeVec.end(),
422 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
423 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
424 A.getSizeInBits() < B.getSizeInBits());
426 auto I = remove_if(TypeVec, [Largest](MVT OtherVT) {
427 // Don't compare vector and non-vector types.
428 if (OtherVT.isVector() != Largest.isVector())
430 return OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
431 OtherVT.getSizeInBits() > Largest.getSizeInBits();
433 MadeChange |= I != TypeVec.end(); // If we're about to remove types.
434 TypeVec.erase(I, TypeVec.end());
436 if (TypeVec.empty()) {
437 TP.error("Type inference contradiction found, '" + InputSet.getName() +
438 "' has nothing smaller than '" + Other.getName() +"'!");
446 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
447 /// whose element is specified by VTOperand.
448 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
450 bool MadeChange = false;
452 MadeChange |= EnforceVector(TP);
454 TypeSet InputSet(*this);
456 // Filter out all the types which don't have the right element type.
457 auto I = remove_if(TypeVec, [VT](MVT VVT) {
458 return VVT.getVectorElementType().SimpleTy != VT;
460 MadeChange |= I != TypeVec.end();
461 TypeVec.erase(I, TypeVec.end());
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 of type " +
473 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
474 /// whose element is specified by VTOperand.
475 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
480 // "This" must be a vector and "VTOperand" must be a scalar.
481 bool MadeChange = false;
482 MadeChange |= EnforceVector(TP);
483 MadeChange |= VTOperand.EnforceScalar(TP);
485 // If we know the vector type, it forces the scalar to agree.
487 MVT IVT = getConcrete();
488 IVT = IVT.getVectorElementType();
489 return MadeChange || 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 MadeChange |= EnforceVectorEltTypeIs(VT, TP);
504 /// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
505 /// vector type specified by VTOperand.
506 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
511 // "This" must be a vector and "VTOperand" must be a vector.
512 bool MadeChange = false;
513 MadeChange |= EnforceVector(TP);
514 MadeChange |= VTOperand.EnforceVector(TP);
516 // If one side is known to be integer or known to be FP but the other side has
517 // no information, get at least the type integrality info in there.
518 if (!hasFloatingPointTypes())
519 MadeChange |= VTOperand.EnforceInteger(TP);
520 else if (!hasIntegerTypes())
521 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
522 if (!VTOperand.hasFloatingPointTypes())
523 MadeChange |= EnforceInteger(TP);
524 else if (!VTOperand.hasIntegerTypes())
525 MadeChange |= EnforceFloatingPoint(TP);
527 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
528 "Should have a type list now");
530 // If we know the vector type, it forces the scalar types to agree.
531 // Also force one vector to have more elements than the other.
533 MVT IVT = getConcrete();
534 unsigned NumElems = IVT.getVectorNumElements();
535 IVT = IVT.getVectorElementType();
537 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
538 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
540 // Only keep types that have less elements than VTOperand.
541 TypeSet InputSet(VTOperand);
543 auto I = remove_if(VTOperand.TypeVec, [NumElems](MVT VVT) {
544 return VVT.getVectorNumElements() >= NumElems;
546 MadeChange |= I != VTOperand.TypeVec.end();
547 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
549 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
550 TP.error("Type inference contradiction found, forcing '" +
551 InputSet.getName() + "' to have less vector elements than '" +
555 } else if (VTOperand.isConcrete()) {
556 MVT IVT = VTOperand.getConcrete();
557 unsigned NumElems = IVT.getVectorNumElements();
558 IVT = IVT.getVectorElementType();
560 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
561 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
563 // Only keep types that have more elements than 'this'.
564 TypeSet InputSet(*this);
566 auto I = remove_if(TypeVec, [NumElems](MVT VVT) {
567 return VVT.getVectorNumElements() <= NumElems;
569 MadeChange |= I != TypeVec.end();
570 TypeVec.erase(I, TypeVec.end());
572 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
573 TP.error("Type inference contradiction found, forcing '" +
574 InputSet.getName() + "' to have more vector elements than '" +
575 VTOperand.getName() + "'");
583 /// EnforceVectorSameNumElts - 'this' is now constrained to
584 /// be a vector with same num elements as VTOperand.
585 bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
590 // "This" must be a vector and "VTOperand" must be a vector.
591 bool MadeChange = false;
592 MadeChange |= EnforceVector(TP);
593 MadeChange |= VTOperand.EnforceVector(TP);
595 // If we know one of the vector types, it forces the other type to agree.
597 MVT IVT = getConcrete();
598 unsigned NumElems = IVT.getVectorNumElements();
600 // Only keep types that have same elements as 'this'.
601 TypeSet InputSet(VTOperand);
603 auto I = remove_if(VTOperand.TypeVec, [NumElems](MVT VVT) {
604 return VVT.getVectorNumElements() != NumElems;
606 MadeChange |= I != VTOperand.TypeVec.end();
607 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
609 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
610 TP.error("Type inference contradiction found, forcing '" +
611 InputSet.getName() + "' to have same number elements as '" +
615 } else if (VTOperand.isConcrete()) {
616 MVT IVT = VTOperand.getConcrete();
617 unsigned NumElems = IVT.getVectorNumElements();
619 // Only keep types that have same elements as VTOperand.
620 TypeSet InputSet(*this);
622 auto I = remove_if(TypeVec, [NumElems](MVT VVT) {
623 return VVT.getVectorNumElements() != NumElems;
625 MadeChange |= I != TypeVec.end();
626 TypeVec.erase(I, TypeVec.end());
628 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
629 TP.error("Type inference contradiction found, forcing '" +
630 InputSet.getName() + "' to have same number elements than '" +
631 VTOperand.getName() + "'");
639 /// EnforceSameSize - 'this' is now constrained to be same size as VTOperand.
640 bool EEVT::TypeSet::EnforceSameSize(EEVT::TypeSet &VTOperand,
645 bool MadeChange = false;
647 // If we know one of the types, it forces the other type agree.
649 MVT IVT = getConcrete();
650 unsigned Size = IVT.getSizeInBits();
652 // Only keep types that have the same size as 'this'.
653 TypeSet InputSet(VTOperand);
655 auto I = remove_if(VTOperand.TypeVec,
656 [&](MVT VT) { return VT.getSizeInBits() != Size; });
657 MadeChange |= I != VTOperand.TypeVec.end();
658 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
660 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
661 TP.error("Type inference contradiction found, forcing '" +
662 InputSet.getName() + "' to have same size as '" +
666 } else if (VTOperand.isConcrete()) {
667 MVT IVT = VTOperand.getConcrete();
668 unsigned Size = IVT.getSizeInBits();
670 // Only keep types that have the same size as VTOperand.
671 TypeSet InputSet(*this);
674 remove_if(TypeVec, [&](MVT VT) { return VT.getSizeInBits() != Size; });
675 MadeChange |= I != TypeVec.end();
676 TypeVec.erase(I, TypeVec.end());
678 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
679 TP.error("Type inference contradiction found, forcing '" +
680 InputSet.getName() + "' to have same size as '" +
681 VTOperand.getName() + "'");
689 //===----------------------------------------------------------------------===//
690 // Helpers for working with extended types.
692 /// Dependent variable map for CodeGenDAGPattern variant generation
693 typedef std::map<std::string, int> DepVarMap;
695 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
697 if (isa<DefInit>(N->getLeafValue()))
698 DepMap[N->getName()]++;
700 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
701 FindDepVarsOf(N->getChild(i), DepMap);
705 /// Find dependent variables within child patterns
706 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
708 FindDepVarsOf(N, depcounts);
709 for (const std::pair<std::string, int> &Pair : depcounts) {
711 DepVars.insert(Pair.first);
716 /// Dump the dependent variable set:
717 static void DumpDepVars(MultipleUseVarSet &DepVars) {
718 if (DepVars.empty()) {
719 DEBUG(errs() << "<empty set>");
721 DEBUG(errs() << "[ ");
722 for (const std::string &DepVar : DepVars) {
723 DEBUG(errs() << DepVar << " ");
725 DEBUG(errs() << "]");
731 //===----------------------------------------------------------------------===//
732 // TreePredicateFn Implementation
733 //===----------------------------------------------------------------------===//
735 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
736 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
737 assert((getPredCode().empty() || getImmCode().empty()) &&
738 ".td file corrupt: can't have a node predicate *and* an imm predicate");
741 std::string TreePredicateFn::getPredCode() const {
742 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
745 std::string TreePredicateFn::getImmCode() const {
746 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
750 /// isAlwaysTrue - Return true if this is a noop predicate.
751 bool TreePredicateFn::isAlwaysTrue() const {
752 return getPredCode().empty() && getImmCode().empty();
755 /// Return the name to use in the generated code to reference this, this is
756 /// "Predicate_foo" if from a pattern fragment "foo".
757 std::string TreePredicateFn::getFnName() const {
758 return "Predicate_" + PatFragRec->getRecord()->getName().str();
761 /// getCodeToRunOnSDNode - Return the code for the function body that
762 /// evaluates this predicate. The argument is expected to be in "Node",
763 /// not N. This handles casting and conversion to a concrete node type as
765 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
766 // Handle immediate predicates first.
767 std::string ImmCode = getImmCode();
768 if (!ImmCode.empty()) {
770 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
771 return Result + ImmCode;
774 // Handle arbitrary node predicates.
775 assert(!getPredCode().empty() && "Don't have any predicate code!");
776 std::string ClassName;
777 if (PatFragRec->getOnlyTree()->isLeaf())
778 ClassName = "SDNode";
780 Record *Op = PatFragRec->getOnlyTree()->getOperator();
781 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
784 if (ClassName == "SDNode")
785 Result = " SDNode *N = Node;\n";
787 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
789 return Result + getPredCode();
792 //===----------------------------------------------------------------------===//
793 // PatternToMatch implementation
797 /// getPatternSize - Return the 'size' of this pattern. We want to match large
798 /// patterns before small ones. This is used to determine the size of a
800 static unsigned getPatternSize(const TreePatternNode *P,
801 const CodeGenDAGPatterns &CGP) {
802 unsigned Size = 3; // The node itself.
803 // If the root node is a ConstantSDNode, increases its size.
804 // e.g. (set R32:$dst, 0).
805 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
808 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
810 Size += AM->getComplexity();
812 // We don't want to count any children twice, so return early.
816 // If this node has some predicate function that must match, it adds to the
817 // complexity of this node.
818 if (!P->getPredicateFns().empty())
821 // Count children in the count if they are also nodes.
822 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
823 TreePatternNode *Child = P->getChild(i);
824 if (!Child->isLeaf() && Child->getNumTypes() &&
825 Child->getType(0) != MVT::Other)
826 Size += getPatternSize(Child, CGP);
827 else if (Child->isLeaf()) {
828 if (isa<IntInit>(Child->getLeafValue()))
829 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
830 else if (Child->getComplexPatternInfo(CGP))
831 Size += getPatternSize(Child, CGP);
832 else if (!Child->getPredicateFns().empty())
840 /// Compute the complexity metric for the input pattern. This roughly
841 /// corresponds to the number of nodes that are covered.
843 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
844 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
848 /// getPredicateCheck - Return a single string containing all of this
849 /// pattern's predicates concatenated with "&&" operators.
851 std::string PatternToMatch::getPredicateCheck() const {
852 SmallVector<Record *, 4> PredicateRecs;
853 for (Init *I : Predicates->getValues()) {
854 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
855 Record *Def = Pred->getDef();
856 if (!Def->isSubClassOf("Predicate")) {
860 llvm_unreachable("Unknown predicate type!");
862 PredicateRecs.push_back(Def);
865 // Sort so that different orders get canonicalized to the same string.
866 std::sort(PredicateRecs.begin(), PredicateRecs.end(), LessRecord());
868 SmallString<128> PredicateCheck;
869 for (Record *Pred : PredicateRecs) {
870 if (!PredicateCheck.empty())
871 PredicateCheck += " && ";
872 PredicateCheck += "(" + Pred->getValueAsString("CondString") + ")";
875 return PredicateCheck.str();
878 //===----------------------------------------------------------------------===//
879 // SDTypeConstraint implementation
882 SDTypeConstraint::SDTypeConstraint(Record *R) {
883 OperandNo = R->getValueAsInt("OperandNum");
885 if (R->isSubClassOf("SDTCisVT")) {
886 ConstraintType = SDTCisVT;
887 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
888 if (x.SDTCisVT_Info.VT == MVT::isVoid)
889 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
891 } else if (R->isSubClassOf("SDTCisPtrTy")) {
892 ConstraintType = SDTCisPtrTy;
893 } else if (R->isSubClassOf("SDTCisInt")) {
894 ConstraintType = SDTCisInt;
895 } else if (R->isSubClassOf("SDTCisFP")) {
896 ConstraintType = SDTCisFP;
897 } else if (R->isSubClassOf("SDTCisVec")) {
898 ConstraintType = SDTCisVec;
899 } else if (R->isSubClassOf("SDTCisSameAs")) {
900 ConstraintType = SDTCisSameAs;
901 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
902 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
903 ConstraintType = SDTCisVTSmallerThanOp;
904 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
905 R->getValueAsInt("OtherOperandNum");
906 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
907 ConstraintType = SDTCisOpSmallerThanOp;
908 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
909 R->getValueAsInt("BigOperandNum");
910 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
911 ConstraintType = SDTCisEltOfVec;
912 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
913 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
914 ConstraintType = SDTCisSubVecOfVec;
915 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
916 R->getValueAsInt("OtherOpNum");
917 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
918 ConstraintType = SDTCVecEltisVT;
919 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
920 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
921 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
922 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
923 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
924 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
925 "as SDTCVecEltisVT");
926 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
927 ConstraintType = SDTCisSameNumEltsAs;
928 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
929 R->getValueAsInt("OtherOperandNum");
930 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
931 ConstraintType = SDTCisSameSizeAs;
932 x.SDTCisSameSizeAs_Info.OtherOperandNum =
933 R->getValueAsInt("OtherOperandNum");
935 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
939 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
940 /// N, and the result number in ResNo.
941 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
942 const SDNodeInfo &NodeInfo,
944 unsigned NumResults = NodeInfo.getNumResults();
945 if (OpNo < NumResults) {
952 if (OpNo >= N->getNumChildren()) {
954 raw_string_ostream OS(S);
955 OS << "Invalid operand number in type constraint "
956 << (OpNo+NumResults) << " ";
958 PrintFatalError(OS.str());
961 return N->getChild(OpNo);
964 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
965 /// constraint to the nodes operands. This returns true if it makes a
966 /// change, false otherwise. If a type contradiction is found, flag an error.
967 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
968 const SDNodeInfo &NodeInfo,
969 TreePattern &TP) const {
973 unsigned ResNo = 0; // The result number being referenced.
974 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
976 switch (ConstraintType) {
978 // Operand must be a particular type.
979 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
981 // Operand must be same as target pointer type.
982 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
984 // Require it to be one of the legal integer VTs.
985 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
987 // Require it to be one of the legal fp VTs.
988 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
990 // Require it to be one of the legal vector VTs.
991 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
994 TreePatternNode *OtherNode =
995 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
996 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
997 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
999 case SDTCisVTSmallerThanOp: {
1000 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1001 // have an integer type that is smaller than the VT.
1002 if (!NodeToApply->isLeaf() ||
1003 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1004 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
1005 ->isSubClassOf("ValueType")) {
1006 TP.error(N->getOperator()->getName() + " expects a VT operand!");
1009 MVT::SimpleValueType VT =
1010 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
1012 EEVT::TypeSet TypeListTmp(VT, TP);
1014 unsigned OResNo = 0;
1015 TreePatternNode *OtherNode =
1016 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1019 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
1021 case SDTCisOpSmallerThanOp: {
1022 unsigned BResNo = 0;
1023 TreePatternNode *BigOperand =
1024 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1026 return NodeToApply->getExtType(ResNo).
1027 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
1029 case SDTCisEltOfVec: {
1030 unsigned VResNo = 0;
1031 TreePatternNode *VecOperand =
1032 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1035 // Filter vector types out of VecOperand that don't have the right element
1037 return VecOperand->getExtType(VResNo).
1038 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
1040 case SDTCisSubVecOfVec: {
1041 unsigned VResNo = 0;
1042 TreePatternNode *BigVecOperand =
1043 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1046 // Filter vector types out of BigVecOperand that don't have the
1047 // right subvector type.
1048 return BigVecOperand->getExtType(VResNo).
1049 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1051 case SDTCVecEltisVT: {
1052 return NodeToApply->getExtType(ResNo).
1053 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1055 case SDTCisSameNumEltsAs: {
1056 unsigned OResNo = 0;
1057 TreePatternNode *OtherNode =
1058 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1059 N, NodeInfo, OResNo);
1060 return OtherNode->getExtType(OResNo).
1061 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1063 case SDTCisSameSizeAs: {
1064 unsigned OResNo = 0;
1065 TreePatternNode *OtherNode =
1066 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1067 N, NodeInfo, OResNo);
1068 return OtherNode->getExtType(OResNo).
1069 EnforceSameSize(NodeToApply->getExtType(ResNo), TP);
1072 llvm_unreachable("Invalid ConstraintType!");
1075 // Update the node type to match an instruction operand or result as specified
1076 // in the ins or outs lists on the instruction definition. Return true if the
1077 // type was actually changed.
1078 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1081 // The 'unknown' operand indicates that types should be inferred from the
1083 if (Operand->isSubClassOf("unknown_class"))
1086 // The Operand class specifies a type directly.
1087 if (Operand->isSubClassOf("Operand"))
1088 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1091 // PointerLikeRegClass has a type that is determined at runtime.
1092 if (Operand->isSubClassOf("PointerLikeRegClass"))
1093 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1095 // Both RegisterClass and RegisterOperand operands derive their types from a
1096 // register class def.
1097 Record *RC = nullptr;
1098 if (Operand->isSubClassOf("RegisterClass"))
1100 else if (Operand->isSubClassOf("RegisterOperand"))
1101 RC = Operand->getValueAsDef("RegClass");
1103 assert(RC && "Unknown operand type");
1104 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1105 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1109 //===----------------------------------------------------------------------===//
1110 // SDNodeInfo implementation
1112 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1113 EnumName = R->getValueAsString("Opcode");
1114 SDClassName = R->getValueAsString("SDClass");
1115 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1116 NumResults = TypeProfile->getValueAsInt("NumResults");
1117 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1119 // Parse the properties.
1121 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1122 if (Property->getName() == "SDNPCommutative") {
1123 Properties |= 1 << SDNPCommutative;
1124 } else if (Property->getName() == "SDNPAssociative") {
1125 Properties |= 1 << SDNPAssociative;
1126 } else if (Property->getName() == "SDNPHasChain") {
1127 Properties |= 1 << SDNPHasChain;
1128 } else if (Property->getName() == "SDNPOutGlue") {
1129 Properties |= 1 << SDNPOutGlue;
1130 } else if (Property->getName() == "SDNPInGlue") {
1131 Properties |= 1 << SDNPInGlue;
1132 } else if (Property->getName() == "SDNPOptInGlue") {
1133 Properties |= 1 << SDNPOptInGlue;
1134 } else if (Property->getName() == "SDNPMayStore") {
1135 Properties |= 1 << SDNPMayStore;
1136 } else if (Property->getName() == "SDNPMayLoad") {
1137 Properties |= 1 << SDNPMayLoad;
1138 } else if (Property->getName() == "SDNPSideEffect") {
1139 Properties |= 1 << SDNPSideEffect;
1140 } else if (Property->getName() == "SDNPMemOperand") {
1141 Properties |= 1 << SDNPMemOperand;
1142 } else if (Property->getName() == "SDNPVariadic") {
1143 Properties |= 1 << SDNPVariadic;
1145 PrintFatalError("Unknown SD Node property '" +
1146 Property->getName() + "' on node '" +
1147 R->getName() + "'!");
1152 // Parse the type constraints.
1153 std::vector<Record*> ConstraintList =
1154 TypeProfile->getValueAsListOfDefs("Constraints");
1155 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1158 /// getKnownType - If the type constraints on this node imply a fixed type
1159 /// (e.g. all stores return void, etc), then return it as an
1160 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1161 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1162 unsigned NumResults = getNumResults();
1163 assert(NumResults <= 1 &&
1164 "We only work with nodes with zero or one result so far!");
1165 assert(ResNo == 0 && "Only handles single result nodes so far");
1167 for (const SDTypeConstraint &Constraint : TypeConstraints) {
1168 // Make sure that this applies to the correct node result.
1169 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1172 switch (Constraint.ConstraintType) {
1174 case SDTypeConstraint::SDTCisVT:
1175 return Constraint.x.SDTCisVT_Info.VT;
1176 case SDTypeConstraint::SDTCisPtrTy:
1183 //===----------------------------------------------------------------------===//
1184 // TreePatternNode implementation
1187 TreePatternNode::~TreePatternNode() {
1188 #if 0 // FIXME: implement refcounted tree nodes!
1189 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1194 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1195 if (Operator->getName() == "set" ||
1196 Operator->getName() == "implicit")
1197 return 0; // All return nothing.
1199 if (Operator->isSubClassOf("Intrinsic"))
1200 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1202 if (Operator->isSubClassOf("SDNode"))
1203 return CDP.getSDNodeInfo(Operator).getNumResults();
1205 if (Operator->isSubClassOf("PatFrag")) {
1206 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1207 // the forward reference case where one pattern fragment references another
1208 // before it is processed.
1209 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1210 return PFRec->getOnlyTree()->getNumTypes();
1212 // Get the result tree.
1213 DagInit *Tree = Operator->getValueAsDag("Fragment");
1214 Record *Op = nullptr;
1216 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1218 assert(Op && "Invalid Fragment");
1219 return GetNumNodeResults(Op, CDP);
1222 if (Operator->isSubClassOf("Instruction")) {
1223 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1225 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1227 // Subtract any defaulted outputs.
1228 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1229 Record *OperandNode = InstInfo.Operands[i].Rec;
1231 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1232 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1236 // Add on one implicit def if it has a resolvable type.
1237 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1239 return NumDefsToAdd;
1242 if (Operator->isSubClassOf("SDNodeXForm"))
1243 return 1; // FIXME: Generalize SDNodeXForm
1245 if (Operator->isSubClassOf("ValueType"))
1246 return 1; // A type-cast of one result.
1248 if (Operator->isSubClassOf("ComplexPattern"))
1252 PrintFatalError("Unhandled node in GetNumNodeResults");
1255 void TreePatternNode::print(raw_ostream &OS) const {
1257 OS << *getLeafValue();
1259 OS << '(' << getOperator()->getName();
1261 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1262 OS << ':' << getExtType(i).getName();
1265 if (getNumChildren() != 0) {
1267 getChild(0)->print(OS);
1268 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1270 getChild(i)->print(OS);
1276 for (const TreePredicateFn &Pred : PredicateFns)
1277 OS << "<<P:" << Pred.getFnName() << ">>";
1279 OS << "<<X:" << TransformFn->getName() << ">>";
1280 if (!getName().empty())
1281 OS << ":$" << getName();
1284 void TreePatternNode::dump() const {
1288 /// isIsomorphicTo - Return true if this node is recursively
1289 /// isomorphic to the specified node. For this comparison, the node's
1290 /// entire state is considered. The assigned name is ignored, since
1291 /// nodes with differing names are considered isomorphic. However, if
1292 /// the assigned name is present in the dependent variable set, then
1293 /// the assigned name is considered significant and the node is
1294 /// isomorphic if the names match.
1295 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1296 const MultipleUseVarSet &DepVars) const {
1297 if (N == this) return true;
1298 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1299 getPredicateFns() != N->getPredicateFns() ||
1300 getTransformFn() != N->getTransformFn())
1304 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1305 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1306 return ((DI->getDef() == NDI->getDef())
1307 && (DepVars.find(getName()) == DepVars.end()
1308 || getName() == N->getName()));
1311 return getLeafValue() == N->getLeafValue();
1314 if (N->getOperator() != getOperator() ||
1315 N->getNumChildren() != getNumChildren()) return false;
1316 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1317 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1322 /// clone - Make a copy of this tree and all of its children.
1324 TreePatternNode *TreePatternNode::clone() const {
1325 TreePatternNode *New;
1327 New = new TreePatternNode(getLeafValue(), getNumTypes());
1329 std::vector<TreePatternNode*> CChildren;
1330 CChildren.reserve(Children.size());
1331 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1332 CChildren.push_back(getChild(i)->clone());
1333 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1335 New->setName(getName());
1337 New->setPredicateFns(getPredicateFns());
1338 New->setTransformFn(getTransformFn());
1342 /// RemoveAllTypes - Recursively strip all the types of this tree.
1343 void TreePatternNode::RemoveAllTypes() {
1344 // Reset to unknown type.
1345 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
1346 if (isLeaf()) return;
1347 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1348 getChild(i)->RemoveAllTypes();
1352 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1353 /// with actual values specified by ArgMap.
1354 void TreePatternNode::
1355 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1356 if (isLeaf()) return;
1358 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1359 TreePatternNode *Child = getChild(i);
1360 if (Child->isLeaf()) {
1361 Init *Val = Child->getLeafValue();
1362 // Note that, when substituting into an output pattern, Val might be an
1364 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1365 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1366 // We found a use of a formal argument, replace it with its value.
1367 TreePatternNode *NewChild = ArgMap[Child->getName()];
1368 assert(NewChild && "Couldn't find formal argument!");
1369 assert((Child->getPredicateFns().empty() ||
1370 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1371 "Non-empty child predicate clobbered!");
1372 setChild(i, NewChild);
1375 getChild(i)->SubstituteFormalArguments(ArgMap);
1381 /// InlinePatternFragments - If this pattern refers to any pattern
1382 /// fragments, inline them into place, giving us a pattern without any
1383 /// PatFrag references.
1384 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1389 return this; // nothing to do.
1390 Record *Op = getOperator();
1392 if (!Op->isSubClassOf("PatFrag")) {
1393 // Just recursively inline children nodes.
1394 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1395 TreePatternNode *Child = getChild(i);
1396 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1398 assert((Child->getPredicateFns().empty() ||
1399 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1400 "Non-empty child predicate clobbered!");
1402 setChild(i, NewChild);
1407 // Otherwise, we found a reference to a fragment. First, look up its
1408 // TreePattern record.
1409 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1411 // Verify that we are passing the right number of operands.
1412 if (Frag->getNumArgs() != Children.size()) {
1413 TP.error("'" + Op->getName() + "' fragment requires " +
1414 utostr(Frag->getNumArgs()) + " operands!");
1418 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1420 TreePredicateFn PredFn(Frag);
1421 if (!PredFn.isAlwaysTrue())
1422 FragTree->addPredicateFn(PredFn);
1424 // Resolve formal arguments to their actual value.
1425 if (Frag->getNumArgs()) {
1426 // Compute the map of formal to actual arguments.
1427 std::map<std::string, TreePatternNode*> ArgMap;
1428 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1429 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1431 FragTree->SubstituteFormalArguments(ArgMap);
1434 FragTree->setName(getName());
1435 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1436 FragTree->UpdateNodeType(i, getExtType(i), TP);
1438 // Transfer in the old predicates.
1439 for (const TreePredicateFn &Pred : getPredicateFns())
1440 FragTree->addPredicateFn(Pred);
1442 // Get a new copy of this fragment to stitch into here.
1443 //delete this; // FIXME: implement refcounting!
1445 // The fragment we inlined could have recursive inlining that is needed. See
1446 // if there are any pattern fragments in it and inline them as needed.
1447 return FragTree->InlinePatternFragments(TP);
1450 /// getImplicitType - Check to see if the specified record has an implicit
1451 /// type which should be applied to it. This will infer the type of register
1452 /// references from the register file information, for example.
1454 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1455 /// the F8RC register class argument in:
1457 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
1459 /// When Unnamed is false, return the type of a named DAG operand such as the
1460 /// GPR:$src operand above.
1462 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1466 // Check to see if this is a register operand.
1467 if (R->isSubClassOf("RegisterOperand")) {
1468 assert(ResNo == 0 && "Regoperand ref only has one result!");
1470 return EEVT::TypeSet(); // Unknown.
1471 Record *RegClass = R->getValueAsDef("RegClass");
1472 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1473 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1476 // Check to see if this is a register or a register class.
1477 if (R->isSubClassOf("RegisterClass")) {
1478 assert(ResNo == 0 && "Regclass ref only has one result!");
1479 // An unnamed register class represents itself as an i32 immediate, for
1480 // example on a COPY_TO_REGCLASS instruction.
1482 return EEVT::TypeSet(MVT::i32, TP);
1484 // In a named operand, the register class provides the possible set of
1487 return EEVT::TypeSet(); // Unknown.
1488 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1489 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1492 if (R->isSubClassOf("PatFrag")) {
1493 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1494 // Pattern fragment types will be resolved when they are inlined.
1495 return EEVT::TypeSet(); // Unknown.
1498 if (R->isSubClassOf("Register")) {
1499 assert(ResNo == 0 && "Registers only produce one result!");
1501 return EEVT::TypeSet(); // Unknown.
1502 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1503 return EEVT::TypeSet(T.getRegisterVTs(R));
1506 if (R->isSubClassOf("SubRegIndex")) {
1507 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1508 return EEVT::TypeSet(MVT::i32, TP);
1511 if (R->isSubClassOf("ValueType")) {
1512 assert(ResNo == 0 && "This node only has one result!");
1513 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1515 // (sext_inreg GPR:$src, i16)
1518 return EEVT::TypeSet(MVT::Other, TP);
1519 // With a name, the ValueType simply provides the type of the named
1522 // (sext_inreg i32:$src, i16)
1525 return EEVT::TypeSet(); // Unknown.
1526 return EEVT::TypeSet(getValueType(R), TP);
1529 if (R->isSubClassOf("CondCode")) {
1530 assert(ResNo == 0 && "This node only has one result!");
1531 // Using a CondCodeSDNode.
1532 return EEVT::TypeSet(MVT::Other, TP);
1535 if (R->isSubClassOf("ComplexPattern")) {
1536 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1538 return EEVT::TypeSet(); // Unknown.
1539 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1542 if (R->isSubClassOf("PointerLikeRegClass")) {
1543 assert(ResNo == 0 && "Regclass can only have one result!");
1544 return EEVT::TypeSet(MVT::iPTR, TP);
1547 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1548 R->getName() == "zero_reg") {
1550 return EEVT::TypeSet(); // Unknown.
1553 if (R->isSubClassOf("Operand"))
1554 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1556 TP.error("Unknown node flavor used in pattern: " + R->getName());
1557 return EEVT::TypeSet(MVT::Other, TP);
1561 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1562 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1563 const CodeGenIntrinsic *TreePatternNode::
1564 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1565 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1566 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1567 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1570 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
1571 return &CDP.getIntrinsicInfo(IID);
1574 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1575 /// return the ComplexPattern information, otherwise return null.
1576 const ComplexPattern *
1577 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1580 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1585 Rec = getOperator();
1587 if (!Rec->isSubClassOf("ComplexPattern"))
1589 return &CGP.getComplexPattern(Rec);
1592 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1593 // A ComplexPattern specifically declares how many results it fills in.
1594 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1595 return CP->getNumOperands();
1597 // If MIOperandInfo is specified, that gives the count.
1599 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1600 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1601 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1602 if (MIOps->getNumArgs())
1603 return MIOps->getNumArgs();
1607 // Otherwise there is just one result.
1611 /// NodeHasProperty - Return true if this node has the specified property.
1612 bool TreePatternNode::NodeHasProperty(SDNP Property,
1613 const CodeGenDAGPatterns &CGP) const {
1615 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1616 return CP->hasProperty(Property);
1620 Record *Operator = getOperator();
1621 if (!Operator->isSubClassOf("SDNode")) return false;
1623 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1629 /// TreeHasProperty - Return true if any node in this tree has the specified
1631 bool TreePatternNode::TreeHasProperty(SDNP Property,
1632 const CodeGenDAGPatterns &CGP) const {
1633 if (NodeHasProperty(Property, CGP))
1635 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1636 if (getChild(i)->TreeHasProperty(Property, CGP))
1641 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1642 /// commutative intrinsic.
1644 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1645 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1646 return Int->isCommutative;
1650 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1652 return N->getOperator()->isSubClassOf(Class);
1654 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1655 if (DI && DI->getDef()->isSubClassOf(Class))
1661 static void emitTooManyOperandsError(TreePattern &TP,
1665 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1666 " operands but expected only " + Twine(Expected) + "!");
1669 static void emitTooFewOperandsError(TreePattern &TP,
1672 TP.error("Instruction '" + InstName +
1673 "' expects more than the provided " + Twine(Actual) + " operands!");
1676 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1677 /// this node and its children in the tree. This returns true if it makes a
1678 /// change, false otherwise. If a type contradiction is found, flag an error.
1679 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1683 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1685 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1686 // If it's a regclass or something else known, include the type.
1687 bool MadeChange = false;
1688 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1689 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1691 !hasName(), TP), TP);
1695 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
1696 assert(Types.size() == 1 && "Invalid IntInit");
1698 // Int inits are always integers. :)
1699 bool MadeChange = Types[0].EnforceInteger(TP);
1701 if (!Types[0].isConcrete())
1704 MVT::SimpleValueType VT = getType(0);
1705 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1708 unsigned Size = MVT(VT).getSizeInBits();
1709 // Make sure that the value is representable for this type.
1710 if (Size >= 32) return MadeChange;
1712 // Check that the value doesn't use more bits than we have. It must either
1713 // be a sign- or zero-extended equivalent of the original.
1714 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1715 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1718 TP.error("Integer value '" + itostr(II->getValue()) +
1719 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1725 // special handling for set, which isn't really an SDNode.
1726 if (getOperator()->getName() == "set") {
1727 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1728 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1729 unsigned NC = getNumChildren();
1731 TreePatternNode *SetVal = getChild(NC-1);
1732 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1734 for (unsigned i = 0; i < NC-1; ++i) {
1735 TreePatternNode *Child = getChild(i);
1736 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1738 // Types of operands must match.
1739 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1740 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1745 if (getOperator()->getName() == "implicit") {
1746 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1748 bool MadeChange = false;
1749 for (unsigned i = 0; i < getNumChildren(); ++i)
1750 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1754 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1755 bool MadeChange = false;
1757 // Apply the result type to the node.
1758 unsigned NumRetVTs = Int->IS.RetVTs.size();
1759 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1761 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1762 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1764 if (getNumChildren() != NumParamVTs + 1) {
1765 TP.error("Intrinsic '" + Int->Name + "' expects " +
1766 utostr(NumParamVTs) + " operands, not " +
1767 utostr(getNumChildren() - 1) + " operands!");
1771 // Apply type info to the intrinsic ID.
1772 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1774 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1775 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1777 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1778 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1779 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1784 if (getOperator()->isSubClassOf("SDNode")) {
1785 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1787 // Check that the number of operands is sane. Negative operands -> varargs.
1788 if (NI.getNumOperands() >= 0 &&
1789 getNumChildren() != (unsigned)NI.getNumOperands()) {
1790 TP.error(getOperator()->getName() + " node requires exactly " +
1791 itostr(NI.getNumOperands()) + " operands!");
1795 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1796 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1797 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1801 if (getOperator()->isSubClassOf("Instruction")) {
1802 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1803 CodeGenInstruction &InstInfo =
1804 CDP.getTargetInfo().getInstruction(getOperator());
1806 bool MadeChange = false;
1808 // Apply the result types to the node, these come from the things in the
1809 // (outs) list of the instruction.
1810 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1811 Inst.getNumResults());
1812 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1813 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
1815 // If the instruction has implicit defs, we apply the first one as a result.
1816 // FIXME: This sucks, it should apply all implicit defs.
1817 if (!InstInfo.ImplicitDefs.empty()) {
1818 unsigned ResNo = NumResultsToAdd;
1820 // FIXME: Generalize to multiple possible types and multiple possible
1822 MVT::SimpleValueType VT =
1823 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1825 if (VT != MVT::Other)
1826 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1829 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1831 if (getOperator()->getName() == "INSERT_SUBREG") {
1832 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1833 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1834 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1835 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1836 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1839 unsigned NChild = getNumChildren();
1841 TP.error("REG_SEQUENCE requires at least 3 operands!");
1845 if (NChild % 2 == 0) {
1846 TP.error("REG_SEQUENCE requires an odd number of operands!");
1850 if (!isOperandClass(getChild(0), "RegisterClass")) {
1851 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1855 for (unsigned I = 1; I < NChild; I += 2) {
1856 TreePatternNode *SubIdxChild = getChild(I + 1);
1857 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1858 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1859 itostr(I + 1) + "!");
1865 unsigned ChildNo = 0;
1866 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1867 Record *OperandNode = Inst.getOperand(i);
1869 // If the instruction expects a predicate or optional def operand, we
1870 // codegen this by setting the operand to it's default value if it has a
1871 // non-empty DefaultOps field.
1872 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1873 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1876 // Verify that we didn't run out of provided operands.
1877 if (ChildNo >= getNumChildren()) {
1878 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
1882 TreePatternNode *Child = getChild(ChildNo++);
1883 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1885 // If the operand has sub-operands, they may be provided by distinct
1886 // child patterns, so attempt to match each sub-operand separately.
1887 if (OperandNode->isSubClassOf("Operand")) {
1888 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1889 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1890 // But don't do that if the whole operand is being provided by
1891 // a single ComplexPattern-related Operand.
1893 if (Child->getNumMIResults(CDP) < NumArgs) {
1894 // Match first sub-operand against the child we already have.
1895 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1897 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1899 // And the remaining sub-operands against subsequent children.
1900 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1901 if (ChildNo >= getNumChildren()) {
1902 emitTooFewOperandsError(TP, getOperator()->getName(),
1906 Child = getChild(ChildNo++);
1908 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1910 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1917 // If we didn't match by pieces above, attempt to match the whole
1919 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
1922 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
1923 emitTooManyOperandsError(TP, getOperator()->getName(),
1924 ChildNo, getNumChildren());
1928 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1929 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1933 if (getOperator()->isSubClassOf("ComplexPattern")) {
1934 bool MadeChange = false;
1936 for (unsigned i = 0; i < getNumChildren(); ++i)
1937 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1942 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1944 // Node transforms always take one operand.
1945 if (getNumChildren() != 1) {
1946 TP.error("Node transform '" + getOperator()->getName() +
1947 "' requires one operand!");
1951 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1954 // If either the output or input of the xform does not have exact
1955 // type info. We assume they must be the same. Otherwise, it is perfectly
1956 // legal to transform from one type to a completely different type.
1958 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1959 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1960 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1967 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1968 /// RHS of a commutative operation, not the on LHS.
1969 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1970 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1972 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
1978 /// canPatternMatch - If it is impossible for this pattern to match on this
1979 /// target, fill in Reason and return false. Otherwise, return true. This is
1980 /// used as a sanity check for .td files (to prevent people from writing stuff
1981 /// that can never possibly work), and to prevent the pattern permuter from
1982 /// generating stuff that is useless.
1983 bool TreePatternNode::canPatternMatch(std::string &Reason,
1984 const CodeGenDAGPatterns &CDP) {
1985 if (isLeaf()) return true;
1987 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1988 if (!getChild(i)->canPatternMatch(Reason, CDP))
1991 // If this is an intrinsic, handle cases that would make it not match. For
1992 // example, if an operand is required to be an immediate.
1993 if (getOperator()->isSubClassOf("Intrinsic")) {
1998 if (getOperator()->isSubClassOf("ComplexPattern"))
2001 // If this node is a commutative operator, check that the LHS isn't an
2003 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
2004 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2005 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2006 // Scan all of the operands of the node and make sure that only the last one
2007 // is a constant node, unless the RHS also is.
2008 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
2009 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2010 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
2011 if (OnlyOnRHSOfCommutative(getChild(i))) {
2012 Reason="Immediate value must be on the RHS of commutative operators!";
2021 //===----------------------------------------------------------------------===//
2022 // TreePattern implementation
2025 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
2026 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2027 isInputPattern(isInput), HasError(false) {
2028 for (Init *I : RawPat->getValues())
2029 Trees.push_back(ParseTreePattern(I, ""));
2032 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
2033 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2034 isInputPattern(isInput), HasError(false) {
2035 Trees.push_back(ParseTreePattern(Pat, ""));
2038 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
2039 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2040 isInputPattern(isInput), HasError(false) {
2041 Trees.push_back(Pat);
2044 void TreePattern::error(const Twine &Msg) {
2048 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2052 void TreePattern::ComputeNamedNodes() {
2053 for (TreePatternNode *Tree : Trees)
2054 ComputeNamedNodes(Tree);
2057 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2058 if (!N->getName().empty())
2059 NamedNodes[N->getName()].push_back(N);
2061 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2062 ComputeNamedNodes(N->getChild(i));
2066 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2067 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2068 Record *R = DI->getDef();
2070 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2071 // TreePatternNode of its own. For example:
2072 /// (foo GPR, imm) -> (foo GPR, (imm))
2073 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2074 return ParseTreePattern(
2075 DagInit::get(DI, nullptr,
2076 std::vector<std::pair<Init*, StringInit*> >()),
2080 TreePatternNode *Res = new TreePatternNode(DI, 1);
2081 if (R->getName() == "node" && !OpName.empty()) {
2083 error("'node' argument requires a name to match with operand list");
2084 Args.push_back(OpName);
2087 Res->setName(OpName);
2091 // ?:$name or just $name.
2092 if (isa<UnsetInit>(TheInit)) {
2094 error("'?' argument requires a name to match with operand list");
2095 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2096 Args.push_back(OpName);
2097 Res->setName(OpName);
2101 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2102 if (!OpName.empty())
2103 error("Constant int argument should not have a name!");
2104 return new TreePatternNode(II, 1);
2107 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2108 // Turn this into an IntInit.
2109 Init *II = BI->convertInitializerTo(IntRecTy::get());
2110 if (!II || !isa<IntInit>(II))
2111 error("Bits value must be constants!");
2112 return ParseTreePattern(II, OpName);
2115 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2118 error("Pattern has unexpected init kind!");
2120 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2121 if (!OpDef) error("Pattern has unexpected operator type!");
2122 Record *Operator = OpDef->getDef();
2124 if (Operator->isSubClassOf("ValueType")) {
2125 // If the operator is a ValueType, then this must be "type cast" of a leaf
2127 if (Dag->getNumArgs() != 1)
2128 error("Type cast only takes one operand!");
2130 TreePatternNode *New = ParseTreePattern(Dag->getArg(0),
2131 Dag->getArgNameStr(0));
2133 // Apply the type cast.
2134 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2135 New->UpdateNodeType(0, getValueType(Operator), *this);
2137 if (!OpName.empty())
2138 error("ValueType cast should not have a name!");
2142 // Verify that this is something that makes sense for an operator.
2143 if (!Operator->isSubClassOf("PatFrag") &&
2144 !Operator->isSubClassOf("SDNode") &&
2145 !Operator->isSubClassOf("Instruction") &&
2146 !Operator->isSubClassOf("SDNodeXForm") &&
2147 !Operator->isSubClassOf("Intrinsic") &&
2148 !Operator->isSubClassOf("ComplexPattern") &&
2149 Operator->getName() != "set" &&
2150 Operator->getName() != "implicit")
2151 error("Unrecognized node '" + Operator->getName() + "'!");
2153 // Check to see if this is something that is illegal in an input pattern.
2154 if (isInputPattern) {
2155 if (Operator->isSubClassOf("Instruction") ||
2156 Operator->isSubClassOf("SDNodeXForm"))
2157 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2159 if (Operator->isSubClassOf("Intrinsic"))
2160 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2162 if (Operator->isSubClassOf("SDNode") &&
2163 Operator->getName() != "imm" &&
2164 Operator->getName() != "fpimm" &&
2165 Operator->getName() != "tglobaltlsaddr" &&
2166 Operator->getName() != "tconstpool" &&
2167 Operator->getName() != "tjumptable" &&
2168 Operator->getName() != "tframeindex" &&
2169 Operator->getName() != "texternalsym" &&
2170 Operator->getName() != "tblockaddress" &&
2171 Operator->getName() != "tglobaladdr" &&
2172 Operator->getName() != "bb" &&
2173 Operator->getName() != "vt" &&
2174 Operator->getName() != "mcsym")
2175 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2178 std::vector<TreePatternNode*> Children;
2180 // Parse all the operands.
2181 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2182 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
2184 // If the operator is an intrinsic, then this is just syntactic sugar for for
2185 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2186 // convert the intrinsic name to a number.
2187 if (Operator->isSubClassOf("Intrinsic")) {
2188 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2189 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2191 // If this intrinsic returns void, it must have side-effects and thus a
2193 if (Int.IS.RetVTs.empty())
2194 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2195 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2196 // Has side-effects, requires chain.
2197 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2198 else // Otherwise, no chain.
2199 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2201 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2202 Children.insert(Children.begin(), IIDNode);
2205 if (Operator->isSubClassOf("ComplexPattern")) {
2206 for (unsigned i = 0; i < Children.size(); ++i) {
2207 TreePatternNode *Child = Children[i];
2209 if (Child->getName().empty())
2210 error("All arguments to a ComplexPattern must be named");
2212 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2213 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2214 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2215 auto OperandId = std::make_pair(Operator, i);
2216 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2217 if (PrevOp != ComplexPatternOperands.end()) {
2218 if (PrevOp->getValue() != OperandId)
2219 error("All ComplexPattern operands must appear consistently: "
2220 "in the same order in just one ComplexPattern instance.");
2222 ComplexPatternOperands[Child->getName()] = OperandId;
2226 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2227 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2228 Result->setName(OpName);
2230 if (Dag->getName()) {
2231 assert(Result->getName().empty());
2232 Result->setName(Dag->getNameStr());
2237 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2238 /// will never match in favor of something obvious that will. This is here
2239 /// strictly as a convenience to target authors because it allows them to write
2240 /// more type generic things and have useless type casts fold away.
2242 /// This returns true if any change is made.
2243 static bool SimplifyTree(TreePatternNode *&N) {
2247 // If we have a bitconvert with a resolved type and if the source and
2248 // destination types are the same, then the bitconvert is useless, remove it.
2249 if (N->getOperator()->getName() == "bitconvert" &&
2250 N->getExtType(0).isConcrete() &&
2251 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2252 N->getName().empty()) {
2258 // Walk all children.
2259 bool MadeChange = false;
2260 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2261 TreePatternNode *Child = N->getChild(i);
2262 MadeChange |= SimplifyTree(Child);
2263 N->setChild(i, Child);
2270 /// InferAllTypes - Infer/propagate as many types throughout the expression
2271 /// patterns as possible. Return true if all types are inferred, false
2272 /// otherwise. Flags an error if a type contradiction is found.
2274 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2275 if (NamedNodes.empty())
2276 ComputeNamedNodes();
2278 bool MadeChange = true;
2279 while (MadeChange) {
2281 for (TreePatternNode *Tree : Trees) {
2282 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2283 MadeChange |= SimplifyTree(Tree);
2286 // If there are constraints on our named nodes, apply them.
2287 for (auto &Entry : NamedNodes) {
2288 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
2290 // If we have input named node types, propagate their types to the named
2293 if (!InNamedTypes->count(Entry.getKey())) {
2294 error("Node '" + std::string(Entry.getKey()) +
2295 "' in output pattern but not input pattern");
2299 const SmallVectorImpl<TreePatternNode*> &InNodes =
2300 InNamedTypes->find(Entry.getKey())->second;
2302 // The input types should be fully resolved by now.
2303 for (TreePatternNode *Node : Nodes) {
2304 // If this node is a register class, and it is the root of the pattern
2305 // then we're mapping something onto an input register. We allow
2306 // changing the type of the input register in this case. This allows
2307 // us to match things like:
2308 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2309 if (Node == Trees[0] && Node->isLeaf()) {
2310 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
2311 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2312 DI->getDef()->isSubClassOf("RegisterOperand")))
2316 assert(Node->getNumTypes() == 1 &&
2317 InNodes[0]->getNumTypes() == 1 &&
2318 "FIXME: cannot name multiple result nodes yet");
2319 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2324 // If there are multiple nodes with the same name, they must all have the
2326 if (Entry.second.size() > 1) {
2327 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2328 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2329 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2330 "FIXME: cannot name multiple result nodes yet");
2332 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2333 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2339 bool HasUnresolvedTypes = false;
2340 for (const TreePatternNode *Tree : Trees)
2341 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
2342 return !HasUnresolvedTypes;
2345 void TreePattern::print(raw_ostream &OS) const {
2346 OS << getRecord()->getName();
2347 if (!Args.empty()) {
2348 OS << "(" << Args[0];
2349 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2350 OS << ", " << Args[i];
2355 if (Trees.size() > 1)
2357 for (const TreePatternNode *Tree : Trees) {
2363 if (Trees.size() > 1)
2367 void TreePattern::dump() const { print(errs()); }
2369 //===----------------------------------------------------------------------===//
2370 // CodeGenDAGPatterns implementation
2373 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2374 Records(R), Target(R) {
2376 Intrinsics = CodeGenIntrinsicTable(Records, false);
2377 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
2379 ParseNodeTransforms();
2380 ParseComplexPatterns();
2381 ParsePatternFragments();
2382 ParseDefaultOperands();
2383 ParseInstructions();
2384 ParsePatternFragments(/*OutFrags*/true);
2387 // Generate variants. For example, commutative patterns can match
2388 // multiple ways. Add them to PatternsToMatch as well.
2391 // Infer instruction flags. For example, we can detect loads,
2392 // stores, and side effects in many cases by examining an
2393 // instruction's pattern.
2394 InferInstructionFlags();
2396 // Verify that instruction flags match the patterns.
2397 VerifyInstructionFlags();
2400 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2401 Record *N = Records.getDef(Name);
2402 if (!N || !N->isSubClassOf("SDNode"))
2403 PrintFatalError("Error getting SDNode '" + Name + "'!");
2408 // Parse all of the SDNode definitions for the target, populating SDNodes.
2409 void CodeGenDAGPatterns::ParseNodeInfo() {
2410 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2411 while (!Nodes.empty()) {
2412 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2416 // Get the builtin intrinsic nodes.
2417 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2418 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2419 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2422 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2423 /// map, and emit them to the file as functions.
2424 void CodeGenDAGPatterns::ParseNodeTransforms() {
2425 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2426 while (!Xforms.empty()) {
2427 Record *XFormNode = Xforms.back();
2428 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2429 std::string Code = XFormNode->getValueAsString("XFormFunction");
2430 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2436 void CodeGenDAGPatterns::ParseComplexPatterns() {
2437 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2438 while (!AMs.empty()) {
2439 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2445 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2446 /// file, building up the PatternFragments map. After we've collected them all,
2447 /// inline fragments together as necessary, so that there are no references left
2448 /// inside a pattern fragment to a pattern fragment.
2450 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2451 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2453 // First step, parse all of the fragments.
2454 for (Record *Frag : Fragments) {
2455 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2458 DagInit *Tree = Frag->getValueAsDag("Fragment");
2460 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2461 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
2464 // Validate the argument list, converting it to set, to discard duplicates.
2465 std::vector<std::string> &Args = P->getArgList();
2466 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2468 if (OperandsSet.count(""))
2469 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2471 // Parse the operands list.
2472 DagInit *OpsList = Frag->getValueAsDag("Operands");
2473 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2474 // Special cases: ops == outs == ins. Different names are used to
2475 // improve readability.
2477 (OpsOp->getDef()->getName() != "ops" &&
2478 OpsOp->getDef()->getName() != "outs" &&
2479 OpsOp->getDef()->getName() != "ins"))
2480 P->error("Operands list should start with '(ops ... '!");
2482 // Copy over the arguments.
2484 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2485 if (!isa<DefInit>(OpsList->getArg(j)) ||
2486 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2487 P->error("Operands list should all be 'node' values.");
2488 if (!OpsList->getArgName(j))
2489 P->error("Operands list should have names for each operand!");
2490 StringRef ArgNameStr = OpsList->getArgNameStr(j);
2491 if (!OperandsSet.count(ArgNameStr))
2492 P->error("'" + ArgNameStr +
2493 "' does not occur in pattern or was multiply specified!");
2494 OperandsSet.erase(ArgNameStr);
2495 Args.push_back(ArgNameStr);
2498 if (!OperandsSet.empty())
2499 P->error("Operands list does not contain an entry for operand '" +
2500 *OperandsSet.begin() + "'!");
2502 // If there is a code init for this fragment, keep track of the fact that
2503 // this fragment uses it.
2504 TreePredicateFn PredFn(P);
2505 if (!PredFn.isAlwaysTrue())
2506 P->getOnlyTree()->addPredicateFn(PredFn);
2508 // If there is a node transformation corresponding to this, keep track of
2510 Record *Transform = Frag->getValueAsDef("OperandTransform");
2511 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2512 P->getOnlyTree()->setTransformFn(Transform);
2515 // Now that we've parsed all of the tree fragments, do a closure on them so
2516 // that there are not references to PatFrags left inside of them.
2517 for (Record *Frag : Fragments) {
2518 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
2521 TreePattern &ThePat = *PatternFragments[Frag];
2522 ThePat.InlinePatternFragments();
2524 // Infer as many types as possible. Don't worry about it if we don't infer
2525 // all of them, some may depend on the inputs of the pattern.
2526 ThePat.InferAllTypes();
2527 ThePat.resetError();
2529 // If debugging, print out the pattern fragment result.
2530 DEBUG(ThePat.dump());
2534 void CodeGenDAGPatterns::ParseDefaultOperands() {
2535 std::vector<Record*> DefaultOps;
2536 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2538 // Find some SDNode.
2539 assert(!SDNodes.empty() && "No SDNodes parsed?");
2540 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2542 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2543 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
2545 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2546 // SomeSDnode so that we can parse this.
2547 std::vector<std::pair<Init*, StringInit*> > Ops;
2548 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2549 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2550 DefaultInfo->getArgName(op)));
2551 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
2553 // Create a TreePattern to parse this.
2554 TreePattern P(DefaultOps[i], DI, false, *this);
2555 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2557 // Copy the operands over into a DAGDefaultOperand.
2558 DAGDefaultOperand DefaultOpInfo;
2560 TreePatternNode *T = P.getTree(0);
2561 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2562 TreePatternNode *TPN = T->getChild(op);
2563 while (TPN->ApplyTypeConstraints(P, false))
2564 /* Resolve all types */;
2566 if (TPN->ContainsUnresolvedType()) {
2567 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2568 DefaultOps[i]->getName() +
2569 "' doesn't have a concrete type!");
2571 DefaultOpInfo.DefaultOps.push_back(TPN);
2574 // Insert it into the DefaultOperands map so we can find it later.
2575 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
2579 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2580 /// instruction input. Return true if this is a real use.
2581 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2582 std::map<std::string, TreePatternNode*> &InstInputs) {
2583 // No name -> not interesting.
2584 if (Pat->getName().empty()) {
2585 if (Pat->isLeaf()) {
2586 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2587 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2588 DI->getDef()->isSubClassOf("RegisterOperand")))
2589 I->error("Input " + DI->getDef()->getName() + " must be named!");
2595 if (Pat->isLeaf()) {
2596 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2597 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2600 Rec = Pat->getOperator();
2603 // SRCVALUE nodes are ignored.
2604 if (Rec->getName() == "srcvalue")
2607 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2613 if (Slot->isLeaf()) {
2614 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
2616 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2617 SlotRec = Slot->getOperator();
2620 // Ensure that the inputs agree if we've already seen this input.
2622 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2623 if (Slot->getExtTypes() != Pat->getExtTypes())
2624 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2628 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2629 /// part of "I", the instruction), computing the set of inputs and outputs of
2630 /// the pattern. Report errors if we see anything naughty.
2631 void CodeGenDAGPatterns::
2632 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2633 std::map<std::string, TreePatternNode*> &InstInputs,
2634 std::map<std::string, TreePatternNode*>&InstResults,
2635 std::vector<Record*> &InstImpResults) {
2636 if (Pat->isLeaf()) {
2637 bool isUse = HandleUse(I, Pat, InstInputs);
2638 if (!isUse && Pat->getTransformFn())
2639 I->error("Cannot specify a transform function for a non-input value!");
2643 if (Pat->getOperator()->getName() == "implicit") {
2644 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2645 TreePatternNode *Dest = Pat->getChild(i);
2646 if (!Dest->isLeaf())
2647 I->error("implicitly defined value should be a register!");
2649 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2650 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2651 I->error("implicitly defined value should be a register!");
2652 InstImpResults.push_back(Val->getDef());
2657 if (Pat->getOperator()->getName() != "set") {
2658 // If this is not a set, verify that the children nodes are not void typed,
2660 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2661 if (Pat->getChild(i)->getNumTypes() == 0)
2662 I->error("Cannot have void nodes inside of patterns!");
2663 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2667 // If this is a non-leaf node with no children, treat it basically as if
2668 // it were a leaf. This handles nodes like (imm).
2669 bool isUse = HandleUse(I, Pat, InstInputs);
2671 if (!isUse && Pat->getTransformFn())
2672 I->error("Cannot specify a transform function for a non-input value!");
2676 // Otherwise, this is a set, validate and collect instruction results.
2677 if (Pat->getNumChildren() == 0)
2678 I->error("set requires operands!");
2680 if (Pat->getTransformFn())
2681 I->error("Cannot specify a transform function on a set node!");
2683 // Check the set destinations.
2684 unsigned NumDests = Pat->getNumChildren()-1;
2685 for (unsigned i = 0; i != NumDests; ++i) {
2686 TreePatternNode *Dest = Pat->getChild(i);
2687 if (!Dest->isLeaf())
2688 I->error("set destination should be a register!");
2690 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2692 I->error("set destination should be a register!");
2696 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2697 Val->getDef()->isSubClassOf("ValueType") ||
2698 Val->getDef()->isSubClassOf("RegisterOperand") ||
2699 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2700 if (Dest->getName().empty())
2701 I->error("set destination must have a name!");
2702 if (InstResults.count(Dest->getName()))
2703 I->error("cannot set '" + Dest->getName() +"' multiple times");
2704 InstResults[Dest->getName()] = Dest;
2705 } else if (Val->getDef()->isSubClassOf("Register")) {
2706 InstImpResults.push_back(Val->getDef());
2708 I->error("set destination should be a register!");
2712 // Verify and collect info from the computation.
2713 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2714 InstInputs, InstResults, InstImpResults);
2717 //===----------------------------------------------------------------------===//
2718 // Instruction Analysis
2719 //===----------------------------------------------------------------------===//
2721 class InstAnalyzer {
2722 const CodeGenDAGPatterns &CDP;
2724 bool hasSideEffects;
2730 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2731 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2732 isBitcast(false), isVariadic(false) {}
2734 void Analyze(const TreePattern *Pat) {
2735 // Assume only the first tree is the pattern. The others are clobber nodes.
2736 AnalyzeNode(Pat->getTree(0));
2739 void Analyze(const PatternToMatch *Pat) {
2740 AnalyzeNode(Pat->getSrcPattern());
2744 bool IsNodeBitcast(const TreePatternNode *N) const {
2745 if (hasSideEffects || mayLoad || mayStore || isVariadic)
2748 if (N->getNumChildren() != 2)
2751 const TreePatternNode *N0 = N->getChild(0);
2752 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
2755 const TreePatternNode *N1 = N->getChild(1);
2758 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2761 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2762 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2764 return OpInfo.getEnumName() == "ISD::BITCAST";
2768 void AnalyzeNode(const TreePatternNode *N) {
2770 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
2771 Record *LeafRec = DI->getDef();
2772 // Handle ComplexPattern leaves.
2773 if (LeafRec->isSubClassOf("ComplexPattern")) {
2774 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2775 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2776 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2777 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2783 // Analyze children.
2784 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2785 AnalyzeNode(N->getChild(i));
2787 // Ignore set nodes, which are not SDNodes.
2788 if (N->getOperator()->getName() == "set") {
2789 isBitcast = IsNodeBitcast(N);
2793 // Notice properties of the node.
2794 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2795 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2796 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2797 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
2799 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2800 // If this is an intrinsic, analyze it.
2801 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
2802 mayLoad = true;// These may load memory.
2804 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
2805 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2807 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2808 // ReadWriteMem intrinsics can have other strange effects.
2809 hasSideEffects = true;
2815 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2816 const InstAnalyzer &PatInfo,
2820 // Remember where InstInfo got its flags.
2821 if (InstInfo.hasUndefFlags())
2822 InstInfo.InferredFrom = PatDef;
2824 // Check explicitly set flags for consistency.
2825 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2826 !InstInfo.hasSideEffects_Unset) {
2827 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2828 // the pattern has no side effects. That could be useful for div/rem
2829 // instructions that may trap.
2830 if (!InstInfo.hasSideEffects) {
2832 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2833 Twine(InstInfo.hasSideEffects));
2837 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2839 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2840 Twine(InstInfo.mayStore));
2843 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2844 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2845 // Some targets translate immediates to loads.
2846 if (!InstInfo.mayLoad) {
2848 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2849 Twine(InstInfo.mayLoad));
2853 // Transfer inferred flags.
2854 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2855 InstInfo.mayStore |= PatInfo.mayStore;
2856 InstInfo.mayLoad |= PatInfo.mayLoad;
2858 // These flags are silently added without any verification.
2859 InstInfo.isBitcast |= PatInfo.isBitcast;
2861 // Don't infer isVariadic. This flag means something different on SDNodes and
2862 // instructions. For example, a CALL SDNode is variadic because it has the
2863 // call arguments as operands, but a CALL instruction is not variadic - it
2864 // has argument registers as implicit, not explicit uses.
2869 /// hasNullFragReference - Return true if the DAG has any reference to the
2870 /// null_frag operator.
2871 static bool hasNullFragReference(DagInit *DI) {
2872 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
2873 if (!OpDef) return false;
2874 Record *Operator = OpDef->getDef();
2876 // If this is the null fragment, return true.
2877 if (Operator->getName() == "null_frag") return true;
2878 // If any of the arguments reference the null fragment, return true.
2879 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2880 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
2881 if (Arg && hasNullFragReference(Arg))
2888 /// hasNullFragReference - Return true if any DAG in the list references
2889 /// the null_frag operator.
2890 static bool hasNullFragReference(ListInit *LI) {
2891 for (Init *I : LI->getValues()) {
2892 DagInit *DI = dyn_cast<DagInit>(I);
2893 assert(DI && "non-dag in an instruction Pattern list?!");
2894 if (hasNullFragReference(DI))
2900 /// Get all the instructions in a tree.
2902 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2905 if (Tree->getOperator()->isSubClassOf("Instruction"))
2906 Instrs.push_back(Tree->getOperator());
2907 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2908 getInstructionsInTree(Tree->getChild(i), Instrs);
2911 /// Check the class of a pattern leaf node against the instruction operand it
2913 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2918 // Allow direct value types to be used in instruction set patterns.
2919 // The type will be checked later.
2920 if (Leaf->isSubClassOf("ValueType"))
2923 // Patterns can also be ComplexPattern instances.
2924 if (Leaf->isSubClassOf("ComplexPattern"))
2930 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2931 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
2933 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
2935 // Parse the instruction.
2936 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2937 // Inline pattern fragments into it.
2938 I->InlinePatternFragments();
2940 // Infer as many types as possible. If we cannot infer all of them, we can
2941 // never do anything with this instruction pattern: report it to the user.
2942 if (!I->InferAllTypes())
2943 I->error("Could not infer all types in pattern!");
2945 // InstInputs - Keep track of all of the inputs of the instruction, along
2946 // with the record they are declared as.
2947 std::map<std::string, TreePatternNode*> InstInputs;
2949 // InstResults - Keep track of all the virtual registers that are 'set'
2950 // in the instruction, including what reg class they are.
2951 std::map<std::string, TreePatternNode*> InstResults;
2953 std::vector<Record*> InstImpResults;
2955 // Verify that the top-level forms in the instruction are of void type, and
2956 // fill in the InstResults map.
2957 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2958 TreePatternNode *Pat = I->getTree(j);
2959 if (Pat->getNumTypes() != 0) {
2961 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
2964 Types += Pat->getExtType(k).getName();
2966 I->error("Top-level forms in instruction pattern should have"
2967 " void types, has types " + Types);
2970 // Find inputs and outputs, and verify the structure of the uses/defs.
2971 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2975 // Now that we have inputs and outputs of the pattern, inspect the operands
2976 // list for the instruction. This determines the order that operands are
2977 // added to the machine instruction the node corresponds to.
2978 unsigned NumResults = InstResults.size();
2980 // Parse the operands list from the (ops) list, validating it.
2981 assert(I->getArgList().empty() && "Args list should still be empty here!");
2983 // Check that all of the results occur first in the list.
2984 std::vector<Record*> Results;
2985 SmallVector<TreePatternNode *, 2> ResNodes;
2986 for (unsigned i = 0; i != NumResults; ++i) {
2987 if (i == CGI.Operands.size())
2988 I->error("'" + InstResults.begin()->first +
2989 "' set but does not appear in operand list!");
2990 const std::string &OpName = CGI.Operands[i].Name;
2992 // Check that it exists in InstResults.
2993 TreePatternNode *RNode = InstResults[OpName];
2995 I->error("Operand $" + OpName + " does not exist in operand list!");
2997 ResNodes.push_back(RNode);
2999 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3001 I->error("Operand $" + OpName + " should be a set destination: all "
3002 "outputs must occur before inputs in operand list!");
3004 if (!checkOperandClass(CGI.Operands[i], R))
3005 I->error("Operand $" + OpName + " class mismatch!");
3007 // Remember the return type.
3008 Results.push_back(CGI.Operands[i].Rec);
3010 // Okay, this one checks out.
3011 InstResults.erase(OpName);
3014 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3015 // the copy while we're checking the inputs.
3016 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3018 std::vector<TreePatternNode*> ResultNodeOperands;
3019 std::vector<Record*> Operands;
3020 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3021 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3022 const std::string &OpName = Op.Name;
3024 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3026 if (!InstInputsCheck.count(OpName)) {
3027 // If this is an operand with a DefaultOps set filled in, we can ignore
3028 // this. When we codegen it, we will do so as always executed.
3029 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3030 // Does it have a non-empty DefaultOps field? If so, ignore this
3032 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3035 I->error("Operand $" + OpName +
3036 " does not appear in the instruction pattern");
3038 TreePatternNode *InVal = InstInputsCheck[OpName];
3039 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3041 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3042 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3043 if (!checkOperandClass(Op, InRec))
3044 I->error("Operand $" + OpName + "'s register class disagrees"
3045 " between the operand and pattern");
3047 Operands.push_back(Op.Rec);
3049 // Construct the result for the dest-pattern operand list.
3050 TreePatternNode *OpNode = InVal->clone();
3052 // No predicate is useful on the result.
3053 OpNode->clearPredicateFns();
3055 // Promote the xform function to be an explicit node if set.
3056 if (Record *Xform = OpNode->getTransformFn()) {
3057 OpNode->setTransformFn(nullptr);
3058 std::vector<TreePatternNode*> Children;
3059 Children.push_back(OpNode);
3060 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3063 ResultNodeOperands.push_back(OpNode);
3066 if (!InstInputsCheck.empty())
3067 I->error("Input operand $" + InstInputsCheck.begin()->first +
3068 " occurs in pattern but not in operands list!");
3070 TreePatternNode *ResultPattern =
3071 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3072 GetNumNodeResults(I->getRecord(), *this));
3073 // Copy fully inferred output node types to instruction result pattern.
3074 for (unsigned i = 0; i != NumResults; ++i) {
3075 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3076 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3079 // Create and insert the instruction.
3080 // FIXME: InstImpResults should not be part of DAGInstruction.
3081 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3082 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3084 // Use a temporary tree pattern to infer all types and make sure that the
3085 // constructed result is correct. This depends on the instruction already
3086 // being inserted into the DAGInsts map.
3087 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3088 Temp.InferAllTypes(&I->getNamedNodesMap());
3090 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3091 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3093 return TheInsertedInst;
3096 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3097 /// any fragments involved. This populates the Instructions list with fully
3098 /// resolved instructions.
3099 void CodeGenDAGPatterns::ParseInstructions() {
3100 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3102 for (Record *Instr : Instrs) {
3103 ListInit *LI = nullptr;
3105 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3106 LI = Instr->getValueAsListInit("Pattern");
3108 // If there is no pattern, only collect minimal information about the
3109 // instruction for its operand list. We have to assume that there is one
3110 // result, as we have no detailed info. A pattern which references the
3111 // null_frag operator is as-if no pattern were specified. Normally this
3112 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3114 if (!LI || LI->empty() || hasNullFragReference(LI)) {
3115 std::vector<Record*> Results;
3116 std::vector<Record*> Operands;
3118 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3120 if (InstInfo.Operands.size() != 0) {
3121 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3122 Results.push_back(InstInfo.Operands[j].Rec);
3124 // The rest are inputs.
3125 for (unsigned j = InstInfo.Operands.NumDefs,
3126 e = InstInfo.Operands.size(); j < e; ++j)
3127 Operands.push_back(InstInfo.Operands[j].Rec);
3130 // Create and insert the instruction.
3131 std::vector<Record*> ImpResults;
3132 Instructions.insert(std::make_pair(Instr,
3133 DAGInstruction(nullptr, Results, Operands, ImpResults)));
3134 continue; // no pattern.
3137 CodeGenInstruction &CGI = Target.getInstruction(Instr);
3138 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3141 DEBUG(DI.getPattern()->dump());
3144 // If we can, convert the instructions to be patterns that are matched!
3145 for (auto &Entry : Instructions) {
3146 DAGInstruction &TheInst = Entry.second;
3147 TreePattern *I = TheInst.getPattern();
3148 if (!I) continue; // No pattern.
3150 // FIXME: Assume only the first tree is the pattern. The others are clobber
3152 TreePatternNode *Pattern = I->getTree(0);
3153 TreePatternNode *SrcPattern;
3154 if (Pattern->getOperator()->getName() == "set") {
3155 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3157 // Not a set (store or something?)
3158 SrcPattern = Pattern;
3161 Record *Instr = Entry.first;
3162 AddPatternToMatch(I,
3163 PatternToMatch(Instr,
3164 Instr->getValueAsListInit("Predicates"),
3166 TheInst.getResultPattern(),
3167 TheInst.getImpResults(),
3168 Instr->getValueAsInt("AddedComplexity"),
3174 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3176 static void FindNames(const TreePatternNode *P,
3177 std::map<std::string, NameRecord> &Names,
3178 TreePattern *PatternTop) {
3179 if (!P->getName().empty()) {
3180 NameRecord &Rec = Names[P->getName()];
3181 // If this is the first instance of the name, remember the node.
3182 if (Rec.second++ == 0)
3184 else if (Rec.first->getExtTypes() != P->getExtTypes())
3185 PatternTop->error("repetition of value: $" + P->getName() +
3186 " where different uses have different types!");
3190 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3191 FindNames(P->getChild(i), Names, PatternTop);
3195 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3196 const PatternToMatch &PTM) {
3197 // Do some sanity checking on the pattern we're about to match.
3199 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3200 PrintWarning(Pattern->getRecord()->getLoc(),
3201 Twine("Pattern can never match: ") + Reason);
3205 // If the source pattern's root is a complex pattern, that complex pattern
3206 // must specify the nodes it can potentially match.
3207 if (const ComplexPattern *CP =
3208 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3209 if (CP->getRootNodes().empty())
3210 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3214 // Find all of the named values in the input and output, ensure they have the
3216 std::map<std::string, NameRecord> SrcNames, DstNames;
3217 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3218 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3220 // Scan all of the named values in the destination pattern, rejecting them if
3221 // they don't exist in the input pattern.
3222 for (const auto &Entry : DstNames) {
3223 if (SrcNames[Entry.first].first == nullptr)
3224 Pattern->error("Pattern has input without matching name in output: $" +
3228 // Scan all of the named values in the source pattern, rejecting them if the
3229 // name isn't used in the dest, and isn't used to tie two values together.
3230 for (const auto &Entry : SrcNames)
3231 if (DstNames[Entry.first].first == nullptr &&
3232 SrcNames[Entry.first].second == 1)
3233 Pattern->error("Pattern has dead named input: $" + Entry.first);
3235 PatternsToMatch.push_back(PTM);
3240 void CodeGenDAGPatterns::InferInstructionFlags() {
3241 ArrayRef<const CodeGenInstruction*> Instructions =
3242 Target.getInstructionsByEnumValue();
3244 // First try to infer flags from the primary instruction pattern, if any.
3245 SmallVector<CodeGenInstruction*, 8> Revisit;
3246 unsigned Errors = 0;
3247 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3248 CodeGenInstruction &InstInfo =
3249 const_cast<CodeGenInstruction &>(*Instructions[i]);
3251 // Get the primary instruction pattern.
3252 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3254 if (InstInfo.hasUndefFlags())
3255 Revisit.push_back(&InstInfo);
3258 InstAnalyzer PatInfo(*this);
3259 PatInfo.Analyze(Pattern);
3260 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3263 // Second, look for single-instruction patterns defined outside the
3265 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3266 const PatternToMatch &PTM = *I;
3268 // We can only infer from single-instruction patterns, otherwise we won't
3269 // know which instruction should get the flags.
3270 SmallVector<Record*, 8> PatInstrs;
3271 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3272 if (PatInstrs.size() != 1)
3275 // Get the single instruction.
3276 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3278 // Only infer properties from the first pattern. We'll verify the others.
3279 if (InstInfo.InferredFrom)
3282 InstAnalyzer PatInfo(*this);
3283 PatInfo.Analyze(&PTM);
3284 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3288 PrintFatalError("pattern conflicts");
3290 // Revisit instructions with undefined flags and no pattern.
3291 if (Target.guessInstructionProperties()) {
3292 for (CodeGenInstruction *InstInfo : Revisit) {
3293 if (InstInfo->InferredFrom)
3295 // The mayLoad and mayStore flags default to false.
3296 // Conservatively assume hasSideEffects if it wasn't explicit.
3297 if (InstInfo->hasSideEffects_Unset)
3298 InstInfo->hasSideEffects = true;
3303 // Complain about any flags that are still undefined.
3304 for (CodeGenInstruction *InstInfo : Revisit) {
3305 if (InstInfo->InferredFrom)
3307 if (InstInfo->hasSideEffects_Unset)
3308 PrintError(InstInfo->TheDef->getLoc(),
3309 "Can't infer hasSideEffects from patterns");
3310 if (InstInfo->mayStore_Unset)
3311 PrintError(InstInfo->TheDef->getLoc(),
3312 "Can't infer mayStore from patterns");
3313 if (InstInfo->mayLoad_Unset)
3314 PrintError(InstInfo->TheDef->getLoc(),
3315 "Can't infer mayLoad from patterns");
3320 /// Verify instruction flags against pattern node properties.
3321 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3322 unsigned Errors = 0;
3323 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3324 const PatternToMatch &PTM = *I;
3325 SmallVector<Record*, 8> Instrs;
3326 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3330 // Count the number of instructions with each flag set.
3331 unsigned NumSideEffects = 0;
3332 unsigned NumStores = 0;
3333 unsigned NumLoads = 0;
3334 for (const Record *Instr : Instrs) {
3335 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3336 NumSideEffects += InstInfo.hasSideEffects;
3337 NumStores += InstInfo.mayStore;
3338 NumLoads += InstInfo.mayLoad;
3341 // Analyze the source pattern.
3342 InstAnalyzer PatInfo(*this);
3343 PatInfo.Analyze(&PTM);
3345 // Collect error messages.
3346 SmallVector<std::string, 4> Msgs;
3348 // Check for missing flags in the output.
3349 // Permit extra flags for now at least.
3350 if (PatInfo.hasSideEffects && !NumSideEffects)
3351 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3353 // Don't verify store flags on instructions with side effects. At least for
3354 // intrinsics, side effects implies mayStore.
3355 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3356 Msgs.push_back("pattern may store, but mayStore isn't set");
3358 // Similarly, mayStore implies mayLoad on intrinsics.
3359 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3360 Msgs.push_back("pattern may load, but mayLoad isn't set");
3362 // Print error messages.
3367 for (const std::string &Msg : Msgs)
3368 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
3369 (Instrs.size() == 1 ?
3370 "instruction" : "output instructions"));
3371 // Provide the location of the relevant instruction definitions.
3372 for (const Record *Instr : Instrs) {
3373 if (Instr != PTM.getSrcRecord())
3374 PrintError(Instr->getLoc(), "defined here");
3375 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3376 if (InstInfo.InferredFrom &&
3377 InstInfo.InferredFrom != InstInfo.TheDef &&
3378 InstInfo.InferredFrom != PTM.getSrcRecord())
3379 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
3383 PrintFatalError("Errors in DAG patterns");
3386 /// Given a pattern result with an unresolved type, see if we can find one
3387 /// instruction with an unresolved result type. Force this result type to an
3388 /// arbitrary element if it's possible types to converge results.
3389 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3393 // Analyze children.
3394 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3395 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3398 if (!N->getOperator()->isSubClassOf("Instruction"))
3401 // If this type is already concrete or completely unknown we can't do
3403 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3404 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3407 // Otherwise, force its type to the first possibility (an arbitrary choice).
3408 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3415 void CodeGenDAGPatterns::ParsePatterns() {
3416 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3418 for (Record *CurPattern : Patterns) {
3419 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3421 // If the pattern references the null_frag, there's nothing to do.
3422 if (hasNullFragReference(Tree))
3425 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3427 // Inline pattern fragments into it.
3428 Pattern->InlinePatternFragments();
3430 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3431 if (LI->empty()) continue; // no pattern.
3433 // Parse the instruction.
3434 TreePattern Result(CurPattern, LI, false, *this);
3436 // Inline pattern fragments into it.
3437 Result.InlinePatternFragments();
3439 if (Result.getNumTrees() != 1)
3440 Result.error("Cannot handle instructions producing instructions "
3441 "with temporaries yet!");
3443 bool IterateInference;
3444 bool InferredAllPatternTypes, InferredAllResultTypes;
3446 // Infer as many types as possible. If we cannot infer all of them, we
3447 // can never do anything with this pattern: report it to the user.
3448 InferredAllPatternTypes =
3449 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3451 // Infer as many types as possible. If we cannot infer all of them, we
3452 // can never do anything with this pattern: report it to the user.
3453 InferredAllResultTypes =
3454 Result.InferAllTypes(&Pattern->getNamedNodesMap());
3456 IterateInference = false;
3458 // Apply the type of the result to the source pattern. This helps us
3459 // resolve cases where the input type is known to be a pointer type (which
3460 // is considered resolved), but the result knows it needs to be 32- or
3461 // 64-bits. Infer the other way for good measure.
3462 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3463 Pattern->getTree(0)->getNumTypes());
3465 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3466 i, Result.getTree(0)->getExtType(i), Result);
3467 IterateInference |= Result.getTree(0)->UpdateNodeType(
3468 i, Pattern->getTree(0)->getExtType(i), Result);
3471 // If our iteration has converged and the input pattern's types are fully
3472 // resolved but the result pattern is not fully resolved, we may have a
3473 // situation where we have two instructions in the result pattern and
3474 // the instructions require a common register class, but don't care about
3475 // what actual MVT is used. This is actually a bug in our modelling:
3476 // output patterns should have register classes, not MVTs.
3478 // In any case, to handle this, we just go through and disambiguate some
3479 // arbitrary types to the result pattern's nodes.
3480 if (!IterateInference && InferredAllPatternTypes &&
3481 !InferredAllResultTypes)
3483 ForceArbitraryInstResultType(Result.getTree(0), Result);
3484 } while (IterateInference);
3486 // Verify that we inferred enough types that we can do something with the
3487 // pattern and result. If these fire the user has to add type casts.
3488 if (!InferredAllPatternTypes)
3489 Pattern->error("Could not infer all types in pattern!");
3490 if (!InferredAllResultTypes) {
3492 Result.error("Could not infer all types in pattern result!");
3495 // Validate that the input pattern is correct.
3496 std::map<std::string, TreePatternNode*> InstInputs;
3497 std::map<std::string, TreePatternNode*> InstResults;
3498 std::vector<Record*> InstImpResults;
3499 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3500 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3501 InstInputs, InstResults,
3504 // Promote the xform function to be an explicit node if set.
3505 TreePatternNode *DstPattern = Result.getOnlyTree();
3506 std::vector<TreePatternNode*> ResultNodeOperands;
3507 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3508 TreePatternNode *OpNode = DstPattern->getChild(ii);
3509 if (Record *Xform = OpNode->getTransformFn()) {
3510 OpNode->setTransformFn(nullptr);
3511 std::vector<TreePatternNode*> Children;
3512 Children.push_back(OpNode);
3513 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3515 ResultNodeOperands.push_back(OpNode);
3517 DstPattern = Result.getOnlyTree();
3518 if (!DstPattern->isLeaf())
3519 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3521 DstPattern->getNumTypes());
3523 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3524 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3526 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
3527 Temp.InferAllTypes();
3530 AddPatternToMatch(Pattern,
3531 PatternToMatch(CurPattern,
3532 CurPattern->getValueAsListInit("Predicates"),
3533 Pattern->getTree(0),
3534 Temp.getOnlyTree(), InstImpResults,
3535 CurPattern->getValueAsInt("AddedComplexity"),
3536 CurPattern->getID()));
3540 /// CombineChildVariants - Given a bunch of permutations of each child of the
3541 /// 'operator' node, put them together in all possible ways.
3542 static void CombineChildVariants(TreePatternNode *Orig,
3543 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3544 std::vector<TreePatternNode*> &OutVariants,
3545 CodeGenDAGPatterns &CDP,
3546 const MultipleUseVarSet &DepVars) {
3547 // Make sure that each operand has at least one variant to choose from.
3548 for (const auto &Variants : ChildVariants)
3549 if (Variants.empty())
3552 // The end result is an all-pairs construction of the resultant pattern.
3553 std::vector<unsigned> Idxs;
3554 Idxs.resize(ChildVariants.size());
3558 DEBUG(if (!Idxs.empty()) {
3559 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3560 for (unsigned Idx : Idxs) {
3561 errs() << Idx << " ";
3566 // Create the variant and add it to the output list.
3567 std::vector<TreePatternNode*> NewChildren;
3568 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3569 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3570 auto R = llvm::make_unique<TreePatternNode>(
3571 Orig->getOperator(), NewChildren, Orig->getNumTypes());
3573 // Copy over properties.
3574 R->setName(Orig->getName());
3575 R->setPredicateFns(Orig->getPredicateFns());
3576 R->setTransformFn(Orig->getTransformFn());
3577 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3578 R->setType(i, Orig->getExtType(i));
3580 // If this pattern cannot match, do not include it as a variant.
3581 std::string ErrString;
3582 // Scan to see if this pattern has already been emitted. We can get
3583 // duplication due to things like commuting:
3584 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3585 // which are the same pattern. Ignore the dups.
3586 if (R->canPatternMatch(ErrString, CDP) &&
3587 none_of(OutVariants, [&](TreePatternNode *Variant) {
3588 return R->isIsomorphicTo(Variant, DepVars);
3590 OutVariants.push_back(R.release());
3592 // Increment indices to the next permutation by incrementing the
3593 // indices from last index backward, e.g., generate the sequence
3594 // [0, 0], [0, 1], [1, 0], [1, 1].
3596 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3597 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3602 NotDone = (IdxsIdx >= 0);
3606 /// CombineChildVariants - A helper function for binary operators.
3608 static void CombineChildVariants(TreePatternNode *Orig,
3609 const std::vector<TreePatternNode*> &LHS,
3610 const std::vector<TreePatternNode*> &RHS,
3611 std::vector<TreePatternNode*> &OutVariants,
3612 CodeGenDAGPatterns &CDP,
3613 const MultipleUseVarSet &DepVars) {
3614 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3615 ChildVariants.push_back(LHS);
3616 ChildVariants.push_back(RHS);
3617 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3621 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3622 std::vector<TreePatternNode *> &Children) {
3623 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3624 Record *Operator = N->getOperator();
3626 // Only permit raw nodes.
3627 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3628 N->getTransformFn()) {
3629 Children.push_back(N);
3633 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3634 Children.push_back(N->getChild(0));
3636 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3638 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3639 Children.push_back(N->getChild(1));
3641 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3644 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3645 /// the (potentially recursive) pattern by using algebraic laws.
3647 static void GenerateVariantsOf(TreePatternNode *N,
3648 std::vector<TreePatternNode*> &OutVariants,
3649 CodeGenDAGPatterns &CDP,
3650 const MultipleUseVarSet &DepVars) {
3651 // We cannot permute leaves or ComplexPattern uses.
3652 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
3653 OutVariants.push_back(N);
3657 // Look up interesting info about the node.
3658 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3660 // If this node is associative, re-associate.
3661 if (NodeInfo.hasProperty(SDNPAssociative)) {
3662 // Re-associate by pulling together all of the linked operators
3663 std::vector<TreePatternNode*> MaximalChildren;
3664 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3666 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3668 if (MaximalChildren.size() == 3) {
3669 // Find the variants of all of our maximal children.
3670 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3671 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3672 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3673 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3675 // There are only two ways we can permute the tree:
3676 // (A op B) op C and A op (B op C)
3677 // Within these forms, we can also permute A/B/C.
3679 // Generate legal pair permutations of A/B/C.
3680 std::vector<TreePatternNode*> ABVariants;
3681 std::vector<TreePatternNode*> BAVariants;
3682 std::vector<TreePatternNode*> ACVariants;
3683 std::vector<TreePatternNode*> CAVariants;
3684 std::vector<TreePatternNode*> BCVariants;
3685 std::vector<TreePatternNode*> CBVariants;
3686 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3687 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3688 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3689 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3690 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3691 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3693 // Combine those into the result: (x op x) op x
3694 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3695 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3696 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3697 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3698 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3699 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3701 // Combine those into the result: x op (x op x)
3702 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3703 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3704 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3705 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3706 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3707 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3712 // Compute permutations of all children.
3713 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3714 ChildVariants.resize(N->getNumChildren());
3715 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3716 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3718 // Build all permutations based on how the children were formed.
3719 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3721 // If this node is commutative, consider the commuted order.
3722 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3723 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3724 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3725 "Commutative but doesn't have 2 children!");
3726 // Don't count children which are actually register references.
3728 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3729 TreePatternNode *Child = N->getChild(i);
3730 if (Child->isLeaf())
3731 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
3732 Record *RR = DI->getDef();
3733 if (RR->isSubClassOf("Register"))
3738 // Consider the commuted order.
3739 if (isCommIntrinsic) {
3740 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3741 // operands are the commutative operands, and there might be more operands
3744 "Commutative intrinsic should have at least 3 children!");
3745 std::vector<std::vector<TreePatternNode*> > Variants;
3746 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3747 Variants.push_back(ChildVariants[2]);
3748 Variants.push_back(ChildVariants[1]);
3749 for (unsigned i = 3; i != NC; ++i)
3750 Variants.push_back(ChildVariants[i]);
3751 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3753 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3754 OutVariants, CDP, DepVars);
3759 // GenerateVariants - Generate variants. For example, commutative patterns can
3760 // match multiple ways. Add them to PatternsToMatch as well.
3761 void CodeGenDAGPatterns::GenerateVariants() {
3762 DEBUG(errs() << "Generating instruction variants.\n");
3764 // Loop over all of the patterns we've collected, checking to see if we can
3765 // generate variants of the instruction, through the exploitation of
3766 // identities. This permits the target to provide aggressive matching without
3767 // the .td file having to contain tons of variants of instructions.
3769 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3770 // intentionally do not reconsider these. Any variants of added patterns have
3771 // already been added.
3773 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3774 MultipleUseVarSet DepVars;
3775 std::vector<TreePatternNode*> Variants;
3776 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3777 DEBUG(errs() << "Dependent/multiply used variables: ");
3778 DEBUG(DumpDepVars(DepVars));
3779 DEBUG(errs() << "\n");
3780 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3783 assert(!Variants.empty() && "Must create at least original variant!");
3784 Variants.erase(Variants.begin()); // Remove the original pattern.
3786 if (Variants.empty()) // No variants for this pattern.
3789 DEBUG(errs() << "FOUND VARIANTS OF: ";
3790 PatternsToMatch[i].getSrcPattern()->dump();
3793 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3794 TreePatternNode *Variant = Variants[v];
3796 DEBUG(errs() << " VAR#" << v << ": ";
3800 // Scan to see if an instruction or explicit pattern already matches this.
3801 bool AlreadyExists = false;
3802 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3803 // Skip if the top level predicates do not match.
3804 if (PatternsToMatch[i].getPredicates() !=
3805 PatternsToMatch[p].getPredicates())
3807 // Check to see if this variant already exists.
3808 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3810 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3811 AlreadyExists = true;
3815 // If we already have it, ignore the variant.
3816 if (AlreadyExists) continue;
3818 // Otherwise, add it to the list of patterns we have.
3819 PatternsToMatch.emplace_back(
3820 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3821 Variant, PatternsToMatch[i].getDstPattern(),
3822 PatternsToMatch[i].getDstRegs(),
3823 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
3826 DEBUG(errs() << "\n");