1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
13 //===----------------------------------------------------------------------===//
15 #include "CodeGenDAGPatterns.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/TableGen/Error.h"
22 #include "llvm/TableGen/Record.h"
28 #define DEBUG_TYPE "dag-patterns"
30 //===----------------------------------------------------------------------===//
31 // EEVT::TypeSet Implementation
32 //===----------------------------------------------------------------------===//
34 static inline bool isInteger(MVT::SimpleValueType VT) {
35 return MVT(VT).isInteger();
37 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
38 return MVT(VT).isFloatingPoint();
40 static inline bool isVector(MVT::SimpleValueType VT) {
41 return MVT(VT).isVector();
43 static inline bool isScalar(MVT::SimpleValueType VT) {
44 return !MVT(VT).isVector();
47 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
50 else if (VT == MVT::fAny)
51 EnforceFloatingPoint(TP);
52 else if (VT == MVT::vAny)
55 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
56 VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!");
57 TypeVec.push_back(VT);
62 EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
63 assert(!VTList.empty() && "empty list?");
64 TypeVec.append(VTList.begin(), VTList.end());
67 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
68 VTList[0] != MVT::fAny);
70 // Verify no duplicates.
71 array_pod_sort(TypeVec.begin(), TypeVec.end());
72 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
75 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
76 /// on completely unknown type sets.
77 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
78 bool (*Pred)(MVT::SimpleValueType),
79 const char *PredicateName) {
80 assert(isCompletelyUnknown());
81 ArrayRef<MVT::SimpleValueType> LegalTypes =
82 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
87 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
88 if (!Pred || Pred(LegalTypes[i]))
89 TypeVec.push_back(LegalTypes[i]);
91 // If we have nothing that matches the predicate, bail out.
92 if (TypeVec.empty()) {
93 TP.error("Type inference contradiction found, no " +
94 std::string(PredicateName) + " types found");
97 // No need to sort with one element.
98 if (TypeVec.size() == 1) return true;
100 // Remove duplicates.
101 array_pod_sort(TypeVec.begin(), TypeVec.end());
102 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
107 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
108 /// integer value type.
109 bool EEVT::TypeSet::hasIntegerTypes() const {
110 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
111 if (isInteger(TypeVec[i]))
116 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
117 /// a floating point value type.
118 bool EEVT::TypeSet::hasFloatingPointTypes() const {
119 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
120 if (isFloatingPoint(TypeVec[i]))
125 /// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
126 bool EEVT::TypeSet::hasScalarTypes() const {
127 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
128 if (isScalar(TypeVec[i]))
133 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
135 bool EEVT::TypeSet::hasVectorTypes() const {
136 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
137 if (isVector(TypeVec[i]))
143 std::string EEVT::TypeSet::getName() const {
144 if (TypeVec.empty()) return "<empty>";
148 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
149 std::string VTName = llvm::getEnumName(TypeVec[i]);
150 // Strip off MVT:: prefix if present.
151 if (VTName.substr(0,5) == "MVT::")
152 VTName = VTName.substr(5);
153 if (i) Result += ':';
157 if (TypeVec.size() == 1)
159 return "{" + Result + "}";
162 /// MergeInTypeInfo - This merges in type information from the specified
163 /// argument. If 'this' changes, it returns true. If the two types are
164 /// contradictory (e.g. merge f32 into i32) then this flags an error.
165 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
166 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
169 if (isCompletelyUnknown()) {
174 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
176 // Handle the abstract cases, seeing if we can resolve them better.
177 switch (TypeVec[0]) {
181 if (InVT.hasIntegerTypes()) {
182 EEVT::TypeSet InCopy(InVT);
183 InCopy.EnforceInteger(TP);
184 InCopy.EnforceScalar(TP);
186 if (InCopy.isConcrete()) {
187 // If the RHS has one integer type, upgrade iPTR to i32.
188 TypeVec[0] = InVT.TypeVec[0];
192 // If the input has multiple scalar integers, this doesn't add any info.
193 if (!InCopy.isCompletelyUnknown())
199 // If the input constraint is iAny/iPTR and this is an integer type list,
200 // remove non-integer types from the list.
201 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
203 bool MadeChange = EnforceInteger(TP);
205 // If we're merging in iPTR/iPTRAny and the node currently has a list of
206 // multiple different integer types, replace them with a single iPTR.
207 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
208 TypeVec.size() != 1) {
210 TypeVec[0] = InVT.TypeVec[0];
217 // If this is a type list and the RHS is a typelist as well, eliminate entries
218 // from this list that aren't in the other one.
219 bool MadeChange = false;
220 TypeSet InputSet(*this);
222 for (unsigned i = 0; i != TypeVec.size(); ++i) {
224 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
225 if (TypeVec[i] == InVT.TypeVec[j]) {
230 if (InInVT) continue;
231 TypeVec.erase(TypeVec.begin()+i--);
235 // If we removed all of our types, we have a type contradiction.
236 if (!TypeVec.empty())
239 // FIXME: Really want an SMLoc here!
240 TP.error("Type inference contradiction found, merging '" +
241 InVT.getName() + "' into '" + InputSet.getName() + "'");
245 /// EnforceInteger - Remove all non-integer types from this set.
246 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
249 // If we know nothing, then get the full set.
251 return FillWithPossibleTypes(TP, isInteger, "integer");
252 if (!hasFloatingPointTypes())
255 TypeSet InputSet(*this);
257 // Filter out all the fp types.
258 for (unsigned i = 0; i != TypeVec.size(); ++i)
259 if (!isInteger(TypeVec[i]))
260 TypeVec.erase(TypeVec.begin()+i--);
262 if (TypeVec.empty()) {
263 TP.error("Type inference contradiction found, '" +
264 InputSet.getName() + "' needs to be integer");
270 /// EnforceFloatingPoint - Remove all integer types from this set.
271 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
274 // If we know nothing, then get the full set.
276 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
278 if (!hasIntegerTypes())
281 TypeSet InputSet(*this);
283 // Filter out all the fp types.
284 for (unsigned i = 0; i != TypeVec.size(); ++i)
285 if (!isFloatingPoint(TypeVec[i]))
286 TypeVec.erase(TypeVec.begin()+i--);
288 if (TypeVec.empty()) {
289 TP.error("Type inference contradiction found, '" +
290 InputSet.getName() + "' needs to be floating point");
296 /// EnforceScalar - Remove all vector types from this.
297 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
301 // If we know nothing, then get the full set.
303 return FillWithPossibleTypes(TP, isScalar, "scalar");
305 if (!hasVectorTypes())
308 TypeSet InputSet(*this);
310 // Filter out all the vector types.
311 for (unsigned i = 0; i != TypeVec.size(); ++i)
312 if (!isScalar(TypeVec[i]))
313 TypeVec.erase(TypeVec.begin()+i--);
315 if (TypeVec.empty()) {
316 TP.error("Type inference contradiction found, '" +
317 InputSet.getName() + "' needs to be scalar");
323 /// EnforceVector - Remove all vector types from this.
324 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
328 // If we know nothing, then get the full set.
330 return FillWithPossibleTypes(TP, isVector, "vector");
332 TypeSet InputSet(*this);
333 bool MadeChange = false;
335 // Filter out all the scalar types.
336 for (unsigned i = 0; i != TypeVec.size(); ++i)
337 if (!isVector(TypeVec[i])) {
338 TypeVec.erase(TypeVec.begin()+i--);
342 if (TypeVec.empty()) {
343 TP.error("Type inference contradiction found, '" +
344 InputSet.getName() + "' needs to be a vector");
352 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
353 /// this shoud be based on the element type. Update this and other based on
354 /// this information.
355 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
359 // Both operands must be integer or FP, but we don't care which.
360 bool MadeChange = false;
362 if (isCompletelyUnknown())
363 MadeChange = FillWithPossibleTypes(TP);
365 if (Other.isCompletelyUnknown())
366 MadeChange = Other.FillWithPossibleTypes(TP);
368 // If one side is known to be integer or known to be FP but the other side has
369 // no information, get at least the type integrality info in there.
370 if (!hasFloatingPointTypes())
371 MadeChange |= Other.EnforceInteger(TP);
372 else if (!hasIntegerTypes())
373 MadeChange |= Other.EnforceFloatingPoint(TP);
374 if (!Other.hasFloatingPointTypes())
375 MadeChange |= EnforceInteger(TP);
376 else if (!Other.hasIntegerTypes())
377 MadeChange |= EnforceFloatingPoint(TP);
379 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
380 "Should have a type list now");
382 // If one contains vectors but the other doesn't pull vectors out.
383 if (!hasVectorTypes())
384 MadeChange |= Other.EnforceScalar(TP);
385 else if (!hasScalarTypes())
386 MadeChange |= Other.EnforceVector(TP);
387 if (!Other.hasVectorTypes())
388 MadeChange |= EnforceScalar(TP);
389 else if (!Other.hasScalarTypes())
390 MadeChange |= EnforceVector(TP);
392 // For vectors we need to ensure that smaller size doesn't produce larger
393 // vector and vice versa.
394 if (isConcrete() && isVector(getConcrete())) {
395 MVT IVT = getConcrete();
396 unsigned Size = IVT.getSizeInBits();
398 // Only keep types that have at least as many bits.
399 TypeSet InputSet(Other);
401 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
402 assert(isVector(Other.TypeVec[i]) && "EnforceVector didn't work");
403 if (MVT(Other.TypeVec[i]).getSizeInBits() < Size) {
404 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
409 if (Other.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
410 TP.error("Type inference contradiction found, forcing '" +
411 InputSet.getName() + "' to have at least as many bits as " +
415 } else if (Other.isConcrete() && isVector(Other.getConcrete())) {
416 MVT IVT = Other.getConcrete();
417 unsigned Size = IVT.getSizeInBits();
419 // Only keep types with the same or fewer total bits
420 TypeSet InputSet(*this);
422 for (unsigned i = 0; i != TypeVec.size(); ++i) {
423 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
424 if (MVT(TypeVec[i]).getSizeInBits() > Size) {
425 TypeVec.erase(TypeVec.begin()+i--);
430 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
431 TP.error("Type inference contradiction found, forcing '" +
432 InputSet.getName() + "' to have the same or fewer bits than " +
433 Other.getName() + "'");
438 // This code does not currently handle nodes which have multiple types,
439 // where some types are integer, and some are fp. Assert that this is not
441 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
442 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
443 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
448 // Okay, find the smallest scalar type from the other set and remove
449 // anything the same or smaller from the current set.
450 TypeSet InputSet(Other);
451 MVT::SimpleValueType Smallest = TypeVec[0];
452 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
453 if (Other.TypeVec[i] <= Smallest) {
454 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
459 if (Other.TypeVec.empty()) {
460 TP.error("Type inference contradiction found, '" + InputSet.getName() +
461 "' has nothing larger than '" + getName() +"'!");
465 // Okay, find the largest scalar type from the other set and remove
466 // anything the same or larger from the current set.
467 InputSet = TypeSet(*this);
468 MVT::SimpleValueType Largest = Other.TypeVec[Other.TypeVec.size()-1];
469 for (unsigned i = 0; i != TypeVec.size(); ++i) {
470 if (TypeVec[i] >= Largest) {
471 TypeVec.erase(TypeVec.begin()+i--);
476 if (TypeVec.empty()) {
477 TP.error("Type inference contradiction found, '" + InputSet.getName() +
478 "' has nothing smaller than '" + Other.getName() +"'!");
485 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
486 /// whose element is specified by VTOperand.
487 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
489 bool MadeChange = false;
491 MadeChange |= EnforceVector(TP);
493 TypeSet InputSet(*this);
495 // Filter out all the types which don't have the right element type.
496 for (unsigned i = 0; i != TypeVec.size(); ++i) {
497 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
498 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
499 TypeVec.erase(TypeVec.begin()+i--);
504 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
505 TP.error("Type inference contradiction found, forcing '" +
506 InputSet.getName() + "' to have a vector element");
513 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
514 /// whose element is specified by VTOperand.
515 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
520 // "This" must be a vector and "VTOperand" must be a scalar.
521 bool MadeChange = false;
522 MadeChange |= EnforceVector(TP);
523 MadeChange |= VTOperand.EnforceScalar(TP);
525 // If we know the vector type, it forces the scalar to agree.
527 MVT IVT = getConcrete();
528 IVT = IVT.getVectorElementType();
530 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
533 // If the scalar type is known, filter out vector types whose element types
535 if (!VTOperand.isConcrete())
538 MVT::SimpleValueType VT = VTOperand.getConcrete();
540 TypeSet InputSet(*this);
542 // Filter out all the types which don't have the right element type.
543 for (unsigned i = 0; i != TypeVec.size(); ++i) {
544 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
545 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
546 TypeVec.erase(TypeVec.begin()+i--);
551 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
552 TP.error("Type inference contradiction found, forcing '" +
553 InputSet.getName() + "' to have a vector element");
559 /// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
560 /// vector type specified by VTOperand.
561 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
566 // "This" must be a vector and "VTOperand" must be a vector.
567 bool MadeChange = false;
568 MadeChange |= EnforceVector(TP);
569 MadeChange |= VTOperand.EnforceVector(TP);
571 // If one side is known to be integer or known to be FP but the other side has
572 // no information, get at least the type integrality info in there.
573 if (!hasFloatingPointTypes())
574 MadeChange |= VTOperand.EnforceInteger(TP);
575 else if (!hasIntegerTypes())
576 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
577 if (!VTOperand.hasFloatingPointTypes())
578 MadeChange |= EnforceInteger(TP);
579 else if (!VTOperand.hasIntegerTypes())
580 MadeChange |= EnforceFloatingPoint(TP);
582 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
583 "Should have a type list now");
585 // If we know the vector type, it forces the scalar types to agree.
586 // Also force one vector to have more elements than the other.
588 MVT IVT = getConcrete();
589 unsigned NumElems = IVT.getVectorNumElements();
590 IVT = IVT.getVectorElementType();
592 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
593 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
595 // Only keep types that have less elements than VTOperand.
596 TypeSet InputSet(VTOperand);
598 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
599 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
600 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
601 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
605 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
606 TP.error("Type inference contradiction found, forcing '" +
607 InputSet.getName() + "' to have less vector elements than '" +
611 } else if (VTOperand.isConcrete()) {
612 MVT IVT = VTOperand.getConcrete();
613 unsigned NumElems = IVT.getVectorNumElements();
614 IVT = IVT.getVectorElementType();
616 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
617 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
619 // Only keep types that have more elements than 'this'.
620 TypeSet InputSet(*this);
622 for (unsigned i = 0; i != TypeVec.size(); ++i) {
623 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
624 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
625 TypeVec.erase(TypeVec.begin()+i--);
629 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
630 TP.error("Type inference contradiction found, forcing '" +
631 InputSet.getName() + "' to have more vector elements than '" +
632 VTOperand.getName() + "'");
640 /// EnforceVectorSameNumElts - 'this' is now constrainted to
641 /// be a vector with same num elements as VTOperand.
642 bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
647 // "This" must be a vector and "VTOperand" must be a vector.
648 bool MadeChange = false;
649 MadeChange |= EnforceVector(TP);
650 MadeChange |= VTOperand.EnforceVector(TP);
652 // If we know one of the vector types, it forces the other type to agree.
654 MVT IVT = getConcrete();
655 unsigned NumElems = IVT.getVectorNumElements();
657 // Only keep types that have same elements as VTOperand.
658 TypeSet InputSet(VTOperand);
660 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
661 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
662 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
663 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
667 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
668 TP.error("Type inference contradiction found, forcing '" +
669 InputSet.getName() + "' to have same number elements as '" +
673 } else if (VTOperand.isConcrete()) {
674 MVT IVT = VTOperand.getConcrete();
675 unsigned NumElems = IVT.getVectorNumElements();
677 // Only keep types that have same elements as 'this'.
678 TypeSet InputSet(*this);
680 for (unsigned i = 0; i != TypeVec.size(); ++i) {
681 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
682 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
683 TypeVec.erase(TypeVec.begin()+i--);
687 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
688 TP.error("Type inference contradiction found, forcing '" +
689 InputSet.getName() + "' to have same number elements than '" +
690 VTOperand.getName() + "'");
698 //===----------------------------------------------------------------------===//
699 // Helpers for working with extended types.
701 /// Dependent variable map for CodeGenDAGPattern variant generation
702 typedef std::map<std::string, int> DepVarMap;
704 /// Const iterator shorthand for DepVarMap
705 typedef DepVarMap::const_iterator DepVarMap_citer;
707 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
709 if (isa<DefInit>(N->getLeafValue()))
710 DepMap[N->getName()]++;
712 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
713 FindDepVarsOf(N->getChild(i), DepMap);
717 /// Find dependent variables within child patterns
718 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
720 FindDepVarsOf(N, depcounts);
721 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
722 if (i->second > 1) // std::pair<std::string, int>
723 DepVars.insert(i->first);
728 /// Dump the dependent variable set:
729 static void DumpDepVars(MultipleUseVarSet &DepVars) {
730 if (DepVars.empty()) {
731 DEBUG(errs() << "<empty set>");
733 DEBUG(errs() << "[ ");
734 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
735 e = DepVars.end(); i != e; ++i) {
736 DEBUG(errs() << (*i) << " ");
738 DEBUG(errs() << "]");
744 //===----------------------------------------------------------------------===//
745 // TreePredicateFn Implementation
746 //===----------------------------------------------------------------------===//
748 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
749 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
750 assert((getPredCode().empty() || getImmCode().empty()) &&
751 ".td file corrupt: can't have a node predicate *and* an imm predicate");
754 std::string TreePredicateFn::getPredCode() const {
755 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
758 std::string TreePredicateFn::getImmCode() const {
759 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
763 /// isAlwaysTrue - Return true if this is a noop predicate.
764 bool TreePredicateFn::isAlwaysTrue() const {
765 return getPredCode().empty() && getImmCode().empty();
768 /// Return the name to use in the generated code to reference this, this is
769 /// "Predicate_foo" if from a pattern fragment "foo".
770 std::string TreePredicateFn::getFnName() const {
771 return "Predicate_" + PatFragRec->getRecord()->getName();
774 /// getCodeToRunOnSDNode - Return the code for the function body that
775 /// evaluates this predicate. The argument is expected to be in "Node",
776 /// not N. This handles casting and conversion to a concrete node type as
778 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
779 // Handle immediate predicates first.
780 std::string ImmCode = getImmCode();
781 if (!ImmCode.empty()) {
783 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
784 return Result + ImmCode;
787 // Handle arbitrary node predicates.
788 assert(!getPredCode().empty() && "Don't have any predicate code!");
789 std::string ClassName;
790 if (PatFragRec->getOnlyTree()->isLeaf())
791 ClassName = "SDNode";
793 Record *Op = PatFragRec->getOnlyTree()->getOperator();
794 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
797 if (ClassName == "SDNode")
798 Result = " SDNode *N = Node;\n";
800 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
802 return Result + getPredCode();
805 //===----------------------------------------------------------------------===//
806 // PatternToMatch implementation
810 /// getPatternSize - Return the 'size' of this pattern. We want to match large
811 /// patterns before small ones. This is used to determine the size of a
813 static unsigned getPatternSize(const TreePatternNode *P,
814 const CodeGenDAGPatterns &CGP) {
815 unsigned Size = 3; // The node itself.
816 // If the root node is a ConstantSDNode, increases its size.
817 // e.g. (set R32:$dst, 0).
818 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
821 // FIXME: This is a hack to statically increase the priority of patterns
822 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
823 // Later we can allow complexity / cost for each pattern to be (optionally)
824 // specified. To get best possible pattern match we'll need to dynamically
825 // calculate the complexity of all patterns a dag can potentially map to.
826 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
828 Size += AM->getNumOperands() * 3;
830 // We don't want to count any children twice, so return early.
834 // If this node has some predicate function that must match, it adds to the
835 // complexity of this node.
836 if (!P->getPredicateFns().empty())
839 // Count children in the count if they are also nodes.
840 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
841 TreePatternNode *Child = P->getChild(i);
842 if (!Child->isLeaf() && Child->getNumTypes() &&
843 Child->getType(0) != MVT::Other)
844 Size += getPatternSize(Child, CGP);
845 else if (Child->isLeaf()) {
846 if (isa<IntInit>(Child->getLeafValue()))
847 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
848 else if (Child->getComplexPatternInfo(CGP))
849 Size += getPatternSize(Child, CGP);
850 else if (!Child->getPredicateFns().empty())
858 /// Compute the complexity metric for the input pattern. This roughly
859 /// corresponds to the number of nodes that are covered.
861 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
862 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
866 /// getPredicateCheck - Return a single string containing all of this
867 /// pattern's predicates concatenated with "&&" operators.
869 std::string PatternToMatch::getPredicateCheck() const {
870 std::string PredicateCheck;
871 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
872 if (DefInit *Pred = dyn_cast<DefInit>(Predicates->getElement(i))) {
873 Record *Def = Pred->getDef();
874 if (!Def->isSubClassOf("Predicate")) {
878 llvm_unreachable("Unknown predicate type!");
880 if (!PredicateCheck.empty())
881 PredicateCheck += " && ";
882 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
886 return PredicateCheck;
889 //===----------------------------------------------------------------------===//
890 // SDTypeConstraint implementation
893 SDTypeConstraint::SDTypeConstraint(Record *R) {
894 OperandNo = R->getValueAsInt("OperandNum");
896 if (R->isSubClassOf("SDTCisVT")) {
897 ConstraintType = SDTCisVT;
898 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
899 if (x.SDTCisVT_Info.VT == MVT::isVoid)
900 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
902 } else if (R->isSubClassOf("SDTCisPtrTy")) {
903 ConstraintType = SDTCisPtrTy;
904 } else if (R->isSubClassOf("SDTCisInt")) {
905 ConstraintType = SDTCisInt;
906 } else if (R->isSubClassOf("SDTCisFP")) {
907 ConstraintType = SDTCisFP;
908 } else if (R->isSubClassOf("SDTCisVec")) {
909 ConstraintType = SDTCisVec;
910 } else if (R->isSubClassOf("SDTCisSameAs")) {
911 ConstraintType = SDTCisSameAs;
912 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
913 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
914 ConstraintType = SDTCisVTSmallerThanOp;
915 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
916 R->getValueAsInt("OtherOperandNum");
917 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
918 ConstraintType = SDTCisOpSmallerThanOp;
919 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
920 R->getValueAsInt("BigOperandNum");
921 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
922 ConstraintType = SDTCisEltOfVec;
923 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
924 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
925 ConstraintType = SDTCisSubVecOfVec;
926 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
927 R->getValueAsInt("OtherOpNum");
928 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
929 ConstraintType = SDTCVecEltisVT;
930 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
931 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
932 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
933 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
934 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
935 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
936 "as SDTCVecEltisVT");
937 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
938 ConstraintType = SDTCisSameNumEltsAs;
939 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
940 R->getValueAsInt("OtherOperandNum");
942 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
947 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
948 /// N, and the result number in ResNo.
949 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
950 const SDNodeInfo &NodeInfo,
952 unsigned NumResults = NodeInfo.getNumResults();
953 if (OpNo < NumResults) {
960 if (OpNo >= N->getNumChildren()) {
961 errs() << "Invalid operand number in type constraint "
962 << (OpNo+NumResults) << " ";
968 return N->getChild(OpNo);
971 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
972 /// constraint to the nodes operands. This returns true if it makes a
973 /// change, false otherwise. If a type contradiction is found, flag an error.
974 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
975 const SDNodeInfo &NodeInfo,
976 TreePattern &TP) const {
980 unsigned ResNo = 0; // The result number being referenced.
981 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
983 switch (ConstraintType) {
985 // Operand must be a particular type.
986 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
988 // Operand must be same as target pointer type.
989 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
991 // Require it to be one of the legal integer VTs.
992 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
994 // Require it to be one of the legal fp VTs.
995 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
997 // Require it to be one of the legal vector VTs.
998 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
1000 unsigned OResNo = 0;
1001 TreePatternNode *OtherNode =
1002 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
1003 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1004 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
1006 case SDTCisVTSmallerThanOp: {
1007 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1008 // have an integer type that is smaller than the VT.
1009 if (!NodeToApply->isLeaf() ||
1010 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1011 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
1012 ->isSubClassOf("ValueType")) {
1013 TP.error(N->getOperator()->getName() + " expects a VT operand!");
1016 MVT::SimpleValueType VT =
1017 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
1019 EEVT::TypeSet TypeListTmp(VT, TP);
1021 unsigned OResNo = 0;
1022 TreePatternNode *OtherNode =
1023 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1026 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
1028 case SDTCisOpSmallerThanOp: {
1029 unsigned BResNo = 0;
1030 TreePatternNode *BigOperand =
1031 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1033 return NodeToApply->getExtType(ResNo).
1034 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
1036 case SDTCisEltOfVec: {
1037 unsigned VResNo = 0;
1038 TreePatternNode *VecOperand =
1039 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1042 // Filter vector types out of VecOperand that don't have the right element
1044 return VecOperand->getExtType(VResNo).
1045 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
1047 case SDTCisSubVecOfVec: {
1048 unsigned VResNo = 0;
1049 TreePatternNode *BigVecOperand =
1050 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1053 // Filter vector types out of BigVecOperand that don't have the
1054 // right subvector type.
1055 return BigVecOperand->getExtType(VResNo).
1056 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1058 case SDTCVecEltisVT: {
1059 return NodeToApply->getExtType(ResNo).
1060 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1062 case SDTCisSameNumEltsAs: {
1063 unsigned OResNo = 0;
1064 TreePatternNode *OtherNode =
1065 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1066 N, NodeInfo, OResNo);
1067 return OtherNode->getExtType(OResNo).
1068 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1071 llvm_unreachable("Invalid ConstraintType!");
1074 // Update the node type to match an instruction operand or result as specified
1075 // in the ins or outs lists on the instruction definition. Return true if the
1076 // type was actually changed.
1077 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1080 // The 'unknown' operand indicates that types should be inferred from the
1082 if (Operand->isSubClassOf("unknown_class"))
1085 // The Operand class specifies a type directly.
1086 if (Operand->isSubClassOf("Operand"))
1087 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1090 // PointerLikeRegClass has a type that is determined at runtime.
1091 if (Operand->isSubClassOf("PointerLikeRegClass"))
1092 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1094 // Both RegisterClass and RegisterOperand operands derive their types from a
1095 // register class def.
1096 Record *RC = nullptr;
1097 if (Operand->isSubClassOf("RegisterClass"))
1099 else if (Operand->isSubClassOf("RegisterOperand"))
1100 RC = Operand->getValueAsDef("RegClass");
1102 assert(RC && "Unknown operand type");
1103 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1104 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1108 //===----------------------------------------------------------------------===//
1109 // SDNodeInfo implementation
1111 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1112 EnumName = R->getValueAsString("Opcode");
1113 SDClassName = R->getValueAsString("SDClass");
1114 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1115 NumResults = TypeProfile->getValueAsInt("NumResults");
1116 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1118 // Parse the properties.
1120 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
1121 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
1122 if (PropList[i]->getName() == "SDNPCommutative") {
1123 Properties |= 1 << SDNPCommutative;
1124 } else if (PropList[i]->getName() == "SDNPAssociative") {
1125 Properties |= 1 << SDNPAssociative;
1126 } else if (PropList[i]->getName() == "SDNPHasChain") {
1127 Properties |= 1 << SDNPHasChain;
1128 } else if (PropList[i]->getName() == "SDNPOutGlue") {
1129 Properties |= 1 << SDNPOutGlue;
1130 } else if (PropList[i]->getName() == "SDNPInGlue") {
1131 Properties |= 1 << SDNPInGlue;
1132 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
1133 Properties |= 1 << SDNPOptInGlue;
1134 } else if (PropList[i]->getName() == "SDNPMayStore") {
1135 Properties |= 1 << SDNPMayStore;
1136 } else if (PropList[i]->getName() == "SDNPMayLoad") {
1137 Properties |= 1 << SDNPMayLoad;
1138 } else if (PropList[i]->getName() == "SDNPSideEffect") {
1139 Properties |= 1 << SDNPSideEffect;
1140 } else if (PropList[i]->getName() == "SDNPMemOperand") {
1141 Properties |= 1 << SDNPMemOperand;
1142 } else if (PropList[i]->getName() == "SDNPVariadic") {
1143 Properties |= 1 << SDNPVariadic;
1145 errs() << "Unknown SD Node property '" << PropList[i]->getName()
1146 << "' on node '" << R->getName() << "'!\n";
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 (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
1168 // Make sure that this applies to the correct node result.
1169 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
1172 switch (TypeConstraints[i].ConstraintType) {
1174 case SDTypeConstraint::SDTCisVT:
1175 return TypeConstraints[i].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 // FIXME: Should allow access to all the results here.
1226 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
1228 // Add on one implicit def if it has a resolvable type.
1229 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1231 return NumDefsToAdd;
1234 if (Operator->isSubClassOf("SDNodeXForm"))
1235 return 1; // FIXME: Generalize SDNodeXForm
1237 if (Operator->isSubClassOf("ValueType"))
1238 return 1; // A type-cast of one result.
1240 if (Operator->isSubClassOf("ComplexPattern"))
1244 errs() << "Unhandled node in GetNumNodeResults\n";
1248 void TreePatternNode::print(raw_ostream &OS) const {
1250 OS << *getLeafValue();
1252 OS << '(' << getOperator()->getName();
1254 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1255 OS << ':' << getExtType(i).getName();
1258 if (getNumChildren() != 0) {
1260 getChild(0)->print(OS);
1261 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1263 getChild(i)->print(OS);
1269 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
1270 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
1272 OS << "<<X:" << TransformFn->getName() << ">>";
1273 if (!getName().empty())
1274 OS << ":$" << getName();
1277 void TreePatternNode::dump() const {
1281 /// isIsomorphicTo - Return true if this node is recursively
1282 /// isomorphic to the specified node. For this comparison, the node's
1283 /// entire state is considered. The assigned name is ignored, since
1284 /// nodes with differing names are considered isomorphic. However, if
1285 /// the assigned name is present in the dependent variable set, then
1286 /// the assigned name is considered significant and the node is
1287 /// isomorphic if the names match.
1288 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1289 const MultipleUseVarSet &DepVars) const {
1290 if (N == this) return true;
1291 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1292 getPredicateFns() != N->getPredicateFns() ||
1293 getTransformFn() != N->getTransformFn())
1297 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1298 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1299 return ((DI->getDef() == NDI->getDef())
1300 && (DepVars.find(getName()) == DepVars.end()
1301 || getName() == N->getName()));
1304 return getLeafValue() == N->getLeafValue();
1307 if (N->getOperator() != getOperator() ||
1308 N->getNumChildren() != getNumChildren()) return false;
1309 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1310 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1315 /// clone - Make a copy of this tree and all of its children.
1317 TreePatternNode *TreePatternNode::clone() const {
1318 TreePatternNode *New;
1320 New = new TreePatternNode(getLeafValue(), getNumTypes());
1322 std::vector<TreePatternNode*> CChildren;
1323 CChildren.reserve(Children.size());
1324 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1325 CChildren.push_back(getChild(i)->clone());
1326 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1328 New->setName(getName());
1330 New->setPredicateFns(getPredicateFns());
1331 New->setTransformFn(getTransformFn());
1335 /// RemoveAllTypes - Recursively strip all the types of this tree.
1336 void TreePatternNode::RemoveAllTypes() {
1337 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1338 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
1339 if (isLeaf()) return;
1340 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1341 getChild(i)->RemoveAllTypes();
1345 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1346 /// with actual values specified by ArgMap.
1347 void TreePatternNode::
1348 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1349 if (isLeaf()) return;
1351 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1352 TreePatternNode *Child = getChild(i);
1353 if (Child->isLeaf()) {
1354 Init *Val = Child->getLeafValue();
1355 // Note that, when substituting into an output pattern, Val might be an
1357 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1358 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1359 // We found a use of a formal argument, replace it with its value.
1360 TreePatternNode *NewChild = ArgMap[Child->getName()];
1361 assert(NewChild && "Couldn't find formal argument!");
1362 assert((Child->getPredicateFns().empty() ||
1363 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1364 "Non-empty child predicate clobbered!");
1365 setChild(i, NewChild);
1368 getChild(i)->SubstituteFormalArguments(ArgMap);
1374 /// InlinePatternFragments - If this pattern refers to any pattern
1375 /// fragments, inline them into place, giving us a pattern without any
1376 /// PatFrag references.
1377 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1382 return this; // nothing to do.
1383 Record *Op = getOperator();
1385 if (!Op->isSubClassOf("PatFrag")) {
1386 // Just recursively inline children nodes.
1387 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1388 TreePatternNode *Child = getChild(i);
1389 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1391 assert((Child->getPredicateFns().empty() ||
1392 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1393 "Non-empty child predicate clobbered!");
1395 setChild(i, NewChild);
1400 // Otherwise, we found a reference to a fragment. First, look up its
1401 // TreePattern record.
1402 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1404 // Verify that we are passing the right number of operands.
1405 if (Frag->getNumArgs() != Children.size()) {
1406 TP.error("'" + Op->getName() + "' fragment requires " +
1407 utostr(Frag->getNumArgs()) + " operands!");
1411 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1413 TreePredicateFn PredFn(Frag);
1414 if (!PredFn.isAlwaysTrue())
1415 FragTree->addPredicateFn(PredFn);
1417 // Resolve formal arguments to their actual value.
1418 if (Frag->getNumArgs()) {
1419 // Compute the map of formal to actual arguments.
1420 std::map<std::string, TreePatternNode*> ArgMap;
1421 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1422 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1424 FragTree->SubstituteFormalArguments(ArgMap);
1427 FragTree->setName(getName());
1428 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1429 FragTree->UpdateNodeType(i, getExtType(i), TP);
1431 // Transfer in the old predicates.
1432 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1433 FragTree->addPredicateFn(getPredicateFns()[i]);
1435 // Get a new copy of this fragment to stitch into here.
1436 //delete this; // FIXME: implement refcounting!
1438 // The fragment we inlined could have recursive inlining that is needed. See
1439 // if there are any pattern fragments in it and inline them as needed.
1440 return FragTree->InlinePatternFragments(TP);
1443 /// getImplicitType - Check to see if the specified record has an implicit
1444 /// type which should be applied to it. This will infer the type of register
1445 /// references from the register file information, for example.
1447 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1448 /// the F8RC register class argument in:
1450 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
1452 /// When Unnamed is false, return the type of a named DAG operand such as the
1453 /// GPR:$src operand above.
1455 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1459 // Check to see if this is a register operand.
1460 if (R->isSubClassOf("RegisterOperand")) {
1461 assert(ResNo == 0 && "Regoperand ref only has one result!");
1463 return EEVT::TypeSet(); // Unknown.
1464 Record *RegClass = R->getValueAsDef("RegClass");
1465 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1466 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1469 // Check to see if this is a register or a register class.
1470 if (R->isSubClassOf("RegisterClass")) {
1471 assert(ResNo == 0 && "Regclass ref only has one result!");
1472 // An unnamed register class represents itself as an i32 immediate, for
1473 // example on a COPY_TO_REGCLASS instruction.
1475 return EEVT::TypeSet(MVT::i32, TP);
1477 // In a named operand, the register class provides the possible set of
1480 return EEVT::TypeSet(); // Unknown.
1481 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1482 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1485 if (R->isSubClassOf("PatFrag")) {
1486 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1487 // Pattern fragment types will be resolved when they are inlined.
1488 return EEVT::TypeSet(); // Unknown.
1491 if (R->isSubClassOf("Register")) {
1492 assert(ResNo == 0 && "Registers only produce one result!");
1494 return EEVT::TypeSet(); // Unknown.
1495 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1496 return EEVT::TypeSet(T.getRegisterVTs(R));
1499 if (R->isSubClassOf("SubRegIndex")) {
1500 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1501 return EEVT::TypeSet(MVT::i32, TP);
1504 if (R->isSubClassOf("ValueType")) {
1505 assert(ResNo == 0 && "This node only has one result!");
1506 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1508 // (sext_inreg GPR:$src, i16)
1511 return EEVT::TypeSet(MVT::Other, TP);
1512 // With a name, the ValueType simply provides the type of the named
1515 // (sext_inreg i32:$src, i16)
1518 return EEVT::TypeSet(); // Unknown.
1519 return EEVT::TypeSet(getValueType(R), TP);
1522 if (R->isSubClassOf("CondCode")) {
1523 assert(ResNo == 0 && "This node only has one result!");
1524 // Using a CondCodeSDNode.
1525 return EEVT::TypeSet(MVT::Other, TP);
1528 if (R->isSubClassOf("ComplexPattern")) {
1529 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1531 return EEVT::TypeSet(); // Unknown.
1532 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1535 if (R->isSubClassOf("PointerLikeRegClass")) {
1536 assert(ResNo == 0 && "Regclass can only have one result!");
1537 return EEVT::TypeSet(MVT::iPTR, TP);
1540 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1541 R->getName() == "zero_reg") {
1543 return EEVT::TypeSet(); // Unknown.
1546 if (R->isSubClassOf("Operand"))
1547 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1549 TP.error("Unknown node flavor used in pattern: " + R->getName());
1550 return EEVT::TypeSet(MVT::Other, TP);
1554 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1555 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1556 const CodeGenIntrinsic *TreePatternNode::
1557 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1558 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1559 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1560 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1563 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
1564 return &CDP.getIntrinsicInfo(IID);
1567 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1568 /// return the ComplexPattern information, otherwise return null.
1569 const ComplexPattern *
1570 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1573 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1578 Rec = getOperator();
1580 if (!Rec->isSubClassOf("ComplexPattern"))
1582 return &CGP.getComplexPattern(Rec);
1585 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1586 // A ComplexPattern specifically declares how many results it fills in.
1587 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1588 return CP->getNumOperands();
1590 // If MIOperandInfo is specified, that gives the count.
1592 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1593 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1594 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1595 if (MIOps->getNumArgs())
1596 return MIOps->getNumArgs();
1600 // Otherwise there is just one result.
1604 /// NodeHasProperty - Return true if this node has the specified property.
1605 bool TreePatternNode::NodeHasProperty(SDNP Property,
1606 const CodeGenDAGPatterns &CGP) const {
1608 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1609 return CP->hasProperty(Property);
1613 Record *Operator = getOperator();
1614 if (!Operator->isSubClassOf("SDNode")) return false;
1616 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1622 /// TreeHasProperty - Return true if any node in this tree has the specified
1624 bool TreePatternNode::TreeHasProperty(SDNP Property,
1625 const CodeGenDAGPatterns &CGP) const {
1626 if (NodeHasProperty(Property, CGP))
1628 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1629 if (getChild(i)->TreeHasProperty(Property, CGP))
1634 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1635 /// commutative intrinsic.
1637 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1638 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1639 return Int->isCommutative;
1643 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1645 return N->getOperator()->isSubClassOf(Class);
1647 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1648 if (DI && DI->getDef()->isSubClassOf(Class))
1654 static void emitTooManyOperandsError(TreePattern &TP,
1658 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1659 " operands but expected only " + Twine(Expected) + "!");
1662 static void emitTooFewOperandsError(TreePattern &TP,
1665 TP.error("Instruction '" + InstName +
1666 "' expects more than the provided " + Twine(Actual) + " operands!");
1669 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1670 /// this node and its children in the tree. This returns true if it makes a
1671 /// change, false otherwise. If a type contradiction is found, flag an error.
1672 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1676 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1678 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1679 // If it's a regclass or something else known, include the type.
1680 bool MadeChange = false;
1681 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1682 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1684 !hasName(), TP), TP);
1688 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
1689 assert(Types.size() == 1 && "Invalid IntInit");
1691 // Int inits are always integers. :)
1692 bool MadeChange = Types[0].EnforceInteger(TP);
1694 if (!Types[0].isConcrete())
1697 MVT::SimpleValueType VT = getType(0);
1698 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1701 unsigned Size = MVT(VT).getSizeInBits();
1702 // Make sure that the value is representable for this type.
1703 if (Size >= 32) return MadeChange;
1705 // Check that the value doesn't use more bits than we have. It must either
1706 // be a sign- or zero-extended equivalent of the original.
1707 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1708 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1711 TP.error("Integer value '" + itostr(II->getValue()) +
1712 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1718 // special handling for set, which isn't really an SDNode.
1719 if (getOperator()->getName() == "set") {
1720 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1721 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1722 unsigned NC = getNumChildren();
1724 TreePatternNode *SetVal = getChild(NC-1);
1725 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1727 for (unsigned i = 0; i < NC-1; ++i) {
1728 TreePatternNode *Child = getChild(i);
1729 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1731 // Types of operands must match.
1732 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1733 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1738 if (getOperator()->getName() == "implicit") {
1739 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1741 bool MadeChange = false;
1742 for (unsigned i = 0; i < getNumChildren(); ++i)
1743 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1747 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1748 bool MadeChange = false;
1750 // Apply the result type to the node.
1751 unsigned NumRetVTs = Int->IS.RetVTs.size();
1752 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1754 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1755 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1757 if (getNumChildren() != NumParamVTs + 1) {
1758 TP.error("Intrinsic '" + Int->Name + "' expects " +
1759 utostr(NumParamVTs) + " operands, not " +
1760 utostr(getNumChildren() - 1) + " operands!");
1764 // Apply type info to the intrinsic ID.
1765 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1767 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1768 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1770 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1771 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1772 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1777 if (getOperator()->isSubClassOf("SDNode")) {
1778 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1780 // Check that the number of operands is sane. Negative operands -> varargs.
1781 if (NI.getNumOperands() >= 0 &&
1782 getNumChildren() != (unsigned)NI.getNumOperands()) {
1783 TP.error(getOperator()->getName() + " node requires exactly " +
1784 itostr(NI.getNumOperands()) + " operands!");
1788 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1789 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1790 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1794 if (getOperator()->isSubClassOf("Instruction")) {
1795 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1796 CodeGenInstruction &InstInfo =
1797 CDP.getTargetInfo().getInstruction(getOperator());
1799 bool MadeChange = false;
1801 // Apply the result types to the node, these come from the things in the
1802 // (outs) list of the instruction.
1803 // FIXME: Cap at one result so far.
1804 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
1805 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1806 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
1808 // If the instruction has implicit defs, we apply the first one as a result.
1809 // FIXME: This sucks, it should apply all implicit defs.
1810 if (!InstInfo.ImplicitDefs.empty()) {
1811 unsigned ResNo = NumResultsToAdd;
1813 // FIXME: Generalize to multiple possible types and multiple possible
1815 MVT::SimpleValueType VT =
1816 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1818 if (VT != MVT::Other)
1819 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1822 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1824 if (getOperator()->getName() == "INSERT_SUBREG") {
1825 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1826 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1827 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1828 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1829 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1832 unsigned NChild = getNumChildren();
1834 TP.error("REG_SEQUENCE requires at least 3 operands!");
1838 if (NChild % 2 == 0) {
1839 TP.error("REG_SEQUENCE requires an odd number of operands!");
1843 if (!isOperandClass(getChild(0), "RegisterClass")) {
1844 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1848 for (unsigned I = 1; I < NChild; I += 2) {
1849 TreePatternNode *SubIdxChild = getChild(I + 1);
1850 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1851 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1852 itostr(I + 1) + "!");
1858 unsigned ChildNo = 0;
1859 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1860 Record *OperandNode = Inst.getOperand(i);
1862 // If the instruction expects a predicate or optional def operand, we
1863 // codegen this by setting the operand to it's default value if it has a
1864 // non-empty DefaultOps field.
1865 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1866 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1869 // Verify that we didn't run out of provided operands.
1870 if (ChildNo >= getNumChildren()) {
1871 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
1875 TreePatternNode *Child = getChild(ChildNo++);
1876 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1878 // If the operand has sub-operands, they may be provided by distinct
1879 // child patterns, so attempt to match each sub-operand separately.
1880 if (OperandNode->isSubClassOf("Operand")) {
1881 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1882 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1883 // But don't do that if the whole operand is being provided by
1884 // a single ComplexPattern-related Operand.
1886 if (Child->getNumMIResults(CDP) < NumArgs) {
1887 // Match first sub-operand against the child we already have.
1888 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1890 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1892 // And the remaining sub-operands against subsequent children.
1893 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1894 if (ChildNo >= getNumChildren()) {
1895 emitTooFewOperandsError(TP, getOperator()->getName(),
1899 Child = getChild(ChildNo++);
1901 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1903 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1910 // If we didn't match by pieces above, attempt to match the whole
1912 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
1915 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
1916 emitTooManyOperandsError(TP, getOperator()->getName(),
1917 ChildNo, getNumChildren());
1921 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1922 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1926 if (getOperator()->isSubClassOf("ComplexPattern")) {
1927 bool MadeChange = false;
1929 for (unsigned i = 0; i < getNumChildren(); ++i)
1930 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1935 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1937 // Node transforms always take one operand.
1938 if (getNumChildren() != 1) {
1939 TP.error("Node transform '" + getOperator()->getName() +
1940 "' requires one operand!");
1944 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1947 // If either the output or input of the xform does not have exact
1948 // type info. We assume they must be the same. Otherwise, it is perfectly
1949 // legal to transform from one type to a completely different type.
1951 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1952 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1953 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1960 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1961 /// RHS of a commutative operation, not the on LHS.
1962 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1963 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1965 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
1971 /// canPatternMatch - If it is impossible for this pattern to match on this
1972 /// target, fill in Reason and return false. Otherwise, return true. This is
1973 /// used as a sanity check for .td files (to prevent people from writing stuff
1974 /// that can never possibly work), and to prevent the pattern permuter from
1975 /// generating stuff that is useless.
1976 bool TreePatternNode::canPatternMatch(std::string &Reason,
1977 const CodeGenDAGPatterns &CDP) {
1978 if (isLeaf()) return true;
1980 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1981 if (!getChild(i)->canPatternMatch(Reason, CDP))
1984 // If this is an intrinsic, handle cases that would make it not match. For
1985 // example, if an operand is required to be an immediate.
1986 if (getOperator()->isSubClassOf("Intrinsic")) {
1991 if (getOperator()->isSubClassOf("ComplexPattern"))
1994 // If this node is a commutative operator, check that the LHS isn't an
1996 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1997 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1998 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1999 // Scan all of the operands of the node and make sure that only the last one
2000 // is a constant node, unless the RHS also is.
2001 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
2002 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2003 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
2004 if (OnlyOnRHSOfCommutative(getChild(i))) {
2005 Reason="Immediate value must be on the RHS of commutative operators!";
2014 //===----------------------------------------------------------------------===//
2015 // TreePattern implementation
2018 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
2019 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2020 isInputPattern(isInput), HasError(false) {
2021 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
2022 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
2025 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
2026 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2027 isInputPattern(isInput), HasError(false) {
2028 Trees.push_back(ParseTreePattern(Pat, ""));
2031 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
2032 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2033 isInputPattern(isInput), HasError(false) {
2034 Trees.push_back(Pat);
2037 void TreePattern::error(const Twine &Msg) {
2041 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2045 void TreePattern::ComputeNamedNodes() {
2046 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2047 ComputeNamedNodes(Trees[i]);
2050 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2051 if (!N->getName().empty())
2052 NamedNodes[N->getName()].push_back(N);
2054 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2055 ComputeNamedNodes(N->getChild(i));
2059 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2060 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2061 Record *R = DI->getDef();
2063 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2064 // TreePatternNode of its own. For example:
2065 /// (foo GPR, imm) -> (foo GPR, (imm))
2066 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2067 return ParseTreePattern(
2068 DagInit::get(DI, "",
2069 std::vector<std::pair<Init*, std::string> >()),
2073 TreePatternNode *Res = new TreePatternNode(DI, 1);
2074 if (R->getName() == "node" && !OpName.empty()) {
2076 error("'node' argument requires a name to match with operand list");
2077 Args.push_back(OpName);
2080 Res->setName(OpName);
2084 // ?:$name or just $name.
2085 if (TheInit == UnsetInit::get()) {
2087 error("'?' argument requires a name to match with operand list");
2088 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2089 Args.push_back(OpName);
2090 Res->setName(OpName);
2094 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2095 if (!OpName.empty())
2096 error("Constant int argument should not have a name!");
2097 return new TreePatternNode(II, 1);
2100 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2101 // Turn this into an IntInit.
2102 Init *II = BI->convertInitializerTo(IntRecTy::get());
2103 if (!II || !isa<IntInit>(II))
2104 error("Bits value must be constants!");
2105 return ParseTreePattern(II, OpName);
2108 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2111 error("Pattern has unexpected init kind!");
2113 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2114 if (!OpDef) error("Pattern has unexpected operator type!");
2115 Record *Operator = OpDef->getDef();
2117 if (Operator->isSubClassOf("ValueType")) {
2118 // If the operator is a ValueType, then this must be "type cast" of a leaf
2120 if (Dag->getNumArgs() != 1)
2121 error("Type cast only takes one operand!");
2123 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
2125 // Apply the type cast.
2126 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2127 New->UpdateNodeType(0, getValueType(Operator), *this);
2129 if (!OpName.empty())
2130 error("ValueType cast should not have a name!");
2134 // Verify that this is something that makes sense for an operator.
2135 if (!Operator->isSubClassOf("PatFrag") &&
2136 !Operator->isSubClassOf("SDNode") &&
2137 !Operator->isSubClassOf("Instruction") &&
2138 !Operator->isSubClassOf("SDNodeXForm") &&
2139 !Operator->isSubClassOf("Intrinsic") &&
2140 !Operator->isSubClassOf("ComplexPattern") &&
2141 Operator->getName() != "set" &&
2142 Operator->getName() != "implicit")
2143 error("Unrecognized node '" + Operator->getName() + "'!");
2145 // Check to see if this is something that is illegal in an input pattern.
2146 if (isInputPattern) {
2147 if (Operator->isSubClassOf("Instruction") ||
2148 Operator->isSubClassOf("SDNodeXForm"))
2149 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2151 if (Operator->isSubClassOf("Intrinsic"))
2152 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2154 if (Operator->isSubClassOf("SDNode") &&
2155 Operator->getName() != "imm" &&
2156 Operator->getName() != "fpimm" &&
2157 Operator->getName() != "tglobaltlsaddr" &&
2158 Operator->getName() != "tconstpool" &&
2159 Operator->getName() != "tjumptable" &&
2160 Operator->getName() != "tframeindex" &&
2161 Operator->getName() != "texternalsym" &&
2162 Operator->getName() != "tblockaddress" &&
2163 Operator->getName() != "tglobaladdr" &&
2164 Operator->getName() != "bb" &&
2165 Operator->getName() != "vt")
2166 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2169 std::vector<TreePatternNode*> Children;
2171 // Parse all the operands.
2172 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2173 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
2175 // If the operator is an intrinsic, then this is just syntactic sugar for for
2176 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2177 // convert the intrinsic name to a number.
2178 if (Operator->isSubClassOf("Intrinsic")) {
2179 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2180 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2182 // If this intrinsic returns void, it must have side-effects and thus a
2184 if (Int.IS.RetVTs.empty())
2185 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2186 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2187 // Has side-effects, requires chain.
2188 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2189 else // Otherwise, no chain.
2190 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2192 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2193 Children.insert(Children.begin(), IIDNode);
2196 if (Operator->isSubClassOf("ComplexPattern")) {
2197 for (unsigned i = 0; i < Children.size(); ++i) {
2198 TreePatternNode *Child = Children[i];
2200 if (Child->getName().empty())
2201 error("All arguments to a ComplexPattern must be named");
2203 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2204 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2205 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2206 auto OperandId = std::make_pair(Operator, i);
2207 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2208 if (PrevOp != ComplexPatternOperands.end()) {
2209 if (PrevOp->getValue() != OperandId)
2210 error("All ComplexPattern operands must appear consistently: "
2211 "in the same order in just one ComplexPattern instance.");
2213 ComplexPatternOperands[Child->getName()] = OperandId;
2217 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2218 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2219 Result->setName(OpName);
2221 if (!Dag->getName().empty()) {
2222 assert(Result->getName().empty());
2223 Result->setName(Dag->getName());
2228 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2229 /// will never match in favor of something obvious that will. This is here
2230 /// strictly as a convenience to target authors because it allows them to write
2231 /// more type generic things and have useless type casts fold away.
2233 /// This returns true if any change is made.
2234 static bool SimplifyTree(TreePatternNode *&N) {
2238 // If we have a bitconvert with a resolved type and if the source and
2239 // destination types are the same, then the bitconvert is useless, remove it.
2240 if (N->getOperator()->getName() == "bitconvert" &&
2241 N->getExtType(0).isConcrete() &&
2242 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2243 N->getName().empty()) {
2249 // Walk all children.
2250 bool MadeChange = false;
2251 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2252 TreePatternNode *Child = N->getChild(i);
2253 MadeChange |= SimplifyTree(Child);
2254 N->setChild(i, Child);
2261 /// InferAllTypes - Infer/propagate as many types throughout the expression
2262 /// patterns as possible. Return true if all types are inferred, false
2263 /// otherwise. Flags an error if a type contradiction is found.
2265 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2266 if (NamedNodes.empty())
2267 ComputeNamedNodes();
2269 bool MadeChange = true;
2270 while (MadeChange) {
2272 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2273 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
2274 MadeChange |= SimplifyTree(Trees[i]);
2277 // If there are constraints on our named nodes, apply them.
2278 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
2279 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
2280 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
2282 // If we have input named node types, propagate their types to the named
2285 if (!InNamedTypes->count(I->getKey())) {
2286 error("Node '" + std::string(I->getKey()) +
2287 "' in output pattern but not input pattern");
2291 const SmallVectorImpl<TreePatternNode*> &InNodes =
2292 InNamedTypes->find(I->getKey())->second;
2294 // The input types should be fully resolved by now.
2295 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2296 // If this node is a register class, and it is the root of the pattern
2297 // then we're mapping something onto an input register. We allow
2298 // changing the type of the input register in this case. This allows
2299 // us to match things like:
2300 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2301 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
2302 DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
2303 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2304 DI->getDef()->isSubClassOf("RegisterOperand")))
2308 assert(Nodes[i]->getNumTypes() == 1 &&
2309 InNodes[0]->getNumTypes() == 1 &&
2310 "FIXME: cannot name multiple result nodes yet");
2311 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
2316 // If there are multiple nodes with the same name, they must all have the
2318 if (I->second.size() > 1) {
2319 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2320 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2321 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2322 "FIXME: cannot name multiple result nodes yet");
2324 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2325 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2331 bool HasUnresolvedTypes = false;
2332 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2333 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
2334 return !HasUnresolvedTypes;
2337 void TreePattern::print(raw_ostream &OS) const {
2338 OS << getRecord()->getName();
2339 if (!Args.empty()) {
2340 OS << "(" << Args[0];
2341 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2342 OS << ", " << Args[i];
2347 if (Trees.size() > 1)
2349 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2351 Trees[i]->print(OS);
2355 if (Trees.size() > 1)
2359 void TreePattern::dump() const { print(errs()); }
2361 //===----------------------------------------------------------------------===//
2362 // CodeGenDAGPatterns implementation
2365 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2366 Records(R), Target(R) {
2368 Intrinsics = LoadIntrinsics(Records, false);
2369 TgtIntrinsics = LoadIntrinsics(Records, true);
2371 ParseNodeTransforms();
2372 ParseComplexPatterns();
2373 ParsePatternFragments();
2374 ParseDefaultOperands();
2375 ParseInstructions();
2376 ParsePatternFragments(/*OutFrags*/true);
2379 // Generate variants. For example, commutative patterns can match
2380 // multiple ways. Add them to PatternsToMatch as well.
2383 // Infer instruction flags. For example, we can detect loads,
2384 // stores, and side effects in many cases by examining an
2385 // instruction's pattern.
2386 InferInstructionFlags();
2388 // Verify that instruction flags match the patterns.
2389 VerifyInstructionFlags();
2392 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2393 Record *N = Records.getDef(Name);
2394 if (!N || !N->isSubClassOf("SDNode")) {
2395 errs() << "Error getting SDNode '" << Name << "'!\n";
2401 // Parse all of the SDNode definitions for the target, populating SDNodes.
2402 void CodeGenDAGPatterns::ParseNodeInfo() {
2403 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2404 while (!Nodes.empty()) {
2405 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2409 // Get the builtin intrinsic nodes.
2410 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2411 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2412 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2415 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2416 /// map, and emit them to the file as functions.
2417 void CodeGenDAGPatterns::ParseNodeTransforms() {
2418 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2419 while (!Xforms.empty()) {
2420 Record *XFormNode = Xforms.back();
2421 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2422 std::string Code = XFormNode->getValueAsString("XFormFunction");
2423 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2429 void CodeGenDAGPatterns::ParseComplexPatterns() {
2430 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2431 while (!AMs.empty()) {
2432 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2438 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2439 /// file, building up the PatternFragments map. After we've collected them all,
2440 /// inline fragments together as necessary, so that there are no references left
2441 /// inside a pattern fragment to a pattern fragment.
2443 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2444 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2446 // First step, parse all of the fragments.
2447 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2448 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2451 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
2453 (PatternFragments[Fragments[i]] = llvm::make_unique<TreePattern>(
2454 Fragments[i], Tree, !Fragments[i]->isSubClassOf("OutPatFrag"),
2457 // Validate the argument list, converting it to set, to discard duplicates.
2458 std::vector<std::string> &Args = P->getArgList();
2459 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2461 if (OperandsSet.count(""))
2462 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2464 // Parse the operands list.
2465 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
2466 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2467 // Special cases: ops == outs == ins. Different names are used to
2468 // improve readability.
2470 (OpsOp->getDef()->getName() != "ops" &&
2471 OpsOp->getDef()->getName() != "outs" &&
2472 OpsOp->getDef()->getName() != "ins"))
2473 P->error("Operands list should start with '(ops ... '!");
2475 // Copy over the arguments.
2477 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2478 if (!isa<DefInit>(OpsList->getArg(j)) ||
2479 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2480 P->error("Operands list should all be 'node' values.");
2481 if (OpsList->getArgName(j).empty())
2482 P->error("Operands list should have names for each operand!");
2483 if (!OperandsSet.count(OpsList->getArgName(j)))
2484 P->error("'" + OpsList->getArgName(j) +
2485 "' does not occur in pattern or was multiply specified!");
2486 OperandsSet.erase(OpsList->getArgName(j));
2487 Args.push_back(OpsList->getArgName(j));
2490 if (!OperandsSet.empty())
2491 P->error("Operands list does not contain an entry for operand '" +
2492 *OperandsSet.begin() + "'!");
2494 // If there is a code init for this fragment, keep track of the fact that
2495 // this fragment uses it.
2496 TreePredicateFn PredFn(P);
2497 if (!PredFn.isAlwaysTrue())
2498 P->getOnlyTree()->addPredicateFn(PredFn);
2500 // If there is a node transformation corresponding to this, keep track of
2502 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2503 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2504 P->getOnlyTree()->setTransformFn(Transform);
2507 // Now that we've parsed all of the tree fragments, do a closure on them so
2508 // that there are not references to PatFrags left inside of them.
2509 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2510 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2513 TreePattern &ThePat = *PatternFragments[Fragments[i]];
2514 ThePat.InlinePatternFragments();
2516 // Infer as many types as possible. Don't worry about it if we don't infer
2517 // all of them, some may depend on the inputs of the pattern.
2518 ThePat.InferAllTypes();
2519 ThePat.resetError();
2521 // If debugging, print out the pattern fragment result.
2522 DEBUG(ThePat.dump());
2526 void CodeGenDAGPatterns::ParseDefaultOperands() {
2527 std::vector<Record*> DefaultOps;
2528 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2530 // Find some SDNode.
2531 assert(!SDNodes.empty() && "No SDNodes parsed?");
2532 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2534 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2535 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
2537 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2538 // SomeSDnode so that we can parse this.
2539 std::vector<std::pair<Init*, std::string> > Ops;
2540 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2541 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2542 DefaultInfo->getArgName(op)));
2543 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
2545 // Create a TreePattern to parse this.
2546 TreePattern P(DefaultOps[i], DI, false, *this);
2547 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2549 // Copy the operands over into a DAGDefaultOperand.
2550 DAGDefaultOperand DefaultOpInfo;
2552 TreePatternNode *T = P.getTree(0);
2553 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2554 TreePatternNode *TPN = T->getChild(op);
2555 while (TPN->ApplyTypeConstraints(P, false))
2556 /* Resolve all types */;
2558 if (TPN->ContainsUnresolvedType()) {
2559 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2560 DefaultOps[i]->getName() +
2561 "' doesn't have a concrete type!");
2563 DefaultOpInfo.DefaultOps.push_back(TPN);
2566 // Insert it into the DefaultOperands map so we can find it later.
2567 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
2571 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2572 /// instruction input. Return true if this is a real use.
2573 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2574 std::map<std::string, TreePatternNode*> &InstInputs) {
2575 // No name -> not interesting.
2576 if (Pat->getName().empty()) {
2577 if (Pat->isLeaf()) {
2578 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2579 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2580 DI->getDef()->isSubClassOf("RegisterOperand")))
2581 I->error("Input " + DI->getDef()->getName() + " must be named!");
2587 if (Pat->isLeaf()) {
2588 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2589 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2592 Rec = Pat->getOperator();
2595 // SRCVALUE nodes are ignored.
2596 if (Rec->getName() == "srcvalue")
2599 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2605 if (Slot->isLeaf()) {
2606 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
2608 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2609 SlotRec = Slot->getOperator();
2612 // Ensure that the inputs agree if we've already seen this input.
2614 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2615 if (Slot->getExtTypes() != Pat->getExtTypes())
2616 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2620 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2621 /// part of "I", the instruction), computing the set of inputs and outputs of
2622 /// the pattern. Report errors if we see anything naughty.
2623 void CodeGenDAGPatterns::
2624 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2625 std::map<std::string, TreePatternNode*> &InstInputs,
2626 std::map<std::string, TreePatternNode*>&InstResults,
2627 std::vector<Record*> &InstImpResults) {
2628 if (Pat->isLeaf()) {
2629 bool isUse = HandleUse(I, Pat, InstInputs);
2630 if (!isUse && Pat->getTransformFn())
2631 I->error("Cannot specify a transform function for a non-input value!");
2635 if (Pat->getOperator()->getName() == "implicit") {
2636 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2637 TreePatternNode *Dest = Pat->getChild(i);
2638 if (!Dest->isLeaf())
2639 I->error("implicitly defined value should be a register!");
2641 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2642 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2643 I->error("implicitly defined value should be a register!");
2644 InstImpResults.push_back(Val->getDef());
2649 if (Pat->getOperator()->getName() != "set") {
2650 // If this is not a set, verify that the children nodes are not void typed,
2652 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2653 if (Pat->getChild(i)->getNumTypes() == 0)
2654 I->error("Cannot have void nodes inside of patterns!");
2655 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2659 // If this is a non-leaf node with no children, treat it basically as if
2660 // it were a leaf. This handles nodes like (imm).
2661 bool isUse = HandleUse(I, Pat, InstInputs);
2663 if (!isUse && Pat->getTransformFn())
2664 I->error("Cannot specify a transform function for a non-input value!");
2668 // Otherwise, this is a set, validate and collect instruction results.
2669 if (Pat->getNumChildren() == 0)
2670 I->error("set requires operands!");
2672 if (Pat->getTransformFn())
2673 I->error("Cannot specify a transform function on a set node!");
2675 // Check the set destinations.
2676 unsigned NumDests = Pat->getNumChildren()-1;
2677 for (unsigned i = 0; i != NumDests; ++i) {
2678 TreePatternNode *Dest = Pat->getChild(i);
2679 if (!Dest->isLeaf())
2680 I->error("set destination should be a register!");
2682 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2684 I->error("set destination should be a register!");
2688 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2689 Val->getDef()->isSubClassOf("ValueType") ||
2690 Val->getDef()->isSubClassOf("RegisterOperand") ||
2691 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2692 if (Dest->getName().empty())
2693 I->error("set destination must have a name!");
2694 if (InstResults.count(Dest->getName()))
2695 I->error("cannot set '" + Dest->getName() +"' multiple times");
2696 InstResults[Dest->getName()] = Dest;
2697 } else if (Val->getDef()->isSubClassOf("Register")) {
2698 InstImpResults.push_back(Val->getDef());
2700 I->error("set destination should be a register!");
2704 // Verify and collect info from the computation.
2705 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2706 InstInputs, InstResults, InstImpResults);
2709 //===----------------------------------------------------------------------===//
2710 // Instruction Analysis
2711 //===----------------------------------------------------------------------===//
2713 class InstAnalyzer {
2714 const CodeGenDAGPatterns &CDP;
2716 bool hasSideEffects;
2722 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2723 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2724 isBitcast(false), isVariadic(false) {}
2726 void Analyze(const TreePattern *Pat) {
2727 // Assume only the first tree is the pattern. The others are clobber nodes.
2728 AnalyzeNode(Pat->getTree(0));
2731 void Analyze(const PatternToMatch *Pat) {
2732 AnalyzeNode(Pat->getSrcPattern());
2736 bool IsNodeBitcast(const TreePatternNode *N) const {
2737 if (hasSideEffects || mayLoad || mayStore || isVariadic)
2740 if (N->getNumChildren() != 2)
2743 const TreePatternNode *N0 = N->getChild(0);
2744 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
2747 const TreePatternNode *N1 = N->getChild(1);
2750 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2753 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2754 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2756 return OpInfo.getEnumName() == "ISD::BITCAST";
2760 void AnalyzeNode(const TreePatternNode *N) {
2762 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
2763 Record *LeafRec = DI->getDef();
2764 // Handle ComplexPattern leaves.
2765 if (LeafRec->isSubClassOf("ComplexPattern")) {
2766 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2767 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2768 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2769 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2775 // Analyze children.
2776 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2777 AnalyzeNode(N->getChild(i));
2779 // Ignore set nodes, which are not SDNodes.
2780 if (N->getOperator()->getName() == "set") {
2781 isBitcast = IsNodeBitcast(N);
2785 // Notice properties of the node.
2786 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2787 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2788 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2789 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
2791 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2792 // If this is an intrinsic, analyze it.
2793 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2794 mayLoad = true;// These may load memory.
2796 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2797 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2799 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2800 // WriteMem intrinsics can have other strange effects.
2801 hasSideEffects = true;
2807 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2808 const InstAnalyzer &PatInfo,
2812 // Remember where InstInfo got its flags.
2813 if (InstInfo.hasUndefFlags())
2814 InstInfo.InferredFrom = PatDef;
2816 // Check explicitly set flags for consistency.
2817 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2818 !InstInfo.hasSideEffects_Unset) {
2819 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2820 // the pattern has no side effects. That could be useful for div/rem
2821 // instructions that may trap.
2822 if (!InstInfo.hasSideEffects) {
2824 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2825 Twine(InstInfo.hasSideEffects));
2829 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2831 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2832 Twine(InstInfo.mayStore));
2835 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2836 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2837 // Some targets translate imediates to loads.
2838 if (!InstInfo.mayLoad) {
2840 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2841 Twine(InstInfo.mayLoad));
2845 // Transfer inferred flags.
2846 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2847 InstInfo.mayStore |= PatInfo.mayStore;
2848 InstInfo.mayLoad |= PatInfo.mayLoad;
2850 // These flags are silently added without any verification.
2851 InstInfo.isBitcast |= PatInfo.isBitcast;
2853 // Don't infer isVariadic. This flag means something different on SDNodes and
2854 // instructions. For example, a CALL SDNode is variadic because it has the
2855 // call arguments as operands, but a CALL instruction is not variadic - it
2856 // has argument registers as implicit, not explicit uses.
2861 /// hasNullFragReference - Return true if the DAG has any reference to the
2862 /// null_frag operator.
2863 static bool hasNullFragReference(DagInit *DI) {
2864 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
2865 if (!OpDef) return false;
2866 Record *Operator = OpDef->getDef();
2868 // If this is the null fragment, return true.
2869 if (Operator->getName() == "null_frag") return true;
2870 // If any of the arguments reference the null fragment, return true.
2871 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2872 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
2873 if (Arg && hasNullFragReference(Arg))
2880 /// hasNullFragReference - Return true if any DAG in the list references
2881 /// the null_frag operator.
2882 static bool hasNullFragReference(ListInit *LI) {
2883 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
2884 DagInit *DI = dyn_cast<DagInit>(LI->getElement(i));
2885 assert(DI && "non-dag in an instruction Pattern list?!");
2886 if (hasNullFragReference(DI))
2892 /// Get all the instructions in a tree.
2894 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2897 if (Tree->getOperator()->isSubClassOf("Instruction"))
2898 Instrs.push_back(Tree->getOperator());
2899 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2900 getInstructionsInTree(Tree->getChild(i), Instrs);
2903 /// Check the class of a pattern leaf node against the instruction operand it
2905 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2910 // Allow direct value types to be used in instruction set patterns.
2911 // The type will be checked later.
2912 if (Leaf->isSubClassOf("ValueType"))
2915 // Patterns can also be ComplexPattern instances.
2916 if (Leaf->isSubClassOf("ComplexPattern"))
2922 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2923 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
2925 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
2927 // Parse the instruction.
2928 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2929 // Inline pattern fragments into it.
2930 I->InlinePatternFragments();
2932 // Infer as many types as possible. If we cannot infer all of them, we can
2933 // never do anything with this instruction pattern: report it to the user.
2934 if (!I->InferAllTypes())
2935 I->error("Could not infer all types in pattern!");
2937 // InstInputs - Keep track of all of the inputs of the instruction, along
2938 // with the record they are declared as.
2939 std::map<std::string, TreePatternNode*> InstInputs;
2941 // InstResults - Keep track of all the virtual registers that are 'set'
2942 // in the instruction, including what reg class they are.
2943 std::map<std::string, TreePatternNode*> InstResults;
2945 std::vector<Record*> InstImpResults;
2947 // Verify that the top-level forms in the instruction are of void type, and
2948 // fill in the InstResults map.
2949 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2950 TreePatternNode *Pat = I->getTree(j);
2951 if (Pat->getNumTypes() != 0)
2952 I->error("Top-level forms in instruction pattern should have"
2955 // Find inputs and outputs, and verify the structure of the uses/defs.
2956 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2960 // Now that we have inputs and outputs of the pattern, inspect the operands
2961 // list for the instruction. This determines the order that operands are
2962 // added to the machine instruction the node corresponds to.
2963 unsigned NumResults = InstResults.size();
2965 // Parse the operands list from the (ops) list, validating it.
2966 assert(I->getArgList().empty() && "Args list should still be empty here!");
2968 // Check that all of the results occur first in the list.
2969 std::vector<Record*> Results;
2970 TreePatternNode *Res0Node = nullptr;
2971 for (unsigned i = 0; i != NumResults; ++i) {
2972 if (i == CGI.Operands.size())
2973 I->error("'" + InstResults.begin()->first +
2974 "' set but does not appear in operand list!");
2975 const std::string &OpName = CGI.Operands[i].Name;
2977 // Check that it exists in InstResults.
2978 TreePatternNode *RNode = InstResults[OpName];
2980 I->error("Operand $" + OpName + " does not exist in operand list!");
2984 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2986 I->error("Operand $" + OpName + " should be a set destination: all "
2987 "outputs must occur before inputs in operand list!");
2989 if (!checkOperandClass(CGI.Operands[i], R))
2990 I->error("Operand $" + OpName + " class mismatch!");
2992 // Remember the return type.
2993 Results.push_back(CGI.Operands[i].Rec);
2995 // Okay, this one checks out.
2996 InstResults.erase(OpName);
2999 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3000 // the copy while we're checking the inputs.
3001 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3003 std::vector<TreePatternNode*> ResultNodeOperands;
3004 std::vector<Record*> Operands;
3005 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3006 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3007 const std::string &OpName = Op.Name;
3009 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3011 if (!InstInputsCheck.count(OpName)) {
3012 // If this is an operand with a DefaultOps set filled in, we can ignore
3013 // this. When we codegen it, we will do so as always executed.
3014 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3015 // Does it have a non-empty DefaultOps field? If so, ignore this
3017 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3020 I->error("Operand $" + OpName +
3021 " does not appear in the instruction pattern");
3023 TreePatternNode *InVal = InstInputsCheck[OpName];
3024 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3026 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3027 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3028 if (!checkOperandClass(Op, InRec))
3029 I->error("Operand $" + OpName + "'s register class disagrees"
3030 " between the operand and pattern");
3032 Operands.push_back(Op.Rec);
3034 // Construct the result for the dest-pattern operand list.
3035 TreePatternNode *OpNode = InVal->clone();
3037 // No predicate is useful on the result.
3038 OpNode->clearPredicateFns();
3040 // Promote the xform function to be an explicit node if set.
3041 if (Record *Xform = OpNode->getTransformFn()) {
3042 OpNode->setTransformFn(nullptr);
3043 std::vector<TreePatternNode*> Children;
3044 Children.push_back(OpNode);
3045 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3048 ResultNodeOperands.push_back(OpNode);
3051 if (!InstInputsCheck.empty())
3052 I->error("Input operand $" + InstInputsCheck.begin()->first +
3053 " occurs in pattern but not in operands list!");
3055 TreePatternNode *ResultPattern =
3056 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3057 GetNumNodeResults(I->getRecord(), *this));
3058 // Copy fully inferred output node type to instruction result pattern.
3059 for (unsigned i = 0; i != NumResults; ++i)
3060 ResultPattern->setType(i, Res0Node->getExtType(i));
3062 // Create and insert the instruction.
3063 // FIXME: InstImpResults should not be part of DAGInstruction.
3064 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3065 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3067 // Use a temporary tree pattern to infer all types and make sure that the
3068 // constructed result is correct. This depends on the instruction already
3069 // being inserted into the DAGInsts map.
3070 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3071 Temp.InferAllTypes(&I->getNamedNodesMap());
3073 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3074 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3076 return TheInsertedInst;
3079 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3080 /// any fragments involved. This populates the Instructions list with fully
3081 /// resolved instructions.
3082 void CodeGenDAGPatterns::ParseInstructions() {
3083 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3085 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3086 ListInit *LI = nullptr;
3088 if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
3089 LI = Instrs[i]->getValueAsListInit("Pattern");
3091 // If there is no pattern, only collect minimal information about the
3092 // instruction for its operand list. We have to assume that there is one
3093 // result, as we have no detailed info. A pattern which references the
3094 // null_frag operator is as-if no pattern were specified. Normally this
3095 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3097 if (!LI || LI->getSize() == 0 || hasNullFragReference(LI)) {
3098 std::vector<Record*> Results;
3099 std::vector<Record*> Operands;
3101 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3103 if (InstInfo.Operands.size() != 0) {
3104 if (InstInfo.Operands.NumDefs == 0) {
3105 // These produce no results
3106 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
3107 Operands.push_back(InstInfo.Operands[j].Rec);
3109 // Assume the first operand is the result.
3110 Results.push_back(InstInfo.Operands[0].Rec);
3112 // The rest are inputs.
3113 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
3114 Operands.push_back(InstInfo.Operands[j].Rec);
3118 // Create and insert the instruction.
3119 std::vector<Record*> ImpResults;
3120 Instructions.insert(std::make_pair(Instrs[i],
3121 DAGInstruction(nullptr, Results, Operands, ImpResults)));
3122 continue; // no pattern.
3125 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
3126 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3129 DEBUG(DI.getPattern()->dump());
3132 // If we can, convert the instructions to be patterns that are matched!
3133 for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
3134 Instructions.begin(),
3135 E = Instructions.end(); II != E; ++II) {
3136 DAGInstruction &TheInst = II->second;
3137 TreePattern *I = TheInst.getPattern();
3138 if (!I) continue; // No pattern.
3140 // FIXME: Assume only the first tree is the pattern. The others are clobber
3142 TreePatternNode *Pattern = I->getTree(0);
3143 TreePatternNode *SrcPattern;
3144 if (Pattern->getOperator()->getName() == "set") {
3145 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3147 // Not a set (store or something?)
3148 SrcPattern = Pattern;
3151 Record *Instr = II->first;
3152 AddPatternToMatch(I,
3153 PatternToMatch(Instr,
3154 Instr->getValueAsListInit("Predicates"),
3156 TheInst.getResultPattern(),
3157 TheInst.getImpResults(),
3158 Instr->getValueAsInt("AddedComplexity"),
3164 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3166 static void FindNames(const TreePatternNode *P,
3167 std::map<std::string, NameRecord> &Names,
3168 TreePattern *PatternTop) {
3169 if (!P->getName().empty()) {
3170 NameRecord &Rec = Names[P->getName()];
3171 // If this is the first instance of the name, remember the node.
3172 if (Rec.second++ == 0)
3174 else if (Rec.first->getExtTypes() != P->getExtTypes())
3175 PatternTop->error("repetition of value: $" + P->getName() +
3176 " where different uses have different types!");
3180 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3181 FindNames(P->getChild(i), Names, PatternTop);
3185 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3186 const PatternToMatch &PTM) {
3187 // Do some sanity checking on the pattern we're about to match.
3189 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3190 PrintWarning(Pattern->getRecord()->getLoc(),
3191 Twine("Pattern can never match: ") + Reason);
3195 // If the source pattern's root is a complex pattern, that complex pattern
3196 // must specify the nodes it can potentially match.
3197 if (const ComplexPattern *CP =
3198 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3199 if (CP->getRootNodes().empty())
3200 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3204 // Find all of the named values in the input and output, ensure they have the
3206 std::map<std::string, NameRecord> SrcNames, DstNames;
3207 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3208 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3210 // Scan all of the named values in the destination pattern, rejecting them if
3211 // they don't exist in the input pattern.
3212 for (std::map<std::string, NameRecord>::iterator
3213 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
3214 if (SrcNames[I->first].first == nullptr)
3215 Pattern->error("Pattern has input without matching name in output: $" +
3219 // Scan all of the named values in the source pattern, rejecting them if the
3220 // name isn't used in the dest, and isn't used to tie two values together.
3221 for (std::map<std::string, NameRecord>::iterator
3222 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
3223 if (DstNames[I->first].first == nullptr && SrcNames[I->first].second == 1)
3224 Pattern->error("Pattern has dead named input: $" + I->first);
3226 PatternsToMatch.push_back(PTM);
3231 void CodeGenDAGPatterns::InferInstructionFlags() {
3232 const std::vector<const CodeGenInstruction*> &Instructions =
3233 Target.getInstructionsByEnumValue();
3235 // First try to infer flags from the primary instruction pattern, if any.
3236 SmallVector<CodeGenInstruction*, 8> Revisit;
3237 unsigned Errors = 0;
3238 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3239 CodeGenInstruction &InstInfo =
3240 const_cast<CodeGenInstruction &>(*Instructions[i]);
3242 // Get the primary instruction pattern.
3243 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3245 if (InstInfo.hasUndefFlags())
3246 Revisit.push_back(&InstInfo);
3249 InstAnalyzer PatInfo(*this);
3250 PatInfo.Analyze(Pattern);
3251 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3254 // Second, look for single-instruction patterns defined outside the
3256 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3257 const PatternToMatch &PTM = *I;
3259 // We can only infer from single-instruction patterns, otherwise we won't
3260 // know which instruction should get the flags.
3261 SmallVector<Record*, 8> PatInstrs;
3262 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3263 if (PatInstrs.size() != 1)
3266 // Get the single instruction.
3267 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3269 // Only infer properties from the first pattern. We'll verify the others.
3270 if (InstInfo.InferredFrom)
3273 InstAnalyzer PatInfo(*this);
3274 PatInfo.Analyze(&PTM);
3275 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3279 PrintFatalError("pattern conflicts");
3281 // Revisit instructions with undefined flags and no pattern.
3282 if (Target.guessInstructionProperties()) {
3283 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3284 CodeGenInstruction &InstInfo = *Revisit[i];
3285 if (InstInfo.InferredFrom)
3287 // The mayLoad and mayStore flags default to false.
3288 // Conservatively assume hasSideEffects if it wasn't explicit.
3289 if (InstInfo.hasSideEffects_Unset)
3290 InstInfo.hasSideEffects = true;
3295 // Complain about any flags that are still undefined.
3296 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3297 CodeGenInstruction &InstInfo = *Revisit[i];
3298 if (InstInfo.InferredFrom)
3300 if (InstInfo.hasSideEffects_Unset)
3301 PrintError(InstInfo.TheDef->getLoc(),
3302 "Can't infer hasSideEffects from patterns");
3303 if (InstInfo.mayStore_Unset)
3304 PrintError(InstInfo.TheDef->getLoc(),
3305 "Can't infer mayStore from patterns");
3306 if (InstInfo.mayLoad_Unset)
3307 PrintError(InstInfo.TheDef->getLoc(),
3308 "Can't infer mayLoad from patterns");
3313 /// Verify instruction flags against pattern node properties.
3314 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3315 unsigned Errors = 0;
3316 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3317 const PatternToMatch &PTM = *I;
3318 SmallVector<Record*, 8> Instrs;
3319 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3323 // Count the number of instructions with each flag set.
3324 unsigned NumSideEffects = 0;
3325 unsigned NumStores = 0;
3326 unsigned NumLoads = 0;
3327 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3328 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3329 NumSideEffects += InstInfo.hasSideEffects;
3330 NumStores += InstInfo.mayStore;
3331 NumLoads += InstInfo.mayLoad;
3334 // Analyze the source pattern.
3335 InstAnalyzer PatInfo(*this);
3336 PatInfo.Analyze(&PTM);
3338 // Collect error messages.
3339 SmallVector<std::string, 4> Msgs;
3341 // Check for missing flags in the output.
3342 // Permit extra flags for now at least.
3343 if (PatInfo.hasSideEffects && !NumSideEffects)
3344 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3346 // Don't verify store flags on instructions with side effects. At least for
3347 // intrinsics, side effects implies mayStore.
3348 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3349 Msgs.push_back("pattern may store, but mayStore isn't set");
3351 // Similarly, mayStore implies mayLoad on intrinsics.
3352 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3353 Msgs.push_back("pattern may load, but mayLoad isn't set");
3355 // Print error messages.
3360 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
3361 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
3362 (Instrs.size() == 1 ?
3363 "instruction" : "output instructions"));
3364 // Provide the location of the relevant instruction definitions.
3365 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3366 if (Instrs[i] != PTM.getSrcRecord())
3367 PrintError(Instrs[i]->getLoc(), "defined here");
3368 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3369 if (InstInfo.InferredFrom &&
3370 InstInfo.InferredFrom != InstInfo.TheDef &&
3371 InstInfo.InferredFrom != PTM.getSrcRecord())
3372 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from patttern");
3376 PrintFatalError("Errors in DAG patterns");
3379 /// Given a pattern result with an unresolved type, see if we can find one
3380 /// instruction with an unresolved result type. Force this result type to an
3381 /// arbitrary element if it's possible types to converge results.
3382 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3386 // Analyze children.
3387 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3388 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3391 if (!N->getOperator()->isSubClassOf("Instruction"))
3394 // If this type is already concrete or completely unknown we can't do
3396 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3397 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3400 // Otherwise, force its type to the first possibility (an arbitrary choice).
3401 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3408 void CodeGenDAGPatterns::ParsePatterns() {
3409 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3411 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3412 Record *CurPattern = Patterns[i];
3413 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3415 // If the pattern references the null_frag, there's nothing to do.
3416 if (hasNullFragReference(Tree))
3419 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3421 // Inline pattern fragments into it.
3422 Pattern->InlinePatternFragments();
3424 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3425 if (LI->getSize() == 0) continue; // no pattern.
3427 // Parse the instruction.
3428 TreePattern Result(CurPattern, LI, false, *this);
3430 // Inline pattern fragments into it.
3431 Result.InlinePatternFragments();
3433 if (Result.getNumTrees() != 1)
3434 Result.error("Cannot handle instructions producing instructions "
3435 "with temporaries yet!");
3437 bool IterateInference;
3438 bool InferredAllPatternTypes, InferredAllResultTypes;
3440 // Infer as many types as possible. If we cannot infer all of them, we
3441 // can never do anything with this pattern: report it to the user.
3442 InferredAllPatternTypes =
3443 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3445 // Infer as many types as possible. If we cannot infer all of them, we
3446 // can never do anything with this pattern: report it to the user.
3447 InferredAllResultTypes =
3448 Result.InferAllTypes(&Pattern->getNamedNodesMap());
3450 IterateInference = false;
3452 // Apply the type of the result to the source pattern. This helps us
3453 // resolve cases where the input type is known to be a pointer type (which
3454 // is considered resolved), but the result knows it needs to be 32- or
3455 // 64-bits. Infer the other way for good measure.
3456 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3457 Pattern->getTree(0)->getNumTypes());
3459 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3460 i, Result.getTree(0)->getExtType(i), Result);
3461 IterateInference |= Result.getTree(0)->UpdateNodeType(
3462 i, Pattern->getTree(0)->getExtType(i), Result);
3465 // If our iteration has converged and the input pattern's types are fully
3466 // resolved but the result pattern is not fully resolved, we may have a
3467 // situation where we have two instructions in the result pattern and
3468 // the instructions require a common register class, but don't care about
3469 // what actual MVT is used. This is actually a bug in our modelling:
3470 // output patterns should have register classes, not MVTs.
3472 // In any case, to handle this, we just go through and disambiguate some
3473 // arbitrary types to the result pattern's nodes.
3474 if (!IterateInference && InferredAllPatternTypes &&
3475 !InferredAllResultTypes)
3477 ForceArbitraryInstResultType(Result.getTree(0), Result);
3478 } while (IterateInference);
3480 // Verify that we inferred enough types that we can do something with the
3481 // pattern and result. If these fire the user has to add type casts.
3482 if (!InferredAllPatternTypes)
3483 Pattern->error("Could not infer all types in pattern!");
3484 if (!InferredAllResultTypes) {
3486 Result.error("Could not infer all types in pattern result!");
3489 // Validate that the input pattern is correct.
3490 std::map<std::string, TreePatternNode*> InstInputs;
3491 std::map<std::string, TreePatternNode*> InstResults;
3492 std::vector<Record*> InstImpResults;
3493 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3494 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3495 InstInputs, InstResults,
3498 // Promote the xform function to be an explicit node if set.
3499 TreePatternNode *DstPattern = Result.getOnlyTree();
3500 std::vector<TreePatternNode*> ResultNodeOperands;
3501 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3502 TreePatternNode *OpNode = DstPattern->getChild(ii);
3503 if (Record *Xform = OpNode->getTransformFn()) {
3504 OpNode->setTransformFn(nullptr);
3505 std::vector<TreePatternNode*> Children;
3506 Children.push_back(OpNode);
3507 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3509 ResultNodeOperands.push_back(OpNode);
3511 DstPattern = Result.getOnlyTree();
3512 if (!DstPattern->isLeaf())
3513 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3515 DstPattern->getNumTypes());
3517 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3518 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3520 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
3521 Temp.InferAllTypes();
3524 AddPatternToMatch(Pattern,
3525 PatternToMatch(CurPattern,
3526 CurPattern->getValueAsListInit("Predicates"),
3527 Pattern->getTree(0),
3528 Temp.getOnlyTree(), InstImpResults,
3529 CurPattern->getValueAsInt("AddedComplexity"),
3530 CurPattern->getID()));
3534 /// CombineChildVariants - Given a bunch of permutations of each child of the
3535 /// 'operator' node, put them together in all possible ways.
3536 static void CombineChildVariants(TreePatternNode *Orig,
3537 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3538 std::vector<TreePatternNode*> &OutVariants,
3539 CodeGenDAGPatterns &CDP,
3540 const MultipleUseVarSet &DepVars) {
3541 // Make sure that each operand has at least one variant to choose from.
3542 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3543 if (ChildVariants[i].empty())
3546 // The end result is an all-pairs construction of the resultant pattern.
3547 std::vector<unsigned> Idxs;
3548 Idxs.resize(ChildVariants.size());
3552 DEBUG(if (!Idxs.empty()) {
3553 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3554 for (unsigned i = 0; i < Idxs.size(); ++i) {
3555 errs() << Idxs[i] << " ";
3560 // Create the variant and add it to the output list.
3561 std::vector<TreePatternNode*> NewChildren;
3562 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3563 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3564 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3565 Orig->getNumTypes());
3567 // Copy over properties.
3568 R->setName(Orig->getName());
3569 R->setPredicateFns(Orig->getPredicateFns());
3570 R->setTransformFn(Orig->getTransformFn());
3571 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3572 R->setType(i, Orig->getExtType(i));
3574 // If this pattern cannot match, do not include it as a variant.
3575 std::string ErrString;
3576 if (!R->canPatternMatch(ErrString, CDP)) {
3579 bool AlreadyExists = false;
3581 // Scan to see if this pattern has already been emitted. We can get
3582 // duplication due to things like commuting:
3583 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3584 // which are the same pattern. Ignore the dups.
3585 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
3586 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
3587 AlreadyExists = true;
3594 OutVariants.push_back(R);
3597 // Increment indices to the next permutation by incrementing the
3598 // indicies from last index backward, e.g., generate the sequence
3599 // [0, 0], [0, 1], [1, 0], [1, 1].
3601 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3602 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3607 NotDone = (IdxsIdx >= 0);
3611 /// CombineChildVariants - A helper function for binary operators.
3613 static void CombineChildVariants(TreePatternNode *Orig,
3614 const std::vector<TreePatternNode*> &LHS,
3615 const std::vector<TreePatternNode*> &RHS,
3616 std::vector<TreePatternNode*> &OutVariants,
3617 CodeGenDAGPatterns &CDP,
3618 const MultipleUseVarSet &DepVars) {
3619 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3620 ChildVariants.push_back(LHS);
3621 ChildVariants.push_back(RHS);
3622 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3626 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3627 std::vector<TreePatternNode *> &Children) {
3628 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3629 Record *Operator = N->getOperator();
3631 // Only permit raw nodes.
3632 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3633 N->getTransformFn()) {
3634 Children.push_back(N);
3638 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3639 Children.push_back(N->getChild(0));
3641 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3643 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3644 Children.push_back(N->getChild(1));
3646 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3649 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3650 /// the (potentially recursive) pattern by using algebraic laws.
3652 static void GenerateVariantsOf(TreePatternNode *N,
3653 std::vector<TreePatternNode*> &OutVariants,
3654 CodeGenDAGPatterns &CDP,
3655 const MultipleUseVarSet &DepVars) {
3656 // We cannot permute leaves or ComplexPattern uses.
3657 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
3658 OutVariants.push_back(N);
3662 // Look up interesting info about the node.
3663 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3665 // If this node is associative, re-associate.
3666 if (NodeInfo.hasProperty(SDNPAssociative)) {
3667 // Re-associate by pulling together all of the linked operators
3668 std::vector<TreePatternNode*> MaximalChildren;
3669 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3671 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3673 if (MaximalChildren.size() == 3) {
3674 // Find the variants of all of our maximal children.
3675 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3676 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3677 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3678 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3680 // There are only two ways we can permute the tree:
3681 // (A op B) op C and A op (B op C)
3682 // Within these forms, we can also permute A/B/C.
3684 // Generate legal pair permutations of A/B/C.
3685 std::vector<TreePatternNode*> ABVariants;
3686 std::vector<TreePatternNode*> BAVariants;
3687 std::vector<TreePatternNode*> ACVariants;
3688 std::vector<TreePatternNode*> CAVariants;
3689 std::vector<TreePatternNode*> BCVariants;
3690 std::vector<TreePatternNode*> CBVariants;
3691 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3692 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3693 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3694 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3695 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3696 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3698 // Combine those into the result: (x op x) op x
3699 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3700 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3701 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3702 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3703 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3704 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3706 // Combine those into the result: x op (x op x)
3707 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3708 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3709 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3710 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3711 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3712 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3717 // Compute permutations of all children.
3718 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3719 ChildVariants.resize(N->getNumChildren());
3720 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3721 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3723 // Build all permutations based on how the children were formed.
3724 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3726 // If this node is commutative, consider the commuted order.
3727 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3728 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3729 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3730 "Commutative but doesn't have 2 children!");
3731 // Don't count children which are actually register references.
3733 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3734 TreePatternNode *Child = N->getChild(i);
3735 if (Child->isLeaf())
3736 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
3737 Record *RR = DI->getDef();
3738 if (RR->isSubClassOf("Register"))
3743 // Consider the commuted order.
3744 if (isCommIntrinsic) {
3745 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3746 // operands are the commutative operands, and there might be more operands
3749 "Commutative intrinsic should have at least 3 childrean!");
3750 std::vector<std::vector<TreePatternNode*> > Variants;
3751 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3752 Variants.push_back(ChildVariants[2]);
3753 Variants.push_back(ChildVariants[1]);
3754 for (unsigned i = 3; i != NC; ++i)
3755 Variants.push_back(ChildVariants[i]);
3756 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3758 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3759 OutVariants, CDP, DepVars);
3764 // GenerateVariants - Generate variants. For example, commutative patterns can
3765 // match multiple ways. Add them to PatternsToMatch as well.
3766 void CodeGenDAGPatterns::GenerateVariants() {
3767 DEBUG(errs() << "Generating instruction variants.\n");
3769 // Loop over all of the patterns we've collected, checking to see if we can
3770 // generate variants of the instruction, through the exploitation of
3771 // identities. This permits the target to provide aggressive matching without
3772 // the .td file having to contain tons of variants of instructions.
3774 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3775 // intentionally do not reconsider these. Any variants of added patterns have
3776 // already been added.
3778 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3779 MultipleUseVarSet DepVars;
3780 std::vector<TreePatternNode*> Variants;
3781 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3782 DEBUG(errs() << "Dependent/multiply used variables: ");
3783 DEBUG(DumpDepVars(DepVars));
3784 DEBUG(errs() << "\n");
3785 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3788 assert(!Variants.empty() && "Must create at least original variant!");
3789 Variants.erase(Variants.begin()); // Remove the original pattern.
3791 if (Variants.empty()) // No variants for this pattern.
3794 DEBUG(errs() << "FOUND VARIANTS OF: ";
3795 PatternsToMatch[i].getSrcPattern()->dump();
3798 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3799 TreePatternNode *Variant = Variants[v];
3801 DEBUG(errs() << " VAR#" << v << ": ";
3805 // Scan to see if an instruction or explicit pattern already matches this.
3806 bool AlreadyExists = false;
3807 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3808 // Skip if the top level predicates do not match.
3809 if (PatternsToMatch[i].getPredicates() !=
3810 PatternsToMatch[p].getPredicates())
3812 // Check to see if this variant already exists.
3813 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3815 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3816 AlreadyExists = true;
3820 // If we already have it, ignore the variant.
3821 if (AlreadyExists) continue;
3823 // Otherwise, add it to the list of patterns we have.
3825 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3826 PatternsToMatch[i].getPredicates(),
3827 Variant, PatternsToMatch[i].getDstPattern(),
3828 PatternsToMatch[i].getDstRegs(),
3829 PatternsToMatch[i].getAddedComplexity(),
3830 Record::getNewUID()));
3833 DEBUG(errs() << "\n");