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