now that predicates have a decent abstraction layer on them, introduce a new
[oota-llvm.git] / utils / TableGen / CodeGenDAGPatterns.cpp
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.
12 //
13 //===----------------------------------------------------------------------===//
14
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;
23
24 //===----------------------------------------------------------------------===//
25 //  EEVT::TypeSet Implementation
26 //===----------------------------------------------------------------------===//
27
28 static inline bool isInteger(MVT::SimpleValueType VT) {
29   return EVT(VT).isInteger();
30 }
31 static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
32   return EVT(VT).isFloatingPoint();
33 }
34 static inline bool isVector(MVT::SimpleValueType VT) {
35   return EVT(VT).isVector();
36 }
37 static inline bool isScalar(MVT::SimpleValueType VT) {
38   return !EVT(VT).isVector();
39 }
40
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);
52   }
53 }
54
55
56 EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
57   assert(!VTList.empty() && "empty list?");
58   TypeVec.append(VTList.begin(), VTList.end());
59
60   if (!VTList.empty())
61     assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
62            VTList[0] != MVT::fAny);
63
64   // Verify no duplicates.
65   array_pod_sort(TypeVec.begin(), TypeVec.end());
66   assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
67 }
68
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();
77
78   for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
79     if (Pred == 0 || Pred(LegalTypes[i]))
80       TypeVec.push_back(LegalTypes[i]);
81
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;
88
89   // Remove duplicates.
90   array_pod_sort(TypeVec.begin(), TypeVec.end());
91   TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
92
93   return true;
94 }
95
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;
103 }
104
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;
112 }
113
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;
121 }
122
123
124 std::string EEVT::TypeSet::getName() const {
125   if (TypeVec.empty()) return "<empty>";
126
127   std::string Result;
128
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;
136   }
137
138   if (TypeVec.size() == 1)
139     return Result;
140   return "{" + Result + "}";
141 }
142
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;
149
150   if (isCompletelyUnknown()) {
151     *this = InVT;
152     return true;
153   }
154
155   assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
156
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);
166
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;
171       }
172
173       // If the input has multiple scalar integers, this doesn't add any info.
174       if (!InCopy.isCompletelyUnknown())
175         return false;
176     }
177     break;
178   }
179
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);
185
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;
193     }
194
195     return MadeChange;
196   }
197
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);
202
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;
209       }
210
211     if (InInVT) continue;
212     TypeVec.erase(TypeVec.begin()+i--);
213     MadeChange = true;
214   }
215
216   // If we removed all of our types, we have a type contradiction.
217   if (!TypeVec.empty())
218     return MadeChange;
219
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
224 }
225
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;
233
234   TypeSet InputSet(*this);
235
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--);
240
241   if (TypeVec.empty())
242     TP.error("Type inference contradiction found, '" +
243              InputSet.getName() + "' needs to be integer");
244   return true;
245 }
246
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");
252
253   if (!hasIntegerTypes())
254     return false;
255
256   TypeSet InputSet(*this);
257
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--);
262
263   if (TypeVec.empty())
264     TP.error("Type inference contradiction found, '" +
265              InputSet.getName() + "' needs to be floating point");
266   return true;
267 }
268
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");
274
275   if (!hasVectorTypes())
276     return false;
277
278   TypeSet InputSet(*this);
279
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--);
284
285   if (TypeVec.empty())
286     TP.error("Type inference contradiction found, '" +
287              InputSet.getName() + "' needs to be scalar");
288   return true;
289 }
290
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");
296
297   TypeSet InputSet(*this);
298   bool MadeChange = false;
299
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;
305     }
306
307   if (TypeVec.empty())
308     TP.error("Type inference contradiction found, '" +
309              InputSet.getName() + "' needs to be a vector");
310   return MadeChange;
311 }
312
313
314
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;
320
321   if (isCompletelyUnknown())
322     MadeChange = FillWithPossibleTypes(TP);
323
324   if (Other.isCompletelyUnknown())
325     MadeChange = Other.FillWithPossibleTypes(TP);
326
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);
337
338   assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
339          "Should have a type list now");
340
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);
346
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!");
354
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]);
360
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() +"'!");
368     }
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() +"'!");
376
377   }
378   
379
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.
383
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;
391     }
392   for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
393     if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
394       SmallestInt = TypeVec[i];
395
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;
401     }
402   for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
403     if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
404       SmallestFP = TypeVec[i];
405
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;
419       }
420     }
421     else if (isFloatingPoint(*TVI)) {
422       ++OtherFPSize;
423       if (*TVI == SmallestFP) {
424         TVI = Other.TypeVec.erase(TVI);
425         --OtherFPSize;
426         MadeChange = true;
427         continue;
428       }
429     }
430     ++TVI;
431   }
432
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() +"'!");
439
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;
447     }
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];
451
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;
457     }
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];
461
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;
475       }
476     }
477     else if (isFloatingPoint(*TVI)) {
478       ++FPSize;
479       if (*TVI == LargestFP) {
480         TVI = TypeVec.erase(TVI);
481         --FPSize;
482         MadeChange = true;
483         continue;
484       }
485     }
486     ++TVI;
487   }
488
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()+"'!");
495
496   return MadeChange;
497 }
498
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);
507
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);
514   }
515
516   // If the scalar type is known, filter out vector types whose element types
517   // disagree.
518   if (!VTOperand.isConcrete())
519     return MadeChange;
520
521   MVT::SimpleValueType VT = VTOperand.getConcrete();
522
523   TypeSet InputSet(*this);
524
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;
531     }
532   }
533
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;
538 }
539
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);
548
549   // "This" must be larger than "VTOperand."
550   MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
551
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();
556
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();
562
563     EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
564     MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
565   }
566
567   return MadeChange;
568 }
569
570 //===----------------------------------------------------------------------===//
571 // Helpers for working with extended types.
572
573 bool RecordPtrCmp::operator()(const Record *LHS, const Record *RHS) const {
574   return LHS->getID() < RHS->getID();
575 }
576
577 /// Dependent variable map for CodeGenDAGPattern variant generation
578 typedef std::map<std::string, int> DepVarMap;
579
580 /// Const iterator shorthand for DepVarMap
581 typedef DepVarMap::const_iterator DepVarMap_citer;
582
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);
590   }
591 }
592   
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);
600   }
601 }
602
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) << " ");
613     }
614     DEBUG(errs() << "]");
615   }
616 }
617 #endif
618
619
620 //===----------------------------------------------------------------------===//
621 // TreePredicateFn Implementation
622 //===----------------------------------------------------------------------===//
623
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");
628 }
629
630 std::string TreePredicateFn::getPredCode() const {
631   return PatFragRec->getRecord()->getValueAsCode("PredicateCode");
632 }
633
634 std::string TreePredicateFn::getImmCode() const {
635   return PatFragRec->getRecord()->getValueAsCode("ImmediateCode");
636 }
637
638
639 /// isAlwaysTrue - Return true if this is a noop predicate.
640 bool TreePredicateFn::isAlwaysTrue() const {
641   return getPredCode().empty() && getImmCode().empty();
642 }
643
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();
648 }
649
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     if (ImmCode.find("VT") != std::string::npos)
661       Result += "    MVT VT = Node->getValueType(0).getSimpleVT();\n";
662     return Result + ImmCode;
663   }
664   
665   // Handle arbitrary node predicates.
666   assert(!getPredCode().empty() && "Don't have any predicate code!");
667   std::string ClassName;
668   if (PatFragRec->getOnlyTree()->isLeaf())
669     ClassName = "SDNode";
670   else {
671     Record *Op = PatFragRec->getOnlyTree()->getOperator();
672     ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
673   }
674   std::string Result;
675   if (ClassName == "SDNode")
676     Result = "    SDNode *N = Node;\n";
677   else
678     Result = "    " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
679   
680   return Result + getPredCode();
681 }
682
683 //===----------------------------------------------------------------------===//
684 // PatternToMatch implementation
685 //
686
687
688 /// getPatternSize - Return the 'size' of this pattern.  We want to match large
689 /// patterns before small ones.  This is used to determine the size of a
690 /// pattern.
691 static unsigned getPatternSize(const TreePatternNode *P,
692                                const CodeGenDAGPatterns &CGP) {
693   unsigned Size = 3;  // The node itself.
694   // If the root node is a ConstantSDNode, increases its size.
695   // e.g. (set R32:$dst, 0).
696   if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
697     Size += 2;
698
699   // FIXME: This is a hack to statically increase the priority of patterns
700   // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
701   // Later we can allow complexity / cost for each pattern to be (optionally)
702   // specified. To get best possible pattern match we'll need to dynamically
703   // calculate the complexity of all patterns a dag can potentially map to.
704   const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
705   if (AM)
706     Size += AM->getNumOperands() * 3;
707
708   // If this node has some predicate function that must match, it adds to the
709   // complexity of this node.
710   if (!P->getPredicateFns().empty())
711     ++Size;
712
713   // Count children in the count if they are also nodes.
714   for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
715     TreePatternNode *Child = P->getChild(i);
716     if (!Child->isLeaf() && Child->getNumTypes() &&
717         Child->getType(0) != MVT::Other)
718       Size += getPatternSize(Child, CGP);
719     else if (Child->isLeaf()) {
720       if (dynamic_cast<IntInit*>(Child->getLeafValue()))
721         Size += 5;  // Matches a ConstantSDNode (+3) and a specific value (+2).
722       else if (Child->getComplexPatternInfo(CGP))
723         Size += getPatternSize(Child, CGP);
724       else if (!Child->getPredicateFns().empty())
725         ++Size;
726     }
727   }
728
729   return Size;
730 }
731
732 /// Compute the complexity metric for the input pattern.  This roughly
733 /// corresponds to the number of nodes that are covered.
734 unsigned PatternToMatch::
735 getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
736   return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
737 }
738
739
740 /// getPredicateCheck - Return a single string containing all of this
741 /// pattern's predicates concatenated with "&&" operators.
742 ///
743 std::string PatternToMatch::getPredicateCheck() const {
744   std::string PredicateCheck;
745   for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
746     if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
747       Record *Def = Pred->getDef();
748       if (!Def->isSubClassOf("Predicate")) {
749 #ifndef NDEBUG
750         Def->dump();
751 #endif
752         assert(0 && "Unknown predicate type!");
753       }
754       if (!PredicateCheck.empty())
755         PredicateCheck += " && ";
756       PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
757     }
758   }
759
760   return PredicateCheck;
761 }
762
763 //===----------------------------------------------------------------------===//
764 // SDTypeConstraint implementation
765 //
766
767 SDTypeConstraint::SDTypeConstraint(Record *R) {
768   OperandNo = R->getValueAsInt("OperandNum");
769
770   if (R->isSubClassOf("SDTCisVT")) {
771     ConstraintType = SDTCisVT;
772     x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
773     if (x.SDTCisVT_Info.VT == MVT::isVoid)
774       throw TGError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
775
776   } else if (R->isSubClassOf("SDTCisPtrTy")) {
777     ConstraintType = SDTCisPtrTy;
778   } else if (R->isSubClassOf("SDTCisInt")) {
779     ConstraintType = SDTCisInt;
780   } else if (R->isSubClassOf("SDTCisFP")) {
781     ConstraintType = SDTCisFP;
782   } else if (R->isSubClassOf("SDTCisVec")) {
783     ConstraintType = SDTCisVec;
784   } else if (R->isSubClassOf("SDTCisSameAs")) {
785     ConstraintType = SDTCisSameAs;
786     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
787   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
788     ConstraintType = SDTCisVTSmallerThanOp;
789     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
790       R->getValueAsInt("OtherOperandNum");
791   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
792     ConstraintType = SDTCisOpSmallerThanOp;
793     x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
794       R->getValueAsInt("BigOperandNum");
795   } else if (R->isSubClassOf("SDTCisEltOfVec")) {
796     ConstraintType = SDTCisEltOfVec;
797     x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
798   } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
799     ConstraintType = SDTCisSubVecOfVec;
800     x.SDTCisSubVecOfVec_Info.OtherOperandNum =
801       R->getValueAsInt("OtherOpNum");
802   } else {
803     errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
804     exit(1);
805   }
806 }
807
808 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
809 /// N, and the result number in ResNo.
810 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
811                                       const SDNodeInfo &NodeInfo,
812                                       unsigned &ResNo) {
813   unsigned NumResults = NodeInfo.getNumResults();
814   if (OpNo < NumResults) {
815     ResNo = OpNo;
816     return N;
817   }
818
819   OpNo -= NumResults;
820
821   if (OpNo >= N->getNumChildren()) {
822     errs() << "Invalid operand number in type constraint "
823            << (OpNo+NumResults) << " ";
824     N->dump();
825     errs() << '\n';
826     exit(1);
827   }
828
829   return N->getChild(OpNo);
830 }
831
832 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
833 /// constraint to the nodes operands.  This returns true if it makes a
834 /// change, false otherwise.  If a type contradiction is found, throw an
835 /// exception.
836 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
837                                            const SDNodeInfo &NodeInfo,
838                                            TreePattern &TP) const {
839   unsigned ResNo = 0; // The result number being referenced.
840   TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
841
842   switch (ConstraintType) {
843   default: assert(0 && "Unknown constraint type!");
844   case SDTCisVT:
845     // Operand must be a particular type.
846     return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
847   case SDTCisPtrTy:
848     // Operand must be same as target pointer type.
849     return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
850   case SDTCisInt:
851     // Require it to be one of the legal integer VTs.
852     return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
853   case SDTCisFP:
854     // Require it to be one of the legal fp VTs.
855     return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
856   case SDTCisVec:
857     // Require it to be one of the legal vector VTs.
858     return NodeToApply->getExtType(ResNo).EnforceVector(TP);
859   case SDTCisSameAs: {
860     unsigned OResNo = 0;
861     TreePatternNode *OtherNode =
862       getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
863     return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
864            OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
865   }
866   case SDTCisVTSmallerThanOp: {
867     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
868     // have an integer type that is smaller than the VT.
869     if (!NodeToApply->isLeaf() ||
870         !dynamic_cast<DefInit*>(NodeToApply->getLeafValue()) ||
871         !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
872                ->isSubClassOf("ValueType"))
873       TP.error(N->getOperator()->getName() + " expects a VT operand!");
874     MVT::SimpleValueType VT =
875      getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
876
877     EEVT::TypeSet TypeListTmp(VT, TP);
878
879     unsigned OResNo = 0;
880     TreePatternNode *OtherNode =
881       getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
882                     OResNo);
883
884     return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
885   }
886   case SDTCisOpSmallerThanOp: {
887     unsigned BResNo = 0;
888     TreePatternNode *BigOperand =
889       getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
890                     BResNo);
891     return NodeToApply->getExtType(ResNo).
892                   EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
893   }
894   case SDTCisEltOfVec: {
895     unsigned VResNo = 0;
896     TreePatternNode *VecOperand =
897       getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
898                     VResNo);
899
900     // Filter vector types out of VecOperand that don't have the right element
901     // type.
902     return VecOperand->getExtType(VResNo).
903       EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
904   }
905   case SDTCisSubVecOfVec: {
906     unsigned VResNo = 0;
907     TreePatternNode *BigVecOperand =
908       getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
909                     VResNo);
910
911     // Filter vector types out of BigVecOperand that don't have the
912     // right subvector type.
913     return BigVecOperand->getExtType(VResNo).
914       EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
915   }
916   }
917   return false;
918 }
919
920 //===----------------------------------------------------------------------===//
921 // SDNodeInfo implementation
922 //
923 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
924   EnumName    = R->getValueAsString("Opcode");
925   SDClassName = R->getValueAsString("SDClass");
926   Record *TypeProfile = R->getValueAsDef("TypeProfile");
927   NumResults = TypeProfile->getValueAsInt("NumResults");
928   NumOperands = TypeProfile->getValueAsInt("NumOperands");
929
930   // Parse the properties.
931   Properties = 0;
932   std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
933   for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
934     if (PropList[i]->getName() == "SDNPCommutative") {
935       Properties |= 1 << SDNPCommutative;
936     } else if (PropList[i]->getName() == "SDNPAssociative") {
937       Properties |= 1 << SDNPAssociative;
938     } else if (PropList[i]->getName() == "SDNPHasChain") {
939       Properties |= 1 << SDNPHasChain;
940     } else if (PropList[i]->getName() == "SDNPOutGlue") {
941       Properties |= 1 << SDNPOutGlue;
942     } else if (PropList[i]->getName() == "SDNPInGlue") {
943       Properties |= 1 << SDNPInGlue;
944     } else if (PropList[i]->getName() == "SDNPOptInGlue") {
945       Properties |= 1 << SDNPOptInGlue;
946     } else if (PropList[i]->getName() == "SDNPMayStore") {
947       Properties |= 1 << SDNPMayStore;
948     } else if (PropList[i]->getName() == "SDNPMayLoad") {
949       Properties |= 1 << SDNPMayLoad;
950     } else if (PropList[i]->getName() == "SDNPSideEffect") {
951       Properties |= 1 << SDNPSideEffect;
952     } else if (PropList[i]->getName() == "SDNPMemOperand") {
953       Properties |= 1 << SDNPMemOperand;
954     } else if (PropList[i]->getName() == "SDNPVariadic") {
955       Properties |= 1 << SDNPVariadic;
956     } else {
957       errs() << "Unknown SD Node property '" << PropList[i]->getName()
958              << "' on node '" << R->getName() << "'!\n";
959       exit(1);
960     }
961   }
962
963
964   // Parse the type constraints.
965   std::vector<Record*> ConstraintList =
966     TypeProfile->getValueAsListOfDefs("Constraints");
967   TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
968 }
969
970 /// getKnownType - If the type constraints on this node imply a fixed type
971 /// (e.g. all stores return void, etc), then return it as an
972 /// MVT::SimpleValueType.  Otherwise, return EEVT::Other.
973 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
974   unsigned NumResults = getNumResults();
975   assert(NumResults <= 1 &&
976          "We only work with nodes with zero or one result so far!");
977   assert(ResNo == 0 && "Only handles single result nodes so far");
978
979   for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
980     // Make sure that this applies to the correct node result.
981     if (TypeConstraints[i].OperandNo >= NumResults)  // FIXME: need value #
982       continue;
983
984     switch (TypeConstraints[i].ConstraintType) {
985     default: break;
986     case SDTypeConstraint::SDTCisVT:
987       return TypeConstraints[i].x.SDTCisVT_Info.VT;
988     case SDTypeConstraint::SDTCisPtrTy:
989       return MVT::iPTR;
990     }
991   }
992   return MVT::Other;
993 }
994
995 //===----------------------------------------------------------------------===//
996 // TreePatternNode implementation
997 //
998
999 TreePatternNode::~TreePatternNode() {
1000 #if 0 // FIXME: implement refcounted tree nodes!
1001   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1002     delete getChild(i);
1003 #endif
1004 }
1005
1006 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1007   if (Operator->getName() == "set" ||
1008       Operator->getName() == "implicit")
1009     return 0;  // All return nothing.
1010
1011   if (Operator->isSubClassOf("Intrinsic"))
1012     return CDP.getIntrinsic(Operator).IS.RetVTs.size();
1013
1014   if (Operator->isSubClassOf("SDNode"))
1015     return CDP.getSDNodeInfo(Operator).getNumResults();
1016
1017   if (Operator->isSubClassOf("PatFrag")) {
1018     // If we've already parsed this pattern fragment, get it.  Otherwise, handle
1019     // the forward reference case where one pattern fragment references another
1020     // before it is processed.
1021     if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1022       return PFRec->getOnlyTree()->getNumTypes();
1023
1024     // Get the result tree.
1025     DagInit *Tree = Operator->getValueAsDag("Fragment");
1026     Record *Op = 0;
1027     if (Tree && dynamic_cast<DefInit*>(Tree->getOperator()))
1028       Op = dynamic_cast<DefInit*>(Tree->getOperator())->getDef();
1029     assert(Op && "Invalid Fragment");
1030     return GetNumNodeResults(Op, CDP);
1031   }
1032
1033   if (Operator->isSubClassOf("Instruction")) {
1034     CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
1035
1036     // FIXME: Should allow access to all the results here.
1037     unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
1038
1039     // Add on one implicit def if it has a resolvable type.
1040     if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1041       ++NumDefsToAdd;
1042     return NumDefsToAdd;
1043   }
1044
1045   if (Operator->isSubClassOf("SDNodeXForm"))
1046     return 1;  // FIXME: Generalize SDNodeXForm
1047
1048   Operator->dump();
1049   errs() << "Unhandled node in GetNumNodeResults\n";
1050   exit(1);
1051 }
1052
1053 void TreePatternNode::print(raw_ostream &OS) const {
1054   if (isLeaf())
1055     OS << *getLeafValue();
1056   else
1057     OS << '(' << getOperator()->getName();
1058
1059   for (unsigned i = 0, e = Types.size(); i != e; ++i)
1060     OS << ':' << getExtType(i).getName();
1061
1062   if (!isLeaf()) {
1063     if (getNumChildren() != 0) {
1064       OS << " ";
1065       getChild(0)->print(OS);
1066       for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1067         OS << ", ";
1068         getChild(i)->print(OS);
1069       }
1070     }
1071     OS << ")";
1072   }
1073
1074   for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
1075     OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
1076   if (TransformFn)
1077     OS << "<<X:" << TransformFn->getName() << ">>";
1078   if (!getName().empty())
1079     OS << ":$" << getName();
1080
1081 }
1082 void TreePatternNode::dump() const {
1083   print(errs());
1084 }
1085
1086 /// isIsomorphicTo - Return true if this node is recursively
1087 /// isomorphic to the specified node.  For this comparison, the node's
1088 /// entire state is considered. The assigned name is ignored, since
1089 /// nodes with differing names are considered isomorphic. However, if
1090 /// the assigned name is present in the dependent variable set, then
1091 /// the assigned name is considered significant and the node is
1092 /// isomorphic if the names match.
1093 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1094                                      const MultipleUseVarSet &DepVars) const {
1095   if (N == this) return true;
1096   if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1097       getPredicateFns() != N->getPredicateFns() ||
1098       getTransformFn() != N->getTransformFn())
1099     return false;
1100
1101   if (isLeaf()) {
1102     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1103       if (DefInit *NDI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1104         return ((DI->getDef() == NDI->getDef())
1105                 && (DepVars.find(getName()) == DepVars.end()
1106                     || getName() == N->getName()));
1107       }
1108     }
1109     return getLeafValue() == N->getLeafValue();
1110   }
1111
1112   if (N->getOperator() != getOperator() ||
1113       N->getNumChildren() != getNumChildren()) return false;
1114   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1115     if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
1116       return false;
1117   return true;
1118 }
1119
1120 /// clone - Make a copy of this tree and all of its children.
1121 ///
1122 TreePatternNode *TreePatternNode::clone() const {
1123   TreePatternNode *New;
1124   if (isLeaf()) {
1125     New = new TreePatternNode(getLeafValue(), getNumTypes());
1126   } else {
1127     std::vector<TreePatternNode*> CChildren;
1128     CChildren.reserve(Children.size());
1129     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1130       CChildren.push_back(getChild(i)->clone());
1131     New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
1132   }
1133   New->setName(getName());
1134   New->Types = Types;
1135   New->setPredicateFns(getPredicateFns());
1136   New->setTransformFn(getTransformFn());
1137   return New;
1138 }
1139
1140 /// RemoveAllTypes - Recursively strip all the types of this tree.
1141 void TreePatternNode::RemoveAllTypes() {
1142   for (unsigned i = 0, e = Types.size(); i != e; ++i)
1143     Types[i] = EEVT::TypeSet();  // Reset to unknown type.
1144   if (isLeaf()) return;
1145   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1146     getChild(i)->RemoveAllTypes();
1147 }
1148
1149
1150 /// SubstituteFormalArguments - Replace the formal arguments in this tree
1151 /// with actual values specified by ArgMap.
1152 void TreePatternNode::
1153 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1154   if (isLeaf()) return;
1155
1156   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1157     TreePatternNode *Child = getChild(i);
1158     if (Child->isLeaf()) {
1159       Init *Val = Child->getLeafValue();
1160       if (dynamic_cast<DefInit*>(Val) &&
1161           static_cast<DefInit*>(Val)->getDef()->getName() == "node") {
1162         // We found a use of a formal argument, replace it with its value.
1163         TreePatternNode *NewChild = ArgMap[Child->getName()];
1164         assert(NewChild && "Couldn't find formal argument!");
1165         assert((Child->getPredicateFns().empty() ||
1166                 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1167                "Non-empty child predicate clobbered!");
1168         setChild(i, NewChild);
1169       }
1170     } else {
1171       getChild(i)->SubstituteFormalArguments(ArgMap);
1172     }
1173   }
1174 }
1175
1176
1177 /// InlinePatternFragments - If this pattern refers to any pattern
1178 /// fragments, inline them into place, giving us a pattern without any
1179 /// PatFrag references.
1180 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
1181   if (isLeaf()) return this;  // nothing to do.
1182   Record *Op = getOperator();
1183
1184   if (!Op->isSubClassOf("PatFrag")) {
1185     // Just recursively inline children nodes.
1186     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1187       TreePatternNode *Child = getChild(i);
1188       TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1189
1190       assert((Child->getPredicateFns().empty() ||
1191               NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1192              "Non-empty child predicate clobbered!");
1193
1194       setChild(i, NewChild);
1195     }
1196     return this;
1197   }
1198
1199   // Otherwise, we found a reference to a fragment.  First, look up its
1200   // TreePattern record.
1201   TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
1202
1203   // Verify that we are passing the right number of operands.
1204   if (Frag->getNumArgs() != Children.size())
1205     TP.error("'" + Op->getName() + "' fragment requires " +
1206              utostr(Frag->getNumArgs()) + " operands!");
1207
1208   TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1209
1210   TreePredicateFn PredFn(Frag);
1211   if (!PredFn.isAlwaysTrue())
1212     FragTree->addPredicateFn(PredFn);
1213
1214   // Resolve formal arguments to their actual value.
1215   if (Frag->getNumArgs()) {
1216     // Compute the map of formal to actual arguments.
1217     std::map<std::string, TreePatternNode*> ArgMap;
1218     for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1219       ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
1220
1221     FragTree->SubstituteFormalArguments(ArgMap);
1222   }
1223
1224   FragTree->setName(getName());
1225   for (unsigned i = 0, e = Types.size(); i != e; ++i)
1226     FragTree->UpdateNodeType(i, getExtType(i), TP);
1227
1228   // Transfer in the old predicates.
1229   for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1230     FragTree->addPredicateFn(getPredicateFns()[i]);
1231
1232   // Get a new copy of this fragment to stitch into here.
1233   //delete this;    // FIXME: implement refcounting!
1234
1235   // The fragment we inlined could have recursive inlining that is needed.  See
1236   // if there are any pattern fragments in it and inline them as needed.
1237   return FragTree->InlinePatternFragments(TP);
1238 }
1239
1240 /// getImplicitType - Check to see if the specified record has an implicit
1241 /// type which should be applied to it.  This will infer the type of register
1242 /// references from the register file information, for example.
1243 ///
1244 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
1245                                      bool NotRegisters, TreePattern &TP) {
1246   // Check to see if this is a register or a register class.
1247   if (R->isSubClassOf("RegisterClass")) {
1248     assert(ResNo == 0 && "Regclass ref only has one result!");
1249     if (NotRegisters)
1250       return EEVT::TypeSet(); // Unknown.
1251     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1252     return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
1253   }
1254
1255   if (R->isSubClassOf("PatFrag")) {
1256     assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
1257     // Pattern fragment types will be resolved when they are inlined.
1258     return EEVT::TypeSet(); // Unknown.
1259   }
1260
1261   if (R->isSubClassOf("Register")) {
1262     assert(ResNo == 0 && "Registers only produce one result!");
1263     if (NotRegisters)
1264       return EEVT::TypeSet(); // Unknown.
1265     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1266     return EEVT::TypeSet(T.getRegisterVTs(R));
1267   }
1268
1269   if (R->isSubClassOf("SubRegIndex")) {
1270     assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1271     return EEVT::TypeSet();
1272   }
1273
1274   if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
1275     assert(ResNo == 0 && "This node only has one result!");
1276     // Using a VTSDNode or CondCodeSDNode.
1277     return EEVT::TypeSet(MVT::Other, TP);
1278   }
1279
1280   if (R->isSubClassOf("ComplexPattern")) {
1281     assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
1282     if (NotRegisters)
1283       return EEVT::TypeSet(); // Unknown.
1284    return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1285                          TP);
1286   }
1287   if (R->isSubClassOf("PointerLikeRegClass")) {
1288     assert(ResNo == 0 && "Regclass can only have one result!");
1289     return EEVT::TypeSet(MVT::iPTR, TP);
1290   }
1291
1292   if (R->getName() == "node" || R->getName() == "srcvalue" ||
1293       R->getName() == "zero_reg") {
1294     // Placeholder.
1295     return EEVT::TypeSet(); // Unknown.
1296   }
1297
1298   TP.error("Unknown node flavor used in pattern: " + R->getName());
1299   return EEVT::TypeSet(MVT::Other, TP);
1300 }
1301
1302
1303 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1304 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
1305 const CodeGenIntrinsic *TreePatternNode::
1306 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1307   if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1308       getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1309       getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1310     return 0;
1311
1312   unsigned IID =
1313     dynamic_cast<IntInit*>(getChild(0)->getLeafValue())->getValue();
1314   return &CDP.getIntrinsicInfo(IID);
1315 }
1316
1317 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1318 /// return the ComplexPattern information, otherwise return null.
1319 const ComplexPattern *
1320 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1321   if (!isLeaf()) return 0;
1322
1323   DefInit *DI = dynamic_cast<DefInit*>(getLeafValue());
1324   if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1325     return &CGP.getComplexPattern(DI->getDef());
1326   return 0;
1327 }
1328
1329 /// NodeHasProperty - Return true if this node has the specified property.
1330 bool TreePatternNode::NodeHasProperty(SDNP Property,
1331                                       const CodeGenDAGPatterns &CGP) const {
1332   if (isLeaf()) {
1333     if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1334       return CP->hasProperty(Property);
1335     return false;
1336   }
1337
1338   Record *Operator = getOperator();
1339   if (!Operator->isSubClassOf("SDNode")) return false;
1340
1341   return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1342 }
1343
1344
1345
1346
1347 /// TreeHasProperty - Return true if any node in this tree has the specified
1348 /// property.
1349 bool TreePatternNode::TreeHasProperty(SDNP Property,
1350                                       const CodeGenDAGPatterns &CGP) const {
1351   if (NodeHasProperty(Property, CGP))
1352     return true;
1353   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1354     if (getChild(i)->TreeHasProperty(Property, CGP))
1355       return true;
1356   return false;
1357 }
1358
1359 /// isCommutativeIntrinsic - Return true if the node corresponds to a
1360 /// commutative intrinsic.
1361 bool
1362 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1363   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1364     return Int->isCommutative;
1365   return false;
1366 }
1367
1368
1369 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
1370 /// this node and its children in the tree.  This returns true if it makes a
1371 /// change, false otherwise.  If a type contradiction is found, throw an
1372 /// exception.
1373 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
1374   CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1375   if (isLeaf()) {
1376     if (DefInit *DI = dynamic_cast<DefInit*>(getLeafValue())) {
1377       // If it's a regclass or something else known, include the type.
1378       bool MadeChange = false;
1379       for (unsigned i = 0, e = Types.size(); i != e; ++i)
1380         MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
1381                                                         NotRegisters, TP), TP);
1382       return MadeChange;
1383     }
1384
1385     if (IntInit *II = dynamic_cast<IntInit*>(getLeafValue())) {
1386       assert(Types.size() == 1 && "Invalid IntInit");
1387
1388       // Int inits are always integers. :)
1389       bool MadeChange = Types[0].EnforceInteger(TP);
1390
1391       if (!Types[0].isConcrete())
1392         return MadeChange;
1393
1394       MVT::SimpleValueType VT = getType(0);
1395       if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1396         return MadeChange;
1397
1398       unsigned Size = EVT(VT).getSizeInBits();
1399       // Make sure that the value is representable for this type.
1400       if (Size >= 32) return MadeChange;
1401
1402       int Val = (II->getValue() << (32-Size)) >> (32-Size);
1403       if (Val == II->getValue()) return MadeChange;
1404
1405       // If sign-extended doesn't fit, does it fit as unsigned?
1406       unsigned ValueMask;
1407       unsigned UnsignedVal;
1408       ValueMask = unsigned(~uint32_t(0UL) >> (32-Size));
1409       UnsignedVal = unsigned(II->getValue());
1410
1411       if ((ValueMask & UnsignedVal) == UnsignedVal)
1412         return MadeChange;
1413
1414       TP.error("Integer value '" + itostr(II->getValue())+
1415                "' is out of range for type '" + getEnumName(getType(0)) + "'!");
1416       return MadeChange;
1417     }
1418     return false;
1419   }
1420
1421   // special handling for set, which isn't really an SDNode.
1422   if (getOperator()->getName() == "set") {
1423     assert(getNumTypes() == 0 && "Set doesn't produce a value");
1424     assert(getNumChildren() >= 2 && "Missing RHS of a set?");
1425     unsigned NC = getNumChildren();
1426
1427     TreePatternNode *SetVal = getChild(NC-1);
1428     bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1429
1430     for (unsigned i = 0; i < NC-1; ++i) {
1431       TreePatternNode *Child = getChild(i);
1432       MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1433
1434       // Types of operands must match.
1435       MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1436       MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
1437     }
1438     return MadeChange;
1439   }
1440
1441   if (getOperator()->getName() == "implicit") {
1442     assert(getNumTypes() == 0 && "Node doesn't produce a value");
1443
1444     bool MadeChange = false;
1445     for (unsigned i = 0; i < getNumChildren(); ++i)
1446       MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1447     return MadeChange;
1448   }
1449
1450   if (getOperator()->getName() == "COPY_TO_REGCLASS") {
1451     bool MadeChange = false;
1452     MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1453     MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
1454
1455     assert(getChild(0)->getNumTypes() == 1 &&
1456            getChild(1)->getNumTypes() == 1 && "Unhandled case");
1457
1458     // child #1 of COPY_TO_REGCLASS should be a register class.  We don't care
1459     // what type it gets, so if it didn't get a concrete type just give it the
1460     // first viable type from the reg class.
1461     if (!getChild(1)->hasTypeSet(0) &&
1462         !getChild(1)->getExtType(0).isCompletelyUnknown()) {
1463       MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
1464       MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
1465     }
1466     return MadeChange;
1467   }
1468
1469   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
1470     bool MadeChange = false;
1471
1472     // Apply the result type to the node.
1473     unsigned NumRetVTs = Int->IS.RetVTs.size();
1474     unsigned NumParamVTs = Int->IS.ParamVTs.size();
1475
1476     for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
1477       MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
1478
1479     if (getNumChildren() != NumParamVTs + 1)
1480       TP.error("Intrinsic '" + Int->Name + "' expects " +
1481                utostr(NumParamVTs) + " operands, not " +
1482                utostr(getNumChildren() - 1) + " operands!");
1483
1484     // Apply type info to the intrinsic ID.
1485     MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
1486
1487     for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1488       MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
1489
1490       MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1491       assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1492       MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
1493     }
1494     return MadeChange;
1495   }
1496
1497   if (getOperator()->isSubClassOf("SDNode")) {
1498     const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
1499
1500     // Check that the number of operands is sane.  Negative operands -> varargs.
1501     if (NI.getNumOperands() >= 0 &&
1502         getNumChildren() != (unsigned)NI.getNumOperands())
1503       TP.error(getOperator()->getName() + " node requires exactly " +
1504                itostr(NI.getNumOperands()) + " operands!");
1505
1506     bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1507     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1508       MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1509     return MadeChange;
1510   }
1511
1512   if (getOperator()->isSubClassOf("Instruction")) {
1513     const DAGInstruction &Inst = CDP.getInstruction(getOperator());
1514     CodeGenInstruction &InstInfo =
1515       CDP.getTargetInfo().getInstruction(getOperator());
1516
1517     bool MadeChange = false;
1518
1519     // Apply the result types to the node, these come from the things in the
1520     // (outs) list of the instruction.
1521     // FIXME: Cap at one result so far.
1522     unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
1523     for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
1524       Record *ResultNode = Inst.getResult(ResNo);
1525
1526       if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
1527         MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
1528       } else if (ResultNode->getName() == "unknown") {
1529         // Nothing to do.
1530       } else {
1531         assert(ResultNode->isSubClassOf("RegisterClass") &&
1532                "Operands should be register classes!");
1533         const CodeGenRegisterClass &RC =
1534           CDP.getTargetInfo().getRegisterClass(ResultNode);
1535         MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
1536       }
1537     }
1538
1539     // If the instruction has implicit defs, we apply the first one as a result.
1540     // FIXME: This sucks, it should apply all implicit defs.
1541     if (!InstInfo.ImplicitDefs.empty()) {
1542       unsigned ResNo = NumResultsToAdd;
1543
1544       // FIXME: Generalize to multiple possible types and multiple possible
1545       // ImplicitDefs.
1546       MVT::SimpleValueType VT =
1547         InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
1548
1549       if (VT != MVT::Other)
1550         MadeChange |= UpdateNodeType(ResNo, VT, TP);
1551     }
1552
1553     // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1554     // be the same.
1555     if (getOperator()->getName() == "INSERT_SUBREG") {
1556       assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1557       MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1558       MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
1559     }
1560
1561     unsigned ChildNo = 0;
1562     for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1563       Record *OperandNode = Inst.getOperand(i);
1564
1565       // If the instruction expects a predicate or optional def operand, we
1566       // codegen this by setting the operand to it's default value if it has a
1567       // non-empty DefaultOps field.
1568       if ((OperandNode->isSubClassOf("PredicateOperand") ||
1569            OperandNode->isSubClassOf("OptionalDefOperand")) &&
1570           !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1571         continue;
1572
1573       // Verify that we didn't run out of provided operands.
1574       if (ChildNo >= getNumChildren())
1575         TP.error("Instruction '" + getOperator()->getName() +
1576                  "' expects more operands than were provided.");
1577
1578       MVT::SimpleValueType VT;
1579       TreePatternNode *Child = getChild(ChildNo++);
1580       unsigned ChildResNo = 0;  // Instructions always use res #0 of their op.
1581
1582       if (OperandNode->isSubClassOf("RegisterClass")) {
1583         const CodeGenRegisterClass &RC =
1584           CDP.getTargetInfo().getRegisterClass(OperandNode);
1585         MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
1586       } else if (OperandNode->isSubClassOf("Operand")) {
1587         VT = getValueType(OperandNode->getValueAsDef("Type"));
1588         MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
1589       } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
1590         MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
1591       } else if (OperandNode->getName() == "unknown") {
1592         // Nothing to do.
1593       } else {
1594         assert(0 && "Unknown operand type!");
1595         abort();
1596       }
1597       MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
1598     }
1599
1600     if (ChildNo != getNumChildren())
1601       TP.error("Instruction '" + getOperator()->getName() +
1602                "' was provided too many operands!");
1603
1604     return MadeChange;
1605   }
1606
1607   assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
1608
1609   // Node transforms always take one operand.
1610   if (getNumChildren() != 1)
1611     TP.error("Node transform '" + getOperator()->getName() +
1612              "' requires one operand!");
1613
1614   bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1615
1616
1617   // If either the output or input of the xform does not have exact
1618   // type info. We assume they must be the same. Otherwise, it is perfectly
1619   // legal to transform from one type to a completely different type.
1620 #if 0
1621   if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
1622     bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1623     MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
1624     return MadeChange;
1625   }
1626 #endif
1627   return MadeChange;
1628 }
1629
1630 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1631 /// RHS of a commutative operation, not the on LHS.
1632 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1633   if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1634     return true;
1635   if (N->isLeaf() && dynamic_cast<IntInit*>(N->getLeafValue()))
1636     return true;
1637   return false;
1638 }
1639
1640
1641 /// canPatternMatch - If it is impossible for this pattern to match on this
1642 /// target, fill in Reason and return false.  Otherwise, return true.  This is
1643 /// used as a sanity check for .td files (to prevent people from writing stuff
1644 /// that can never possibly work), and to prevent the pattern permuter from
1645 /// generating stuff that is useless.
1646 bool TreePatternNode::canPatternMatch(std::string &Reason,
1647                                       const CodeGenDAGPatterns &CDP) {
1648   if (isLeaf()) return true;
1649
1650   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1651     if (!getChild(i)->canPatternMatch(Reason, CDP))
1652       return false;
1653
1654   // If this is an intrinsic, handle cases that would make it not match.  For
1655   // example, if an operand is required to be an immediate.
1656   if (getOperator()->isSubClassOf("Intrinsic")) {
1657     // TODO:
1658     return true;
1659   }
1660
1661   // If this node is a commutative operator, check that the LHS isn't an
1662   // immediate.
1663   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
1664   bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1665   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
1666     // Scan all of the operands of the node and make sure that only the last one
1667     // is a constant node, unless the RHS also is.
1668     if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
1669       bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1670       for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
1671         if (OnlyOnRHSOfCommutative(getChild(i))) {
1672           Reason="Immediate value must be on the RHS of commutative operators!";
1673           return false;
1674         }
1675     }
1676   }
1677
1678   return true;
1679 }
1680
1681 //===----------------------------------------------------------------------===//
1682 // TreePattern implementation
1683 //
1684
1685 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
1686                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1687   isInputPattern = isInput;
1688   for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
1689     Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
1690 }
1691
1692 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
1693                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1694   isInputPattern = isInput;
1695   Trees.push_back(ParseTreePattern(Pat, ""));
1696 }
1697
1698 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
1699                          CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp){
1700   isInputPattern = isInput;
1701   Trees.push_back(Pat);
1702 }
1703
1704 void TreePattern::error(const std::string &Msg) const {
1705   dump();
1706   throw TGError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1707 }
1708
1709 void TreePattern::ComputeNamedNodes() {
1710   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1711     ComputeNamedNodes(Trees[i]);
1712 }
1713
1714 void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1715   if (!N->getName().empty())
1716     NamedNodes[N->getName()].push_back(N);
1717
1718   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1719     ComputeNamedNodes(N->getChild(i));
1720 }
1721
1722
1723 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
1724   if (DefInit *DI = dynamic_cast<DefInit*>(TheInit)) {
1725     Record *R = DI->getDef();
1726
1727     // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
1728     // TreePatternNode if its own.  For example:
1729     ///   (foo GPR, imm) -> (foo GPR, (imm))
1730     if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
1731       return ParseTreePattern(new DagInit(DI, "",
1732                           std::vector<std::pair<Init*, std::string> >()),
1733                               OpName);
1734
1735     // Input argument?
1736     TreePatternNode *Res = new TreePatternNode(DI, 1);
1737     if (R->getName() == "node" && !OpName.empty()) {
1738       if (OpName.empty())
1739         error("'node' argument requires a name to match with operand list");
1740       Args.push_back(OpName);
1741     }
1742
1743     Res->setName(OpName);
1744     return Res;
1745   }
1746
1747   if (IntInit *II = dynamic_cast<IntInit*>(TheInit)) {
1748     if (!OpName.empty())
1749       error("Constant int argument should not have a name!");
1750     return new TreePatternNode(II, 1);
1751   }
1752
1753   if (BitsInit *BI = dynamic_cast<BitsInit*>(TheInit)) {
1754     // Turn this into an IntInit.
1755     Init *II = BI->convertInitializerTo(new IntRecTy());
1756     if (II == 0 || !dynamic_cast<IntInit*>(II))
1757       error("Bits value must be constants!");
1758     return ParseTreePattern(II, OpName);
1759   }
1760
1761   DagInit *Dag = dynamic_cast<DagInit*>(TheInit);
1762   if (!Dag) {
1763     TheInit->dump();
1764     error("Pattern has unexpected init kind!");
1765   }
1766   DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
1767   if (!OpDef) error("Pattern has unexpected operator type!");
1768   Record *Operator = OpDef->getDef();
1769
1770   if (Operator->isSubClassOf("ValueType")) {
1771     // If the operator is a ValueType, then this must be "type cast" of a leaf
1772     // node.
1773     if (Dag->getNumArgs() != 1)
1774       error("Type cast only takes one operand!");
1775
1776     TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
1777
1778     // Apply the type cast.
1779     assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1780     New->UpdateNodeType(0, getValueType(Operator), *this);
1781
1782     if (!OpName.empty())
1783       error("ValueType cast should not have a name!");
1784     return New;
1785   }
1786
1787   // Verify that this is something that makes sense for an operator.
1788   if (!Operator->isSubClassOf("PatFrag") &&
1789       !Operator->isSubClassOf("SDNode") &&
1790       !Operator->isSubClassOf("Instruction") &&
1791       !Operator->isSubClassOf("SDNodeXForm") &&
1792       !Operator->isSubClassOf("Intrinsic") &&
1793       Operator->getName() != "set" &&
1794       Operator->getName() != "implicit")
1795     error("Unrecognized node '" + Operator->getName() + "'!");
1796
1797   //  Check to see if this is something that is illegal in an input pattern.
1798   if (isInputPattern) {
1799     if (Operator->isSubClassOf("Instruction") ||
1800         Operator->isSubClassOf("SDNodeXForm"))
1801       error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1802   } else {
1803     if (Operator->isSubClassOf("Intrinsic"))
1804       error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1805
1806     if (Operator->isSubClassOf("SDNode") &&
1807         Operator->getName() != "imm" &&
1808         Operator->getName() != "fpimm" &&
1809         Operator->getName() != "tglobaltlsaddr" &&
1810         Operator->getName() != "tconstpool" &&
1811         Operator->getName() != "tjumptable" &&
1812         Operator->getName() != "tframeindex" &&
1813         Operator->getName() != "texternalsym" &&
1814         Operator->getName() != "tblockaddress" &&
1815         Operator->getName() != "tglobaladdr" &&
1816         Operator->getName() != "bb" &&
1817         Operator->getName() != "vt")
1818       error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1819   }
1820
1821   std::vector<TreePatternNode*> Children;
1822
1823   // Parse all the operands.
1824   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1825     Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
1826
1827   // If the operator is an intrinsic, then this is just syntactic sugar for for
1828   // (intrinsic_* <number>, ..children..).  Pick the right intrinsic node, and
1829   // convert the intrinsic name to a number.
1830   if (Operator->isSubClassOf("Intrinsic")) {
1831     const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1832     unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1833
1834     // If this intrinsic returns void, it must have side-effects and thus a
1835     // chain.
1836     if (Int.IS.RetVTs.empty())
1837       Operator = getDAGPatterns().get_intrinsic_void_sdnode();
1838     else if (Int.ModRef != CodeGenIntrinsic::NoMem)
1839       // Has side-effects, requires chain.
1840       Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
1841     else // Otherwise, no chain.
1842       Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
1843
1844     TreePatternNode *IIDNode = new TreePatternNode(new IntInit(IID), 1);
1845     Children.insert(Children.begin(), IIDNode);
1846   }
1847
1848   unsigned NumResults = GetNumNodeResults(Operator, CDP);
1849   TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
1850   Result->setName(OpName);
1851
1852   if (!Dag->getName().empty()) {
1853     assert(Result->getName().empty());
1854     Result->setName(Dag->getName());
1855   }
1856   return Result;
1857 }
1858
1859 /// SimplifyTree - See if we can simplify this tree to eliminate something that
1860 /// will never match in favor of something obvious that will.  This is here
1861 /// strictly as a convenience to target authors because it allows them to write
1862 /// more type generic things and have useless type casts fold away.
1863 ///
1864 /// This returns true if any change is made.
1865 static bool SimplifyTree(TreePatternNode *&N) {
1866   if (N->isLeaf())
1867     return false;
1868
1869   // If we have a bitconvert with a resolved type and if the source and
1870   // destination types are the same, then the bitconvert is useless, remove it.
1871   if (N->getOperator()->getName() == "bitconvert" &&
1872       N->getExtType(0).isConcrete() &&
1873       N->getExtType(0) == N->getChild(0)->getExtType(0) &&
1874       N->getName().empty()) {
1875     N = N->getChild(0);
1876     SimplifyTree(N);
1877     return true;
1878   }
1879
1880   // Walk all children.
1881   bool MadeChange = false;
1882   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
1883     TreePatternNode *Child = N->getChild(i);
1884     MadeChange |= SimplifyTree(Child);
1885     N->setChild(i, Child);
1886   }
1887   return MadeChange;
1888 }
1889
1890
1891
1892 /// InferAllTypes - Infer/propagate as many types throughout the expression
1893 /// patterns as possible.  Return true if all types are inferred, false
1894 /// otherwise.  Throw an exception if a type contradiction is found.
1895 bool TreePattern::
1896 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
1897   if (NamedNodes.empty())
1898     ComputeNamedNodes();
1899
1900   bool MadeChange = true;
1901   while (MadeChange) {
1902     MadeChange = false;
1903     for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1904       MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
1905       MadeChange |= SimplifyTree(Trees[i]);
1906     }
1907
1908     // If there are constraints on our named nodes, apply them.
1909     for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
1910          I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
1911       SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
1912
1913       // If we have input named node types, propagate their types to the named
1914       // values here.
1915       if (InNamedTypes) {
1916         // FIXME: Should be error?
1917         assert(InNamedTypes->count(I->getKey()) &&
1918                "Named node in output pattern but not input pattern?");
1919
1920         const SmallVectorImpl<TreePatternNode*> &InNodes =
1921           InNamedTypes->find(I->getKey())->second;
1922
1923         // The input types should be fully resolved by now.
1924         for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1925           // If this node is a register class, and it is the root of the pattern
1926           // then we're mapping something onto an input register.  We allow
1927           // changing the type of the input register in this case.  This allows
1928           // us to match things like:
1929           //  def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
1930           if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
1931             DefInit *DI = dynamic_cast<DefInit*>(Nodes[i]->getLeafValue());
1932             if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
1933               continue;
1934           }
1935
1936           assert(Nodes[i]->getNumTypes() == 1 &&
1937                  InNodes[0]->getNumTypes() == 1 &&
1938                  "FIXME: cannot name multiple result nodes yet");
1939           MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
1940                                                  *this);
1941         }
1942       }
1943
1944       // If there are multiple nodes with the same name, they must all have the
1945       // same type.
1946       if (I->second.size() > 1) {
1947         for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
1948           TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
1949           assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
1950                  "FIXME: cannot name multiple result nodes yet");
1951
1952           MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
1953           MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
1954         }
1955       }
1956     }
1957   }
1958
1959   bool HasUnresolvedTypes = false;
1960   for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1961     HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
1962   return !HasUnresolvedTypes;
1963 }
1964
1965 void TreePattern::print(raw_ostream &OS) const {
1966   OS << getRecord()->getName();
1967   if (!Args.empty()) {
1968     OS << "(" << Args[0];
1969     for (unsigned i = 1, e = Args.size(); i != e; ++i)
1970       OS << ", " << Args[i];
1971     OS << ")";
1972   }
1973   OS << ": ";
1974
1975   if (Trees.size() > 1)
1976     OS << "[\n";
1977   for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
1978     OS << "\t";
1979     Trees[i]->print(OS);
1980     OS << "\n";
1981   }
1982
1983   if (Trees.size() > 1)
1984     OS << "]\n";
1985 }
1986
1987 void TreePattern::dump() const { print(errs()); }
1988
1989 //===----------------------------------------------------------------------===//
1990 // CodeGenDAGPatterns implementation
1991 //
1992
1993 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
1994   Records(R), Target(R) {
1995
1996   Intrinsics = LoadIntrinsics(Records, false);
1997   TgtIntrinsics = LoadIntrinsics(Records, true);
1998   ParseNodeInfo();
1999   ParseNodeTransforms();
2000   ParseComplexPatterns();
2001   ParsePatternFragments();
2002   ParseDefaultOperands();
2003   ParseInstructions();
2004   ParsePatterns();
2005
2006   // Generate variants.  For example, commutative patterns can match
2007   // multiple ways.  Add them to PatternsToMatch as well.
2008   GenerateVariants();
2009
2010   // Infer instruction flags.  For example, we can detect loads,
2011   // stores, and side effects in many cases by examining an
2012   // instruction's pattern.
2013   InferInstructionFlags();
2014 }
2015
2016 CodeGenDAGPatterns::~CodeGenDAGPatterns() {
2017   for (pf_iterator I = PatternFragments.begin(),
2018        E = PatternFragments.end(); I != E; ++I)
2019     delete I->second;
2020 }
2021
2022
2023 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
2024   Record *N = Records.getDef(Name);
2025   if (!N || !N->isSubClassOf("SDNode")) {
2026     errs() << "Error getting SDNode '" << Name << "'!\n";
2027     exit(1);
2028   }
2029   return N;
2030 }
2031
2032 // Parse all of the SDNode definitions for the target, populating SDNodes.
2033 void CodeGenDAGPatterns::ParseNodeInfo() {
2034   std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2035   while (!Nodes.empty()) {
2036     SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2037     Nodes.pop_back();
2038   }
2039
2040   // Get the builtin intrinsic nodes.
2041   intrinsic_void_sdnode     = getSDNodeNamed("intrinsic_void");
2042   intrinsic_w_chain_sdnode  = getSDNodeNamed("intrinsic_w_chain");
2043   intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2044 }
2045
2046 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2047 /// map, and emit them to the file as functions.
2048 void CodeGenDAGPatterns::ParseNodeTransforms() {
2049   std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2050   while (!Xforms.empty()) {
2051     Record *XFormNode = Xforms.back();
2052     Record *SDNode = XFormNode->getValueAsDef("Opcode");
2053     std::string Code = XFormNode->getValueAsCode("XFormFunction");
2054     SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
2055
2056     Xforms.pop_back();
2057   }
2058 }
2059
2060 void CodeGenDAGPatterns::ParseComplexPatterns() {
2061   std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2062   while (!AMs.empty()) {
2063     ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2064     AMs.pop_back();
2065   }
2066 }
2067
2068
2069 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2070 /// file, building up the PatternFragments map.  After we've collected them all,
2071 /// inline fragments together as necessary, so that there are no references left
2072 /// inside a pattern fragment to a pattern fragment.
2073 ///
2074 void CodeGenDAGPatterns::ParsePatternFragments() {
2075   std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
2076
2077   // First step, parse all of the fragments.
2078   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2079     DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
2080     TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2081     PatternFragments[Fragments[i]] = P;
2082
2083     // Validate the argument list, converting it to set, to discard duplicates.
2084     std::vector<std::string> &Args = P->getArgList();
2085     std::set<std::string> OperandsSet(Args.begin(), Args.end());
2086
2087     if (OperandsSet.count(""))
2088       P->error("Cannot have unnamed 'node' values in pattern fragment!");
2089
2090     // Parse the operands list.
2091     DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
2092     DefInit *OpsOp = dynamic_cast<DefInit*>(OpsList->getOperator());
2093     // Special cases: ops == outs == ins. Different names are used to
2094     // improve readability.
2095     if (!OpsOp ||
2096         (OpsOp->getDef()->getName() != "ops" &&
2097          OpsOp->getDef()->getName() != "outs" &&
2098          OpsOp->getDef()->getName() != "ins"))
2099       P->error("Operands list should start with '(ops ... '!");
2100
2101     // Copy over the arguments.
2102     Args.clear();
2103     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
2104       if (!dynamic_cast<DefInit*>(OpsList->getArg(j)) ||
2105           static_cast<DefInit*>(OpsList->getArg(j))->
2106           getDef()->getName() != "node")
2107         P->error("Operands list should all be 'node' values.");
2108       if (OpsList->getArgName(j).empty())
2109         P->error("Operands list should have names for each operand!");
2110       if (!OperandsSet.count(OpsList->getArgName(j)))
2111         P->error("'" + OpsList->getArgName(j) +
2112                  "' does not occur in pattern or was multiply specified!");
2113       OperandsSet.erase(OpsList->getArgName(j));
2114       Args.push_back(OpsList->getArgName(j));
2115     }
2116
2117     if (!OperandsSet.empty())
2118       P->error("Operands list does not contain an entry for operand '" +
2119                *OperandsSet.begin() + "'!");
2120
2121     // If there is a code init for this fragment, keep track of the fact that
2122     // this fragment uses it.
2123     TreePredicateFn PredFn(P);
2124     if (!PredFn.isAlwaysTrue())
2125       P->getOnlyTree()->addPredicateFn(PredFn);
2126
2127     // If there is a node transformation corresponding to this, keep track of
2128     // it.
2129     Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2130     if (!getSDNodeTransform(Transform).second.empty())    // not noop xform?
2131       P->getOnlyTree()->setTransformFn(Transform);
2132   }
2133
2134   // Now that we've parsed all of the tree fragments, do a closure on them so
2135   // that there are not references to PatFrags left inside of them.
2136   for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2137     TreePattern *ThePat = PatternFragments[Fragments[i]];
2138     ThePat->InlinePatternFragments();
2139
2140     // Infer as many types as possible.  Don't worry about it if we don't infer
2141     // all of them, some may depend on the inputs of the pattern.
2142     try {
2143       ThePat->InferAllTypes();
2144     } catch (...) {
2145       // If this pattern fragment is not supported by this target (no types can
2146       // satisfy its constraints), just ignore it.  If the bogus pattern is
2147       // actually used by instructions, the type consistency error will be
2148       // reported there.
2149     }
2150
2151     // If debugging, print out the pattern fragment result.
2152     DEBUG(ThePat->dump());
2153   }
2154 }
2155
2156 void CodeGenDAGPatterns::ParseDefaultOperands() {
2157   std::vector<Record*> DefaultOps[2];
2158   DefaultOps[0] = Records.getAllDerivedDefinitions("PredicateOperand");
2159   DefaultOps[1] = Records.getAllDerivedDefinitions("OptionalDefOperand");
2160
2161   // Find some SDNode.
2162   assert(!SDNodes.empty() && "No SDNodes parsed?");
2163   Init *SomeSDNode = new DefInit(SDNodes.begin()->first);
2164
2165   for (unsigned iter = 0; iter != 2; ++iter) {
2166     for (unsigned i = 0, e = DefaultOps[iter].size(); i != e; ++i) {
2167       DagInit *DefaultInfo = DefaultOps[iter][i]->getValueAsDag("DefaultOps");
2168
2169       // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2170       // SomeSDnode so that we can parse this.
2171       std::vector<std::pair<Init*, std::string> > Ops;
2172       for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2173         Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2174                                      DefaultInfo->getArgName(op)));
2175       DagInit *DI = new DagInit(SomeSDNode, "", Ops);
2176
2177       // Create a TreePattern to parse this.
2178       TreePattern P(DefaultOps[iter][i], DI, false, *this);
2179       assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
2180
2181       // Copy the operands over into a DAGDefaultOperand.
2182       DAGDefaultOperand DefaultOpInfo;
2183
2184       TreePatternNode *T = P.getTree(0);
2185       for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2186         TreePatternNode *TPN = T->getChild(op);
2187         while (TPN->ApplyTypeConstraints(P, false))
2188           /* Resolve all types */;
2189
2190         if (TPN->ContainsUnresolvedType()) {
2191           if (iter == 0)
2192             throw "Value #" + utostr(i) + " of PredicateOperand '" +
2193               DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
2194           else
2195             throw "Value #" + utostr(i) + " of OptionalDefOperand '" +
2196               DefaultOps[iter][i]->getName() +"' doesn't have a concrete type!";
2197         }
2198         DefaultOpInfo.DefaultOps.push_back(TPN);
2199       }
2200
2201       // Insert it into the DefaultOperands map so we can find it later.
2202       DefaultOperands[DefaultOps[iter][i]] = DefaultOpInfo;
2203     }
2204   }
2205 }
2206
2207 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2208 /// instruction input.  Return true if this is a real use.
2209 static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
2210                       std::map<std::string, TreePatternNode*> &InstInputs) {
2211   // No name -> not interesting.
2212   if (Pat->getName().empty()) {
2213     if (Pat->isLeaf()) {
2214       DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2215       if (DI && DI->getDef()->isSubClassOf("RegisterClass"))
2216         I->error("Input " + DI->getDef()->getName() + " must be named!");
2217     }
2218     return false;
2219   }
2220
2221   Record *Rec;
2222   if (Pat->isLeaf()) {
2223     DefInit *DI = dynamic_cast<DefInit*>(Pat->getLeafValue());
2224     if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2225     Rec = DI->getDef();
2226   } else {
2227     Rec = Pat->getOperator();
2228   }
2229
2230   // SRCVALUE nodes are ignored.
2231   if (Rec->getName() == "srcvalue")
2232     return false;
2233
2234   TreePatternNode *&Slot = InstInputs[Pat->getName()];
2235   if (!Slot) {
2236     Slot = Pat;
2237     return true;
2238   }
2239   Record *SlotRec;
2240   if (Slot->isLeaf()) {
2241     SlotRec = dynamic_cast<DefInit*>(Slot->getLeafValue())->getDef();
2242   } else {
2243     assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2244     SlotRec = Slot->getOperator();
2245   }
2246
2247   // Ensure that the inputs agree if we've already seen this input.
2248   if (Rec != SlotRec)
2249     I->error("All $" + Pat->getName() + " inputs must agree with each other");
2250   if (Slot->getExtTypes() != Pat->getExtTypes())
2251     I->error("All $" + Pat->getName() + " inputs must agree with each other");
2252   return true;
2253 }
2254
2255 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2256 /// part of "I", the instruction), computing the set of inputs and outputs of
2257 /// the pattern.  Report errors if we see anything naughty.
2258 void CodeGenDAGPatterns::
2259 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2260                             std::map<std::string, TreePatternNode*> &InstInputs,
2261                             std::map<std::string, TreePatternNode*>&InstResults,
2262                             std::vector<Record*> &InstImpResults) {
2263   if (Pat->isLeaf()) {
2264     bool isUse = HandleUse(I, Pat, InstInputs);
2265     if (!isUse && Pat->getTransformFn())
2266       I->error("Cannot specify a transform function for a non-input value!");
2267     return;
2268   }
2269
2270   if (Pat->getOperator()->getName() == "implicit") {
2271     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2272       TreePatternNode *Dest = Pat->getChild(i);
2273       if (!Dest->isLeaf())
2274         I->error("implicitly defined value should be a register!");
2275
2276       DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2277       if (!Val || !Val->getDef()->isSubClassOf("Register"))
2278         I->error("implicitly defined value should be a register!");
2279       InstImpResults.push_back(Val->getDef());
2280     }
2281     return;
2282   }
2283
2284   if (Pat->getOperator()->getName() != "set") {
2285     // If this is not a set, verify that the children nodes are not void typed,
2286     // and recurse.
2287     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2288       if (Pat->getChild(i)->getNumTypes() == 0)
2289         I->error("Cannot have void nodes inside of patterns!");
2290       FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
2291                                   InstImpResults);
2292     }
2293
2294     // If this is a non-leaf node with no children, treat it basically as if
2295     // it were a leaf.  This handles nodes like (imm).
2296     bool isUse = HandleUse(I, Pat, InstInputs);
2297
2298     if (!isUse && Pat->getTransformFn())
2299       I->error("Cannot specify a transform function for a non-input value!");
2300     return;
2301   }
2302
2303   // Otherwise, this is a set, validate and collect instruction results.
2304   if (Pat->getNumChildren() == 0)
2305     I->error("set requires operands!");
2306
2307   if (Pat->getTransformFn())
2308     I->error("Cannot specify a transform function on a set node!");
2309
2310   // Check the set destinations.
2311   unsigned NumDests = Pat->getNumChildren()-1;
2312   for (unsigned i = 0; i != NumDests; ++i) {
2313     TreePatternNode *Dest = Pat->getChild(i);
2314     if (!Dest->isLeaf())
2315       I->error("set destination should be a register!");
2316
2317     DefInit *Val = dynamic_cast<DefInit*>(Dest->getLeafValue());
2318     if (!Val)
2319       I->error("set destination should be a register!");
2320
2321     if (Val->getDef()->isSubClassOf("RegisterClass") ||
2322         Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
2323       if (Dest->getName().empty())
2324         I->error("set destination must have a name!");
2325       if (InstResults.count(Dest->getName()))
2326         I->error("cannot set '" + Dest->getName() +"' multiple times");
2327       InstResults[Dest->getName()] = Dest;
2328     } else if (Val->getDef()->isSubClassOf("Register")) {
2329       InstImpResults.push_back(Val->getDef());
2330     } else {
2331       I->error("set destination should be a register!");
2332     }
2333   }
2334
2335   // Verify and collect info from the computation.
2336   FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
2337                               InstInputs, InstResults, InstImpResults);
2338 }
2339
2340 //===----------------------------------------------------------------------===//
2341 // Instruction Analysis
2342 //===----------------------------------------------------------------------===//
2343
2344 class InstAnalyzer {
2345   const CodeGenDAGPatterns &CDP;
2346   bool &mayStore;
2347   bool &mayLoad;
2348   bool &IsBitcast;
2349   bool &HasSideEffects;
2350   bool &IsVariadic;
2351 public:
2352   InstAnalyzer(const CodeGenDAGPatterns &cdp,
2353                bool &maystore, bool &mayload, bool &isbc, bool &hse, bool &isv)
2354     : CDP(cdp), mayStore(maystore), mayLoad(mayload), IsBitcast(isbc),
2355       HasSideEffects(hse), IsVariadic(isv) {
2356   }
2357
2358   /// Analyze - Analyze the specified instruction, returning true if the
2359   /// instruction had a pattern.
2360   bool Analyze(Record *InstRecord) {
2361     const TreePattern *Pattern = CDP.getInstruction(InstRecord).getPattern();
2362     if (Pattern == 0) {
2363       HasSideEffects = 1;
2364       return false;  // No pattern.
2365     }
2366
2367     // FIXME: Assume only the first tree is the pattern. The others are clobber
2368     // nodes.
2369     AnalyzeNode(Pattern->getTree(0));
2370     return true;
2371   }
2372
2373 private:
2374   bool IsNodeBitcast(const TreePatternNode *N) const {
2375     if (HasSideEffects || mayLoad || mayStore || IsVariadic)
2376       return false;
2377
2378     if (N->getNumChildren() != 2)
2379       return false;
2380
2381     const TreePatternNode *N0 = N->getChild(0);
2382     if (!N0->isLeaf() || !dynamic_cast<DefInit*>(N0->getLeafValue()))
2383       return false;
2384
2385     const TreePatternNode *N1 = N->getChild(1);
2386     if (N1->isLeaf())
2387       return false;
2388     if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2389       return false;
2390
2391     const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2392     if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2393       return false;
2394     return OpInfo.getEnumName() == "ISD::BITCAST";
2395   }
2396
2397   void AnalyzeNode(const TreePatternNode *N) {
2398     if (N->isLeaf()) {
2399       if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
2400         Record *LeafRec = DI->getDef();
2401         // Handle ComplexPattern leaves.
2402         if (LeafRec->isSubClassOf("ComplexPattern")) {
2403           const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2404           if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2405           if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
2406           if (CP.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2407         }
2408       }
2409       return;
2410     }
2411
2412     // Analyze children.
2413     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2414       AnalyzeNode(N->getChild(i));
2415
2416     // Ignore set nodes, which are not SDNodes.
2417     if (N->getOperator()->getName() == "set") {
2418       IsBitcast = IsNodeBitcast(N);
2419       return;
2420     }
2421
2422     // Get information about the SDNode for the operator.
2423     const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2424
2425     // Notice properties of the node.
2426     if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2427     if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
2428     if (OpInfo.hasProperty(SDNPSideEffect)) HasSideEffects = true;
2429     if (OpInfo.hasProperty(SDNPVariadic)) IsVariadic = true;
2430
2431     if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2432       // If this is an intrinsic, analyze it.
2433       if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2434         mayLoad = true;// These may load memory.
2435
2436       if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
2437         mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2438
2439       if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
2440         // WriteMem intrinsics can have other strange effects.
2441         HasSideEffects = true;
2442     }
2443   }
2444
2445 };
2446
2447 static void InferFromPattern(const CodeGenInstruction &Inst,
2448                              bool &MayStore, bool &MayLoad,
2449                              bool &IsBitcast,
2450                              bool &HasSideEffects, bool &IsVariadic,
2451                              const CodeGenDAGPatterns &CDP) {
2452   MayStore = MayLoad = IsBitcast = HasSideEffects = IsVariadic = false;
2453
2454   bool HadPattern =
2455     InstAnalyzer(CDP, MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic)
2456     .Analyze(Inst.TheDef);
2457
2458   // InstAnalyzer only correctly analyzes mayStore/mayLoad so far.
2459   if (Inst.mayStore) {  // If the .td file explicitly sets mayStore, use it.
2460     // If we decided that this is a store from the pattern, then the .td file
2461     // entry is redundant.
2462     if (MayStore)
2463       fprintf(stderr,
2464               "Warning: mayStore flag explicitly set on instruction '%s'"
2465               " but flag already inferred from pattern.\n",
2466               Inst.TheDef->getName().c_str());
2467     MayStore = true;
2468   }
2469
2470   if (Inst.mayLoad) {  // If the .td file explicitly sets mayLoad, use it.
2471     // If we decided that this is a load from the pattern, then the .td file
2472     // entry is redundant.
2473     if (MayLoad)
2474       fprintf(stderr,
2475               "Warning: mayLoad flag explicitly set on instruction '%s'"
2476               " but flag already inferred from pattern.\n",
2477               Inst.TheDef->getName().c_str());
2478     MayLoad = true;
2479   }
2480
2481   if (Inst.neverHasSideEffects) {
2482     if (HadPattern)
2483       fprintf(stderr, "Warning: neverHasSideEffects set on instruction '%s' "
2484               "which already has a pattern\n", Inst.TheDef->getName().c_str());
2485     HasSideEffects = false;
2486   }
2487
2488   if (Inst.hasSideEffects) {
2489     if (HasSideEffects)
2490       fprintf(stderr, "Warning: hasSideEffects set on instruction '%s' "
2491               "which already inferred this.\n", Inst.TheDef->getName().c_str());
2492     HasSideEffects = true;
2493   }
2494
2495   if (Inst.Operands.isVariadic)
2496     IsVariadic = true;  // Can warn if we want.
2497 }
2498
2499 /// ParseInstructions - Parse all of the instructions, inlining and resolving
2500 /// any fragments involved.  This populates the Instructions list with fully
2501 /// resolved instructions.
2502 void CodeGenDAGPatterns::ParseInstructions() {
2503   std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2504
2505   for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2506     ListInit *LI = 0;
2507
2508     if (dynamic_cast<ListInit*>(Instrs[i]->getValueInit("Pattern")))
2509       LI = Instrs[i]->getValueAsListInit("Pattern");
2510
2511     // If there is no pattern, only collect minimal information about the
2512     // instruction for its operand list.  We have to assume that there is one
2513     // result, as we have no detailed info.
2514     if (!LI || LI->getSize() == 0) {
2515       std::vector<Record*> Results;
2516       std::vector<Record*> Operands;
2517
2518       CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2519
2520       if (InstInfo.Operands.size() != 0) {
2521         if (InstInfo.Operands.NumDefs == 0) {
2522           // These produce no results
2523           for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2524             Operands.push_back(InstInfo.Operands[j].Rec);
2525         } else {
2526           // Assume the first operand is the result.
2527           Results.push_back(InstInfo.Operands[0].Rec);
2528
2529           // The rest are inputs.
2530           for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2531             Operands.push_back(InstInfo.Operands[j].Rec);
2532         }
2533       }
2534
2535       // Create and insert the instruction.
2536       std::vector<Record*> ImpResults;
2537       Instructions.insert(std::make_pair(Instrs[i],
2538                           DAGInstruction(0, Results, Operands, ImpResults)));
2539       continue;  // no pattern.
2540     }
2541
2542     // Parse the instruction.
2543     TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
2544     // Inline pattern fragments into it.
2545     I->InlinePatternFragments();
2546
2547     // Infer as many types as possible.  If we cannot infer all of them, we can
2548     // never do anything with this instruction pattern: report it to the user.
2549     if (!I->InferAllTypes())
2550       I->error("Could not infer all types in pattern!");
2551
2552     // InstInputs - Keep track of all of the inputs of the instruction, along
2553     // with the record they are declared as.
2554     std::map<std::string, TreePatternNode*> InstInputs;
2555
2556     // InstResults - Keep track of all the virtual registers that are 'set'
2557     // in the instruction, including what reg class they are.
2558     std::map<std::string, TreePatternNode*> InstResults;
2559
2560     std::vector<Record*> InstImpResults;
2561
2562     // Verify that the top-level forms in the instruction are of void type, and
2563     // fill in the InstResults map.
2564     for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2565       TreePatternNode *Pat = I->getTree(j);
2566       if (Pat->getNumTypes() != 0)
2567         I->error("Top-level forms in instruction pattern should have"
2568                  " void types");
2569
2570       // Find inputs and outputs, and verify the structure of the uses/defs.
2571       FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2572                                   InstImpResults);
2573     }
2574
2575     // Now that we have inputs and outputs of the pattern, inspect the operands
2576     // list for the instruction.  This determines the order that operands are
2577     // added to the machine instruction the node corresponds to.
2578     unsigned NumResults = InstResults.size();
2579
2580     // Parse the operands list from the (ops) list, validating it.
2581     assert(I->getArgList().empty() && "Args list should still be empty here!");
2582     CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2583
2584     // Check that all of the results occur first in the list.
2585     std::vector<Record*> Results;
2586     TreePatternNode *Res0Node = 0;
2587     for (unsigned i = 0; i != NumResults; ++i) {
2588       if (i == CGI.Operands.size())
2589         I->error("'" + InstResults.begin()->first +
2590                  "' set but does not appear in operand list!");
2591       const std::string &OpName = CGI.Operands[i].Name;
2592
2593       // Check that it exists in InstResults.
2594       TreePatternNode *RNode = InstResults[OpName];
2595       if (RNode == 0)
2596         I->error("Operand $" + OpName + " does not exist in operand list!");
2597
2598       if (i == 0)
2599         Res0Node = RNode;
2600       Record *R = dynamic_cast<DefInit*>(RNode->getLeafValue())->getDef();
2601       if (R == 0)
2602         I->error("Operand $" + OpName + " should be a set destination: all "
2603                  "outputs must occur before inputs in operand list!");
2604
2605       if (CGI.Operands[i].Rec != R)
2606         I->error("Operand $" + OpName + " class mismatch!");
2607
2608       // Remember the return type.
2609       Results.push_back(CGI.Operands[i].Rec);
2610
2611       // Okay, this one checks out.
2612       InstResults.erase(OpName);
2613     }
2614
2615     // Loop over the inputs next.  Make a copy of InstInputs so we can destroy
2616     // the copy while we're checking the inputs.
2617     std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2618
2619     std::vector<TreePatternNode*> ResultNodeOperands;
2620     std::vector<Record*> Operands;
2621     for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2622       CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2623       const std::string &OpName = Op.Name;
2624       if (OpName.empty())
2625         I->error("Operand #" + utostr(i) + " in operands list has no name!");
2626
2627       if (!InstInputsCheck.count(OpName)) {
2628         // If this is an predicate operand or optional def operand with an
2629         // DefaultOps set filled in, we can ignore this.  When we codegen it,
2630         // we will do so as always executed.
2631         if (Op.Rec->isSubClassOf("PredicateOperand") ||
2632             Op.Rec->isSubClassOf("OptionalDefOperand")) {
2633           // Does it have a non-empty DefaultOps field?  If so, ignore this
2634           // operand.
2635           if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2636             continue;
2637         }
2638         I->error("Operand $" + OpName +
2639                  " does not appear in the instruction pattern");
2640       }
2641       TreePatternNode *InVal = InstInputsCheck[OpName];
2642       InstInputsCheck.erase(OpName);   // It occurred, remove from map.
2643
2644       if (InVal->isLeaf() &&
2645           dynamic_cast<DefInit*>(InVal->getLeafValue())) {
2646         Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2647         if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
2648           I->error("Operand $" + OpName + "'s register class disagrees"
2649                    " between the operand and pattern");
2650       }
2651       Operands.push_back(Op.Rec);
2652
2653       // Construct the result for the dest-pattern operand list.
2654       TreePatternNode *OpNode = InVal->clone();
2655
2656       // No predicate is useful on the result.
2657       OpNode->clearPredicateFns();
2658
2659       // Promote the xform function to be an explicit node if set.
2660       if (Record *Xform = OpNode->getTransformFn()) {
2661         OpNode->setTransformFn(0);
2662         std::vector<TreePatternNode*> Children;
2663         Children.push_back(OpNode);
2664         OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2665       }
2666
2667       ResultNodeOperands.push_back(OpNode);
2668     }
2669
2670     if (!InstInputsCheck.empty())
2671       I->error("Input operand $" + InstInputsCheck.begin()->first +
2672                " occurs in pattern but not in operands list!");
2673
2674     TreePatternNode *ResultPattern =
2675       new TreePatternNode(I->getRecord(), ResultNodeOperands,
2676                           GetNumNodeResults(I->getRecord(), *this));
2677     // Copy fully inferred output node type to instruction result pattern.
2678     for (unsigned i = 0; i != NumResults; ++i)
2679       ResultPattern->setType(i, Res0Node->getExtType(i));
2680
2681     // Create and insert the instruction.
2682     // FIXME: InstImpResults should not be part of DAGInstruction.
2683     DAGInstruction TheInst(I, Results, Operands, InstImpResults);
2684     Instructions.insert(std::make_pair(I->getRecord(), TheInst));
2685
2686     // Use a temporary tree pattern to infer all types and make sure that the
2687     // constructed result is correct.  This depends on the instruction already
2688     // being inserted into the Instructions map.
2689     TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
2690     Temp.InferAllTypes(&I->getNamedNodesMap());
2691
2692     DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
2693     TheInsertedInst.setResultPattern(Temp.getOnlyTree());
2694
2695     DEBUG(I->dump());
2696   }
2697
2698   // If we can, convert the instructions to be patterns that are matched!
2699   for (std::map<Record*, DAGInstruction, RecordPtrCmp>::iterator II =
2700         Instructions.begin(),
2701        E = Instructions.end(); II != E; ++II) {
2702     DAGInstruction &TheInst = II->second;
2703     const TreePattern *I = TheInst.getPattern();
2704     if (I == 0) continue;  // No pattern.
2705
2706     // FIXME: Assume only the first tree is the pattern. The others are clobber
2707     // nodes.
2708     TreePatternNode *Pattern = I->getTree(0);
2709     TreePatternNode *SrcPattern;
2710     if (Pattern->getOperator()->getName() == "set") {
2711       SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2712     } else{
2713       // Not a set (store or something?)
2714       SrcPattern = Pattern;
2715     }
2716
2717     Record *Instr = II->first;
2718     AddPatternToMatch(I,
2719                       PatternToMatch(Instr,
2720                                      Instr->getValueAsListInit("Predicates"),
2721                                      SrcPattern,
2722                                      TheInst.getResultPattern(),
2723                                      TheInst.getImpResults(),
2724                                      Instr->getValueAsInt("AddedComplexity"),
2725                                      Instr->getID()));
2726   }
2727 }
2728
2729
2730 typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2731
2732 static void FindNames(const TreePatternNode *P,
2733                       std::map<std::string, NameRecord> &Names,
2734                       const TreePattern *PatternTop) {
2735   if (!P->getName().empty()) {
2736     NameRecord &Rec = Names[P->getName()];
2737     // If this is the first instance of the name, remember the node.
2738     if (Rec.second++ == 0)
2739       Rec.first = P;
2740     else if (Rec.first->getExtTypes() != P->getExtTypes())
2741       PatternTop->error("repetition of value: $" + P->getName() +
2742                         " where different uses have different types!");
2743   }
2744
2745   if (!P->isLeaf()) {
2746     for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
2747       FindNames(P->getChild(i), Names, PatternTop);
2748   }
2749 }
2750
2751 void CodeGenDAGPatterns::AddPatternToMatch(const TreePattern *Pattern,
2752                                            const PatternToMatch &PTM) {
2753   // Do some sanity checking on the pattern we're about to match.
2754   std::string Reason;
2755   if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this))
2756     Pattern->error("Pattern can never match: " + Reason);
2757
2758   // If the source pattern's root is a complex pattern, that complex pattern
2759   // must specify the nodes it can potentially match.
2760   if (const ComplexPattern *CP =
2761         PTM.getSrcPattern()->getComplexPatternInfo(*this))
2762     if (CP->getRootNodes().empty())
2763       Pattern->error("ComplexPattern at root must specify list of opcodes it"
2764                      " could match");
2765
2766
2767   // Find all of the named values in the input and output, ensure they have the
2768   // same type.
2769   std::map<std::string, NameRecord> SrcNames, DstNames;
2770   FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2771   FindNames(PTM.getDstPattern(), DstNames, Pattern);
2772
2773   // Scan all of the named values in the destination pattern, rejecting them if
2774   // they don't exist in the input pattern.
2775   for (std::map<std::string, NameRecord>::iterator
2776        I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
2777     if (SrcNames[I->first].first == 0)
2778       Pattern->error("Pattern has input without matching name in output: $" +
2779                      I->first);
2780   }
2781
2782   // Scan all of the named values in the source pattern, rejecting them if the
2783   // name isn't used in the dest, and isn't used to tie two values together.
2784   for (std::map<std::string, NameRecord>::iterator
2785        I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2786     if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2787       Pattern->error("Pattern has dead named input: $" + I->first);
2788
2789   PatternsToMatch.push_back(PTM);
2790 }
2791
2792
2793
2794 void CodeGenDAGPatterns::InferInstructionFlags() {
2795   const std::vector<const CodeGenInstruction*> &Instructions =
2796     Target.getInstructionsByEnumValue();
2797   for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2798     CodeGenInstruction &InstInfo =
2799       const_cast<CodeGenInstruction &>(*Instructions[i]);
2800     // Determine properties of the instruction from its pattern.
2801     bool MayStore, MayLoad, IsBitcast, HasSideEffects, IsVariadic;
2802     InferFromPattern(InstInfo, MayStore, MayLoad, IsBitcast,
2803                      HasSideEffects, IsVariadic, *this);
2804     InstInfo.mayStore = MayStore;
2805     InstInfo.mayLoad = MayLoad;
2806     InstInfo.isBitcast = IsBitcast;
2807     InstInfo.hasSideEffects = HasSideEffects;
2808     InstInfo.Operands.isVariadic = IsVariadic;
2809   }
2810 }
2811
2812 /// Given a pattern result with an unresolved type, see if we can find one
2813 /// instruction with an unresolved result type.  Force this result type to an
2814 /// arbitrary element if it's possible types to converge results.
2815 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
2816   if (N->isLeaf())
2817     return false;
2818
2819   // Analyze children.
2820   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2821     if (ForceArbitraryInstResultType(N->getChild(i), TP))
2822       return true;
2823
2824   if (!N->getOperator()->isSubClassOf("Instruction"))
2825     return false;
2826
2827   // If this type is already concrete or completely unknown we can't do
2828   // anything.
2829   for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
2830     if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
2831       continue;
2832
2833     // Otherwise, force its type to the first possibility (an arbitrary choice).
2834     if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
2835       return true;
2836   }
2837
2838   return false;
2839 }
2840
2841 void CodeGenDAGPatterns::ParsePatterns() {
2842   std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
2843
2844   for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
2845     Record *CurPattern = Patterns[i];
2846     DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
2847     TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
2848
2849     // Inline pattern fragments into it.
2850     Pattern->InlinePatternFragments();
2851
2852     ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
2853     if (LI->getSize() == 0) continue;  // no pattern.
2854
2855     // Parse the instruction.
2856     TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
2857
2858     // Inline pattern fragments into it.
2859     Result->InlinePatternFragments();
2860
2861     if (Result->getNumTrees() != 1)
2862       Result->error("Cannot handle instructions producing instructions "
2863                     "with temporaries yet!");
2864
2865     bool IterateInference;
2866     bool InferredAllPatternTypes, InferredAllResultTypes;
2867     do {
2868       // Infer as many types as possible.  If we cannot infer all of them, we
2869       // can never do anything with this pattern: report it to the user.
2870       InferredAllPatternTypes =
2871         Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
2872
2873       // Infer as many types as possible.  If we cannot infer all of them, we
2874       // can never do anything with this pattern: report it to the user.
2875       InferredAllResultTypes =
2876         Result->InferAllTypes(&Pattern->getNamedNodesMap());
2877
2878       IterateInference = false;
2879
2880       // Apply the type of the result to the source pattern.  This helps us
2881       // resolve cases where the input type is known to be a pointer type (which
2882       // is considered resolved), but the result knows it needs to be 32- or
2883       // 64-bits.  Infer the other way for good measure.
2884       for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
2885                                         Pattern->getTree(0)->getNumTypes());
2886            i != e; ++i) {
2887         IterateInference = Pattern->getTree(0)->
2888           UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
2889         IterateInference |= Result->getTree(0)->
2890           UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
2891       }
2892
2893       // If our iteration has converged and the input pattern's types are fully
2894       // resolved but the result pattern is not fully resolved, we may have a
2895       // situation where we have two instructions in the result pattern and
2896       // the instructions require a common register class, but don't care about
2897       // what actual MVT is used.  This is actually a bug in our modelling:
2898       // output patterns should have register classes, not MVTs.
2899       //
2900       // In any case, to handle this, we just go through and disambiguate some
2901       // arbitrary types to the result pattern's nodes.
2902       if (!IterateInference && InferredAllPatternTypes &&
2903           !InferredAllResultTypes)
2904         IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
2905                                                         *Result);
2906     } while (IterateInference);
2907
2908     // Verify that we inferred enough types that we can do something with the
2909     // pattern and result.  If these fire the user has to add type casts.
2910     if (!InferredAllPatternTypes)
2911       Pattern->error("Could not infer all types in pattern!");
2912     if (!InferredAllResultTypes) {
2913       Pattern->dump();
2914       Result->error("Could not infer all types in pattern result!");
2915     }
2916
2917     // Validate that the input pattern is correct.
2918     std::map<std::string, TreePatternNode*> InstInputs;
2919     std::map<std::string, TreePatternNode*> InstResults;
2920     std::vector<Record*> InstImpResults;
2921     for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
2922       FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
2923                                   InstInputs, InstResults,
2924                                   InstImpResults);
2925
2926     // Promote the xform function to be an explicit node if set.
2927     TreePatternNode *DstPattern = Result->getOnlyTree();
2928     std::vector<TreePatternNode*> ResultNodeOperands;
2929     for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
2930       TreePatternNode *OpNode = DstPattern->getChild(ii);
2931       if (Record *Xform = OpNode->getTransformFn()) {
2932         OpNode->setTransformFn(0);
2933         std::vector<TreePatternNode*> Children;
2934         Children.push_back(OpNode);
2935         OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
2936       }
2937       ResultNodeOperands.push_back(OpNode);
2938     }
2939     DstPattern = Result->getOnlyTree();
2940     if (!DstPattern->isLeaf())
2941       DstPattern = new TreePatternNode(DstPattern->getOperator(),
2942                                        ResultNodeOperands,
2943                                        DstPattern->getNumTypes());
2944
2945     for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
2946       DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
2947
2948     TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
2949     Temp.InferAllTypes();
2950
2951
2952     AddPatternToMatch(Pattern,
2953                     PatternToMatch(CurPattern,
2954                                    CurPattern->getValueAsListInit("Predicates"),
2955                                    Pattern->getTree(0),
2956                                    Temp.getOnlyTree(), InstImpResults,
2957                                    CurPattern->getValueAsInt("AddedComplexity"),
2958                                    CurPattern->getID()));
2959   }
2960 }
2961
2962 /// CombineChildVariants - Given a bunch of permutations of each child of the
2963 /// 'operator' node, put them together in all possible ways.
2964 static void CombineChildVariants(TreePatternNode *Orig,
2965                const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
2966                                  std::vector<TreePatternNode*> &OutVariants,
2967                                  CodeGenDAGPatterns &CDP,
2968                                  const MultipleUseVarSet &DepVars) {
2969   // Make sure that each operand has at least one variant to choose from.
2970   for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2971     if (ChildVariants[i].empty())
2972       return;
2973
2974   // The end result is an all-pairs construction of the resultant pattern.
2975   std::vector<unsigned> Idxs;
2976   Idxs.resize(ChildVariants.size());
2977   bool NotDone;
2978   do {
2979 #ifndef NDEBUG
2980     DEBUG(if (!Idxs.empty()) {
2981             errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
2982               for (unsigned i = 0; i < Idxs.size(); ++i) {
2983                 errs() << Idxs[i] << " ";
2984             }
2985             errs() << "]\n";
2986           });
2987 #endif
2988     // Create the variant and add it to the output list.
2989     std::vector<TreePatternNode*> NewChildren;
2990     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
2991       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
2992     TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
2993                                              Orig->getNumTypes());
2994
2995     // Copy over properties.
2996     R->setName(Orig->getName());
2997     R->setPredicateFns(Orig->getPredicateFns());
2998     R->setTransformFn(Orig->getTransformFn());
2999     for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3000       R->setType(i, Orig->getExtType(i));
3001
3002     // If this pattern cannot match, do not include it as a variant.
3003     std::string ErrString;
3004     if (!R->canPatternMatch(ErrString, CDP)) {
3005       delete R;
3006     } else {
3007       bool AlreadyExists = false;
3008
3009       // Scan to see if this pattern has already been emitted.  We can get
3010       // duplication due to things like commuting:
3011       //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3012       // which are the same pattern.  Ignore the dups.
3013       for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
3014         if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
3015           AlreadyExists = true;
3016           break;
3017         }
3018
3019       if (AlreadyExists)
3020         delete R;
3021       else
3022         OutVariants.push_back(R);
3023     }
3024
3025     // Increment indices to the next permutation by incrementing the
3026     // indicies from last index backward, e.g., generate the sequence
3027     // [0, 0], [0, 1], [1, 0], [1, 1].
3028     int IdxsIdx;
3029     for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3030       if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3031         Idxs[IdxsIdx] = 0;
3032       else
3033         break;
3034     }
3035     NotDone = (IdxsIdx >= 0);
3036   } while (NotDone);
3037 }
3038
3039 /// CombineChildVariants - A helper function for binary operators.
3040 ///
3041 static void CombineChildVariants(TreePatternNode *Orig,
3042                                  const std::vector<TreePatternNode*> &LHS,
3043                                  const std::vector<TreePatternNode*> &RHS,
3044                                  std::vector<TreePatternNode*> &OutVariants,
3045                                  CodeGenDAGPatterns &CDP,
3046                                  const MultipleUseVarSet &DepVars) {
3047   std::vector<std::vector<TreePatternNode*> > ChildVariants;
3048   ChildVariants.push_back(LHS);
3049   ChildVariants.push_back(RHS);
3050   CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
3051 }
3052
3053
3054 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3055                                      std::vector<TreePatternNode *> &Children) {
3056   assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3057   Record *Operator = N->getOperator();
3058
3059   // Only permit raw nodes.
3060   if (!N->getName().empty() || !N->getPredicateFns().empty() ||
3061       N->getTransformFn()) {
3062     Children.push_back(N);
3063     return;
3064   }
3065
3066   if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3067     Children.push_back(N->getChild(0));
3068   else
3069     GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3070
3071   if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3072     Children.push_back(N->getChild(1));
3073   else
3074     GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3075 }
3076
3077 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3078 /// the (potentially recursive) pattern by using algebraic laws.
3079 ///
3080 static void GenerateVariantsOf(TreePatternNode *N,
3081                                std::vector<TreePatternNode*> &OutVariants,
3082                                CodeGenDAGPatterns &CDP,
3083                                const MultipleUseVarSet &DepVars) {
3084   // We cannot permute leaves.
3085   if (N->isLeaf()) {
3086     OutVariants.push_back(N);
3087     return;
3088   }
3089
3090   // Look up interesting info about the node.
3091   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3092
3093   // If this node is associative, re-associate.
3094   if (NodeInfo.hasProperty(SDNPAssociative)) {
3095     // Re-associate by pulling together all of the linked operators
3096     std::vector<TreePatternNode*> MaximalChildren;
3097     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3098
3099     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
3100     // permutations.
3101     if (MaximalChildren.size() == 3) {
3102       // Find the variants of all of our maximal children.
3103       std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
3104       GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3105       GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3106       GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
3107
3108       // There are only two ways we can permute the tree:
3109       //   (A op B) op C    and    A op (B op C)
3110       // Within these forms, we can also permute A/B/C.
3111
3112       // Generate legal pair permutations of A/B/C.
3113       std::vector<TreePatternNode*> ABVariants;
3114       std::vector<TreePatternNode*> BAVariants;
3115       std::vector<TreePatternNode*> ACVariants;
3116       std::vector<TreePatternNode*> CAVariants;
3117       std::vector<TreePatternNode*> BCVariants;
3118       std::vector<TreePatternNode*> CBVariants;
3119       CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3120       CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3121       CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3122       CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3123       CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3124       CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
3125
3126       // Combine those into the result: (x op x) op x
3127       CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3128       CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3129       CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3130       CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3131       CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3132       CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
3133
3134       // Combine those into the result: x op (x op x)
3135       CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3136       CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3137       CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3138       CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3139       CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3140       CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
3141       return;
3142     }
3143   }
3144
3145   // Compute permutations of all children.
3146   std::vector<std::vector<TreePatternNode*> > ChildVariants;
3147   ChildVariants.resize(N->getNumChildren());
3148   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3149     GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
3150
3151   // Build all permutations based on how the children were formed.
3152   CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
3153
3154   // If this node is commutative, consider the commuted order.
3155   bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3156   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3157     assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3158            "Commutative but doesn't have 2 children!");
3159     // Don't count children which are actually register references.
3160     unsigned NC = 0;
3161     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3162       TreePatternNode *Child = N->getChild(i);
3163       if (Child->isLeaf())
3164         if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
3165           Record *RR = DI->getDef();
3166           if (RR->isSubClassOf("Register"))
3167             continue;
3168         }
3169       NC++;
3170     }
3171     // Consider the commuted order.
3172     if (isCommIntrinsic) {
3173       // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3174       // operands are the commutative operands, and there might be more operands
3175       // after those.
3176       assert(NC >= 3 &&
3177              "Commutative intrinsic should have at least 3 childrean!");
3178       std::vector<std::vector<TreePatternNode*> > Variants;
3179       Variants.push_back(ChildVariants[0]); // Intrinsic id.
3180       Variants.push_back(ChildVariants[2]);
3181       Variants.push_back(ChildVariants[1]);
3182       for (unsigned i = 3; i != NC; ++i)
3183         Variants.push_back(ChildVariants[i]);
3184       CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3185     } else if (NC == 2)
3186       CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
3187                            OutVariants, CDP, DepVars);
3188   }
3189 }
3190
3191
3192 // GenerateVariants - Generate variants.  For example, commutative patterns can
3193 // match multiple ways.  Add them to PatternsToMatch as well.
3194 void CodeGenDAGPatterns::GenerateVariants() {
3195   DEBUG(errs() << "Generating instruction variants.\n");
3196
3197   // Loop over all of the patterns we've collected, checking to see if we can
3198   // generate variants of the instruction, through the exploitation of
3199   // identities.  This permits the target to provide aggressive matching without
3200   // the .td file having to contain tons of variants of instructions.
3201   //
3202   // Note that this loop adds new patterns to the PatternsToMatch list, but we
3203   // intentionally do not reconsider these.  Any variants of added patterns have
3204   // already been added.
3205   //
3206   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
3207     MultipleUseVarSet             DepVars;
3208     std::vector<TreePatternNode*> Variants;
3209     FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
3210     DEBUG(errs() << "Dependent/multiply used variables: ");
3211     DEBUG(DumpDepVars(DepVars));
3212     DEBUG(errs() << "\n");
3213     GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3214                        DepVars);
3215
3216     assert(!Variants.empty() && "Must create at least original variant!");
3217     Variants.erase(Variants.begin());  // Remove the original pattern.
3218
3219     if (Variants.empty())  // No variants for this pattern.
3220       continue;
3221
3222     DEBUG(errs() << "FOUND VARIANTS OF: ";
3223           PatternsToMatch[i].getSrcPattern()->dump();
3224           errs() << "\n");
3225
3226     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3227       TreePatternNode *Variant = Variants[v];
3228
3229       DEBUG(errs() << "  VAR#" << v <<  ": ";
3230             Variant->dump();
3231             errs() << "\n");
3232
3233       // Scan to see if an instruction or explicit pattern already matches this.
3234       bool AlreadyExists = false;
3235       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
3236         // Skip if the top level predicates do not match.
3237         if (PatternsToMatch[i].getPredicates() !=
3238             PatternsToMatch[p].getPredicates())
3239           continue;
3240         // Check to see if this variant already exists.
3241         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3242                                     DepVars)) {
3243           DEBUG(errs() << "  *** ALREADY EXISTS, ignoring variant.\n");
3244           AlreadyExists = true;
3245           break;
3246         }
3247       }
3248       // If we already have it, ignore the variant.
3249       if (AlreadyExists) continue;
3250
3251       // Otherwise, add it to the list of patterns we have.
3252       PatternsToMatch.
3253         push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3254                                  PatternsToMatch[i].getPredicates(),
3255                                  Variant, PatternsToMatch[i].getDstPattern(),
3256                                  PatternsToMatch[i].getDstRegs(),
3257                                  PatternsToMatch[i].getAddedComplexity(),
3258                                  Record::getNewUID()));
3259     }
3260
3261     DEBUG(errs() << "\n");
3262   }
3263 }
3264