Fold assert-only-used variable into the assert.
[llvm/stm8.git] / utils / TableGen / CodeGenDAGPatterns.cpp
bloba08cde60fb2a9e2451ccc77634dc69a4dc3a8dd0
1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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 "Record.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/Debug.h"
20 #include <set>
21 #include <algorithm>
22 using namespace llvm;
24 //===----------------------------------------------------------------------===//
25 // EEVT::TypeSet Implementation
26 //===----------------------------------------------------------------------===//
28 static inline bool isInteger(MVT::SimpleValueType VT) {
29 return EVT(VT).isInteger();
31 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
32 return EVT(VT).isFloatingPoint();
34 static inline bool isVector(MVT::SimpleValueType VT) {
35 return EVT(VT).isVector();
37 static inline bool isScalar(MVT::SimpleValueType VT) {
38 return !EVT(VT).isVector();
41 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
42 if (VT == MVT::iAny)
43 EnforceInteger(TP);
44 else if (VT == MVT::fAny)
45 EnforceFloatingPoint(TP);
46 else if (VT == MVT::vAny)
47 EnforceVector(TP);
48 else {
49 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
50 VT == MVT::iPTRAny) && "Not a concrete type!");
51 TypeVec.push_back(VT);
56 EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
57 assert(!VTList.empty() && "empty list?");
58 TypeVec.append(VTList.begin(), VTList.end());
60 if (!VTList.empty())
61 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
62 VTList[0] != MVT::fAny);
64 // Verify no duplicates.
65 array_pod_sort(TypeVec.begin(), TypeVec.end());
66 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
69 /// FillWithPossibleTypes - Set to all legal types and return true, only valid
70 /// on completely unknown type sets.
71 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
72 bool (*Pred)(MVT::SimpleValueType),
73 const char *PredicateName) {
74 assert(isCompletelyUnknown());
75 const std::vector<MVT::SimpleValueType> &LegalTypes =
76 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
78 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
79 if (Pred == 0 || Pred(LegalTypes[i]))
80 TypeVec.push_back(LegalTypes[i]);
82 // If we have nothing that matches the predicate, bail out.
83 if (TypeVec.empty())
84 TP.error("Type inference contradiction found, no " +
85 std::string(PredicateName) + " types found");
86 // No need to sort with one element.
87 if (TypeVec.size() == 1) return true;
89 // Remove duplicates.
90 array_pod_sort(TypeVec.begin(), TypeVec.end());
91 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
93 return true;
96 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
97 /// integer value type.
98 bool EEVT::TypeSet::hasIntegerTypes() const {
99 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
100 if (isInteger(TypeVec[i]))
101 return true;
102 return false;
105 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
106 /// a floating point value type.
107 bool EEVT::TypeSet::hasFloatingPointTypes() const {
108 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
109 if (isFloatingPoint(TypeVec[i]))
110 return true;
111 return false;
114 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
115 /// value type.
116 bool EEVT::TypeSet::hasVectorTypes() const {
117 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
118 if (isVector(TypeVec[i]))
119 return true;
120 return false;
124 std::string EEVT::TypeSet::getName() const {
125 if (TypeVec.empty()) return "<empty>";
127 std::string Result;
129 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
130 std::string VTName = llvm::getEnumName(TypeVec[i]);
131 // Strip off MVT:: prefix if present.
132 if (VTName.substr(0,5) == "MVT::")
133 VTName = VTName.substr(5);
134 if (i) Result += ':';
135 Result += VTName;
138 if (TypeVec.size() == 1)
139 return Result;
140 return "{" + Result + "}";
143 /// MergeInTypeInfo - This merges in type information from the specified
144 /// argument. If 'this' changes, it returns true. If the two types are
145 /// contradictory (e.g. merge f32 into i32) then this throws an exception.
146 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
147 if (InVT.isCompletelyUnknown() || *this == InVT)
148 return false;
150 if (isCompletelyUnknown()) {
151 *this = InVT;
152 return true;
155 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
157 // Handle the abstract cases, seeing if we can resolve them better.
158 switch (TypeVec[0]) {
159 default: break;
160 case MVT::iPTR:
161 case MVT::iPTRAny:
162 if (InVT.hasIntegerTypes()) {
163 EEVT::TypeSet InCopy(InVT);
164 InCopy.EnforceInteger(TP);
165 InCopy.EnforceScalar(TP);
167 if (InCopy.isConcrete()) {
168 // If the RHS has one integer type, upgrade iPTR to i32.
169 TypeVec[0] = InVT.TypeVec[0];
170 return true;
173 // If the input has multiple scalar integers, this doesn't add any info.
174 if (!InCopy.isCompletelyUnknown())
175 return false;
177 break;
180 // If the input constraint is iAny/iPTR and this is an integer type list,
181 // remove non-integer types from the list.
182 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
183 hasIntegerTypes()) {
184 bool MadeChange = EnforceInteger(TP);
186 // If we're merging in iPTR/iPTRAny and the node currently has a list of
187 // multiple different integer types, replace them with a single iPTR.
188 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
189 TypeVec.size() != 1) {
190 TypeVec.resize(1);
191 TypeVec[0] = InVT.TypeVec[0];
192 MadeChange = true;
195 return MadeChange;
198 // If this is a type list and the RHS is a typelist as well, eliminate entries
199 // from this list that aren't in the other one.
200 bool MadeChange = false;
201 TypeSet InputSet(*this);
203 for (unsigned i = 0; i != TypeVec.size(); ++i) {
204 bool InInVT = false;
205 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
206 if (TypeVec[i] == InVT.TypeVec[j]) {
207 InInVT = true;
208 break;
211 if (InInVT) continue;
212 TypeVec.erase(TypeVec.begin()+i--);
213 MadeChange = true;
216 // If we removed all of our types, we have a type contradiction.
217 if (!TypeVec.empty())
218 return MadeChange;
220 // FIXME: Really want an SMLoc here!
221 TP.error("Type inference contradiction found, merging '" +
222 InVT.getName() + "' into '" + InputSet.getName() + "'");
223 return true; // unreachable
226 /// EnforceInteger - Remove all non-integer types from this set.
227 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
228 // If we know nothing, then get the full set.
229 if (TypeVec.empty())
230 return FillWithPossibleTypes(TP, isInteger, "integer");
231 if (!hasFloatingPointTypes())
232 return false;
234 TypeSet InputSet(*this);
236 // Filter out all the fp types.
237 for (unsigned i = 0; i != TypeVec.size(); ++i)
238 if (!isInteger(TypeVec[i]))
239 TypeVec.erase(TypeVec.begin()+i--);
241 if (TypeVec.empty())
242 TP.error("Type inference contradiction found, '" +
243 InputSet.getName() + "' needs to be integer");
244 return true;
247 /// EnforceFloatingPoint - Remove all integer types from this set.
248 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
249 // If we know nothing, then get the full set.
250 if (TypeVec.empty())
251 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
253 if (!hasIntegerTypes())
254 return false;
256 TypeSet InputSet(*this);
258 // Filter out all the fp types.
259 for (unsigned i = 0; i != TypeVec.size(); ++i)
260 if (!isFloatingPoint(TypeVec[i]))
261 TypeVec.erase(TypeVec.begin()+i--);
263 if (TypeVec.empty())
264 TP.error("Type inference contradiction found, '" +
265 InputSet.getName() + "' needs to be floating point");
266 return true;
269 /// EnforceScalar - Remove all vector types from this.
270 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
271 // If we know nothing, then get the full set.
272 if (TypeVec.empty())
273 return FillWithPossibleTypes(TP, isScalar, "scalar");
275 if (!hasVectorTypes())
276 return false;
278 TypeSet InputSet(*this);
280 // Filter out all the vector types.
281 for (unsigned i = 0; i != TypeVec.size(); ++i)
282 if (!isScalar(TypeVec[i]))
283 TypeVec.erase(TypeVec.begin()+i--);
285 if (TypeVec.empty())
286 TP.error("Type inference contradiction found, '" +
287 InputSet.getName() + "' needs to be scalar");
288 return true;
291 /// EnforceVector - Remove all vector types from this.
292 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
293 // If we know nothing, then get the full set.
294 if (TypeVec.empty())
295 return FillWithPossibleTypes(TP, isVector, "vector");
297 TypeSet InputSet(*this);
298 bool MadeChange = false;
300 // Filter out all the scalar types.
301 for (unsigned i = 0; i != TypeVec.size(); ++i)
302 if (!isVector(TypeVec[i])) {
303 TypeVec.erase(TypeVec.begin()+i--);
304 MadeChange = true;
307 if (TypeVec.empty())
308 TP.error("Type inference contradiction found, '" +
309 InputSet.getName() + "' needs to be a vector");
310 return MadeChange;
315 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
316 /// this an other based on this information.
317 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
318 // Both operands must be integer or FP, but we don't care which.
319 bool MadeChange = false;
321 if (isCompletelyUnknown())
322 MadeChange = FillWithPossibleTypes(TP);
324 if (Other.isCompletelyUnknown())
325 MadeChange = Other.FillWithPossibleTypes(TP);
327 // If one side is known to be integer or known to be FP but the other side has
328 // no information, get at least the type integrality info in there.
329 if (!hasFloatingPointTypes())
330 MadeChange |= Other.EnforceInteger(TP);
331 else if (!hasIntegerTypes())
332 MadeChange |= Other.EnforceFloatingPoint(TP);
333 if (!Other.hasFloatingPointTypes())
334 MadeChange |= EnforceInteger(TP);
335 else if (!Other.hasIntegerTypes())
336 MadeChange |= EnforceFloatingPoint(TP);
338 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
339 "Should have a type list now");
341 // If one contains vectors but the other doesn't pull vectors out.
342 if (!hasVectorTypes())
343 MadeChange |= Other.EnforceScalar(TP);
344 if (!hasVectorTypes())
345 MadeChange |= EnforceScalar(TP);
347 if (TypeVec.size() == 1 && Other.TypeVec.size() == 1) {
348 // If we are down to concrete types, this code does not currently
349 // handle nodes which have multiple types, where some types are
350 // integer, and some are fp. Assert that this is not the case.
351 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
352 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
353 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
355 // Otherwise, if these are both vector types, either this vector
356 // must have a larger bitsize than the other, or this element type
357 // must be larger than the other.
358 EVT Type(TypeVec[0]);
359 EVT OtherType(Other.TypeVec[0]);
361 if (hasVectorTypes() && Other.hasVectorTypes()) {
362 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
363 if (Type.getVectorElementType().getSizeInBits()
364 >= OtherType.getVectorElementType().getSizeInBits())
365 TP.error("Type inference contradiction found, '" +
366 getName() + "' element type not smaller than '" +
367 Other.getName() +"'!");
369 else
370 // For scalar types, the bitsize of this type must be larger
371 // than that of the other.
372 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
373 TP.error("Type inference contradiction found, '" +
374 getName() + "' is not smaller than '" +
375 Other.getName() +"'!");
380 // Handle int and fp as disjoint sets. This won't work for patterns
381 // that have mixed fp/int types but those are likely rare and would
382 // not have been accepted by this code previously.
384 // Okay, find the smallest type from the current set and remove it from the
385 // largest set.
386 MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
387 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
388 if (isInteger(TypeVec[i])) {
389 SmallestInt = TypeVec[i];
390 break;
392 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
393 if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
394 SmallestInt = TypeVec[i];
396 MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
397 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
398 if (isFloatingPoint(TypeVec[i])) {
399 SmallestFP = TypeVec[i];
400 break;
402 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
403 if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
404 SmallestFP = TypeVec[i];
406 int OtherIntSize = 0;
407 int OtherFPSize = 0;
408 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
409 Other.TypeVec.begin();
410 TVI != Other.TypeVec.end();
411 /* NULL */) {
412 if (isInteger(*TVI)) {
413 ++OtherIntSize;
414 if (*TVI == SmallestInt) {
415 TVI = Other.TypeVec.erase(TVI);
416 --OtherIntSize;
417 MadeChange = true;
418 continue;
421 else if (isFloatingPoint(*TVI)) {
422 ++OtherFPSize;
423 if (*TVI == SmallestFP) {
424 TVI = Other.TypeVec.erase(TVI);
425 --OtherFPSize;
426 MadeChange = true;
427 continue;
430 ++TVI;
433 // If this is the only type in the large set, the constraint can never be
434 // satisfied.
435 if ((Other.hasIntegerTypes() && OtherIntSize == 0)
436 || (Other.hasFloatingPointTypes() && OtherFPSize == 0))
437 TP.error("Type inference contradiction found, '" +
438 Other.getName() + "' has nothing larger than '" + getName() +"'!");
440 // Okay, find the largest type in the Other set and remove it from the
441 // current set.
442 MVT::SimpleValueType LargestInt = MVT::Other;
443 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
444 if (isInteger(Other.TypeVec[i])) {
445 LargestInt = Other.TypeVec[i];
446 break;
448 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
449 if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
450 LargestInt = Other.TypeVec[i];
452 MVT::SimpleValueType LargestFP = MVT::Other;
453 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
454 if (isFloatingPoint(Other.TypeVec[i])) {
455 LargestFP = Other.TypeVec[i];
456 break;
458 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
459 if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
460 LargestFP = Other.TypeVec[i];
462 int IntSize = 0;
463 int FPSize = 0;
464 for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
465 TypeVec.begin();
466 TVI != TypeVec.end();
467 /* NULL */) {
468 if (isInteger(*TVI)) {
469 ++IntSize;
470 if (*TVI == LargestInt) {
471 TVI = TypeVec.erase(TVI);
472 --IntSize;
473 MadeChange = true;
474 continue;
477 else if (isFloatingPoint(*TVI)) {
478 ++FPSize;
479 if (*TVI == LargestFP) {
480 TVI = TypeVec.erase(TVI);
481 --FPSize;
482 MadeChange = true;
483 continue;
486 ++TVI;
489 // If this is the only type in the small set, the constraint can never be
490 // satisfied.
491 if ((hasIntegerTypes() && IntSize == 0)
492 || (hasFloatingPointTypes() && FPSize == 0))
493 TP.error("Type inference contradiction found, '" +
494 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
496 return MadeChange;
499 /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
500 /// whose element is specified by VTOperand.
501 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
502 TreePattern &TP) {
503 // "This" must be a vector and "VTOperand" must be a scalar.
504 bool MadeChange = false;
505 MadeChange |= EnforceVector(TP);
506 MadeChange |= VTOperand.EnforceScalar(TP);
508 // If we know the vector type, it forces the scalar to agree.
509 if (isConcrete()) {
510 EVT IVT = getConcrete();
511 IVT = IVT.getVectorElementType();
512 return MadeChange |
513 VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
516 // If the scalar type is known, filter out vector types whose element types
517 // disagree.
518 if (!VTOperand.isConcrete())
519 return MadeChange;
521 MVT::SimpleValueType VT = VTOperand.getConcrete();
523 TypeSet InputSet(*this);
525 // Filter out all the types which don't have the right element type.
526 for (unsigned i = 0; i != TypeVec.size(); ++i) {
527 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
528 if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
529 TypeVec.erase(TypeVec.begin()+i--);
530 MadeChange = true;
534 if (TypeVec.empty()) // FIXME: Really want an SMLoc here!
535 TP.error("Type inference contradiction found, forcing '" +
536 InputSet.getName() + "' to have a vector element");
537 return MadeChange;
540 /// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
541 /// vector type specified by VTOperand.
542 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
543 TreePattern &TP) {
544 // "This" must be a vector and "VTOperand" must be a vector.
545 bool MadeChange = false;
546 MadeChange |= EnforceVector(TP);
547 MadeChange |= VTOperand.EnforceVector(TP);
549 // "This" must be larger than "VTOperand."
550 MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
552 // If we know the vector type, it forces the scalar types to agree.
553 if (isConcrete()) {
554 EVT IVT = getConcrete();
555 IVT = IVT.getVectorElementType();
557 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
558 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
559 } else if (VTOperand.isConcrete()) {
560 EVT IVT = VTOperand.getConcrete();
561 IVT = IVT.getVectorElementType();
563 EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
564 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
567 return MadeChange;
570 //===----------------------------------------------------------------------===//
571 // Helpers for working with extended types.
573 bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
574 return LHS->getID() < RHS->getID();
577 /// Dependent variable map for CodeGenDAGPattern variant generation
578 typedef std::map<std::string, int> DepVarMap;
580 /// Const iterator shorthand for DepVarMap
581 typedef DepVarMap::const_iterator DepVarMap_citer;
583 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
584 if (N->isLeaf()) {
585 if (dynamic_cast<DefInit*>(N->getLeafValue()) != NULL)
586 DepMap[N->getName()]++;
587 } else {
588 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
589 FindDepVarsOf(N->getChild(i), DepMap);
593 /// Find dependent variables within child patterns
594 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
595 DepVarMap depcounts;
596 FindDepVarsOf(N, depcounts);
597 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
598 if (i->second > 1) // std::pair<std::string, int>
599 DepVars.insert(i->first);
603 #ifndef NDEBUG
604 /// Dump the dependent variable set:
605 static void DumpDepVars(MultipleUseVarSet &DepVars) {
606 if (DepVars.empty()) {
607 DEBUG(errs() << "<empty set>");
608 } else {
609 DEBUG(errs() << "[ ");
610 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
611 e = DepVars.end(); i != e; ++i) {
612 DEBUG(errs() << (*i) << " ");
614 DEBUG(errs() << "]");
617 #endif
620 //===----------------------------------------------------------------------===//
621 // TreePredicateFn Implementation
622 //===----------------------------------------------------------------------===//
624 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
625 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
626 assert((getPredCode().empty() || getImmCode().empty()) &&
627 ".td file corrupt: can't have a node predicate *and* an imm predicate");
630 std::string TreePredicateFn::getPredCode() const {
631 return PatFragRec->getRecord()->getValueAsCode("PredicateCode");
634 std::string TreePredicateFn::getImmCode() const {
635 return PatFragRec->getRecord()->getValueAsCode("ImmediateCode");
639 /// isAlwaysTrue - Return true if this is a noop predicate.
640 bool TreePredicateFn::isAlwaysTrue() const {
641 return getPredCode().empty() && getImmCode().empty();
644 /// Return the name to use in the generated code to reference this, this is
645 /// "Predicate_foo" if from a pattern fragment "foo".
646 std::string TreePredicateFn::getFnName() const {
647 return "Predicate_" + PatFragRec->getRecord()->getName();
650 /// getCodeToRunOnSDNode - Return the code for the function body that
651 /// evaluates this predicate. The argument is expected to be in "Node",
652 /// not N. This handles casting and conversion to a concrete node type as
653 /// appropriate.
654 std::string TreePredicateFn::getCodeToRunOnSDNode() const {
655 // Handle immediate predicates first.
656 std::string ImmCode = getImmCode();
657 if (!ImmCode.empty()) {
658 std::string Result =
659 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
660 return Result + ImmCode;
663 // Handle arbitrary node predicates.
664 assert(!getPredCode().empty() && "Don't have any predicate code!");
665 std::string ClassName;
666 if (PatFragRec->getOnlyTree()->isLeaf())
667 ClassName = "SDNode";
668 else {
669 Record *Op = PatFragRec->getOnlyTree()->getOperator();
670 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
672 std::string Result;
673 if (ClassName == "SDNode")
674 Result = " SDNode *N = Node;\n";
675 else
676 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
678 return Result + getPredCode();
681 //===----------------------------------------------------------------------===//
682 // PatternToMatch implementation
686 /// getPatternSize - Return the 'size' of this pattern. We want to match large
687 /// patterns before small ones. This is used to determine the size of a
688 /// pattern.
689 static unsigned getPatternSize(const TreePatternNode *P,
690 const CodeGenDAGPatterns &CGP) {
691 unsigned Size = 3; // The node itself.
692 // If the root node is a ConstantSDNode, increases its size.
693 // e.g. (set R32:$dst, 0).
694 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
695 Size += 2;
697 // FIXME: This is a hack to statically increase the priority of patterns
698 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
699 // Later we can allow complexity / cost for each pattern to be (optionally)
700 // specified. To get best possible pattern match we'll need to dynamically
701 // calculate the complexity of all patterns a dag can potentially map to.
702 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
703 if (AM)
704 Size += AM->getNumOperands() * 3;
706 // If this node has some predicate function that must match, it adds to the
707 // complexity of this node.
708 if (!P->getPredicateFns().empty())
709 ++Size;
711 // Count children in the count if they are also nodes.
712 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
713 TreePatternNode *Child = P->getChild(i);
714 if (!Child->isLeaf() && Child->getNumTypes() &&
715 Child->getType(0) != MVT::Other)
716 Size += getPatternSize(Child, CGP);
717 else if (Child->isLeaf()) {
718 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
719 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
720 else if (Child->getComplexPatternInfo(CGP))
721 Size += getPatternSize(Child, CGP);
722 else if (!Child->getPredicateFns().empty())
723 ++Size;
727 return Size;
730 /// Compute the complexity metric for the input pattern. This roughly
731 /// corresponds to the number of nodes that are covered.
732 unsigned PatternToMatch::
733 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
734 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
738 /// getPredicateCheck - Return a single string containing all of this
739 /// pattern's predicates concatenated with "&&" operators.
741 std::string PatternToMatch::getPredicateCheck() const {
742 std::string PredicateCheck;
743 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
744 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
745 Record *Def = Pred->getDef();
746 if (!Def->isSubClassOf("Predicate")) {
747 #ifndef NDEBUG
748 Def->dump();
749 #endif
750 assert(0 && "Unknown predicate type!");
752 if (!PredicateCheck.empty())
753 PredicateCheck += " && ";
754 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
758 return PredicateCheck;
761 //===----------------------------------------------------------------------===//
762 // SDTypeConstraint implementation
765 SDTypeConstraint::SDTypeConstraint(Record *R) {
766 OperandNo = R->getValueAsInt("OperandNum");
768 if (R->isSubClassOf("SDTCisVT")) {
769 ConstraintType = SDTCisVT;
770 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
771 if (x.SDTCisVT_Info.VT == MVT::isVoid)
772 throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
774 } else if (R->isSubClassOf("SDTCisPtrTy")) {
775 ConstraintType = SDTCisPtrTy;
776 } else if (R->isSubClassOf("SDTCisInt")) {
777 ConstraintType = SDTCisInt;
778 } else if (R->isSubClassOf("SDTCisFP")) {
779 ConstraintType = SDTCisFP;
780 } else if (R->isSubClassOf("SDTCisVec")) {
781 ConstraintType = SDTCisVec;
782 } else if (R->isSubClassOf("SDTCisSameAs")) {
783 ConstraintType = SDTCisSameAs;
784 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
785 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
786 ConstraintType = SDTCisVTSmallerThanOp;
787 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
788 R->getValueAsInt("OtherOperandNum");
789 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
790 ConstraintType = SDTCisOpSmallerThanOp;
791 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
792 R->getValueAsInt("BigOperandNum");
793 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
794 ConstraintType = SDTCisEltOfVec;
795 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
796 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
797 ConstraintType = SDTCisSubVecOfVec;
798 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
799 R->getValueAsInt("OtherOpNum");
800 } else {
801 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
802 exit(1);
806 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
807 /// N, and the result number in ResNo.
808 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
809 const SDNodeInfo &NodeInfo,
810 unsigned &ResNo) {
811 unsigned NumResults = NodeInfo.getNumResults();
812 if (OpNo < NumResults) {
813 ResNo = OpNo;
814 return N;
817 OpNo -= NumResults;
819 if (OpNo >= N->getNumChildren()) {
820 errs() << "Invalid operand number in type constraint "
821 << (OpNo+NumResults) << " ";
822 N->dump();
823 errs() << '\n';
824 exit(1);
827 return N->getChild(OpNo);
830 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
831 /// constraint to the nodes operands. This returns true if it makes a
832 /// change, false otherwise. If a type contradiction is found, throw an
833 /// exception.
834 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
835 const SDNodeInfo &NodeInfo,
836 TreePattern &TP) const {
837 unsigned ResNo = 0; // The result number being referenced.
838 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
840 switch (ConstraintType) {
841 default: assert(0 && "Unknown constraint type!");
842 case SDTCisVT:
843 // Operand must be a particular type.
844 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
845 case SDTCisPtrTy:
846 // Operand must be same as target pointer type.
847 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
848 case SDTCisInt:
849 // Require it to be one of the legal integer VTs.
850 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
851 case SDTCisFP:
852 // Require it to be one of the legal fp VTs.
853 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
854 case SDTCisVec:
855 // Require it to be one of the legal vector VTs.
856 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
857 case SDTCisSameAs: {
858 unsigned OResNo = 0;
859 TreePatternNode *OtherNode =
860 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
861 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
862 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
864 case SDTCisVTSmallerThanOp: {
865 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
866 // have an integer type that is smaller than the VT.
867 if (!NodeToApply->isLeaf() ||
868 !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
869 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
870 ->isSubClassOf("ValueType"))
871 TP.error(N->getOperator()->getName() + " expects a VT operand!");
872 MVT::SimpleValueType VT =
873 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
875 EEVT::TypeSet TypeListTmp(VT, TP);
877 unsigned OResNo = 0;
878 TreePatternNode *OtherNode =
879 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
880 OResNo);
882 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
884 case SDTCisOpSmallerThanOp: {
885 unsigned BResNo = 0;
886 TreePatternNode *BigOperand =
887 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
888 BResNo);
889 return NodeToApply->getExtType(ResNo).
890 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
892 case SDTCisEltOfVec: {
893 unsigned VResNo = 0;
894 TreePatternNode *VecOperand =
895 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
896 VResNo);
898 // Filter vector types out of VecOperand that don't have the right element
899 // type.
900 return VecOperand->getExtType(VResNo).
901 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
903 case SDTCisSubVecOfVec: {
904 unsigned VResNo = 0;
905 TreePatternNode *BigVecOperand =
906 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
907 VResNo);
909 // Filter vector types out of BigVecOperand that don't have the
910 // right subvector type.
911 return BigVecOperand->getExtType(VResNo).
912 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
915 return false;
918 //===----------------------------------------------------------------------===//
919 // SDNodeInfo implementation
921 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
922 EnumName = R->getValueAsString("Opcode");
923 SDClassName = R->getValueAsString("SDClass");
924 Record *TypeProfile = R->getValueAsDef("TypeProfile");
925 NumResults = TypeProfile->getValueAsInt("NumResults");
926 NumOperands = TypeProfile->getValueAsInt("NumOperands");
928 // Parse the properties.
929 Properties = 0;
930 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
931 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
932 if (PropList[i]->getName() == "SDNPCommutative") {
933 Properties |= 1 << SDNPCommutative;
934 } else if (PropList[i]->getName() == "SDNPAssociative") {
935 Properties |= 1 << SDNPAssociative;
936 } else if (PropList[i]->getName() == "SDNPHasChain") {
937 Properties |= 1 << SDNPHasChain;
938 } else if (PropList[i]->getName() == "SDNPOutGlue") {
939 Properties |= 1 << SDNPOutGlue;
940 } else if (PropList[i]->getName() == "SDNPInGlue") {
941 Properties |= 1 << SDNPInGlue;
942 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
943 Properties |= 1 << SDNPOptInGlue;
944 } else if (PropList[i]->getName() == "SDNPMayStore") {
945 Properties |= 1 << SDNPMayStore;
946 } else if (PropList[i]->getName() == "SDNPMayLoad") {
947 Properties |= 1 << SDNPMayLoad;
948 } else if (PropList[i]->getName() == "SDNPSideEffect") {
949 Properties |= 1 << SDNPSideEffect;
950 } else if (PropList[i]->getName() == "SDNPMemOperand") {
951 Properties |= 1 << SDNPMemOperand;
952 } else if (PropList[i]->getName() == "SDNPVariadic") {
953 Properties |= 1 << SDNPVariadic;
954 } else {
955 errs() << "Unknown SD Node property '" << PropList[i]->getName()
956 << "' on node '" << R->getName() << "'!\n";
957 exit(1);
962 // Parse the type constraints.
963 std::vector<Record*> ConstraintList =
964 TypeProfile->getValueAsListOfDefs("Constraints");
965 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
968 /// getKnownType - If the type constraints on this node imply a fixed type
969 /// (e.g. all stores return void, etc), then return it as an
970 /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
971 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
972 unsigned NumResults = getNumResults();
973 assert(NumResults <= 1 &&
974 "We only work with nodes with zero or one result so far!");
975 assert(ResNo == 0 && "Only handles single result nodes so far");
977 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
978 // Make sure that this applies to the correct node result.
979 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
980 continue;
982 switch (TypeConstraints[i].ConstraintType) {
983 default: break;
984 case SDTypeConstraint::SDTCisVT:
985 return TypeConstraints[i].x.SDTCisVT_Info.VT;
986 case SDTypeConstraint::SDTCisPtrTy:
987 return MVT::iPTR;
990 return MVT::Other;
993 //===----------------------------------------------------------------------===//
994 // TreePatternNode implementation
997 TreePatternNode::~TreePatternNode() {
998 #if 0 // FIXME: implement refcounted tree nodes!
999 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1000 delete getChild(i);
1001 #endif
1004 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1005 if (Operator->getName() == "set" ||
1006 Operator->getName() == "implicit")
1007 return 0; // All return nothing.
1009 if (Operator->isSubClassOf("Intrinsic"))
1010 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1012 if (Operator->isSubClassOf("SDNode"))
1013 return CDP.getSDNodeInfo(Operator).getNumResults();
1015 if (Operator->isSubClassOf("PatFrag")) {
1016 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1017 // the forward reference case where one pattern fragment references another
1018 // before it is processed.
1019 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1020 return PFRec->getOnlyTree()->getNumTypes();
1022 // Get the result tree.
1023 DagInit *Tree = Operator->getValueAsDag("Fragment");
1024 Record *Op = 0;
1025 if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
1026 Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
1027 assert(Op && "Invalid Fragment");
1028 return GetNumNodeResults(Op, CDP);
1031 if (Operator->isSubClassOf("Instruction")) {
1032 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1034 // FIXME: Should allow access to all the results here.
1035 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
1037 // Add on one implicit def if it has a resolvable type.
1038 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1039 ++NumDefsToAdd;
1040 return NumDefsToAdd;
1043 if (Operator->isSubClassOf("SDNodeXForm"))
1044 return 1; // FIXME: Generalize SDNodeXForm
1046 Operator->dump();
1047 errs() << "Unhandled node in GetNumNodeResults\n";
1048 exit(1);
1051 void TreePatternNode::print(raw_ostream &OS) const {
1052 if (isLeaf())
1053 OS << *getLeafValue();
1054 else
1055 OS << '(' << getOperator()->getName();
1057 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1058 OS << ':' << getExtType(i).getName();
1060 if (!isLeaf()) {
1061 if (getNumChildren() != 0) {
1062 OS << " ";
1063 getChild(0)->print(OS);
1064 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1065 OS << ", ";
1066 getChild(i)->print(OS);
1069 OS << ")";
1072 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
1073 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
1074 if (TransformFn)
1075 OS << "<<X:" << TransformFn->getName() << ">>";
1076 if (!getName().empty())
1077 OS << ":$" << getName();
1080 void TreePatternNode::dump() const {
1081 print(errs());
1084 /// isIsomorphicTo - Return true if this node is recursively
1085 /// isomorphic to the specified node. For this comparison, the node's
1086 /// entire state is considered. The assigned name is ignored, since
1087 /// nodes with differing names are considered isomorphic. However, if
1088 /// the assigned name is present in the dependent variable set, then
1089 /// the assigned name is considered significant and the node is
1090 /// isomorphic if the names match.
1091 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1092 const MultipleUseVarSet &DepVars) const {
1093 if (N == this) return true;
1094 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1095 getPredicateFns() != N->getPredicateFns() ||
1096 getTransformFn() != N->getTransformFn())
1097 return false;
1099 if (isLeaf()) {
1100 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1101 if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1102 return ((DI->getDef() == NDI->getDef())
1103 && (DepVars.find(getName()) == DepVars.end()
1104 || getName() == N->getName()));
1107 return getLeafValue() == N->getLeafValue();
1110 if (N->getOperator() != getOperator() ||
1111 N->getNumChildren() != getNumChildren()) return false;
1112 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1113 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1114 return false;
1115 return true;
1118 /// clone - Make a copy of this tree and all of its children.
1120 TreePatternNode *TreePatternNode::clone() const {
1121 TreePatternNode *New;
1122 if (isLeaf()) {
1123 New = new TreePatternNode(getLeafValue(), getNumTypes());
1124 } else {
1125 std::vector<TreePatternNode*> CChildren;
1126 CChildren.reserve(Children.size());
1127 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1128 CChildren.push_back(getChild(i)->clone());
1129 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1131 New->setName(getName());
1132 New->Types = Types;
1133 New->setPredicateFns(getPredicateFns());
1134 New->setTransformFn(getTransformFn());
1135 return New;
1138 /// RemoveAllTypes - Recursively strip all the types of this tree.
1139 void TreePatternNode::RemoveAllTypes() {
1140 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1141 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
1142 if (isLeaf()) return;
1143 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1144 getChild(i)->RemoveAllTypes();
1148 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1149 /// with actual values specified by ArgMap.
1150 void TreePatternNode::
1151 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1152 if (isLeaf()) return;
1154 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1155 TreePatternNode *Child = getChild(i);
1156 if (Child->isLeaf()) {
1157 Init *Val = Child->getLeafValue();
1158 if (dynamic_cast<DefInit*>(Val) &&
1159 static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
1160 // We found a use of a formal argument, replace it with its value.
1161 TreePatternNode *NewChild = ArgMap[Child->getName()];
1162 assert(NewChild && "Couldn't find formal argument!");
1163 assert((Child->getPredicateFns().empty() ||
1164 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1165 "Non-empty child predicate clobbered!");
1166 setChild(i, NewChild);
1168 } else {
1169 getChild(i)->SubstituteFormalArguments(ArgMap);
1175 /// InlinePatternFragments - If this pattern refers to any pattern
1176 /// fragments, inline them into place, giving us a pattern without any
1177 /// PatFrag references.
1178 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1179 if (isLeaf()) return this; // nothing to do.
1180 Record *Op = getOperator();
1182 if (!Op->isSubClassOf("PatFrag")) {
1183 // Just recursively inline children nodes.
1184 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1185 TreePatternNode *Child = getChild(i);
1186 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1188 assert((Child->getPredicateFns().empty() ||
1189 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1190 "Non-empty child predicate clobbered!");
1192 setChild(i, NewChild);
1194 return this;
1197 // Otherwise, we found a reference to a fragment. First, look up its
1198 // TreePattern record.
1199 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1201 // Verify that we are passing the right number of operands.
1202 if (Frag->getNumArgs() != Children.size())
1203 TP.error("'" + Op->getName() + "' fragment requires " +
1204 utostr(Frag->getNumArgs()) + " operands!");
1206 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1208 TreePredicateFn PredFn(Frag);
1209 if (!PredFn.isAlwaysTrue())
1210 FragTree->addPredicateFn(PredFn);
1212 // Resolve formal arguments to their actual value.
1213 if (Frag->getNumArgs()) {
1214 // Compute the map of formal to actual arguments.
1215 std::map<std::string, TreePatternNode*> ArgMap;
1216 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1217 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1219 FragTree->SubstituteFormalArguments(ArgMap);
1222 FragTree->setName(getName());
1223 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1224 FragTree->UpdateNodeType(i, getExtType(i), TP);
1226 // Transfer in the old predicates.
1227 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1228 FragTree->addPredicateFn(getPredicateFns()[i]);
1230 // Get a new copy of this fragment to stitch into here.
1231 //delete this; // FIXME: implement refcounting!
1233 // The fragment we inlined could have recursive inlining that is needed. See
1234 // if there are any pattern fragments in it and inline them as needed.
1235 return FragTree->InlinePatternFragments(TP);
1238 /// getImplicitType - Check to see if the specified record has an implicit
1239 /// type which should be applied to it. This will infer the type of register
1240 /// references from the register file information, for example.
1242 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1243 bool NotRegisters, TreePattern &TP) {
1244 // Check to see if this is a register or a register class.
1245 if (R->isSubClassOf("RegisterClass")) {
1246 assert(ResNo == 0 && "Regclass ref only has one result!");
1247 if (NotRegisters)
1248 return EEVT::TypeSet(); // Unknown.
1249 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1250 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1253 if (R->isSubClassOf("PatFrag")) {
1254 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1255 // Pattern fragment types will be resolved when they are inlined.
1256 return EEVT::TypeSet(); // Unknown.
1259 if (R->isSubClassOf("Register")) {
1260 assert(ResNo == 0 && "Registers only produce one result!");
1261 if (NotRegisters)
1262 return EEVT::TypeSet(); // Unknown.
1263 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1264 return EEVT::TypeSet(T.getRegisterVTs(R));
1267 if (R->isSubClassOf("SubRegIndex")) {
1268 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1269 return EEVT::TypeSet();
1272 if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1273 assert(ResNo == 0 && "This node only has one result!");
1274 // Using a VTSDNode or CondCodeSDNode.
1275 return EEVT::TypeSet(MVT::Other, TP);
1278 if (R->isSubClassOf("ComplexPattern")) {
1279 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1280 if (NotRegisters)
1281 return EEVT::TypeSet(); // Unknown.
1282 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1283 TP);
1285 if (R->isSubClassOf("PointerLikeRegClass")) {
1286 assert(ResNo == 0 && "Regclass can only have one result!");
1287 return EEVT::TypeSet(MVT::iPTR, TP);
1290 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1291 R->getName() == "zero_reg") {
1292 // Placeholder.
1293 return EEVT::TypeSet(); // Unknown.
1296 TP.error("Unknown node flavor used in pattern: " + R->getName());
1297 return EEVT::TypeSet(MVT::Other, TP);
1301 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1302 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1303 const CodeGenIntrinsic *TreePatternNode::
1304 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1305 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1306 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1307 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1308 return 0;
1310 unsigned IID =
1311 dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1312 return &CDP.getIntrinsicInfo(IID);
1315 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1316 /// return the ComplexPattern information, otherwise return null.
1317 const ComplexPattern *
1318 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1319 if (!isLeaf()) return 0;
1321 DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1322 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1323 return &CGP.getComplexPattern(DI->getDef());
1324 return 0;
1327 /// NodeHasProperty - Return true if this node has the specified property.
1328 bool TreePatternNode::NodeHasProperty(SDNP Property,
1329 const CodeGenDAGPatterns &CGP) const {
1330 if (isLeaf()) {
1331 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1332 return CP->hasProperty(Property);
1333 return false;
1336 Record *Operator = getOperator();
1337 if (!Operator->isSubClassOf("SDNode")) return false;
1339 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1345 /// TreeHasProperty - Return true if any node in this tree has the specified
1346 /// property.
1347 bool TreePatternNode::TreeHasProperty(SDNP Property,
1348 const CodeGenDAGPatterns &CGP) const {
1349 if (NodeHasProperty(Property, CGP))
1350 return true;
1351 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1352 if (getChild(i)->TreeHasProperty(Property, CGP))
1353 return true;
1354 return false;
1357 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1358 /// commutative intrinsic.
1359 bool
1360 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1361 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1362 return Int->isCommutative;
1363 return false;
1367 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1368 /// this node and its children in the tree. This returns true if it makes a
1369 /// change, false otherwise. If a type contradiction is found, throw an
1370 /// exception.
1371 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1372 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1373 if (isLeaf()) {
1374 if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1375 // If it's a regclass or something else known, include the type.
1376 bool MadeChange = false;
1377 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1378 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1379 NotRegisters, TP), TP);
1380 return MadeChange;
1383 if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
1384 assert(Types.size() == 1 && "Invalid IntInit");
1386 // Int inits are always integers. :)
1387 bool MadeChange = Types[0].EnforceInteger(TP);
1389 if (!Types[0].isConcrete())
1390 return MadeChange;
1392 MVT::SimpleValueType VT = getType(0);
1393 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1394 return MadeChange;
1396 unsigned Size = EVT(VT).getSizeInBits();
1397 // Make sure that the value is representable for this type.
1398 if (Size >= 32) return MadeChange;
1400 int Val = (II->getValue() << (32-Size)) >> (32-Size);
1401 if (Val == II->getValue()) return MadeChange;
1403 // If sign-extended doesn't fit, does it fit as unsigned?
1404 unsigned ValueMask;
1405 unsigned UnsignedVal;
1406 ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1407 UnsignedVal = unsigned(II->getValue());
1409 if ((ValueMask & UnsignedVal) == UnsignedVal)
1410 return MadeChange;
1412 TP.error("Integer value '" + itostr(II->getValue())+
1413 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1414 return MadeChange;
1416 return false;
1419 // special handling for set, which isn't really an SDNode.
1420 if (getOperator()->getName() == "set") {
1421 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1422 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1423 unsigned NC = getNumChildren();
1425 TreePatternNode *SetVal = getChild(NC-1);
1426 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1428 for (unsigned i = 0; i < NC-1; ++i) {
1429 TreePatternNode *Child = getChild(i);
1430 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1432 // Types of operands must match.
1433 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1434 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1436 return MadeChange;
1439 if (getOperator()->getName() == "implicit") {
1440 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1442 bool MadeChange = false;
1443 for (unsigned i = 0; i < getNumChildren(); ++i)
1444 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1445 return MadeChange;
1448 if (getOperator()->getName() == "COPY_TO_REGCLASS") {
1449 bool MadeChange = false;
1450 MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1451 MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1453 assert(getChild(0)->getNumTypes() == 1 &&
1454 getChild(1)->getNumTypes() == 1 && "Unhandled case");
1456 // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
1457 // what type it gets, so if it didn't get a concrete type just give it the
1458 // first viable type from the reg class.
1459 if (!getChild(1)->hasTypeSet(0) &&
1460 !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1461 MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1462 MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
1464 return MadeChange;
1467 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1468 bool MadeChange = false;
1470 // Apply the result type to the node.
1471 unsigned NumRetVTs = Int->IS.RetVTs.size();
1472 unsigned NumParamVTs = Int->IS.ParamVTs.size();
1474 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1475 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1477 if (getNumChildren() != NumParamVTs + 1)
1478 TP.error("Intrinsic '" + Int->Name + "' expects " +
1479 utostr(NumParamVTs) + " operands, not " +
1480 utostr(getNumChildren() - 1) + " operands!");
1482 // Apply type info to the intrinsic ID.
1483 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1485 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1486 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1488 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1489 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1490 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1492 return MadeChange;
1495 if (getOperator()->isSubClassOf("SDNode")) {
1496 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1498 // Check that the number of operands is sane. Negative operands -> varargs.
1499 if (NI.getNumOperands() >= 0 &&
1500 getNumChildren() != (unsigned)NI.getNumOperands())
1501 TP.error(getOperator()->getName() + " node requires exactly " +
1502 itostr(NI.getNumOperands()) + " operands!");
1504 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1505 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1506 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1507 return MadeChange;
1510 if (getOperator()->isSubClassOf("Instruction")) {
1511 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1512 CodeGenInstruction &InstInfo =
1513 CDP.getTargetInfo().getInstruction(getOperator());
1515 bool MadeChange = false;
1517 // Apply the result types to the node, these come from the things in the
1518 // (outs) list of the instruction.
1519 // FIXME: Cap at one result so far.
1520 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
1521 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1522 Record *ResultNode = Inst.getResult(ResNo);
1524 if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1525 MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
1526 } else if (ResultNode->getName() == "unknown") {
1527 // Nothing to do.
1528 } else {
1529 assert(ResultNode->isSubClassOf("RegisterClass") &&
1530 "Operands should be register classes!");
1531 const CodeGenRegisterClass &RC =
1532 CDP.getTargetInfo().getRegisterClass(ResultNode);
1533 MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
1537 // If the instruction has implicit defs, we apply the first one as a result.
1538 // FIXME: This sucks, it should apply all implicit defs.
1539 if (!InstInfo.ImplicitDefs.empty()) {
1540 unsigned ResNo = NumResultsToAdd;
1542 // FIXME: Generalize to multiple possible types and multiple possible
1543 // ImplicitDefs.
1544 MVT::SimpleValueType VT =
1545 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1547 if (VT != MVT::Other)
1548 MadeChange |= UpdateNodeType(ResNo, VT, TP);
1551 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1552 // be the same.
1553 if (getOperator()->getName() == "INSERT_SUBREG") {
1554 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1555 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1556 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1559 unsigned ChildNo = 0;
1560 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1561 Record *OperandNode = Inst.getOperand(i);
1563 // If the instruction expects a predicate or optional def operand, we
1564 // codegen this by setting the operand to it's default value if it has a
1565 // non-empty DefaultOps field.
1566 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1567 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1568 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1569 continue;
1571 // Verify that we didn't run out of provided operands.
1572 if (ChildNo >= getNumChildren())
1573 TP.error("Instruction '" + getOperator()->getName() +
1574 "' expects more operands than were provided.");
1576 MVT::SimpleValueType VT;
1577 TreePatternNode *Child = getChild(ChildNo++);
1578 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
1580 if (OperandNode->isSubClassOf("RegisterClass")) {
1581 const CodeGenRegisterClass &RC =
1582 CDP.getTargetInfo().getRegisterClass(OperandNode);
1583 MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
1584 } else if (OperandNode->isSubClassOf("Operand")) {
1585 VT = getValueType(OperandNode->getValueAsDef("Type"));
1586 MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
1587 } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1588 MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
1589 } else if (OperandNode->getName() == "unknown") {
1590 // Nothing to do.
1591 } else {
1592 assert(0 && "Unknown operand type!");
1593 abort();
1595 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1598 if (ChildNo != getNumChildren())
1599 TP.error("Instruction '" + getOperator()->getName() +
1600 "' was provided too many operands!");
1602 return MadeChange;
1605 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1607 // Node transforms always take one operand.
1608 if (getNumChildren() != 1)
1609 TP.error("Node transform '" + getOperator()->getName() +
1610 "' requires one operand!");
1612 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1615 // If either the output or input of the xform does not have exact
1616 // type info. We assume they must be the same. Otherwise, it is perfectly
1617 // legal to transform from one type to a completely different type.
1618 #if 0
1619 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1620 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1621 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1622 return MadeChange;
1624 #endif
1625 return MadeChange;
1628 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1629 /// RHS of a commutative operation, not the on LHS.
1630 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1631 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1632 return true;
1633 if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1634 return true;
1635 return false;
1639 /// canPatternMatch - If it is impossible for this pattern to match on this
1640 /// target, fill in Reason and return false. Otherwise, return true. This is
1641 /// used as a sanity check for .td files (to prevent people from writing stuff
1642 /// that can never possibly work), and to prevent the pattern permuter from
1643 /// generating stuff that is useless.
1644 bool TreePatternNode::canPatternMatch(std::string &Reason,
1645 const CodeGenDAGPatterns &CDP) {
1646 if (isLeaf()) return true;
1648 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1649 if (!getChild(i)->canPatternMatch(Reason, CDP))
1650 return false;
1652 // If this is an intrinsic, handle cases that would make it not match. For
1653 // example, if an operand is required to be an immediate.
1654 if (getOperator()->isSubClassOf("Intrinsic")) {
1655 // TODO:
1656 return true;
1659 // If this node is a commutative operator, check that the LHS isn't an
1660 // immediate.
1661 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1662 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1663 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1664 // Scan all of the operands of the node and make sure that only the last one
1665 // is a constant node, unless the RHS also is.
1666 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1667 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1668 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1669 if (OnlyOnRHSOfCommutative(getChild(i))) {
1670 Reason="Immediate value must be on the RHS of commutative operators!";
1671 return false;
1676 return true;
1679 //===----------------------------------------------------------------------===//
1680 // TreePattern implementation
1683 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1684 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1685 isInputPattern = isInput;
1686 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1687 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
1690 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1691 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1692 isInputPattern = isInput;
1693 Trees.push_back(ParseTreePattern(Pat, ""));
1696 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1697 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1698 isInputPattern = isInput;
1699 Trees.push_back(Pat);
1702 void TreePattern::error(const std::string &Msg) const {
1703 dump();
1704 throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1707 void TreePattern::ComputeNamedNodes() {
1708 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1709 ComputeNamedNodes(Trees[i]);
1712 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1713 if (!N->getName().empty())
1714 NamedNodes[N->getName()].push_back(N);
1716 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1717 ComputeNamedNodes(N->getChild(i));
1721 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
1722 if (DefInit *DI = dynamic_cast<DefInit*>(TheInit)) {
1723 Record *R = DI->getDef();
1725 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
1726 // TreePatternNode if its own. For example:
1727 /// (foo GPR, imm) -> (foo GPR, (imm))
1728 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
1729 return ParseTreePattern(new DagInit(DI, "",
1730 std::vector<std::pair<Init*, std::string> >()),
1731 OpName);
1733 // Input argument?
1734 TreePatternNode *Res = new TreePatternNode(DI, 1);
1735 if (R->getName() == "node" && !OpName.empty()) {
1736 if (OpName.empty())
1737 error("'node' argument requires a name to match with operand list");
1738 Args.push_back(OpName);
1741 Res->setName(OpName);
1742 return Res;
1745 if (IntInit *II = dynamic_cast<IntInit*>(TheInit)) {
1746 if (!OpName.empty())
1747 error("Constant int argument should not have a name!");
1748 return new TreePatternNode(II, 1);
1751 if (BitsInit *BI = dynamic_cast<BitsInit*>(TheInit)) {
1752 // Turn this into an IntInit.
1753 Init *II = BI->convertInitializerTo(new IntRecTy());
1754 if (II == 0 || !dynamic_cast<IntInit*>(II))
1755 error("Bits value must be constants!");
1756 return ParseTreePattern(II, OpName);
1759 DagInit *Dag = dynamic_cast<DagInit*>(TheInit);
1760 if (!Dag) {
1761 TheInit->dump();
1762 error("Pattern has unexpected init kind!");
1764 DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1765 if (!OpDef) error("Pattern has unexpected operator type!");
1766 Record *Operator = OpDef->getDef();
1768 if (Operator->isSubClassOf("ValueType")) {
1769 // If the operator is a ValueType, then this must be "type cast" of a leaf
1770 // node.
1771 if (Dag->getNumArgs() != 1)
1772 error("Type cast only takes one operand!");
1774 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
1776 // Apply the type cast.
1777 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1778 New->UpdateNodeType(0, getValueType(Operator), *this);
1780 if (!OpName.empty())
1781 error("ValueType cast should not have a name!");
1782 return New;
1785 // Verify that this is something that makes sense for an operator.
1786 if (!Operator->isSubClassOf("PatFrag") &&
1787 !Operator->isSubClassOf("SDNode") &&
1788 !Operator->isSubClassOf("Instruction") &&
1789 !Operator->isSubClassOf("SDNodeXForm") &&
1790 !Operator->isSubClassOf("Intrinsic") &&
1791 Operator->getName() != "set" &&
1792 Operator->getName() != "implicit")
1793 error("Unrecognized node '" + Operator->getName() + "'!");
1795 // Check to see if this is something that is illegal in an input pattern.
1796 if (isInputPattern) {
1797 if (Operator->isSubClassOf("Instruction") ||
1798 Operator->isSubClassOf("SDNodeXForm"))
1799 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1800 } else {
1801 if (Operator->isSubClassOf("Intrinsic"))
1802 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1804 if (Operator->isSubClassOf("SDNode") &&
1805 Operator->getName() != "imm" &&
1806 Operator->getName() != "fpimm" &&
1807 Operator->getName() != "tglobaltlsaddr" &&
1808 Operator->getName() != "tconstpool" &&
1809 Operator->getName() != "tjumptable" &&
1810 Operator->getName() != "tframeindex" &&
1811 Operator->getName() != "texternalsym" &&
1812 Operator->getName() != "tblockaddress" &&
1813 Operator->getName() != "tglobaladdr" &&
1814 Operator->getName() != "bb" &&
1815 Operator->getName() != "vt")
1816 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1819 std::vector<TreePatternNode*> Children;
1821 // Parse all the operands.
1822 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1823 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
1825 // If the operator is an intrinsic, then this is just syntactic sugar for for
1826 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
1827 // convert the intrinsic name to a number.
1828 if (Operator->isSubClassOf("Intrinsic")) {
1829 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1830 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1832 // If this intrinsic returns void, it must have side-effects and thus a
1833 // chain.
1834 if (Int.IS.RetVTs.empty())
1835 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1836 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
1837 // Has side-effects, requires chain.
1838 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1839 else // Otherwise, no chain.
1840 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1842 TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID), 1);
1843 Children.insert(Children.begin(), IIDNode);
1846 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1847 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
1848 Result->setName(OpName);
1850 if (!Dag->getName().empty()) {
1851 assert(Result->getName().empty());
1852 Result->setName(Dag->getName());
1854 return Result;
1857 /// SimplifyTree - See if we can simplify this tree to eliminate something that
1858 /// will never match in favor of something obvious that will. This is here
1859 /// strictly as a convenience to target authors because it allows them to write
1860 /// more type generic things and have useless type casts fold away.
1862 /// This returns true if any change is made.
1863 static bool SimplifyTree(TreePatternNode *&N) {
1864 if (N->isLeaf())
1865 return false;
1867 // If we have a bitconvert with a resolved type and if the source and
1868 // destination types are the same, then the bitconvert is useless, remove it.
1869 if (N->getOperator()->getName() == "bitconvert" &&
1870 N->getExtType(0).isConcrete() &&
1871 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1872 N->getName().empty()) {
1873 N = N->getChild(0);
1874 SimplifyTree(N);
1875 return true;
1878 // Walk all children.
1879 bool MadeChange = false;
1880 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1881 TreePatternNode *Child = N->getChild(i);
1882 MadeChange |= SimplifyTree(Child);
1883 N->setChild(i, Child);
1885 return MadeChange;
1890 /// InferAllTypes - Infer/propagate as many types throughout the expression
1891 /// patterns as possible. Return true if all types are inferred, false
1892 /// otherwise. Throw an exception if a type contradiction is found.
1893 bool TreePattern::
1894 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1895 if (NamedNodes.empty())
1896 ComputeNamedNodes();
1898 bool MadeChange = true;
1899 while (MadeChange) {
1900 MadeChange = false;
1901 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1902 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1903 MadeChange |= SimplifyTree(Trees[i]);
1906 // If there are constraints on our named nodes, apply them.
1907 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1908 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1909 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1911 // If we have input named node types, propagate their types to the named
1912 // values here.
1913 if (InNamedTypes) {
1914 // FIXME: Should be error?
1915 assert(InNamedTypes->count(I->getKey()) &&
1916 "Named node in output pattern but not input pattern?");
1918 const SmallVectorImpl<TreePatternNode*> &InNodes =
1919 InNamedTypes->find(I->getKey())->second;
1921 // The input types should be fully resolved by now.
1922 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1923 // If this node is a register class, and it is the root of the pattern
1924 // then we're mapping something onto an input register. We allow
1925 // changing the type of the input register in this case. This allows
1926 // us to match things like:
1927 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1928 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1929 DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1930 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1931 continue;
1934 assert(Nodes[i]->getNumTypes() == 1 &&
1935 InNodes[0]->getNumTypes() == 1 &&
1936 "FIXME: cannot name multiple result nodes yet");
1937 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1938 *this);
1942 // If there are multiple nodes with the same name, they must all have the
1943 // same type.
1944 if (I->second.size() > 1) {
1945 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1946 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
1947 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
1948 "FIXME: cannot name multiple result nodes yet");
1950 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1951 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
1957 bool HasUnresolvedTypes = false;
1958 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1959 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1960 return !HasUnresolvedTypes;
1963 void TreePattern::print(raw_ostream &OS) const {
1964 OS << getRecord()->getName();
1965 if (!Args.empty()) {
1966 OS << "(" << Args[0];
1967 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1968 OS << ", " << Args[i];
1969 OS << ")";
1971 OS << ": ";
1973 if (Trees.size() > 1)
1974 OS << "[\n";
1975 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1976 OS << "\t";
1977 Trees[i]->print(OS);
1978 OS << "\n";
1981 if (Trees.size() > 1)
1982 OS << "]\n";
1985 void TreePattern::dump() const { print(errs()); }
1987 //===----------------------------------------------------------------------===//
1988 // CodeGenDAGPatterns implementation
1991 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
1992 Records(R), Target(R) {
1994 Intrinsics = LoadIntrinsics(Records, false);
1995 TgtIntrinsics = LoadIntrinsics(Records, true);
1996 ParseNodeInfo();
1997 ParseNodeTransforms();
1998 ParseComplexPatterns();
1999 ParsePatternFragments();
2000 ParseDefaultOperands();
2001 ParseInstructions();
2002 ParsePatterns();
2004 // Generate variants. For example, commutative patterns can match
2005 // multiple ways. Add them to PatternsToMatch as well.
2006 GenerateVariants();
2008 // Infer instruction flags. For example, we can detect loads,
2009 // stores, and side effects in many cases by examining an
2010 // instruction's pattern.
2011 InferInstructionFlags();
2014 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
2015 for (pf_iterator I = PatternFragments.begin(),
2016 E = PatternFragments.end(); I != E; ++I)
2017 delete I->second;
2021 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2022 Record *N = Records.getDef(Name);
2023 if (!N || !N->isSubClassOf("SDNode")) {
2024 errs() << "Error getting SDNode '" << Name << "'!\n";
2025 exit(1);
2027 return N;
2030 // Parse all of the SDNode definitions for the target, populating SDNodes.
2031 void CodeGenDAGPatterns::ParseNodeInfo() {
2032 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2033 while (!Nodes.empty()) {
2034 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2035 Nodes.pop_back();
2038 // Get the builtin intrinsic nodes.
2039 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2040 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2041 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2044 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2045 /// map, and emit them to the file as functions.
2046 void CodeGenDAGPatterns::ParseNodeTransforms() {
2047 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2048 while (!Xforms.empty()) {
2049 Record *XFormNode = Xforms.back();
2050 Record *SDNode = XFormNode->getValueAsDef("Opcode");
2051 std::string Code = XFormNode->getValueAsCode("XFormFunction");
2052 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2054 Xforms.pop_back();
2058 void CodeGenDAGPatterns::ParseComplexPatterns() {
2059 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2060 while (!AMs.empty()) {
2061 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2062 AMs.pop_back();
2067 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2068 /// file, building up the PatternFragments map. After we've collected them all,
2069 /// inline fragments together as necessary, so that there are no references left
2070 /// inside a pattern fragment to a pattern fragment.
2072 void CodeGenDAGPatterns::ParsePatternFragments() {
2073 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2075 // First step, parse all of the fragments.
2076 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2077 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
2078 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2079 PatternFragments[Fragments[i]] = P;
2081 // Validate the argument list, converting it to set, to discard duplicates.
2082 std::vector<std::string> &Args = P->getArgList();
2083 std::set<std::string> OperandsSet(Args.begin(), Args.end());
2085 if (OperandsSet.count(""))
2086 P->error("Cannot have unnamed 'node' values in pattern fragment!");
2088 // Parse the operands list.
2089 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
2090 DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
2091 // Special cases: ops == outs == ins. Different names are used to
2092 // improve readability.
2093 if (!OpsOp ||
2094 (OpsOp->getDef()->getName() != "ops" &&
2095 OpsOp->getDef()->getName() != "outs" &&
2096 OpsOp->getDef()->getName() != "ins"))
2097 P->error("Operands list should start with '(ops ... '!");
2099 // Copy over the arguments.
2100 Args.clear();
2101 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2102 if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
2103 static_cast<DefInit*>(OpsList->getArg(j))->
2104 getDef()->getName() != "node")
2105 P->error("Operands list should all be 'node' values.");
2106 if (OpsList->getArgName(j).empty())
2107 P->error("Operands list should have names for each operand!");
2108 if (!OperandsSet.count(OpsList->getArgName(j)))
2109 P->error("'" + OpsList->getArgName(j) +
2110 "' does not occur in pattern or was multiply specified!");
2111 OperandsSet.erase(OpsList->getArgName(j));
2112 Args.push_back(OpsList->getArgName(j));
2115 if (!OperandsSet.empty())
2116 P->error("Operands list does not contain an entry for operand '" +
2117 *OperandsSet.begin() + "'!");
2119 // If there is a code init for this fragment, keep track of the fact that
2120 // this fragment uses it.
2121 TreePredicateFn PredFn(P);
2122 if (!PredFn.isAlwaysTrue())
2123 P->getOnlyTree()->addPredicateFn(PredFn);
2125 // If there is a node transformation corresponding to this, keep track of
2126 // it.
2127 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2128 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2129 P->getOnlyTree()->setTransformFn(Transform);
2132 // Now that we've parsed all of the tree fragments, do a closure on them so
2133 // that there are not references to PatFrags left inside of them.
2134 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2135 TreePattern *ThePat = PatternFragments[Fragments[i]];
2136 ThePat->InlinePatternFragments();
2138 // Infer as many types as possible. Don't worry about it if we don't infer
2139 // all of them, some may depend on the inputs of the pattern.
2140 try {
2141 ThePat->InferAllTypes();
2142 } catch (...) {
2143 // If this pattern fragment is not supported by this target (no types can
2144 // satisfy its constraints), just ignore it. If the bogus pattern is
2145 // actually used by instructions, the type consistency error will be
2146 // reported there.
2149 // If debugging, print out the pattern fragment result.
2150 DEBUG(ThePat->dump());
2154 void CodeGenDAGPatterns::ParseDefaultOperands() {
2155 std::vector<Record*> DefaultOps[2];
2156 DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
2157 DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
2159 // Find some SDNode.
2160 assert(!SDNodes.empty() && "No SDNodes parsed?");
2161 Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
2163 for (unsigned iter = 0; iter != 2; ++iter) {
2164 for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
2165 DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
2167 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2168 // SomeSDnode so that we can parse this.
2169 std::vector<std::pair<Init*, std::string> > Ops;
2170 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2171 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2172 DefaultInfo->getArgName(op)));
2173 DagInit *DI = new DagInit(SomeSDNode, "", Ops);
2175 // Create a TreePattern to parse this.
2176 TreePattern P(DefaultOps[iter][i], DI, false, *this);
2177 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2179 // Copy the operands over into a DAGDefaultOperand.
2180 DAGDefaultOperand DefaultOpInfo;
2182 TreePatternNode *T = P.getTree(0);
2183 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2184 TreePatternNode *TPN = T->getChild(op);
2185 while (TPN->ApplyTypeConstraints(P, false))
2186 /* Resolve all types */;
2188 if (TPN->ContainsUnresolvedType()) {
2189 if (iter == 0)
2190 throw "Value #" + utostr(i) + " of PredicateOperand '" +
2191 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
2192 else
2193 throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
2194 DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
2196 DefaultOpInfo.DefaultOps.push_back(TPN);
2199 // Insert it into the DefaultOperands map so we can find it later.
2200 DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
2205 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2206 /// instruction input. Return true if this is a real use.
2207 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2208 std::map<std::string, TreePatternNode*> &InstInputs) {
2209 // No name -> not interesting.
2210 if (Pat->getName().empty()) {
2211 if (Pat->isLeaf()) {
2212 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2213 if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
2214 I->error("Input " + DI->getDef()->getName() + " must be named!");
2216 return false;
2219 Record *Rec;
2220 if (Pat->isLeaf()) {
2221 DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2222 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2223 Rec = DI->getDef();
2224 } else {
2225 Rec = Pat->getOperator();
2228 // SRCVALUE nodes are ignored.
2229 if (Rec->getName() == "srcvalue")
2230 return false;
2232 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2233 if (!Slot) {
2234 Slot = Pat;
2235 return true;
2237 Record *SlotRec;
2238 if (Slot->isLeaf()) {
2239 SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
2240 } else {
2241 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2242 SlotRec = Slot->getOperator();
2245 // Ensure that the inputs agree if we've already seen this input.
2246 if (Rec != SlotRec)
2247 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2248 if (Slot->getExtTypes() != Pat->getExtTypes())
2249 I->error("All $" + Pat->getName() + " inputs must agree with each other");
2250 return true;
2253 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2254 /// part of "I", the instruction), computing the set of inputs and outputs of
2255 /// the pattern. Report errors if we see anything naughty.
2256 void CodeGenDAGPatterns::
2257 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2258 std::map<std::string, TreePatternNode*> &InstInputs,
2259 std::map<std::string, TreePatternNode*>&InstResults,
2260 std::vector<Record*> &InstImpResults) {
2261 if (Pat->isLeaf()) {
2262 bool isUse = HandleUse(I, Pat, InstInputs);
2263 if (!isUse && Pat->getTransformFn())
2264 I->error("Cannot specify a transform function for a non-input value!");
2265 return;
2268 if (Pat->getOperator()->getName() == "implicit") {
2269 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2270 TreePatternNode *Dest = Pat->getChild(i);
2271 if (!Dest->isLeaf())
2272 I->error("implicitly defined value should be a register!");
2274 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2275 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2276 I->error("implicitly defined value should be a register!");
2277 InstImpResults.push_back(Val->getDef());
2279 return;
2282 if (Pat->getOperator()->getName() != "set") {
2283 // If this is not a set, verify that the children nodes are not void typed,
2284 // and recurse.
2285 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2286 if (Pat->getChild(i)->getNumTypes() == 0)
2287 I->error("Cannot have void nodes inside of patterns!");
2288 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2289 InstImpResults);
2292 // If this is a non-leaf node with no children, treat it basically as if
2293 // it were a leaf. This handles nodes like (imm).
2294 bool isUse = HandleUse(I, Pat, InstInputs);
2296 if (!isUse && Pat->getTransformFn())
2297 I->error("Cannot specify a transform function for a non-input value!");
2298 return;
2301 // Otherwise, this is a set, validate and collect instruction results.
2302 if (Pat->getNumChildren() == 0)
2303 I->error("set requires operands!");
2305 if (Pat->getTransformFn())
2306 I->error("Cannot specify a transform function on a set node!");
2308 // Check the set destinations.
2309 unsigned NumDests = Pat->getNumChildren()-1;
2310 for (unsigned i = 0; i != NumDests; ++i) {
2311 TreePatternNode *Dest = Pat->getChild(i);
2312 if (!Dest->isLeaf())
2313 I->error("set destination should be a register!");
2315 DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2316 if (!Val)
2317 I->error("set destination should be a register!");
2319 if (Val->getDef()->isSubClassOf("RegisterClass") ||
2320 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2321 if (Dest->getName().empty())
2322 I->error("set destination must have a name!");
2323 if (InstResults.count(Dest->getName()))
2324 I->error("cannot set '" + Dest->getName() +"' multiple times");
2325 InstResults[Dest->getName()] = Dest;
2326 } else if (Val->getDef()->isSubClassOf("Register")) {
2327 InstImpResults.push_back(Val->getDef());
2328 } else {
2329 I->error("set destination should be a register!");
2333 // Verify and collect info from the computation.
2334 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2335 InstInputs, InstResults, InstImpResults);
2338 //===----------------------------------------------------------------------===//
2339 // Instruction Analysis
2340 //===----------------------------------------------------------------------===//
2342 class InstAnalyzer {
2343 const CodeGenDAGPatterns &CDP;
2344 bool &mayStore;
2345 bool &mayLoad;
2346 bool &IsBitcast;
2347 bool &HasSideEffects;
2348 bool &IsVariadic;
2349 public:
2350 InstAnalyzer(const CodeGenDAGPatterns &cdp,
2351 bool &maystore, bool &mayload, bool &isbc, bool &hse, bool &isv)
2352 : CDP(cdp), mayStore(maystore), mayLoad(mayload), IsBitcast(isbc),
2353 HasSideEffects(hse), IsVariadic(isv) {
2356 /// Analyze - Analyze the specified instruction, returning true if the
2357 /// instruction had a pattern.
2358 bool Analyze(Record *InstRecord) {
2359 const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2360 if (Pattern == 0) {
2361 HasSideEffects = 1;
2362 return false; // No pattern.
2365 // FIXME: Assume only the first tree is the pattern. The others are clobber
2366 // nodes.
2367 AnalyzeNode(Pattern->getTree(0));
2368 return true;
2371 private:
2372 bool IsNodeBitcast(const TreePatternNode *N) const {
2373 if (HasSideEffects || mayLoad || mayStore || IsVariadic)
2374 return false;
2376 if (N->getNumChildren() != 2)
2377 return false;
2379 const TreePatternNode *N0 = N->getChild(0);
2380 if (!N0->isLeaf() || !dynamic_cast<DefInit*>(N0->getLeafValue()))
2381 return false;
2383 const TreePatternNode *N1 = N->getChild(1);
2384 if (N1->isLeaf())
2385 return false;
2386 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2387 return false;
2389 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2390 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2391 return false;
2392 return OpInfo.getEnumName() == "ISD::BITCAST";
2395 void AnalyzeNode(const TreePatternNode *N) {
2396 if (N->isLeaf()) {
2397 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2398 Record *LeafRec = DI->getDef();
2399 // Handle ComplexPattern leaves.
2400 if (LeafRec->isSubClassOf("ComplexPattern")) {
2401 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2402 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2403 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2404 if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2407 return;
2410 // Analyze children.
2411 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2412 AnalyzeNode(N->getChild(i));
2414 // Ignore set nodes, which are not SDNodes.
2415 if (N->getOperator()->getName() == "set") {
2416 IsBitcast = IsNodeBitcast(N);
2417 return;
2420 // Get information about the SDNode for the operator.
2421 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2423 // Notice properties of the node.
2424 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2425 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2426 if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2427 if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
2429 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2430 // If this is an intrinsic, analyze it.
2431 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2432 mayLoad = true;// These may load memory.
2434 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2435 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2437 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2438 // WriteMem intrinsics can have other strange effects.
2439 HasSideEffects = true;
2445 static void InferFromPattern(const CodeGenInstruction &Inst,
2446 bool &MayStore, bool &MayLoad,
2447 bool &IsBitcast,
2448 bool &HasSideEffects, bool &IsVariadic,
2449 const CodeGenDAGPatterns &CDP) {
2450 MayStore = MayLoad = IsBitcast = HasSideEffects = IsVariadic = false;
2452 bool HadPattern =
2453 InstAnalyzer(CDP, MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic)
2454 .Analyze(Inst.TheDef);
2456 // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2457 if (Inst.mayStore) { // If the .td file explicitly sets mayStore, use it.
2458 // If we decided that this is a store from the pattern, then the .td file
2459 // entry is redundant.
2460 if (MayStore)
2461 fprintf(stderr,
2462 "Warning: mayStore flag explicitly set on instruction '%s'"
2463 " but flag already inferred from pattern.\n",
2464 Inst.TheDef->getName().c_str());
2465 MayStore = true;
2468 if (Inst.mayLoad) { // If the .td file explicitly sets mayLoad, use it.
2469 // If we decided that this is a load from the pattern, then the .td file
2470 // entry is redundant.
2471 if (MayLoad)
2472 fprintf(stderr,
2473 "Warning: mayLoad flag explicitly set on instruction '%s'"
2474 " but flag already inferred from pattern.\n",
2475 Inst.TheDef->getName().c_str());
2476 MayLoad = true;
2479 if (Inst.neverHasSideEffects) {
2480 if (HadPattern)
2481 fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2482 "which already has a pattern\n", Inst.TheDef->getName().c_str());
2483 HasSideEffects = false;
2486 if (Inst.hasSideEffects) {
2487 if (HasSideEffects)
2488 fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2489 "which already inferred this.\n", Inst.TheDef->getName().c_str());
2490 HasSideEffects = true;
2493 if (Inst.Operands.isVariadic)
2494 IsVariadic = true; // Can warn if we want.
2497 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2498 /// any fragments involved. This populates the Instructions list with fully
2499 /// resolved instructions.
2500 void CodeGenDAGPatterns::ParseInstructions() {
2501 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2503 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2504 ListInit *LI = 0;
2506 if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2507 LI = Instrs[i]->getValueAsListInit("Pattern");
2509 // If there is no pattern, only collect minimal information about the
2510 // instruction for its operand list. We have to assume that there is one
2511 // result, as we have no detailed info.
2512 if (!LI || LI->getSize() == 0) {
2513 std::vector<Record*> Results;
2514 std::vector<Record*> Operands;
2516 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2518 if (InstInfo.Operands.size() != 0) {
2519 if (InstInfo.Operands.NumDefs == 0) {
2520 // These produce no results
2521 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2522 Operands.push_back(InstInfo.Operands[j].Rec);
2523 } else {
2524 // Assume the first operand is the result.
2525 Results.push_back(InstInfo.Operands[0].Rec);
2527 // The rest are inputs.
2528 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2529 Operands.push_back(InstInfo.Operands[j].Rec);
2533 // Create and insert the instruction.
2534 std::vector<Record*> ImpResults;
2535 Instructions.insert(std::make_pair(Instrs[i],
2536 DAGInstruction(0, Results, Operands, ImpResults)));
2537 continue; // no pattern.
2540 // Parse the instruction.
2541 TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2542 // Inline pattern fragments into it.
2543 I->InlinePatternFragments();
2545 // Infer as many types as possible. If we cannot infer all of them, we can
2546 // never do anything with this instruction pattern: report it to the user.
2547 if (!I->InferAllTypes())
2548 I->error("Could not infer all types in pattern!");
2550 // InstInputs - Keep track of all of the inputs of the instruction, along
2551 // with the record they are declared as.
2552 std::map<std::string, TreePatternNode*> InstInputs;
2554 // InstResults - Keep track of all the virtual registers that are 'set'
2555 // in the instruction, including what reg class they are.
2556 std::map<std::string, TreePatternNode*> InstResults;
2558 std::vector<Record*> InstImpResults;
2560 // Verify that the top-level forms in the instruction are of void type, and
2561 // fill in the InstResults map.
2562 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2563 TreePatternNode *Pat = I->getTree(j);
2564 if (Pat->getNumTypes() != 0)
2565 I->error("Top-level forms in instruction pattern should have"
2566 " void types");
2568 // Find inputs and outputs, and verify the structure of the uses/defs.
2569 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2570 InstImpResults);
2573 // Now that we have inputs and outputs of the pattern, inspect the operands
2574 // list for the instruction. This determines the order that operands are
2575 // added to the machine instruction the node corresponds to.
2576 unsigned NumResults = InstResults.size();
2578 // Parse the operands list from the (ops) list, validating it.
2579 assert(I->getArgList().empty() && "Args list should still be empty here!");
2580 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2582 // Check that all of the results occur first in the list.
2583 std::vector<Record*> Results;
2584 TreePatternNode *Res0Node = 0;
2585 for (unsigned i = 0; i != NumResults; ++i) {
2586 if (i == CGI.Operands.size())
2587 I->error("'" + InstResults.begin()->first +
2588 "' set but does not appear in operand list!");
2589 const std::string &OpName = CGI.Operands[i].Name;
2591 // Check that it exists in InstResults.
2592 TreePatternNode *RNode = InstResults[OpName];
2593 if (RNode == 0)
2594 I->error("Operand $" + OpName + " does not exist in operand list!");
2596 if (i == 0)
2597 Res0Node = RNode;
2598 Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2599 if (R == 0)
2600 I->error("Operand $" + OpName + " should be a set destination: all "
2601 "outputs must occur before inputs in operand list!");
2603 if (CGI.Operands[i].Rec != R)
2604 I->error("Operand $" + OpName + " class mismatch!");
2606 // Remember the return type.
2607 Results.push_back(CGI.Operands[i].Rec);
2609 // Okay, this one checks out.
2610 InstResults.erase(OpName);
2613 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2614 // the copy while we're checking the inputs.
2615 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2617 std::vector<TreePatternNode*> ResultNodeOperands;
2618 std::vector<Record*> Operands;
2619 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2620 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2621 const std::string &OpName = Op.Name;
2622 if (OpName.empty())
2623 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2625 if (!InstInputsCheck.count(OpName)) {
2626 // If this is an predicate operand or optional def operand with an
2627 // DefaultOps set filled in, we can ignore this. When we codegen it,
2628 // we will do so as always executed.
2629 if (Op.Rec->isSubClassOf("PredicateOperand") ||
2630 Op.Rec->isSubClassOf("OptionalDefOperand")) {
2631 // Does it have a non-empty DefaultOps field? If so, ignore this
2632 // operand.
2633 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2634 continue;
2636 I->error("Operand $" + OpName +
2637 " does not appear in the instruction pattern");
2639 TreePatternNode *InVal = InstInputsCheck[OpName];
2640 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2642 if (InVal->isLeaf() &&
2643 dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2644 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2645 if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2646 I->error("Operand $" + OpName + "'s register class disagrees"
2647 " between the operand and pattern");
2649 Operands.push_back(Op.Rec);
2651 // Construct the result for the dest-pattern operand list.
2652 TreePatternNode *OpNode = InVal->clone();
2654 // No predicate is useful on the result.
2655 OpNode->clearPredicateFns();
2657 // Promote the xform function to be an explicit node if set.
2658 if (Record *Xform = OpNode->getTransformFn()) {
2659 OpNode->setTransformFn(0);
2660 std::vector<TreePatternNode*> Children;
2661 Children.push_back(OpNode);
2662 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2665 ResultNodeOperands.push_back(OpNode);
2668 if (!InstInputsCheck.empty())
2669 I->error("Input operand $" + InstInputsCheck.begin()->first +
2670 " occurs in pattern but not in operands list!");
2672 TreePatternNode *ResultPattern =
2673 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2674 GetNumNodeResults(I->getRecord(), *this));
2675 // Copy fully inferred output node type to instruction result pattern.
2676 for (unsigned i = 0; i != NumResults; ++i)
2677 ResultPattern->setType(i, Res0Node->getExtType(i));
2679 // Create and insert the instruction.
2680 // FIXME: InstImpResults should not be part of DAGInstruction.
2681 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
2682 Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2684 // Use a temporary tree pattern to infer all types and make sure that the
2685 // constructed result is correct. This depends on the instruction already
2686 // being inserted into the Instructions map.
2687 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2688 Temp.InferAllTypes(&I->getNamedNodesMap());
2690 DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2691 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2693 DEBUG(I->dump());
2696 // If we can, convert the instructions to be patterns that are matched!
2697 for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2698 Instructions.begin(),
2699 E = Instructions.end(); II != E; ++II) {
2700 DAGInstruction &TheInst = II->second;
2701 const TreePattern *I = TheInst.getPattern();
2702 if (I == 0) continue; // No pattern.
2704 // FIXME: Assume only the first tree is the pattern. The others are clobber
2705 // nodes.
2706 TreePatternNode *Pattern = I->getTree(0);
2707 TreePatternNode *SrcPattern;
2708 if (Pattern->getOperator()->getName() == "set") {
2709 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2710 } else{
2711 // Not a set (store or something?)
2712 SrcPattern = Pattern;
2715 Record *Instr = II->first;
2716 AddPatternToMatch(I,
2717 PatternToMatch(Instr,
2718 Instr->getValueAsListInit("Predicates"),
2719 SrcPattern,
2720 TheInst.getResultPattern(),
2721 TheInst.getImpResults(),
2722 Instr->getValueAsInt("AddedComplexity"),
2723 Instr->getID()));
2728 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2730 static void FindNames(const TreePatternNode *P,
2731 std::map<std::string, NameRecord> &Names,
2732 const TreePattern *PatternTop) {
2733 if (!P->getName().empty()) {
2734 NameRecord &Rec = Names[P->getName()];
2735 // If this is the first instance of the name, remember the node.
2736 if (Rec.second++ == 0)
2737 Rec.first = P;
2738 else if (Rec.first->getExtTypes() != P->getExtTypes())
2739 PatternTop->error("repetition of value: $" + P->getName() +
2740 " where different uses have different types!");
2743 if (!P->isLeaf()) {
2744 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2745 FindNames(P->getChild(i), Names, PatternTop);
2749 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2750 const PatternToMatch &PTM) {
2751 // Do some sanity checking on the pattern we're about to match.
2752 std::string Reason;
2753 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2754 Pattern->error("Pattern can never match: " + Reason);
2756 // If the source pattern's root is a complex pattern, that complex pattern
2757 // must specify the nodes it can potentially match.
2758 if (const ComplexPattern *CP =
2759 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2760 if (CP->getRootNodes().empty())
2761 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2762 " could match");
2765 // Find all of the named values in the input and output, ensure they have the
2766 // same type.
2767 std::map<std::string, NameRecord> SrcNames, DstNames;
2768 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2769 FindNames(PTM.getDstPattern(), DstNames, Pattern);
2771 // Scan all of the named values in the destination pattern, rejecting them if
2772 // they don't exist in the input pattern.
2773 for (std::map<std::string, NameRecord>::iterator
2774 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2775 if (SrcNames[I->first].first == 0)
2776 Pattern->error("Pattern has input without matching name in output: $" +
2777 I->first);
2780 // Scan all of the named values in the source pattern, rejecting them if the
2781 // name isn't used in the dest, and isn't used to tie two values together.
2782 for (std::map<std::string, NameRecord>::iterator
2783 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2784 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2785 Pattern->error("Pattern has dead named input: $" + I->first);
2787 PatternsToMatch.push_back(PTM);
2792 void CodeGenDAGPatterns::InferInstructionFlags() {
2793 const std::vector<const CodeGenInstruction*> &Instructions =
2794 Target.getInstructionsByEnumValue();
2795 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2796 CodeGenInstruction &InstInfo =
2797 const_cast<CodeGenInstruction &>(*Instructions[i]);
2798 // Determine properties of the instruction from its pattern.
2799 bool MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic;
2800 InferFromPattern(InstInfo, MayStore, MayLoad, IsBitcast,
2801 HasSideEffects, IsVariadic, *this);
2802 InstInfo.mayStore = MayStore;
2803 InstInfo.mayLoad = MayLoad;
2804 InstInfo.isBitcast = IsBitcast;
2805 InstInfo.hasSideEffects = HasSideEffects;
2806 InstInfo.Operands.isVariadic = IsVariadic;
2810 /// Given a pattern result with an unresolved type, see if we can find one
2811 /// instruction with an unresolved result type. Force this result type to an
2812 /// arbitrary element if it's possible types to converge results.
2813 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2814 if (N->isLeaf())
2815 return false;
2817 // Analyze children.
2818 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2819 if (ForceArbitraryInstResultType(N->getChild(i), TP))
2820 return true;
2822 if (!N->getOperator()->isSubClassOf("Instruction"))
2823 return false;
2825 // If this type is already concrete or completely unknown we can't do
2826 // anything.
2827 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2828 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2829 continue;
2831 // Otherwise, force its type to the first possibility (an arbitrary choice).
2832 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2833 return true;
2836 return false;
2839 void CodeGenDAGPatterns::ParsePatterns() {
2840 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2842 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2843 Record *CurPattern = Patterns[i];
2844 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
2845 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
2847 // Inline pattern fragments into it.
2848 Pattern->InlinePatternFragments();
2850 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
2851 if (LI->getSize() == 0) continue; // no pattern.
2853 // Parse the instruction.
2854 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
2856 // Inline pattern fragments into it.
2857 Result->InlinePatternFragments();
2859 if (Result->getNumTrees() != 1)
2860 Result->error("Cannot handle instructions producing instructions "
2861 "with temporaries yet!");
2863 bool IterateInference;
2864 bool InferredAllPatternTypes, InferredAllResultTypes;
2865 do {
2866 // Infer as many types as possible. If we cannot infer all of them, we
2867 // can never do anything with this pattern: report it to the user.
2868 InferredAllPatternTypes =
2869 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
2871 // Infer as many types as possible. If we cannot infer all of them, we
2872 // can never do anything with this pattern: report it to the user.
2873 InferredAllResultTypes =
2874 Result->InferAllTypes(&Pattern->getNamedNodesMap());
2876 IterateInference = false;
2878 // Apply the type of the result to the source pattern. This helps us
2879 // resolve cases where the input type is known to be a pointer type (which
2880 // is considered resolved), but the result knows it needs to be 32- or
2881 // 64-bits. Infer the other way for good measure.
2882 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2883 Pattern->getTree(0)->getNumTypes());
2884 i != e; ++i) {
2885 IterateInference = Pattern->getTree(0)->
2886 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
2887 IterateInference |= Result->getTree(0)->
2888 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
2891 // If our iteration has converged and the input pattern's types are fully
2892 // resolved but the result pattern is not fully resolved, we may have a
2893 // situation where we have two instructions in the result pattern and
2894 // the instructions require a common register class, but don't care about
2895 // what actual MVT is used. This is actually a bug in our modelling:
2896 // output patterns should have register classes, not MVTs.
2898 // In any case, to handle this, we just go through and disambiguate some
2899 // arbitrary types to the result pattern's nodes.
2900 if (!IterateInference && InferredAllPatternTypes &&
2901 !InferredAllResultTypes)
2902 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2903 *Result);
2904 } while (IterateInference);
2906 // Verify that we inferred enough types that we can do something with the
2907 // pattern and result. If these fire the user has to add type casts.
2908 if (!InferredAllPatternTypes)
2909 Pattern->error("Could not infer all types in pattern!");
2910 if (!InferredAllResultTypes) {
2911 Pattern->dump();
2912 Result->error("Could not infer all types in pattern result!");
2915 // Validate that the input pattern is correct.
2916 std::map<std::string, TreePatternNode*> InstInputs;
2917 std::map<std::string, TreePatternNode*> InstResults;
2918 std::vector<Record*> InstImpResults;
2919 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2920 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2921 InstInputs, InstResults,
2922 InstImpResults);
2924 // Promote the xform function to be an explicit node if set.
2925 TreePatternNode *DstPattern = Result->getOnlyTree();
2926 std::vector<TreePatternNode*> ResultNodeOperands;
2927 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2928 TreePatternNode *OpNode = DstPattern->getChild(ii);
2929 if (Record *Xform = OpNode->getTransformFn()) {
2930 OpNode->setTransformFn(0);
2931 std::vector<TreePatternNode*> Children;
2932 Children.push_back(OpNode);
2933 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2935 ResultNodeOperands.push_back(OpNode);
2937 DstPattern = Result->getOnlyTree();
2938 if (!DstPattern->isLeaf())
2939 DstPattern = new TreePatternNode(DstPattern->getOperator(),
2940 ResultNodeOperands,
2941 DstPattern->getNumTypes());
2943 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2944 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
2946 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2947 Temp.InferAllTypes();
2950 AddPatternToMatch(Pattern,
2951 PatternToMatch(CurPattern,
2952 CurPattern->getValueAsListInit("Predicates"),
2953 Pattern->getTree(0),
2954 Temp.getOnlyTree(), InstImpResults,
2955 CurPattern->getValueAsInt("AddedComplexity"),
2956 CurPattern->getID()));
2960 /// CombineChildVariants - Given a bunch of permutations of each child of the
2961 /// 'operator' node, put them together in all possible ways.
2962 static void CombineChildVariants(TreePatternNode *Orig,
2963 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2964 std::vector<TreePatternNode*> &OutVariants,
2965 CodeGenDAGPatterns &CDP,
2966 const MultipleUseVarSet &DepVars) {
2967 // Make sure that each operand has at least one variant to choose from.
2968 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2969 if (ChildVariants[i].empty())
2970 return;
2972 // The end result is an all-pairs construction of the resultant pattern.
2973 std::vector<unsigned> Idxs;
2974 Idxs.resize(ChildVariants.size());
2975 bool NotDone;
2976 do {
2977 #ifndef NDEBUG
2978 DEBUG(if (!Idxs.empty()) {
2979 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2980 for (unsigned i = 0; i < Idxs.size(); ++i) {
2981 errs() << Idxs[i] << " ";
2983 errs() << "]\n";
2985 #endif
2986 // Create the variant and add it to the output list.
2987 std::vector<TreePatternNode*> NewChildren;
2988 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2989 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2990 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
2991 Orig->getNumTypes());
2993 // Copy over properties.
2994 R->setName(Orig->getName());
2995 R->setPredicateFns(Orig->getPredicateFns());
2996 R->setTransformFn(Orig->getTransformFn());
2997 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
2998 R->setType(i, Orig->getExtType(i));
3000 // If this pattern cannot match, do not include it as a variant.
3001 std::string ErrString;
3002 if (!R->canPatternMatch(ErrString, CDP)) {
3003 delete R;
3004 } else {
3005 bool AlreadyExists = false;
3007 // Scan to see if this pattern has already been emitted. We can get
3008 // duplication due to things like commuting:
3009 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3010 // which are the same pattern. Ignore the dups.
3011 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
3012 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
3013 AlreadyExists = true;
3014 break;
3017 if (AlreadyExists)
3018 delete R;
3019 else
3020 OutVariants.push_back(R);
3023 // Increment indices to the next permutation by incrementing the
3024 // indicies from last index backward, e.g., generate the sequence
3025 // [0, 0], [0, 1], [1, 0], [1, 1].
3026 int IdxsIdx;
3027 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3028 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3029 Idxs[IdxsIdx] = 0;
3030 else
3031 break;
3033 NotDone = (IdxsIdx >= 0);
3034 } while (NotDone);
3037 /// CombineChildVariants - A helper function for binary operators.
3039 static void CombineChildVariants(TreePatternNode *Orig,
3040 const std::vector<TreePatternNode*> &LHS,
3041 const std::vector<TreePatternNode*> &RHS,
3042 std::vector<TreePatternNode*> &OutVariants,
3043 CodeGenDAGPatterns &CDP,
3044 const MultipleUseVarSet &DepVars) {
3045 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3046 ChildVariants.push_back(LHS);
3047 ChildVariants.push_back(RHS);
3048 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3052 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3053 std::vector<TreePatternNode *> &Children) {
3054 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3055 Record *Operator = N->getOperator();
3057 // Only permit raw nodes.
3058 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3059 N->getTransformFn()) {
3060 Children.push_back(N);
3061 return;
3064 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3065 Children.push_back(N->getChild(0));
3066 else
3067 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3069 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3070 Children.push_back(N->getChild(1));
3071 else
3072 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3075 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3076 /// the (potentially recursive) pattern by using algebraic laws.
3078 static void GenerateVariantsOf(TreePatternNode *N,
3079 std::vector<TreePatternNode*> &OutVariants,
3080 CodeGenDAGPatterns &CDP,
3081 const MultipleUseVarSet &DepVars) {
3082 // We cannot permute leaves.
3083 if (N->isLeaf()) {
3084 OutVariants.push_back(N);
3085 return;
3088 // Look up interesting info about the node.
3089 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3091 // If this node is associative, re-associate.
3092 if (NodeInfo.hasProperty(SDNPAssociative)) {
3093 // Re-associate by pulling together all of the linked operators
3094 std::vector<TreePatternNode*> MaximalChildren;
3095 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3097 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3098 // permutations.
3099 if (MaximalChildren.size() == 3) {
3100 // Find the variants of all of our maximal children.
3101 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3102 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3103 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3104 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3106 // There are only two ways we can permute the tree:
3107 // (A op B) op C and A op (B op C)
3108 // Within these forms, we can also permute A/B/C.
3110 // Generate legal pair permutations of A/B/C.
3111 std::vector<TreePatternNode*> ABVariants;
3112 std::vector<TreePatternNode*> BAVariants;
3113 std::vector<TreePatternNode*> ACVariants;
3114 std::vector<TreePatternNode*> CAVariants;
3115 std::vector<TreePatternNode*> BCVariants;
3116 std::vector<TreePatternNode*> CBVariants;
3117 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3118 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3119 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3120 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3121 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3122 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3124 // Combine those into the result: (x op x) op x
3125 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3126 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3127 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3128 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3129 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3130 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3132 // Combine those into the result: x op (x op x)
3133 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3134 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3135 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3136 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3137 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3138 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3139 return;
3143 // Compute permutations of all children.
3144 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3145 ChildVariants.resize(N->getNumChildren());
3146 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3147 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3149 // Build all permutations based on how the children were formed.
3150 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3152 // If this node is commutative, consider the commuted order.
3153 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3154 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3155 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3156 "Commutative but doesn't have 2 children!");
3157 // Don't count children which are actually register references.
3158 unsigned NC = 0;
3159 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3160 TreePatternNode *Child = N->getChild(i);
3161 if (Child->isLeaf())
3162 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
3163 Record *RR = DI->getDef();
3164 if (RR->isSubClassOf("Register"))
3165 continue;
3167 NC++;
3169 // Consider the commuted order.
3170 if (isCommIntrinsic) {
3171 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3172 // operands are the commutative operands, and there might be more operands
3173 // after those.
3174 assert(NC >= 3 &&
3175 "Commutative intrinsic should have at least 3 childrean!");
3176 std::vector<std::vector<TreePatternNode*> > Variants;
3177 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3178 Variants.push_back(ChildVariants[2]);
3179 Variants.push_back(ChildVariants[1]);
3180 for (unsigned i = 3; i != NC; ++i)
3181 Variants.push_back(ChildVariants[i]);
3182 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3183 } else if (NC == 2)
3184 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3185 OutVariants, CDP, DepVars);
3190 // GenerateVariants - Generate variants. For example, commutative patterns can
3191 // match multiple ways. Add them to PatternsToMatch as well.
3192 void CodeGenDAGPatterns::GenerateVariants() {
3193 DEBUG(errs() << "Generating instruction variants.\n");
3195 // Loop over all of the patterns we've collected, checking to see if we can
3196 // generate variants of the instruction, through the exploitation of
3197 // identities. This permits the target to provide aggressive matching without
3198 // the .td file having to contain tons of variants of instructions.
3200 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3201 // intentionally do not reconsider these. Any variants of added patterns have
3202 // already been added.
3204 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3205 MultipleUseVarSet DepVars;
3206 std::vector<TreePatternNode*> Variants;
3207 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3208 DEBUG(errs() << "Dependent/multiply used variables: ");
3209 DEBUG(DumpDepVars(DepVars));
3210 DEBUG(errs() << "\n");
3211 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3212 DepVars);
3214 assert(!Variants.empty() && "Must create at least original variant!");
3215 Variants.erase(Variants.begin()); // Remove the original pattern.
3217 if (Variants.empty()) // No variants for this pattern.
3218 continue;
3220 DEBUG(errs() << "FOUND VARIANTS OF: ";
3221 PatternsToMatch[i].getSrcPattern()->dump();
3222 errs() << "\n");
3224 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3225 TreePatternNode *Variant = Variants[v];
3227 DEBUG(errs() << " VAR#" << v << ": ";
3228 Variant->dump();
3229 errs() << "\n");
3231 // Scan to see if an instruction or explicit pattern already matches this.
3232 bool AlreadyExists = false;
3233 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3234 // Skip if the top level predicates do not match.
3235 if (PatternsToMatch[i].getPredicates() !=
3236 PatternsToMatch[p].getPredicates())
3237 continue;
3238 // Check to see if this variant already exists.
3239 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3240 DepVars)) {
3241 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
3242 AlreadyExists = true;
3243 break;
3246 // If we already have it, ignore the variant.
3247 if (AlreadyExists) continue;
3249 // Otherwise, add it to the list of patterns we have.
3250 PatternsToMatch.
3251 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3252 PatternsToMatch[i].getPredicates(),
3253 Variant, PatternsToMatch[i].getDstPattern(),
3254 PatternsToMatch[i].getDstRegs(),
3255 PatternsToMatch[i].getAddedComplexity(),
3256 Record::getNewUID()));
3259 DEBUG(errs() << "\n");