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