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 // This code does not currently handle nodes which have multiple types,
393 // where some types are integer, and some are fp. Assert that this is not
395 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
396 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
397 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
402 // Okay, find the smallest type from current set and remove anything the
403 // same or smaller from the other set. We need to ensure that the scalar
404 // type size is smaller than the scalar size of the smallest type. For
405 // vectors, we also need to make sure that the total size is no larger than
406 // the size of the smallest type.
407 TypeSet InputSet(Other);
408 MVT Smallest = TypeVec[0];
409 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
410 MVT OtherVT = Other.TypeVec[i];
411 // Don't compare vector and non-vector types.
412 if (OtherVT.isVector() != Smallest.isVector())
414 // The getSizeInBits() check here is only needed for vectors, but is
415 // a subset of the scalar check for scalars so no need to qualify.
416 if (OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
417 OtherVT.getSizeInBits() < Smallest.getSizeInBits()) {
418 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
423 if (Other.TypeVec.empty()) {
424 TP.error("Type inference contradiction found, '" + InputSet.getName() +
425 "' has nothing larger than '" + getName() +"'!");
429 // Okay, find the largest type from the other set and remove anything the
430 // same or smaller from the current set. We need to ensure that the scalar
431 // type size is larger than the scalar size of the largest type. For
432 // vectors, we also need to make sure that the total size is no smaller than
433 // the size of the largest type.
434 InputSet = TypeSet(*this);
435 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
436 for (unsigned i = 0; i != TypeVec.size(); ++i) {
437 MVT OtherVT = TypeVec[i];
438 // Don't compare vector and non-vector types.
439 if (OtherVT.isVector() != Largest.isVector())
441 // The getSizeInBits() check here is only needed for vectors, but is
442 // a subset of the scalar check for scalars so no need to qualify.
443 if (OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
444 OtherVT.getSizeInBits() > Largest.getSizeInBits()) {
445 TypeVec.erase(TypeVec.begin()+i--);
450 if (TypeVec.empty()) {
451 TP.error("Type inference contradiction found, '" + InputSet.getName() +
452 "' has nothing smaller than '" + Other.getName() +"'!");
459 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
460 /// whose element is specified by VTOperand.
461 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
463 bool MadeChange = false;
465 MadeChange |= EnforceVector(TP);
467 TypeSet InputSet(*this);
469 // Filter out all the types which don't have the right element type.
470 for (unsigned i = 0; i != TypeVec.size(); ++i) {
471 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
472 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
473 TypeVec.erase(TypeVec.begin()+i--);
478 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
479 TP.error("Type inference contradiction found, forcing '" +
480 InputSet.getName() + "' to have a vector element");
487 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
488 /// whose element is specified by VTOperand.
489 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
494 // "This" must be a vector and "VTOperand" must be a scalar.
495 bool MadeChange = false;
496 MadeChange |= EnforceVector(TP);
497 MadeChange |= VTOperand.EnforceScalar(TP);
499 // If we know the vector type, it forces the scalar to agree.
501 MVT IVT = getConcrete();
502 IVT = IVT.getVectorElementType();
504 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
507 // If the scalar type is known, filter out vector types whose element types
509 if (!VTOperand.isConcrete())
512 MVT::SimpleValueType VT = VTOperand.getConcrete();
514 TypeSet InputSet(*this);
516 // Filter out all the types which don't have the right element type.
517 for (unsigned i = 0; i != TypeVec.size(); ++i) {
518 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
519 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
520 TypeVec.erase(TypeVec.begin()+i--);
525 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
526 TP.error("Type inference contradiction found, forcing '" +
527 InputSet.getName() + "' to have a vector element");
533 /// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
534 /// vector type specified by VTOperand.
535 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
540 // "This" must be a vector and "VTOperand" must be a vector.
541 bool MadeChange = false;
542 MadeChange |= EnforceVector(TP);
543 MadeChange |= VTOperand.EnforceVector(TP);
545 // If one side is known to be integer or known to be FP but the other side has
546 // no information, get at least the type integrality info in there.
547 if (!hasFloatingPointTypes())
548 MadeChange |= VTOperand.EnforceInteger(TP);
549 else if (!hasIntegerTypes())
550 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
551 if (!VTOperand.hasFloatingPointTypes())
552 MadeChange |= EnforceInteger(TP);
553 else if (!VTOperand.hasIntegerTypes())
554 MadeChange |= EnforceFloatingPoint(TP);
556 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
557 "Should have a type list now");
559 // If we know the vector type, it forces the scalar types to agree.
560 // Also force one vector to have more elements than the other.
562 MVT IVT = getConcrete();
563 unsigned NumElems = IVT.getVectorNumElements();
564 IVT = IVT.getVectorElementType();
566 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
567 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
569 // Only keep types that have less elements than VTOperand.
570 TypeSet InputSet(VTOperand);
572 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
573 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
574 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
575 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
579 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
580 TP.error("Type inference contradiction found, forcing '" +
581 InputSet.getName() + "' to have less vector elements than '" +
585 } else if (VTOperand.isConcrete()) {
586 MVT IVT = VTOperand.getConcrete();
587 unsigned NumElems = IVT.getVectorNumElements();
588 IVT = IVT.getVectorElementType();
590 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
591 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
593 // Only keep types that have more elements than 'this'.
594 TypeSet InputSet(*this);
596 for (unsigned i = 0; i != TypeVec.size(); ++i) {
597 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
598 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
599 TypeVec.erase(TypeVec.begin()+i--);
603 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
604 TP.error("Type inference contradiction found, forcing '" +
605 InputSet.getName() + "' to have more vector elements than '" +
606 VTOperand.getName() + "'");
614 /// EnforceVectorSameNumElts - 'this' is now constrainted to
615 /// be a vector with same num elements as VTOperand.
616 bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
621 // "This" must be a vector and "VTOperand" must be a vector.
622 bool MadeChange = false;
623 MadeChange |= EnforceVector(TP);
624 MadeChange |= VTOperand.EnforceVector(TP);
626 // If we know one of the vector types, it forces the other type to agree.
628 MVT IVT = getConcrete();
629 unsigned NumElems = IVT.getVectorNumElements();
631 // Only keep types that have same elements as VTOperand.
632 TypeSet InputSet(VTOperand);
634 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
635 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
636 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
637 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
641 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
642 TP.error("Type inference contradiction found, forcing '" +
643 InputSet.getName() + "' to have same number elements as '" +
647 } else if (VTOperand.isConcrete()) {
648 MVT IVT = VTOperand.getConcrete();
649 unsigned NumElems = IVT.getVectorNumElements();
651 // Only keep types that have same elements as 'this'.
652 TypeSet InputSet(*this);
654 for (unsigned i = 0; i != TypeVec.size(); ++i) {
655 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
656 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
657 TypeVec.erase(TypeVec.begin()+i--);
661 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
662 TP.error("Type inference contradiction found, forcing '" +
663 InputSet.getName() + "' to have same number elements than '" +
664 VTOperand.getName() + "'");
672 //===----------------------------------------------------------------------===//
673 // Helpers for working with extended types.
675 /// Dependent variable map for CodeGenDAGPattern variant generation
676 typedef std::map<std::string, int> DepVarMap;
678 /// Const iterator shorthand for DepVarMap
679 typedef DepVarMap::const_iterator DepVarMap_citer;
681 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
683 if (isa<DefInit>(N->getLeafValue()))
684 DepMap[N->getName()]++;
686 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
687 FindDepVarsOf(N->getChild(i), DepMap);
691 /// Find dependent variables within child patterns
692 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
694 FindDepVarsOf(N, depcounts);
695 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
696 if (i->second > 1) // std::pair<std::string, int>
697 DepVars.insert(i->first);
702 /// Dump the dependent variable set:
703 static void DumpDepVars(MultipleUseVarSet &DepVars) {
704 if (DepVars.empty()) {
705 DEBUG(errs() << "<empty set>");
707 DEBUG(errs() << "[ ");
708 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
709 e = DepVars.end(); i != e; ++i) {
710 DEBUG(errs() << (*i) << " ");
712 DEBUG(errs() << "]");
718 //===----------------------------------------------------------------------===//
719 // TreePredicateFn Implementation
720 //===----------------------------------------------------------------------===//
722 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
723 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
724 assert((getPredCode().empty() || getImmCode().empty()) &&
725 ".td file corrupt: can't have a node predicate *and* an imm predicate");
728 std::string TreePredicateFn::getPredCode() const {
729 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
732 std::string TreePredicateFn::getImmCode() const {
733 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
737 /// isAlwaysTrue - Return true if this is a noop predicate.
738 bool TreePredicateFn::isAlwaysTrue() const {
739 return getPredCode().empty() && getImmCode().empty();
742 /// Return the name to use in the generated code to reference this, this is
743 /// "Predicate_foo" if from a pattern fragment "foo".
744 std::string TreePredicateFn::getFnName() const {
745 return "Predicate_" + PatFragRec->getRecord()->getName();
748 /// getCodeToRunOnSDNode - Return the code for the function body that
749 /// evaluates this predicate. The argument is expected to be in "Node",
750 /// not N. This handles casting and conversion to a concrete node type as
752 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
753 // Handle immediate predicates first.
754 std::string ImmCode = getImmCode();
755 if (!ImmCode.empty()) {
757 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
758 return Result + ImmCode;
761 // Handle arbitrary node predicates.
762 assert(!getPredCode().empty() && "Don't have any predicate code!");
763 std::string ClassName;
764 if (PatFragRec->getOnlyTree()->isLeaf())
765 ClassName = "SDNode";
767 Record *Op = PatFragRec->getOnlyTree()->getOperator();
768 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
771 if (ClassName == "SDNode")
772 Result = " SDNode *N = Node;\n";
774 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
776 return Result + getPredCode();
779 //===----------------------------------------------------------------------===//
780 // PatternToMatch implementation
784 /// getPatternSize - Return the 'size' of this pattern. We want to match large
785 /// patterns before small ones. This is used to determine the size of a
787 static unsigned getPatternSize(const TreePatternNode *P,
788 const CodeGenDAGPatterns &CGP) {
789 unsigned Size = 3; // The node itself.
790 // If the root node is a ConstantSDNode, increases its size.
791 // e.g. (set R32:$dst, 0).
792 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
795 // FIXME: This is a hack to statically increase the priority of patterns
796 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
797 // Later we can allow complexity / cost for each pattern to be (optionally)
798 // specified. To get best possible pattern match we'll need to dynamically
799 // calculate the complexity of all patterns a dag can potentially map to.
800 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
802 Size += AM->getNumOperands() * 3;
804 // We don't want to count any children twice, so return early.
808 // If this node has some predicate function that must match, it adds to the
809 // complexity of this node.
810 if (!P->getPredicateFns().empty())
813 // Count children in the count if they are also nodes.
814 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
815 TreePatternNode *Child = P->getChild(i);
816 if (!Child->isLeaf() && Child->getNumTypes() &&
817 Child->getType(0) != MVT::Other)
818 Size += getPatternSize(Child, CGP);
819 else if (Child->isLeaf()) {
820 if (isa<IntInit>(Child->getLeafValue()))
821 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
822 else if (Child->getComplexPatternInfo(CGP))
823 Size += getPatternSize(Child, CGP);
824 else if (!Child->getPredicateFns().empty())
832 /// Compute the complexity metric for the input pattern. This roughly
833 /// corresponds to the number of nodes that are covered.
835 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
836 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
840 /// getPredicateCheck - Return a single string containing all of this
841 /// pattern's predicates concatenated with "&&" operators.
843 std::string PatternToMatch::getPredicateCheck() const {
844 std::string PredicateCheck;
845 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
846 if (DefInit *Pred = dyn_cast<DefInit>(Predicates->getElement(i))) {
847 Record *Def = Pred->getDef();
848 if (!Def->isSubClassOf("Predicate")) {
852 llvm_unreachable("Unknown predicate type!");
854 if (!PredicateCheck.empty())
855 PredicateCheck += " && ";
856 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
860 return PredicateCheck;
863 //===----------------------------------------------------------------------===//
864 // SDTypeConstraint implementation
867 SDTypeConstraint::SDTypeConstraint(Record *R) {
868 OperandNo = R->getValueAsInt("OperandNum");
870 if (R->isSubClassOf("SDTCisVT")) {
871 ConstraintType = SDTCisVT;
872 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
873 if (x.SDTCisVT_Info.VT == MVT::isVoid)
874 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
876 } else if (R->isSubClassOf("SDTCisPtrTy")) {
877 ConstraintType = SDTCisPtrTy;
878 } else if (R->isSubClassOf("SDTCisInt")) {
879 ConstraintType = SDTCisInt;
880 } else if (R->isSubClassOf("SDTCisFP")) {
881 ConstraintType = SDTCisFP;
882 } else if (R->isSubClassOf("SDTCisVec")) {
883 ConstraintType = SDTCisVec;
884 } else if (R->isSubClassOf("SDTCisSameAs")) {
885 ConstraintType = SDTCisSameAs;
886 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
887 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
888 ConstraintType = SDTCisVTSmallerThanOp;
889 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
890 R->getValueAsInt("OtherOperandNum");
891 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
892 ConstraintType = SDTCisOpSmallerThanOp;
893 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
894 R->getValueAsInt("BigOperandNum");
895 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
896 ConstraintType = SDTCisEltOfVec;
897 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
898 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
899 ConstraintType = SDTCisSubVecOfVec;
900 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
901 R->getValueAsInt("OtherOpNum");
902 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
903 ConstraintType = SDTCVecEltisVT;
904 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
905 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
906 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
907 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
908 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
909 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
910 "as SDTCVecEltisVT");
911 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
912 ConstraintType = SDTCisSameNumEltsAs;
913 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
914 R->getValueAsInt("OtherOperandNum");
916 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
921 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
922 /// N, and the result number in ResNo.
923 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
924 const SDNodeInfo &NodeInfo,
926 unsigned NumResults = NodeInfo.getNumResults();
927 if (OpNo < NumResults) {
934 if (OpNo >= N->getNumChildren()) {
935 errs() << "Invalid operand number in type constraint "
936 << (OpNo+NumResults) << " ";
942 return N->getChild(OpNo);
945 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
946 /// constraint to the nodes operands. This returns true if it makes a
947 /// change, false otherwise. If a type contradiction is found, flag an error.
948 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
949 const SDNodeInfo &NodeInfo,
950 TreePattern &TP) const {
954 unsigned ResNo = 0; // The result number being referenced.
955 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
957 switch (ConstraintType) {
959 // Operand must be a particular type.
960 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
962 // Operand must be same as target pointer type.
963 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
965 // Require it to be one of the legal integer VTs.
966 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
968 // Require it to be one of the legal fp VTs.
969 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
971 // Require it to be one of the legal vector VTs.
972 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
975 TreePatternNode *OtherNode =
976 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
977 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
978 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
980 case SDTCisVTSmallerThanOp: {
981 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
982 // have an integer type that is smaller than the VT.
983 if (!NodeToApply->isLeaf() ||
984 !isa<DefInit>(NodeToApply->getLeafValue()) ||
985 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
986 ->isSubClassOf("ValueType")) {
987 TP.error(N->getOperator()->getName() + " expects a VT operand!");
990 MVT::SimpleValueType VT =
991 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
993 EEVT::TypeSet TypeListTmp(VT, TP);
996 TreePatternNode *OtherNode =
997 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1000 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
1002 case SDTCisOpSmallerThanOp: {
1003 unsigned BResNo = 0;
1004 TreePatternNode *BigOperand =
1005 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1007 return NodeToApply->getExtType(ResNo).
1008 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
1010 case SDTCisEltOfVec: {
1011 unsigned VResNo = 0;
1012 TreePatternNode *VecOperand =
1013 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1016 // Filter vector types out of VecOperand that don't have the right element
1018 return VecOperand->getExtType(VResNo).
1019 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
1021 case SDTCisSubVecOfVec: {
1022 unsigned VResNo = 0;
1023 TreePatternNode *BigVecOperand =
1024 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1027 // Filter vector types out of BigVecOperand that don't have the
1028 // right subvector type.
1029 return BigVecOperand->getExtType(VResNo).
1030 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1032 case SDTCVecEltisVT: {
1033 return NodeToApply->getExtType(ResNo).
1034 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1036 case SDTCisSameNumEltsAs: {
1037 unsigned OResNo = 0;
1038 TreePatternNode *OtherNode =
1039 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1040 N, NodeInfo, OResNo);
1041 return OtherNode->getExtType(OResNo).
1042 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1045 llvm_unreachable("Invalid ConstraintType!");
1048 // Update the node type to match an instruction operand or result as specified
1049 // in the ins or outs lists on the instruction definition. Return true if the
1050 // type was actually changed.
1051 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1054 // The 'unknown' operand indicates that types should be inferred from the
1056 if (Operand->isSubClassOf("unknown_class"))
1059 // The Operand class specifies a type directly.
1060 if (Operand->isSubClassOf("Operand"))
1061 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1064 // PointerLikeRegClass has a type that is determined at runtime.
1065 if (Operand->isSubClassOf("PointerLikeRegClass"))
1066 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1068 // Both RegisterClass and RegisterOperand operands derive their types from a
1069 // register class def.
1070 Record *RC = nullptr;
1071 if (Operand->isSubClassOf("RegisterClass"))
1073 else if (Operand->isSubClassOf("RegisterOperand"))
1074 RC = Operand->getValueAsDef("RegClass");
1076 assert(RC && "Unknown operand type");
1077 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1078 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1082 //===----------------------------------------------------------------------===//
1083 // SDNodeInfo implementation
1085 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1086 EnumName = R->getValueAsString("Opcode");
1087 SDClassName = R->getValueAsString("SDClass");
1088 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1089 NumResults = TypeProfile->getValueAsInt("NumResults");
1090 NumOperands = TypeProfile->getValueAsInt("NumOperands");
1092 // Parse the properties.
1094 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
1095 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
1096 if (PropList[i]->getName() == "SDNPCommutative") {
1097 Properties |= 1 << SDNPCommutative;
1098 } else if (PropList[i]->getName() == "SDNPAssociative") {
1099 Properties |= 1 << SDNPAssociative;
1100 } else if (PropList[i]->getName() == "SDNPHasChain") {
1101 Properties |= 1 << SDNPHasChain;
1102 } else if (PropList[i]->getName() == "SDNPOutGlue") {
1103 Properties |= 1 << SDNPOutGlue;
1104 } else if (PropList[i]->getName() == "SDNPInGlue") {
1105 Properties |= 1 << SDNPInGlue;
1106 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
1107 Properties |= 1 << SDNPOptInGlue;
1108 } else if (PropList[i]->getName() == "SDNPMayStore") {
1109 Properties |= 1 << SDNPMayStore;
1110 } else if (PropList[i]->getName() == "SDNPMayLoad") {
1111 Properties |= 1 << SDNPMayLoad;
1112 } else if (PropList[i]->getName() == "SDNPSideEffect") {
1113 Properties |= 1 << SDNPSideEffect;
1114 } else if (PropList[i]->getName() == "SDNPMemOperand") {
1115 Properties |= 1 << SDNPMemOperand;
1116 } else if (PropList[i]->getName() == "SDNPVariadic") {
1117 Properties |= 1 << SDNPVariadic;
1119 errs() << "Unknown SD Node property '" << PropList[i]->getName()
1120 << "' on node '" << R->getName() << "'!\n";
1126 // Parse the type constraints.
1127 std::vector<Record*> ConstraintList =
1128 TypeProfile->getValueAsListOfDefs("Constraints");
1129 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1132 /// getKnownType - If the type constraints on this node imply a fixed type
1133 /// (e.g. all stores return void, etc), then return it as an
1134 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
1135 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
1136 unsigned NumResults = getNumResults();
1137 assert(NumResults <= 1 &&
1138 "We only work with nodes with zero or one result so far!");
1139 assert(ResNo == 0 && "Only handles single result nodes so far");
1141 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
1142 // Make sure that this applies to the correct node result.
1143 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
1146 switch (TypeConstraints[i].ConstraintType) {
1148 case SDTypeConstraint::SDTCisVT:
1149 return TypeConstraints[i].x.SDTCisVT_Info.VT;
1150 case SDTypeConstraint::SDTCisPtrTy:
1157 //===----------------------------------------------------------------------===//
1158 // TreePatternNode implementation
1161 TreePatternNode::~TreePatternNode() {
1162 #if 0 // FIXME: implement refcounted tree nodes!
1163 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1168 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1169 if (Operator->getName() == "set" ||
1170 Operator->getName() == "implicit")
1171 return 0; // All return nothing.
1173 if (Operator->isSubClassOf("Intrinsic"))
1174 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1176 if (Operator->isSubClassOf("SDNode"))
1177 return CDP.getSDNodeInfo(Operator).getNumResults();
1179 if (Operator->isSubClassOf("PatFrag")) {
1180 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1181 // the forward reference case where one pattern fragment references another
1182 // before it is processed.
1183 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1184 return PFRec->getOnlyTree()->getNumTypes();
1186 // Get the result tree.
1187 DagInit *Tree = Operator->getValueAsDag("Fragment");
1188 Record *Op = nullptr;
1190 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1192 assert(Op && "Invalid Fragment");
1193 return GetNumNodeResults(Op, CDP);
1196 if (Operator->isSubClassOf("Instruction")) {
1197 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1199 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1201 // Subtract any defaulted outputs.
1202 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1203 Record *OperandNode = InstInfo.Operands[i].Rec;
1205 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1206 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1210 // Add on one implicit def if it has a resolvable type.
1211 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1213 return NumDefsToAdd;
1216 if (Operator->isSubClassOf("SDNodeXForm"))
1217 return 1; // FIXME: Generalize SDNodeXForm
1219 if (Operator->isSubClassOf("ValueType"))
1220 return 1; // A type-cast of one result.
1222 if (Operator->isSubClassOf("ComplexPattern"))
1226 errs() << "Unhandled node in GetNumNodeResults\n";
1230 void TreePatternNode::print(raw_ostream &OS) const {
1232 OS << *getLeafValue();
1234 OS << '(' << getOperator()->getName();
1236 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1237 OS << ':' << getExtType(i).getName();
1240 if (getNumChildren() != 0) {
1242 getChild(0)->print(OS);
1243 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1245 getChild(i)->print(OS);
1251 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
1252 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
1254 OS << "<<X:" << TransformFn->getName() << ">>";
1255 if (!getName().empty())
1256 OS << ":$" << getName();
1259 void TreePatternNode::dump() const {
1263 /// isIsomorphicTo - Return true if this node is recursively
1264 /// isomorphic to the specified node. For this comparison, the node's
1265 /// entire state is considered. The assigned name is ignored, since
1266 /// nodes with differing names are considered isomorphic. However, if
1267 /// the assigned name is present in the dependent variable set, then
1268 /// the assigned name is considered significant and the node is
1269 /// isomorphic if the names match.
1270 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1271 const MultipleUseVarSet &DepVars) const {
1272 if (N == this) return true;
1273 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1274 getPredicateFns() != N->getPredicateFns() ||
1275 getTransformFn() != N->getTransformFn())
1279 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1280 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
1281 return ((DI->getDef() == NDI->getDef())
1282 && (DepVars.find(getName()) == DepVars.end()
1283 || getName() == N->getName()));
1286 return getLeafValue() == N->getLeafValue();
1289 if (N->getOperator() != getOperator() ||
1290 N->getNumChildren() != getNumChildren()) return false;
1291 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1292 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1297 /// clone - Make a copy of this tree and all of its children.
1299 TreePatternNode *TreePatternNode::clone() const {
1300 TreePatternNode *New;
1302 New = new TreePatternNode(getLeafValue(), getNumTypes());
1304 std::vector<TreePatternNode*> CChildren;
1305 CChildren.reserve(Children.size());
1306 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1307 CChildren.push_back(getChild(i)->clone());
1308 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1310 New->setName(getName());
1312 New->setPredicateFns(getPredicateFns());
1313 New->setTransformFn(getTransformFn());
1317 /// RemoveAllTypes - Recursively strip all the types of this tree.
1318 void TreePatternNode::RemoveAllTypes() {
1319 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1320 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
1321 if (isLeaf()) return;
1322 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1323 getChild(i)->RemoveAllTypes();
1327 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1328 /// with actual values specified by ArgMap.
1329 void TreePatternNode::
1330 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1331 if (isLeaf()) return;
1333 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1334 TreePatternNode *Child = getChild(i);
1335 if (Child->isLeaf()) {
1336 Init *Val = Child->getLeafValue();
1337 // Note that, when substituting into an output pattern, Val might be an
1339 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1340 cast<DefInit>(Val)->getDef()->getName() == "node")) {
1341 // We found a use of a formal argument, replace it with its value.
1342 TreePatternNode *NewChild = ArgMap[Child->getName()];
1343 assert(NewChild && "Couldn't find formal argument!");
1344 assert((Child->getPredicateFns().empty() ||
1345 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1346 "Non-empty child predicate clobbered!");
1347 setChild(i, NewChild);
1350 getChild(i)->SubstituteFormalArguments(ArgMap);
1356 /// InlinePatternFragments - If this pattern refers to any pattern
1357 /// fragments, inline them into place, giving us a pattern without any
1358 /// PatFrag references.
1359 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1364 return this; // nothing to do.
1365 Record *Op = getOperator();
1367 if (!Op->isSubClassOf("PatFrag")) {
1368 // Just recursively inline children nodes.
1369 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1370 TreePatternNode *Child = getChild(i);
1371 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1373 assert((Child->getPredicateFns().empty() ||
1374 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1375 "Non-empty child predicate clobbered!");
1377 setChild(i, NewChild);
1382 // Otherwise, we found a reference to a fragment. First, look up its
1383 // TreePattern record.
1384 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1386 // Verify that we are passing the right number of operands.
1387 if (Frag->getNumArgs() != Children.size()) {
1388 TP.error("'" + Op->getName() + "' fragment requires " +
1389 utostr(Frag->getNumArgs()) + " operands!");
1393 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1395 TreePredicateFn PredFn(Frag);
1396 if (!PredFn.isAlwaysTrue())
1397 FragTree->addPredicateFn(PredFn);
1399 // Resolve formal arguments to their actual value.
1400 if (Frag->getNumArgs()) {
1401 // Compute the map of formal to actual arguments.
1402 std::map<std::string, TreePatternNode*> ArgMap;
1403 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1404 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1406 FragTree->SubstituteFormalArguments(ArgMap);
1409 FragTree->setName(getName());
1410 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1411 FragTree->UpdateNodeType(i, getExtType(i), TP);
1413 // Transfer in the old predicates.
1414 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1415 FragTree->addPredicateFn(getPredicateFns()[i]);
1417 // Get a new copy of this fragment to stitch into here.
1418 //delete this; // FIXME: implement refcounting!
1420 // The fragment we inlined could have recursive inlining that is needed. See
1421 // if there are any pattern fragments in it and inline them as needed.
1422 return FragTree->InlinePatternFragments(TP);
1425 /// getImplicitType - Check to see if the specified record has an implicit
1426 /// type which should be applied to it. This will infer the type of register
1427 /// references from the register file information, for example.
1429 /// When Unnamed is set, return the type of a DAG operand with no name, such as
1430 /// the F8RC register class argument in:
1432 /// (COPY_TO_REGCLASS GPR:$src, F8RC)
1434 /// When Unnamed is false, return the type of a named DAG operand such as the
1435 /// GPR:$src operand above.
1437 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1441 // Check to see if this is a register operand.
1442 if (R->isSubClassOf("RegisterOperand")) {
1443 assert(ResNo == 0 && "Regoperand ref only has one result!");
1445 return EEVT::TypeSet(); // Unknown.
1446 Record *RegClass = R->getValueAsDef("RegClass");
1447 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1448 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1451 // Check to see if this is a register or a register class.
1452 if (R->isSubClassOf("RegisterClass")) {
1453 assert(ResNo == 0 && "Regclass ref only has one result!");
1454 // An unnamed register class represents itself as an i32 immediate, for
1455 // example on a COPY_TO_REGCLASS instruction.
1457 return EEVT::TypeSet(MVT::i32, TP);
1459 // In a named operand, the register class provides the possible set of
1462 return EEVT::TypeSet(); // Unknown.
1463 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1464 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1467 if (R->isSubClassOf("PatFrag")) {
1468 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1469 // Pattern fragment types will be resolved when they are inlined.
1470 return EEVT::TypeSet(); // Unknown.
1473 if (R->isSubClassOf("Register")) {
1474 assert(ResNo == 0 && "Registers only produce one result!");
1476 return EEVT::TypeSet(); // Unknown.
1477 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1478 return EEVT::TypeSet(T.getRegisterVTs(R));
1481 if (R->isSubClassOf("SubRegIndex")) {
1482 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1483 return EEVT::TypeSet(MVT::i32, TP);
1486 if (R->isSubClassOf("ValueType")) {
1487 assert(ResNo == 0 && "This node only has one result!");
1488 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1490 // (sext_inreg GPR:$src, i16)
1493 return EEVT::TypeSet(MVT::Other, TP);
1494 // With a name, the ValueType simply provides the type of the named
1497 // (sext_inreg i32:$src, i16)
1500 return EEVT::TypeSet(); // Unknown.
1501 return EEVT::TypeSet(getValueType(R), TP);
1504 if (R->isSubClassOf("CondCode")) {
1505 assert(ResNo == 0 && "This node only has one result!");
1506 // Using a CondCodeSDNode.
1507 return EEVT::TypeSet(MVT::Other, TP);
1510 if (R->isSubClassOf("ComplexPattern")) {
1511 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1513 return EEVT::TypeSet(); // Unknown.
1514 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1517 if (R->isSubClassOf("PointerLikeRegClass")) {
1518 assert(ResNo == 0 && "Regclass can only have one result!");
1519 return EEVT::TypeSet(MVT::iPTR, TP);
1522 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1523 R->getName() == "zero_reg") {
1525 return EEVT::TypeSet(); // Unknown.
1528 if (R->isSubClassOf("Operand"))
1529 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1531 TP.error("Unknown node flavor used in pattern: " + R->getName());
1532 return EEVT::TypeSet(MVT::Other, TP);
1536 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1537 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1538 const CodeGenIntrinsic *TreePatternNode::
1539 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1540 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1541 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1542 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1545 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
1546 return &CDP.getIntrinsicInfo(IID);
1549 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1550 /// return the ComplexPattern information, otherwise return null.
1551 const ComplexPattern *
1552 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1555 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1560 Rec = getOperator();
1562 if (!Rec->isSubClassOf("ComplexPattern"))
1564 return &CGP.getComplexPattern(Rec);
1567 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1568 // A ComplexPattern specifically declares how many results it fills in.
1569 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1570 return CP->getNumOperands();
1572 // If MIOperandInfo is specified, that gives the count.
1574 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1575 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1576 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1577 if (MIOps->getNumArgs())
1578 return MIOps->getNumArgs();
1582 // Otherwise there is just one result.
1586 /// NodeHasProperty - Return true if this node has the specified property.
1587 bool TreePatternNode::NodeHasProperty(SDNP Property,
1588 const CodeGenDAGPatterns &CGP) const {
1590 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1591 return CP->hasProperty(Property);
1595 Record *Operator = getOperator();
1596 if (!Operator->isSubClassOf("SDNode")) return false;
1598 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1604 /// TreeHasProperty - Return true if any node in this tree has the specified
1606 bool TreePatternNode::TreeHasProperty(SDNP Property,
1607 const CodeGenDAGPatterns &CGP) const {
1608 if (NodeHasProperty(Property, CGP))
1610 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1611 if (getChild(i)->TreeHasProperty(Property, CGP))
1616 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1617 /// commutative intrinsic.
1619 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1620 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1621 return Int->isCommutative;
1625 static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1627 return N->getOperator()->isSubClassOf(Class);
1629 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1630 if (DI && DI->getDef()->isSubClassOf(Class))
1636 static void emitTooManyOperandsError(TreePattern &TP,
1640 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1641 " operands but expected only " + Twine(Expected) + "!");
1644 static void emitTooFewOperandsError(TreePattern &TP,
1647 TP.error("Instruction '" + InstName +
1648 "' expects more than the provided " + Twine(Actual) + " operands!");
1651 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1652 /// this node and its children in the tree. This returns true if it makes a
1653 /// change, false otherwise. If a type contradiction is found, flag an error.
1654 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1658 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1660 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1661 // If it's a regclass or something else known, include the type.
1662 bool MadeChange = false;
1663 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1664 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1666 !hasName(), TP), TP);
1670 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
1671 assert(Types.size() == 1 && "Invalid IntInit");
1673 // Int inits are always integers. :)
1674 bool MadeChange = Types[0].EnforceInteger(TP);
1676 if (!Types[0].isConcrete())
1679 MVT::SimpleValueType VT = getType(0);
1680 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1683 unsigned Size = MVT(VT).getSizeInBits();
1684 // Make sure that the value is representable for this type.
1685 if (Size >= 32) return MadeChange;
1687 // Check that the value doesn't use more bits than we have. It must either
1688 // be a sign- or zero-extended equivalent of the original.
1689 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1690 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
1693 TP.error("Integer value '" + itostr(II->getValue()) +
1694 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1700 // special handling for set, which isn't really an SDNode.
1701 if (getOperator()->getName() == "set") {
1702 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1703 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1704 unsigned NC = getNumChildren();
1706 TreePatternNode *SetVal = getChild(NC-1);
1707 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1709 for (unsigned i = 0; i < NC-1; ++i) {
1710 TreePatternNode *Child = getChild(i);
1711 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1713 // Types of operands must match.
1714 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1715 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1720 if (getOperator()->getName() == "implicit") {
1721 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1723 bool MadeChange = false;
1724 for (unsigned i = 0; i < getNumChildren(); ++i)
1725 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1729 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1730 bool MadeChange = false;
1732 // Apply the result type to the node.
1733 unsigned NumRetVTs = Int->IS.RetVTs.size();
1734 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1736 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1737 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1739 if (getNumChildren() != NumParamVTs + 1) {
1740 TP.error("Intrinsic '" + Int->Name + "' expects " +
1741 utostr(NumParamVTs) + " operands, not " +
1742 utostr(getNumChildren() - 1) + " operands!");
1746 // Apply type info to the intrinsic ID.
1747 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1749 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1750 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1752 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1753 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1754 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1759 if (getOperator()->isSubClassOf("SDNode")) {
1760 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1762 // Check that the number of operands is sane. Negative operands -> varargs.
1763 if (NI.getNumOperands() >= 0 &&
1764 getNumChildren() != (unsigned)NI.getNumOperands()) {
1765 TP.error(getOperator()->getName() + " node requires exactly " +
1766 itostr(NI.getNumOperands()) + " operands!");
1770 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1771 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1772 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1776 if (getOperator()->isSubClassOf("Instruction")) {
1777 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1778 CodeGenInstruction &InstInfo =
1779 CDP.getTargetInfo().getInstruction(getOperator());
1781 bool MadeChange = false;
1783 // Apply the result types to the node, these come from the things in the
1784 // (outs) list of the instruction.
1785 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1786 Inst.getNumResults());
1787 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1788 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
1790 // If the instruction has implicit defs, we apply the first one as a result.
1791 // FIXME: This sucks, it should apply all implicit defs.
1792 if (!InstInfo.ImplicitDefs.empty()) {
1793 unsigned ResNo = NumResultsToAdd;
1795 // FIXME: Generalize to multiple possible types and multiple possible
1797 MVT::SimpleValueType VT =
1798 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1800 if (VT != MVT::Other)
1801 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1804 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1806 if (getOperator()->getName() == "INSERT_SUBREG") {
1807 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1808 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1809 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1810 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1811 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1814 unsigned NChild = getNumChildren();
1816 TP.error("REG_SEQUENCE requires at least 3 operands!");
1820 if (NChild % 2 == 0) {
1821 TP.error("REG_SEQUENCE requires an odd number of operands!");
1825 if (!isOperandClass(getChild(0), "RegisterClass")) {
1826 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1830 for (unsigned I = 1; I < NChild; I += 2) {
1831 TreePatternNode *SubIdxChild = getChild(I + 1);
1832 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1833 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1834 itostr(I + 1) + "!");
1840 unsigned ChildNo = 0;
1841 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1842 Record *OperandNode = Inst.getOperand(i);
1844 // If the instruction expects a predicate or optional def operand, we
1845 // codegen this by setting the operand to it's default value if it has a
1846 // non-empty DefaultOps field.
1847 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1848 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1851 // Verify that we didn't run out of provided operands.
1852 if (ChildNo >= getNumChildren()) {
1853 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
1857 TreePatternNode *Child = getChild(ChildNo++);
1858 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1860 // If the operand has sub-operands, they may be provided by distinct
1861 // child patterns, so attempt to match each sub-operand separately.
1862 if (OperandNode->isSubClassOf("Operand")) {
1863 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1864 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1865 // But don't do that if the whole operand is being provided by
1866 // a single ComplexPattern-related Operand.
1868 if (Child->getNumMIResults(CDP) < NumArgs) {
1869 // Match first sub-operand against the child we already have.
1870 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1872 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1874 // And the remaining sub-operands against subsequent children.
1875 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1876 if (ChildNo >= getNumChildren()) {
1877 emitTooFewOperandsError(TP, getOperator()->getName(),
1881 Child = getChild(ChildNo++);
1883 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1885 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1892 // If we didn't match by pieces above, attempt to match the whole
1894 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
1897 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
1898 emitTooManyOperandsError(TP, getOperator()->getName(),
1899 ChildNo, getNumChildren());
1903 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1904 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1908 if (getOperator()->isSubClassOf("ComplexPattern")) {
1909 bool MadeChange = false;
1911 for (unsigned i = 0; i < getNumChildren(); ++i)
1912 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1917 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1919 // Node transforms always take one operand.
1920 if (getNumChildren() != 1) {
1921 TP.error("Node transform '" + getOperator()->getName() +
1922 "' requires one operand!");
1926 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1929 // If either the output or input of the xform does not have exact
1930 // type info. We assume they must be the same. Otherwise, it is perfectly
1931 // legal to transform from one type to a completely different type.
1933 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1934 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1935 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1942 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1943 /// RHS of a commutative operation, not the on LHS.
1944 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1945 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1947 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
1953 /// canPatternMatch - If it is impossible for this pattern to match on this
1954 /// target, fill in Reason and return false. Otherwise, return true. This is
1955 /// used as a sanity check for .td files (to prevent people from writing stuff
1956 /// that can never possibly work), and to prevent the pattern permuter from
1957 /// generating stuff that is useless.
1958 bool TreePatternNode::canPatternMatch(std::string &Reason,
1959 const CodeGenDAGPatterns &CDP) {
1960 if (isLeaf()) return true;
1962 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1963 if (!getChild(i)->canPatternMatch(Reason, CDP))
1966 // If this is an intrinsic, handle cases that would make it not match. For
1967 // example, if an operand is required to be an immediate.
1968 if (getOperator()->isSubClassOf("Intrinsic")) {
1973 if (getOperator()->isSubClassOf("ComplexPattern"))
1976 // If this node is a commutative operator, check that the LHS isn't an
1978 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1979 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1980 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1981 // Scan all of the operands of the node and make sure that only the last one
1982 // is a constant node, unless the RHS also is.
1983 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1984 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1985 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1986 if (OnlyOnRHSOfCommutative(getChild(i))) {
1987 Reason="Immediate value must be on the RHS of commutative operators!";
1996 //===----------------------------------------------------------------------===//
1997 // TreePattern implementation
2000 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
2001 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2002 isInputPattern(isInput), HasError(false) {
2003 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
2004 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
2007 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
2008 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2009 isInputPattern(isInput), HasError(false) {
2010 Trees.push_back(ParseTreePattern(Pat, ""));
2013 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
2014 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2015 isInputPattern(isInput), HasError(false) {
2016 Trees.push_back(Pat);
2019 void TreePattern::error(const Twine &Msg) {
2023 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2027 void TreePattern::ComputeNamedNodes() {
2028 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2029 ComputeNamedNodes(Trees[i]);
2032 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2033 if (!N->getName().empty())
2034 NamedNodes[N->getName()].push_back(N);
2036 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2037 ComputeNamedNodes(N->getChild(i));
2041 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
2042 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2043 Record *R = DI->getDef();
2045 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2046 // TreePatternNode of its own. For example:
2047 /// (foo GPR, imm) -> (foo GPR, (imm))
2048 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
2049 return ParseTreePattern(
2050 DagInit::get(DI, "",
2051 std::vector<std::pair<Init*, std::string> >()),
2055 TreePatternNode *Res = new TreePatternNode(DI, 1);
2056 if (R->getName() == "node" && !OpName.empty()) {
2058 error("'node' argument requires a name to match with operand list");
2059 Args.push_back(OpName);
2062 Res->setName(OpName);
2066 // ?:$name or just $name.
2067 if (TheInit == UnsetInit::get()) {
2069 error("'?' argument requires a name to match with operand list");
2070 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
2071 Args.push_back(OpName);
2072 Res->setName(OpName);
2076 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
2077 if (!OpName.empty())
2078 error("Constant int argument should not have a name!");
2079 return new TreePatternNode(II, 1);
2082 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2083 // Turn this into an IntInit.
2084 Init *II = BI->convertInitializerTo(IntRecTy::get());
2085 if (!II || !isa<IntInit>(II))
2086 error("Bits value must be constants!");
2087 return ParseTreePattern(II, OpName);
2090 DagInit *Dag = dyn_cast<DagInit>(TheInit);
2093 error("Pattern has unexpected init kind!");
2095 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
2096 if (!OpDef) error("Pattern has unexpected operator type!");
2097 Record *Operator = OpDef->getDef();
2099 if (Operator->isSubClassOf("ValueType")) {
2100 // If the operator is a ValueType, then this must be "type cast" of a leaf
2102 if (Dag->getNumArgs() != 1)
2103 error("Type cast only takes one operand!");
2105 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
2107 // Apply the type cast.
2108 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2109 New->UpdateNodeType(0, getValueType(Operator), *this);
2111 if (!OpName.empty())
2112 error("ValueType cast should not have a name!");
2116 // Verify that this is something that makes sense for an operator.
2117 if (!Operator->isSubClassOf("PatFrag") &&
2118 !Operator->isSubClassOf("SDNode") &&
2119 !Operator->isSubClassOf("Instruction") &&
2120 !Operator->isSubClassOf("SDNodeXForm") &&
2121 !Operator->isSubClassOf("Intrinsic") &&
2122 !Operator->isSubClassOf("ComplexPattern") &&
2123 Operator->getName() != "set" &&
2124 Operator->getName() != "implicit")
2125 error("Unrecognized node '" + Operator->getName() + "'!");
2127 // Check to see if this is something that is illegal in an input pattern.
2128 if (isInputPattern) {
2129 if (Operator->isSubClassOf("Instruction") ||
2130 Operator->isSubClassOf("SDNodeXForm"))
2131 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2133 if (Operator->isSubClassOf("Intrinsic"))
2134 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2136 if (Operator->isSubClassOf("SDNode") &&
2137 Operator->getName() != "imm" &&
2138 Operator->getName() != "fpimm" &&
2139 Operator->getName() != "tglobaltlsaddr" &&
2140 Operator->getName() != "tconstpool" &&
2141 Operator->getName() != "tjumptable" &&
2142 Operator->getName() != "tframeindex" &&
2143 Operator->getName() != "texternalsym" &&
2144 Operator->getName() != "tblockaddress" &&
2145 Operator->getName() != "tglobaladdr" &&
2146 Operator->getName() != "bb" &&
2147 Operator->getName() != "vt")
2148 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2151 std::vector<TreePatternNode*> Children;
2153 // Parse all the operands.
2154 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2155 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
2157 // If the operator is an intrinsic, then this is just syntactic sugar for for
2158 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
2159 // convert the intrinsic name to a number.
2160 if (Operator->isSubClassOf("Intrinsic")) {
2161 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2162 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2164 // If this intrinsic returns void, it must have side-effects and thus a
2166 if (Int.IS.RetVTs.empty())
2167 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2168 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
2169 // Has side-effects, requires chain.
2170 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2171 else // Otherwise, no chain.
2172 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2174 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
2175 Children.insert(Children.begin(), IIDNode);
2178 if (Operator->isSubClassOf("ComplexPattern")) {
2179 for (unsigned i = 0; i < Children.size(); ++i) {
2180 TreePatternNode *Child = Children[i];
2182 if (Child->getName().empty())
2183 error("All arguments to a ComplexPattern must be named");
2185 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2186 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2187 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2188 auto OperandId = std::make_pair(Operator, i);
2189 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2190 if (PrevOp != ComplexPatternOperands.end()) {
2191 if (PrevOp->getValue() != OperandId)
2192 error("All ComplexPattern operands must appear consistently: "
2193 "in the same order in just one ComplexPattern instance.");
2195 ComplexPatternOperands[Child->getName()] = OperandId;
2199 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2200 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
2201 Result->setName(OpName);
2203 if (!Dag->getName().empty()) {
2204 assert(Result->getName().empty());
2205 Result->setName(Dag->getName());
2210 /// SimplifyTree - See if we can simplify this tree to eliminate something that
2211 /// will never match in favor of something obvious that will. This is here
2212 /// strictly as a convenience to target authors because it allows them to write
2213 /// more type generic things and have useless type casts fold away.
2215 /// This returns true if any change is made.
2216 static bool SimplifyTree(TreePatternNode *&N) {
2220 // If we have a bitconvert with a resolved type and if the source and
2221 // destination types are the same, then the bitconvert is useless, remove it.
2222 if (N->getOperator()->getName() == "bitconvert" &&
2223 N->getExtType(0).isConcrete() &&
2224 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2225 N->getName().empty()) {
2231 // Walk all children.
2232 bool MadeChange = false;
2233 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2234 TreePatternNode *Child = N->getChild(i);
2235 MadeChange |= SimplifyTree(Child);
2236 N->setChild(i, Child);
2243 /// InferAllTypes - Infer/propagate as many types throughout the expression
2244 /// patterns as possible. Return true if all types are inferred, false
2245 /// otherwise. Flags an error if a type contradiction is found.
2247 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2248 if (NamedNodes.empty())
2249 ComputeNamedNodes();
2251 bool MadeChange = true;
2252 while (MadeChange) {
2254 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2255 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
2256 MadeChange |= SimplifyTree(Trees[i]);
2259 // If there are constraints on our named nodes, apply them.
2260 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
2261 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
2262 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
2264 // If we have input named node types, propagate their types to the named
2267 if (!InNamedTypes->count(I->getKey())) {
2268 error("Node '" + std::string(I->getKey()) +
2269 "' in output pattern but not input pattern");
2273 const SmallVectorImpl<TreePatternNode*> &InNodes =
2274 InNamedTypes->find(I->getKey())->second;
2276 // The input types should be fully resolved by now.
2277 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2278 // If this node is a register class, and it is the root of the pattern
2279 // then we're mapping something onto an input register. We allow
2280 // changing the type of the input register in this case. This allows
2281 // us to match things like:
2282 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2283 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
2284 DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
2285 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2286 DI->getDef()->isSubClassOf("RegisterOperand")))
2290 assert(Nodes[i]->getNumTypes() == 1 &&
2291 InNodes[0]->getNumTypes() == 1 &&
2292 "FIXME: cannot name multiple result nodes yet");
2293 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
2298 // If there are multiple nodes with the same name, they must all have the
2300 if (I->second.size() > 1) {
2301 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
2302 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
2303 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
2304 "FIXME: cannot name multiple result nodes yet");
2306 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2307 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
2313 bool HasUnresolvedTypes = false;
2314 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2315 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
2316 return !HasUnresolvedTypes;
2319 void TreePattern::print(raw_ostream &OS) const {
2320 OS << getRecord()->getName();
2321 if (!Args.empty()) {
2322 OS << "(" << Args[0];
2323 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2324 OS << ", " << Args[i];
2329 if (Trees.size() > 1)
2331 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2333 Trees[i]->print(OS);
2337 if (Trees.size() > 1)
2341 void TreePattern::dump() const { print(errs()); }
2343 //===----------------------------------------------------------------------===//
2344 // CodeGenDAGPatterns implementation
2347 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
2348 Records(R), Target(R) {
2350 Intrinsics = LoadIntrinsics(Records, false);
2351 TgtIntrinsics = LoadIntrinsics(Records, true);
2353 ParseNodeTransforms();
2354 ParseComplexPatterns();
2355 ParsePatternFragments();
2356 ParseDefaultOperands();
2357 ParseInstructions();
2358 ParsePatternFragments(/*OutFrags*/true);
2361 // Generate variants. For example, commutative patterns can match
2362 // multiple ways. Add them to PatternsToMatch as well.
2365 // Infer instruction flags. For example, we can detect loads,
2366 // stores, and side effects in many cases by examining an
2367 // instruction's pattern.
2368 InferInstructionFlags();
2370 // Verify that instruction flags match the patterns.
2371 VerifyInstructionFlags();
2374 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2375 Record *N = Records.getDef(Name);
2376 if (!N || !N->isSubClassOf("SDNode")) {
2377 errs() << "Error getting SDNode '" << Name << "'!\n";
2383 // Parse all of the SDNode definitions for the target, populating SDNodes.
2384 void CodeGenDAGPatterns::ParseNodeInfo() {
2385 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2386 while (!Nodes.empty()) {
2387 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2391 // Get the builtin intrinsic nodes.
2392 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2393 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2394 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2397 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2398 /// map, and emit them to the file as functions.
2399 void CodeGenDAGPatterns::ParseNodeTransforms() {
2400 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2401 while (!Xforms.empty()) {
2402 Record *XFormNode = Xforms.back();
2403 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2404 std::string Code = XFormNode->getValueAsString("XFormFunction");
2405 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2411 void CodeGenDAGPatterns::ParseComplexPatterns() {
2412 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2413 while (!AMs.empty()) {
2414 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2420 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2421 /// file, building up the PatternFragments map. After we've collected them all,
2422 /// inline fragments together as necessary, so that there are no references left
2423 /// inside a pattern fragment to a pattern fragment.
2425 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
2426 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2428 // First step, parse all of the fragments.
2429 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2430 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2433 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
2435 (PatternFragments[Fragments[i]] = llvm::make_unique<TreePattern>(
2436 Fragments[i], Tree, !Fragments[i]->isSubClassOf("OutPatFrag"),
2439 // Validate the argument list, converting it to set, to discard duplicates.
2440 std::vector<std::string> &Args = P->getArgList();
2441 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2443 if (OperandsSet.count(""))
2444 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2446 // Parse the operands list.
2447 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
2448 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
2449 // Special cases: ops == outs == ins. Different names are used to
2450 // improve readability.
2452 (OpsOp->getDef()->getName() != "ops" &&
2453 OpsOp->getDef()->getName() != "outs" &&
2454 OpsOp->getDef()->getName() != "ins"))
2455 P->error("Operands list should start with '(ops ... '!");
2457 // Copy over the arguments.
2459 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2460 if (!isa<DefInit>(OpsList->getArg(j)) ||
2461 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
2462 P->error("Operands list should all be 'node' values.");
2463 if (OpsList->getArgName(j).empty())
2464 P->error("Operands list should have names for each operand!");
2465 if (!OperandsSet.count(OpsList->getArgName(j)))
2466 P->error("'" + OpsList->getArgName(j) +
2467 "' does not occur in pattern or was multiply specified!");
2468 OperandsSet.erase(OpsList->getArgName(j));
2469 Args.push_back(OpsList->getArgName(j));
2472 if (!OperandsSet.empty())
2473 P->error("Operands list does not contain an entry for operand '" +
2474 *OperandsSet.begin() + "'!");
2476 // If there is a code init for this fragment, keep track of the fact that
2477 // this fragment uses it.
2478 TreePredicateFn PredFn(P);
2479 if (!PredFn.isAlwaysTrue())
2480 P->getOnlyTree()->addPredicateFn(PredFn);
2482 // If there is a node transformation corresponding to this, keep track of
2484 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2485 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2486 P->getOnlyTree()->setTransformFn(Transform);
2489 // Now that we've parsed all of the tree fragments, do a closure on them so
2490 // that there are not references to PatFrags left inside of them.
2491 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2492 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2495 TreePattern &ThePat = *PatternFragments[Fragments[i]];
2496 ThePat.InlinePatternFragments();
2498 // Infer as many types as possible. Don't worry about it if we don't infer
2499 // all of them, some may depend on the inputs of the pattern.
2500 ThePat.InferAllTypes();
2501 ThePat.resetError();
2503 // If debugging, print out the pattern fragment result.
2504 DEBUG(ThePat.dump());
2508 void CodeGenDAGPatterns::ParseDefaultOperands() {
2509 std::vector<Record*> DefaultOps;
2510 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
2512 // Find some SDNode.
2513 assert(!SDNodes.empty() && "No SDNodes parsed?");
2514 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
2516 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2517 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
2519 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2520 // SomeSDnode so that we can parse this.
2521 std::vector<std::pair<Init*, std::string> > Ops;
2522 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2523 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2524 DefaultInfo->getArgName(op)));
2525 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
2527 // Create a TreePattern to parse this.
2528 TreePattern P(DefaultOps[i], DI, false, *this);
2529 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2531 // Copy the operands over into a DAGDefaultOperand.
2532 DAGDefaultOperand DefaultOpInfo;
2534 TreePatternNode *T = P.getTree(0);
2535 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2536 TreePatternNode *TPN = T->getChild(op);
2537 while (TPN->ApplyTypeConstraints(P, false))
2538 /* Resolve all types */;
2540 if (TPN->ContainsUnresolvedType()) {
2541 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2542 DefaultOps[i]->getName() +
2543 "' doesn't have a concrete type!");
2545 DefaultOpInfo.DefaultOps.push_back(TPN);
2548 // Insert it into the DefaultOperands map so we can find it later.
2549 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
2553 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2554 /// instruction input. Return true if this is a real use.
2555 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2556 std::map<std::string, TreePatternNode*> &InstInputs) {
2557 // No name -> not interesting.
2558 if (Pat->getName().empty()) {
2559 if (Pat->isLeaf()) {
2560 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2561 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2562 DI->getDef()->isSubClassOf("RegisterOperand")))
2563 I->error("Input " + DI->getDef()->getName() + " must be named!");
2569 if (Pat->isLeaf()) {
2570 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
2571 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2574 Rec = Pat->getOperator();
2577 // SRCVALUE nodes are ignored.
2578 if (Rec->getName() == "srcvalue")
2581 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2587 if (Slot->isLeaf()) {
2588 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
2590 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2591 SlotRec = Slot->getOperator();
2594 // Ensure that the inputs agree if we've already seen this input.
2596 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2597 if (Slot->getExtTypes() != Pat->getExtTypes())
2598 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2602 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2603 /// part of "I", the instruction), computing the set of inputs and outputs of
2604 /// the pattern. Report errors if we see anything naughty.
2605 void CodeGenDAGPatterns::
2606 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2607 std::map<std::string, TreePatternNode*> &InstInputs,
2608 std::map<std::string, TreePatternNode*>&InstResults,
2609 std::vector<Record*> &InstImpResults) {
2610 if (Pat->isLeaf()) {
2611 bool isUse = HandleUse(I, Pat, InstInputs);
2612 if (!isUse && Pat->getTransformFn())
2613 I->error("Cannot specify a transform function for a non-input value!");
2617 if (Pat->getOperator()->getName() == "implicit") {
2618 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2619 TreePatternNode *Dest = Pat->getChild(i);
2620 if (!Dest->isLeaf())
2621 I->error("implicitly defined value should be a register!");
2623 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2624 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2625 I->error("implicitly defined value should be a register!");
2626 InstImpResults.push_back(Val->getDef());
2631 if (Pat->getOperator()->getName() != "set") {
2632 // If this is not a set, verify that the children nodes are not void typed,
2634 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2635 if (Pat->getChild(i)->getNumTypes() == 0)
2636 I->error("Cannot have void nodes inside of patterns!");
2637 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2641 // If this is a non-leaf node with no children, treat it basically as if
2642 // it were a leaf. This handles nodes like (imm).
2643 bool isUse = HandleUse(I, Pat, InstInputs);
2645 if (!isUse && Pat->getTransformFn())
2646 I->error("Cannot specify a transform function for a non-input value!");
2650 // Otherwise, this is a set, validate and collect instruction results.
2651 if (Pat->getNumChildren() == 0)
2652 I->error("set requires operands!");
2654 if (Pat->getTransformFn())
2655 I->error("Cannot specify a transform function on a set node!");
2657 // Check the set destinations.
2658 unsigned NumDests = Pat->getNumChildren()-1;
2659 for (unsigned i = 0; i != NumDests; ++i) {
2660 TreePatternNode *Dest = Pat->getChild(i);
2661 if (!Dest->isLeaf())
2662 I->error("set destination should be a register!");
2664 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
2666 I->error("set destination should be a register!");
2670 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2671 Val->getDef()->isSubClassOf("ValueType") ||
2672 Val->getDef()->isSubClassOf("RegisterOperand") ||
2673 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2674 if (Dest->getName().empty())
2675 I->error("set destination must have a name!");
2676 if (InstResults.count(Dest->getName()))
2677 I->error("cannot set '" + Dest->getName() +"' multiple times");
2678 InstResults[Dest->getName()] = Dest;
2679 } else if (Val->getDef()->isSubClassOf("Register")) {
2680 InstImpResults.push_back(Val->getDef());
2682 I->error("set destination should be a register!");
2686 // Verify and collect info from the computation.
2687 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2688 InstInputs, InstResults, InstImpResults);
2691 //===----------------------------------------------------------------------===//
2692 // Instruction Analysis
2693 //===----------------------------------------------------------------------===//
2695 class InstAnalyzer {
2696 const CodeGenDAGPatterns &CDP;
2698 bool hasSideEffects;
2704 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2705 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2706 isBitcast(false), isVariadic(false) {}
2708 void Analyze(const TreePattern *Pat) {
2709 // Assume only the first tree is the pattern. The others are clobber nodes.
2710 AnalyzeNode(Pat->getTree(0));
2713 void Analyze(const PatternToMatch *Pat) {
2714 AnalyzeNode(Pat->getSrcPattern());
2718 bool IsNodeBitcast(const TreePatternNode *N) const {
2719 if (hasSideEffects || mayLoad || mayStore || isVariadic)
2722 if (N->getNumChildren() != 2)
2725 const TreePatternNode *N0 = N->getChild(0);
2726 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
2729 const TreePatternNode *N1 = N->getChild(1);
2732 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2735 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2736 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2738 return OpInfo.getEnumName() == "ISD::BITCAST";
2742 void AnalyzeNode(const TreePatternNode *N) {
2744 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
2745 Record *LeafRec = DI->getDef();
2746 // Handle ComplexPattern leaves.
2747 if (LeafRec->isSubClassOf("ComplexPattern")) {
2748 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2749 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2750 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2751 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2757 // Analyze children.
2758 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2759 AnalyzeNode(N->getChild(i));
2761 // Ignore set nodes, which are not SDNodes.
2762 if (N->getOperator()->getName() == "set") {
2763 isBitcast = IsNodeBitcast(N);
2767 // Notice properties of the node.
2768 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2769 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2770 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2771 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
2773 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2774 // If this is an intrinsic, analyze it.
2775 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2776 mayLoad = true;// These may load memory.
2778 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2779 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2781 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2782 // WriteMem intrinsics can have other strange effects.
2783 hasSideEffects = true;
2789 static bool InferFromPattern(CodeGenInstruction &InstInfo,
2790 const InstAnalyzer &PatInfo,
2794 // Remember where InstInfo got its flags.
2795 if (InstInfo.hasUndefFlags())
2796 InstInfo.InferredFrom = PatDef;
2798 // Check explicitly set flags for consistency.
2799 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2800 !InstInfo.hasSideEffects_Unset) {
2801 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2802 // the pattern has no side effects. That could be useful for div/rem
2803 // instructions that may trap.
2804 if (!InstInfo.hasSideEffects) {
2806 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2807 Twine(InstInfo.hasSideEffects));
2811 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2813 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2814 Twine(InstInfo.mayStore));
2817 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2818 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2819 // Some targets translate imediates to loads.
2820 if (!InstInfo.mayLoad) {
2822 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2823 Twine(InstInfo.mayLoad));
2827 // Transfer inferred flags.
2828 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2829 InstInfo.mayStore |= PatInfo.mayStore;
2830 InstInfo.mayLoad |= PatInfo.mayLoad;
2832 // These flags are silently added without any verification.
2833 InstInfo.isBitcast |= PatInfo.isBitcast;
2835 // Don't infer isVariadic. This flag means something different on SDNodes and
2836 // instructions. For example, a CALL SDNode is variadic because it has the
2837 // call arguments as operands, but a CALL instruction is not variadic - it
2838 // has argument registers as implicit, not explicit uses.
2843 /// hasNullFragReference - Return true if the DAG has any reference to the
2844 /// null_frag operator.
2845 static bool hasNullFragReference(DagInit *DI) {
2846 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
2847 if (!OpDef) return false;
2848 Record *Operator = OpDef->getDef();
2850 // If this is the null fragment, return true.
2851 if (Operator->getName() == "null_frag") return true;
2852 // If any of the arguments reference the null fragment, return true.
2853 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
2854 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
2855 if (Arg && hasNullFragReference(Arg))
2862 /// hasNullFragReference - Return true if any DAG in the list references
2863 /// the null_frag operator.
2864 static bool hasNullFragReference(ListInit *LI) {
2865 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
2866 DagInit *DI = dyn_cast<DagInit>(LI->getElement(i));
2867 assert(DI && "non-dag in an instruction Pattern list?!");
2868 if (hasNullFragReference(DI))
2874 /// Get all the instructions in a tree.
2876 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2879 if (Tree->getOperator()->isSubClassOf("Instruction"))
2880 Instrs.push_back(Tree->getOperator());
2881 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2882 getInstructionsInTree(Tree->getChild(i), Instrs);
2885 /// Check the class of a pattern leaf node against the instruction operand it
2887 static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2892 // Allow direct value types to be used in instruction set patterns.
2893 // The type will be checked later.
2894 if (Leaf->isSubClassOf("ValueType"))
2897 // Patterns can also be ComplexPattern instances.
2898 if (Leaf->isSubClassOf("ComplexPattern"))
2904 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2905 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
2907 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
2909 // Parse the instruction.
2910 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2911 // Inline pattern fragments into it.
2912 I->InlinePatternFragments();
2914 // Infer as many types as possible. If we cannot infer all of them, we can
2915 // never do anything with this instruction pattern: report it to the user.
2916 if (!I->InferAllTypes())
2917 I->error("Could not infer all types in pattern!");
2919 // InstInputs - Keep track of all of the inputs of the instruction, along
2920 // with the record they are declared as.
2921 std::map<std::string, TreePatternNode*> InstInputs;
2923 // InstResults - Keep track of all the virtual registers that are 'set'
2924 // in the instruction, including what reg class they are.
2925 std::map<std::string, TreePatternNode*> InstResults;
2927 std::vector<Record*> InstImpResults;
2929 // Verify that the top-level forms in the instruction are of void type, and
2930 // fill in the InstResults map.
2931 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2932 TreePatternNode *Pat = I->getTree(j);
2933 if (Pat->getNumTypes() != 0)
2934 I->error("Top-level forms in instruction pattern should have"
2937 // Find inputs and outputs, and verify the structure of the uses/defs.
2938 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2942 // Now that we have inputs and outputs of the pattern, inspect the operands
2943 // list for the instruction. This determines the order that operands are
2944 // added to the machine instruction the node corresponds to.
2945 unsigned NumResults = InstResults.size();
2947 // Parse the operands list from the (ops) list, validating it.
2948 assert(I->getArgList().empty() && "Args list should still be empty here!");
2950 // Check that all of the results occur first in the list.
2951 std::vector<Record*> Results;
2952 SmallVector<TreePatternNode *, 2> ResNodes;
2953 for (unsigned i = 0; i != NumResults; ++i) {
2954 if (i == CGI.Operands.size())
2955 I->error("'" + InstResults.begin()->first +
2956 "' set but does not appear in operand list!");
2957 const std::string &OpName = CGI.Operands[i].Name;
2959 // Check that it exists in InstResults.
2960 TreePatternNode *RNode = InstResults[OpName];
2962 I->error("Operand $" + OpName + " does not exist in operand list!");
2964 ResNodes.push_back(RNode);
2966 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2968 I->error("Operand $" + OpName + " should be a set destination: all "
2969 "outputs must occur before inputs in operand list!");
2971 if (!checkOperandClass(CGI.Operands[i], R))
2972 I->error("Operand $" + OpName + " class mismatch!");
2974 // Remember the return type.
2975 Results.push_back(CGI.Operands[i].Rec);
2977 // Okay, this one checks out.
2978 InstResults.erase(OpName);
2981 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2982 // the copy while we're checking the inputs.
2983 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2985 std::vector<TreePatternNode*> ResultNodeOperands;
2986 std::vector<Record*> Operands;
2987 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2988 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2989 const std::string &OpName = Op.Name;
2991 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2993 if (!InstInputsCheck.count(OpName)) {
2994 // If this is an operand with a DefaultOps set filled in, we can ignore
2995 // this. When we codegen it, we will do so as always executed.
2996 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2997 // Does it have a non-empty DefaultOps field? If so, ignore this
2999 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3002 I->error("Operand $" + OpName +
3003 " does not appear in the instruction pattern");
3005 TreePatternNode *InVal = InstInputsCheck[OpName];
3006 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3008 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3009 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3010 if (!checkOperandClass(Op, InRec))
3011 I->error("Operand $" + OpName + "'s register class disagrees"
3012 " between the operand and pattern");
3014 Operands.push_back(Op.Rec);
3016 // Construct the result for the dest-pattern operand list.
3017 TreePatternNode *OpNode = InVal->clone();
3019 // No predicate is useful on the result.
3020 OpNode->clearPredicateFns();
3022 // Promote the xform function to be an explicit node if set.
3023 if (Record *Xform = OpNode->getTransformFn()) {
3024 OpNode->setTransformFn(nullptr);
3025 std::vector<TreePatternNode*> Children;
3026 Children.push_back(OpNode);
3027 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3030 ResultNodeOperands.push_back(OpNode);
3033 if (!InstInputsCheck.empty())
3034 I->error("Input operand $" + InstInputsCheck.begin()->first +
3035 " occurs in pattern but not in operands list!");
3037 TreePatternNode *ResultPattern =
3038 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3039 GetNumNodeResults(I->getRecord(), *this));
3040 // Copy fully inferred output node types to instruction result pattern.
3041 for (unsigned i = 0; i != NumResults; ++i) {
3042 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3043 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3046 // Create and insert the instruction.
3047 // FIXME: InstImpResults should not be part of DAGInstruction.
3048 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3049 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3051 // Use a temporary tree pattern to infer all types and make sure that the
3052 // constructed result is correct. This depends on the instruction already
3053 // being inserted into the DAGInsts map.
3054 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3055 Temp.InferAllTypes(&I->getNamedNodesMap());
3057 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3058 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3060 return TheInsertedInst;
3063 /// ParseInstructions - Parse all of the instructions, inlining and resolving
3064 /// any fragments involved. This populates the Instructions list with fully
3065 /// resolved instructions.
3066 void CodeGenDAGPatterns::ParseInstructions() {
3067 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3069 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3070 ListInit *LI = nullptr;
3072 if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
3073 LI = Instrs[i]->getValueAsListInit("Pattern");
3075 // If there is no pattern, only collect minimal information about the
3076 // instruction for its operand list. We have to assume that there is one
3077 // result, as we have no detailed info. A pattern which references the
3078 // null_frag operator is as-if no pattern were specified. Normally this
3079 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3081 if (!LI || LI->getSize() == 0 || hasNullFragReference(LI)) {
3082 std::vector<Record*> Results;
3083 std::vector<Record*> Operands;
3085 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3087 if (InstInfo.Operands.size() != 0) {
3088 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3089 Results.push_back(InstInfo.Operands[j].Rec);
3091 // The rest are inputs.
3092 for (unsigned j = InstInfo.Operands.NumDefs,
3093 e = InstInfo.Operands.size(); j < e; ++j)
3094 Operands.push_back(InstInfo.Operands[j].Rec);
3097 // Create and insert the instruction.
3098 std::vector<Record*> ImpResults;
3099 Instructions.insert(std::make_pair(Instrs[i],
3100 DAGInstruction(nullptr, Results, Operands, ImpResults)));
3101 continue; // no pattern.
3104 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
3105 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3108 DEBUG(DI.getPattern()->dump());
3111 // If we can, convert the instructions to be patterns that are matched!
3112 for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
3113 Instructions.begin(),
3114 E = Instructions.end(); II != E; ++II) {
3115 DAGInstruction &TheInst = II->second;
3116 TreePattern *I = TheInst.getPattern();
3117 if (!I) continue; // No pattern.
3119 // FIXME: Assume only the first tree is the pattern. The others are clobber
3121 TreePatternNode *Pattern = I->getTree(0);
3122 TreePatternNode *SrcPattern;
3123 if (Pattern->getOperator()->getName() == "set") {
3124 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3126 // Not a set (store or something?)
3127 SrcPattern = Pattern;
3130 Record *Instr = II->first;
3131 AddPatternToMatch(I,
3132 PatternToMatch(Instr,
3133 Instr->getValueAsListInit("Predicates"),
3135 TheInst.getResultPattern(),
3136 TheInst.getImpResults(),
3137 Instr->getValueAsInt("AddedComplexity"),
3143 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3145 static void FindNames(const TreePatternNode *P,
3146 std::map<std::string, NameRecord> &Names,
3147 TreePattern *PatternTop) {
3148 if (!P->getName().empty()) {
3149 NameRecord &Rec = Names[P->getName()];
3150 // If this is the first instance of the name, remember the node.
3151 if (Rec.second++ == 0)
3153 else if (Rec.first->getExtTypes() != P->getExtTypes())
3154 PatternTop->error("repetition of value: $" + P->getName() +
3155 " where different uses have different types!");
3159 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3160 FindNames(P->getChild(i), Names, PatternTop);
3164 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
3165 const PatternToMatch &PTM) {
3166 // Do some sanity checking on the pattern we're about to match.
3168 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3169 PrintWarning(Pattern->getRecord()->getLoc(),
3170 Twine("Pattern can never match: ") + Reason);
3174 // If the source pattern's root is a complex pattern, that complex pattern
3175 // must specify the nodes it can potentially match.
3176 if (const ComplexPattern *CP =
3177 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3178 if (CP->getRootNodes().empty())
3179 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3183 // Find all of the named values in the input and output, ensure they have the
3185 std::map<std::string, NameRecord> SrcNames, DstNames;
3186 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3187 FindNames(PTM.getDstPattern(), DstNames, Pattern);
3189 // Scan all of the named values in the destination pattern, rejecting them if
3190 // they don't exist in the input pattern.
3191 for (std::map<std::string, NameRecord>::iterator
3192 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
3193 if (SrcNames[I->first].first == nullptr)
3194 Pattern->error("Pattern has input without matching name in output: $" +
3198 // Scan all of the named values in the source pattern, rejecting them if the
3199 // name isn't used in the dest, and isn't used to tie two values together.
3200 for (std::map<std::string, NameRecord>::iterator
3201 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
3202 if (DstNames[I->first].first == nullptr && SrcNames[I->first].second == 1)
3203 Pattern->error("Pattern has dead named input: $" + I->first);
3205 PatternsToMatch.push_back(PTM);
3210 void CodeGenDAGPatterns::InferInstructionFlags() {
3211 const std::vector<const CodeGenInstruction*> &Instructions =
3212 Target.getInstructionsByEnumValue();
3214 // First try to infer flags from the primary instruction pattern, if any.
3215 SmallVector<CodeGenInstruction*, 8> Revisit;
3216 unsigned Errors = 0;
3217 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3218 CodeGenInstruction &InstInfo =
3219 const_cast<CodeGenInstruction &>(*Instructions[i]);
3221 // Get the primary instruction pattern.
3222 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3224 if (InstInfo.hasUndefFlags())
3225 Revisit.push_back(&InstInfo);
3228 InstAnalyzer PatInfo(*this);
3229 PatInfo.Analyze(Pattern);
3230 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
3233 // Second, look for single-instruction patterns defined outside the
3235 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3236 const PatternToMatch &PTM = *I;
3238 // We can only infer from single-instruction patterns, otherwise we won't
3239 // know which instruction should get the flags.
3240 SmallVector<Record*, 8> PatInstrs;
3241 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3242 if (PatInstrs.size() != 1)
3245 // Get the single instruction.
3246 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3248 // Only infer properties from the first pattern. We'll verify the others.
3249 if (InstInfo.InferredFrom)
3252 InstAnalyzer PatInfo(*this);
3253 PatInfo.Analyze(&PTM);
3254 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3258 PrintFatalError("pattern conflicts");
3260 // Revisit instructions with undefined flags and no pattern.
3261 if (Target.guessInstructionProperties()) {
3262 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3263 CodeGenInstruction &InstInfo = *Revisit[i];
3264 if (InstInfo.InferredFrom)
3266 // The mayLoad and mayStore flags default to false.
3267 // Conservatively assume hasSideEffects if it wasn't explicit.
3268 if (InstInfo.hasSideEffects_Unset)
3269 InstInfo.hasSideEffects = true;
3274 // Complain about any flags that are still undefined.
3275 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3276 CodeGenInstruction &InstInfo = *Revisit[i];
3277 if (InstInfo.InferredFrom)
3279 if (InstInfo.hasSideEffects_Unset)
3280 PrintError(InstInfo.TheDef->getLoc(),
3281 "Can't infer hasSideEffects from patterns");
3282 if (InstInfo.mayStore_Unset)
3283 PrintError(InstInfo.TheDef->getLoc(),
3284 "Can't infer mayStore from patterns");
3285 if (InstInfo.mayLoad_Unset)
3286 PrintError(InstInfo.TheDef->getLoc(),
3287 "Can't infer mayLoad from patterns");
3292 /// Verify instruction flags against pattern node properties.
3293 void CodeGenDAGPatterns::VerifyInstructionFlags() {
3294 unsigned Errors = 0;
3295 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3296 const PatternToMatch &PTM = *I;
3297 SmallVector<Record*, 8> Instrs;
3298 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3302 // Count the number of instructions with each flag set.
3303 unsigned NumSideEffects = 0;
3304 unsigned NumStores = 0;
3305 unsigned NumLoads = 0;
3306 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3307 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3308 NumSideEffects += InstInfo.hasSideEffects;
3309 NumStores += InstInfo.mayStore;
3310 NumLoads += InstInfo.mayLoad;
3313 // Analyze the source pattern.
3314 InstAnalyzer PatInfo(*this);
3315 PatInfo.Analyze(&PTM);
3317 // Collect error messages.
3318 SmallVector<std::string, 4> Msgs;
3320 // Check for missing flags in the output.
3321 // Permit extra flags for now at least.
3322 if (PatInfo.hasSideEffects && !NumSideEffects)
3323 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3325 // Don't verify store flags on instructions with side effects. At least for
3326 // intrinsics, side effects implies mayStore.
3327 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3328 Msgs.push_back("pattern may store, but mayStore isn't set");
3330 // Similarly, mayStore implies mayLoad on intrinsics.
3331 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3332 Msgs.push_back("pattern may load, but mayLoad isn't set");
3334 // Print error messages.
3339 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
3340 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
3341 (Instrs.size() == 1 ?
3342 "instruction" : "output instructions"));
3343 // Provide the location of the relevant instruction definitions.
3344 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3345 if (Instrs[i] != PTM.getSrcRecord())
3346 PrintError(Instrs[i]->getLoc(), "defined here");
3347 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3348 if (InstInfo.InferredFrom &&
3349 InstInfo.InferredFrom != InstInfo.TheDef &&
3350 InstInfo.InferredFrom != PTM.getSrcRecord())
3351 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from patttern");
3355 PrintFatalError("Errors in DAG patterns");
3358 /// Given a pattern result with an unresolved type, see if we can find one
3359 /// instruction with an unresolved result type. Force this result type to an
3360 /// arbitrary element if it's possible types to converge results.
3361 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3365 // Analyze children.
3366 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3367 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3370 if (!N->getOperator()->isSubClassOf("Instruction"))
3373 // If this type is already concrete or completely unknown we can't do
3375 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3376 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3379 // Otherwise, force its type to the first possibility (an arbitrary choice).
3380 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3387 void CodeGenDAGPatterns::ParsePatterns() {
3388 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3390 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
3391 Record *CurPattern = Patterns[i];
3392 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
3394 // If the pattern references the null_frag, there's nothing to do.
3395 if (hasNullFragReference(Tree))
3398 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
3400 // Inline pattern fragments into it.
3401 Pattern->InlinePatternFragments();
3403 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
3404 if (LI->getSize() == 0) continue; // no pattern.
3406 // Parse the instruction.
3407 TreePattern Result(CurPattern, LI, false, *this);
3409 // Inline pattern fragments into it.
3410 Result.InlinePatternFragments();
3412 if (Result.getNumTrees() != 1)
3413 Result.error("Cannot handle instructions producing instructions "
3414 "with temporaries yet!");
3416 bool IterateInference;
3417 bool InferredAllPatternTypes, InferredAllResultTypes;
3419 // Infer as many types as possible. If we cannot infer all of them, we
3420 // can never do anything with this pattern: report it to the user.
3421 InferredAllPatternTypes =
3422 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
3424 // Infer as many types as possible. If we cannot infer all of them, we
3425 // can never do anything with this pattern: report it to the user.
3426 InferredAllResultTypes =
3427 Result.InferAllTypes(&Pattern->getNamedNodesMap());
3429 IterateInference = false;
3431 // Apply the type of the result to the source pattern. This helps us
3432 // resolve cases where the input type is known to be a pointer type (which
3433 // is considered resolved), but the result knows it needs to be 32- or
3434 // 64-bits. Infer the other way for good measure.
3435 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
3436 Pattern->getTree(0)->getNumTypes());
3438 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3439 i, Result.getTree(0)->getExtType(i), Result);
3440 IterateInference |= Result.getTree(0)->UpdateNodeType(
3441 i, Pattern->getTree(0)->getExtType(i), Result);
3444 // If our iteration has converged and the input pattern's types are fully
3445 // resolved but the result pattern is not fully resolved, we may have a
3446 // situation where we have two instructions in the result pattern and
3447 // the instructions require a common register class, but don't care about
3448 // what actual MVT is used. This is actually a bug in our modelling:
3449 // output patterns should have register classes, not MVTs.
3451 // In any case, to handle this, we just go through and disambiguate some
3452 // arbitrary types to the result pattern's nodes.
3453 if (!IterateInference && InferredAllPatternTypes &&
3454 !InferredAllResultTypes)
3456 ForceArbitraryInstResultType(Result.getTree(0), Result);
3457 } while (IterateInference);
3459 // Verify that we inferred enough types that we can do something with the
3460 // pattern and result. If these fire the user has to add type casts.
3461 if (!InferredAllPatternTypes)
3462 Pattern->error("Could not infer all types in pattern!");
3463 if (!InferredAllResultTypes) {
3465 Result.error("Could not infer all types in pattern result!");
3468 // Validate that the input pattern is correct.
3469 std::map<std::string, TreePatternNode*> InstInputs;
3470 std::map<std::string, TreePatternNode*> InstResults;
3471 std::vector<Record*> InstImpResults;
3472 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3473 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3474 InstInputs, InstResults,
3477 // Promote the xform function to be an explicit node if set.
3478 TreePatternNode *DstPattern = Result.getOnlyTree();
3479 std::vector<TreePatternNode*> ResultNodeOperands;
3480 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3481 TreePatternNode *OpNode = DstPattern->getChild(ii);
3482 if (Record *Xform = OpNode->getTransformFn()) {
3483 OpNode->setTransformFn(nullptr);
3484 std::vector<TreePatternNode*> Children;
3485 Children.push_back(OpNode);
3486 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3488 ResultNodeOperands.push_back(OpNode);
3490 DstPattern = Result.getOnlyTree();
3491 if (!DstPattern->isLeaf())
3492 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3494 DstPattern->getNumTypes());
3496 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3497 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3499 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
3500 Temp.InferAllTypes();
3503 AddPatternToMatch(Pattern,
3504 PatternToMatch(CurPattern,
3505 CurPattern->getValueAsListInit("Predicates"),
3506 Pattern->getTree(0),
3507 Temp.getOnlyTree(), InstImpResults,
3508 CurPattern->getValueAsInt("AddedComplexity"),
3509 CurPattern->getID()));
3513 /// CombineChildVariants - Given a bunch of permutations of each child of the
3514 /// 'operator' node, put them together in all possible ways.
3515 static void CombineChildVariants(TreePatternNode *Orig,
3516 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3517 std::vector<TreePatternNode*> &OutVariants,
3518 CodeGenDAGPatterns &CDP,
3519 const MultipleUseVarSet &DepVars) {
3520 // Make sure that each operand has at least one variant to choose from.
3521 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3522 if (ChildVariants[i].empty())
3525 // The end result is an all-pairs construction of the resultant pattern.
3526 std::vector<unsigned> Idxs;
3527 Idxs.resize(ChildVariants.size());
3531 DEBUG(if (!Idxs.empty()) {
3532 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3533 for (unsigned i = 0; i < Idxs.size(); ++i) {
3534 errs() << Idxs[i] << " ";
3539 // Create the variant and add it to the output list.
3540 std::vector<TreePatternNode*> NewChildren;
3541 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3542 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
3543 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3544 Orig->getNumTypes());
3546 // Copy over properties.
3547 R->setName(Orig->getName());
3548 R->setPredicateFns(Orig->getPredicateFns());
3549 R->setTransformFn(Orig->getTransformFn());
3550 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3551 R->setType(i, Orig->getExtType(i));
3553 // If this pattern cannot match, do not include it as a variant.
3554 std::string ErrString;
3555 if (!R->canPatternMatch(ErrString, CDP)) {
3558 bool AlreadyExists = false;
3560 // Scan to see if this pattern has already been emitted. We can get
3561 // duplication due to things like commuting:
3562 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3563 // which are the same pattern. Ignore the dups.
3564 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
3565 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
3566 AlreadyExists = true;
3573 OutVariants.push_back(R);
3576 // Increment indices to the next permutation by incrementing the
3577 // indicies from last index backward, e.g., generate the sequence
3578 // [0, 0], [0, 1], [1, 0], [1, 1].
3580 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3581 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3586 NotDone = (IdxsIdx >= 0);
3590 /// CombineChildVariants - A helper function for binary operators.
3592 static void CombineChildVariants(TreePatternNode *Orig,
3593 const std::vector<TreePatternNode*> &LHS,
3594 const std::vector<TreePatternNode*> &RHS,
3595 std::vector<TreePatternNode*> &OutVariants,
3596 CodeGenDAGPatterns &CDP,
3597 const MultipleUseVarSet &DepVars) {
3598 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3599 ChildVariants.push_back(LHS);
3600 ChildVariants.push_back(RHS);
3601 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3605 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3606 std::vector<TreePatternNode *> &Children) {
3607 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3608 Record *Operator = N->getOperator();
3610 // Only permit raw nodes.
3611 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3612 N->getTransformFn()) {
3613 Children.push_back(N);
3617 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3618 Children.push_back(N->getChild(0));
3620 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3622 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3623 Children.push_back(N->getChild(1));
3625 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3628 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3629 /// the (potentially recursive) pattern by using algebraic laws.
3631 static void GenerateVariantsOf(TreePatternNode *N,
3632 std::vector<TreePatternNode*> &OutVariants,
3633 CodeGenDAGPatterns &CDP,
3634 const MultipleUseVarSet &DepVars) {
3635 // We cannot permute leaves or ComplexPattern uses.
3636 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
3637 OutVariants.push_back(N);
3641 // Look up interesting info about the node.
3642 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3644 // If this node is associative, re-associate.
3645 if (NodeInfo.hasProperty(SDNPAssociative)) {
3646 // Re-associate by pulling together all of the linked operators
3647 std::vector<TreePatternNode*> MaximalChildren;
3648 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3650 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3652 if (MaximalChildren.size() == 3) {
3653 // Find the variants of all of our maximal children.
3654 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3655 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3656 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3657 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3659 // There are only two ways we can permute the tree:
3660 // (A op B) op C and A op (B op C)
3661 // Within these forms, we can also permute A/B/C.
3663 // Generate legal pair permutations of A/B/C.
3664 std::vector<TreePatternNode*> ABVariants;
3665 std::vector<TreePatternNode*> BAVariants;
3666 std::vector<TreePatternNode*> ACVariants;
3667 std::vector<TreePatternNode*> CAVariants;
3668 std::vector<TreePatternNode*> BCVariants;
3669 std::vector<TreePatternNode*> CBVariants;
3670 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3671 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3672 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3673 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3674 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3675 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3677 // Combine those into the result: (x op x) op x
3678 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3679 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3680 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3681 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3682 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3683 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3685 // Combine those into the result: x op (x op x)
3686 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3687 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3688 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3689 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3690 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3691 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3696 // Compute permutations of all children.
3697 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3698 ChildVariants.resize(N->getNumChildren());
3699 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3700 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3702 // Build all permutations based on how the children were formed.
3703 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3705 // If this node is commutative, consider the commuted order.
3706 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3707 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3708 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3709 "Commutative but doesn't have 2 children!");
3710 // Don't count children which are actually register references.
3712 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3713 TreePatternNode *Child = N->getChild(i);
3714 if (Child->isLeaf())
3715 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
3716 Record *RR = DI->getDef();
3717 if (RR->isSubClassOf("Register"))
3722 // Consider the commuted order.
3723 if (isCommIntrinsic) {
3724 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3725 // operands are the commutative operands, and there might be more operands
3728 "Commutative intrinsic should have at least 3 childrean!");
3729 std::vector<std::vector<TreePatternNode*> > Variants;
3730 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3731 Variants.push_back(ChildVariants[2]);
3732 Variants.push_back(ChildVariants[1]);
3733 for (unsigned i = 3; i != NC; ++i)
3734 Variants.push_back(ChildVariants[i]);
3735 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3737 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3738 OutVariants, CDP, DepVars);
3743 // GenerateVariants - Generate variants. For example, commutative patterns can
3744 // match multiple ways. Add them to PatternsToMatch as well.
3745 void CodeGenDAGPatterns::GenerateVariants() {
3746 DEBUG(errs() << "Generating instruction variants.\n");
3748 // Loop over all of the patterns we've collected, checking to see if we can
3749 // generate variants of the instruction, through the exploitation of
3750 // identities. This permits the target to provide aggressive matching without
3751 // the .td file having to contain tons of variants of instructions.
3753 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3754 // intentionally do not reconsider these. Any variants of added patterns have
3755 // already been added.
3757 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3758 MultipleUseVarSet DepVars;
3759 std::vector<TreePatternNode*> Variants;
3760 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3761 DEBUG(errs() << "Dependent/multiply used variables: ");
3762 DEBUG(DumpDepVars(DepVars));
3763 DEBUG(errs() << "\n");
3764 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3767 assert(!Variants.empty() && "Must create at least original variant!");
3768 Variants.erase(Variants.begin()); // Remove the original pattern.
3770 if (Variants.empty()) // No variants for this pattern.
3773 DEBUG(errs() << "FOUND VARIANTS OF: ";
3774 PatternsToMatch[i].getSrcPattern()->dump();
3777 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3778 TreePatternNode *Variant = Variants[v];
3780 DEBUG(errs() << " VAR#" << v << ": ";
3784 // Scan to see if an instruction or explicit pattern already matches this.
3785 bool AlreadyExists = false;
3786 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3787 // Skip if the top level predicates do not match.
3788 if (PatternsToMatch[i].getPredicates() !=
3789 PatternsToMatch[p].getPredicates())
3791 // Check to see if this variant already exists.
3792 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3794 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3795 AlreadyExists = true;
3799 // If we already have it, ignore the variant.
3800 if (AlreadyExists) continue;
3802 // Otherwise, add it to the list of patterns we have.
3804 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3805 PatternsToMatch[i].getPredicates(),
3806 Variant, PatternsToMatch[i].getDstPattern(),
3807 PatternsToMatch[i].getDstRegs(),
3808 PatternsToMatch[i].getAddedComplexity(),
3809 Record::getNewUID()));
3812 DEBUG(errs() << "\n");