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