blob: fe2ac1d21bc0a29ee222b49086ad99cac51a4c76 [file] [log] [blame]
Chris Lattnerab3242f2008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerab3242f2008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner8cab0212008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner78ac0742008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Chris Lattnercabe0372010-03-15 06:00:16 +000016#include "llvm/ADT/STLExtras.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000017#include "llvm/ADT/StringExtras.h"
Jim Grosbach3ae48a62012-04-18 17:46:41 +000018#include "llvm/ADT/Twine.h"
Chris Lattner8cab0212008-01-05 22:25:12 +000019#include "llvm/Support/Debug.h"
David Blaikieb48ed1a2012-01-17 04:43:56 +000020#include "llvm/Support/ErrorHandling.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000021#include "llvm/TableGen/Error.h"
22#include "llvm/TableGen/Record.h"
Chuck Rose IIIfe2714f2008-01-15 21:43:17 +000023#include <algorithm>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000024#include <cstdio>
25#include <set>
Chris Lattner8cab0212008-01-05 22:25:12 +000026using namespace llvm;
27
28//===----------------------------------------------------------------------===//
Chris Lattnercabe0372010-03-15 06:00:16 +000029// EEVT::TypeSet Implementation
30//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +000031
Owen Anderson9f944592009-08-11 20:47:22 +000032static inline bool isInteger(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000033 return MVT(VT).isInteger();
Duncan Sands13237ac2008-06-06 12:08:01 +000034}
Owen Anderson9f944592009-08-11 20:47:22 +000035static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000036 return MVT(VT).isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000037}
Owen Anderson9f944592009-08-11 20:47:22 +000038static inline bool isVector(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000039 return MVT(VT).isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000040}
Chris Lattner6d765eb2010-03-19 17:41:26 +000041static inline bool isScalar(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000042 return !MVT(VT).isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000043}
Duncan Sands13237ac2008-06-06 12:08:01 +000044
Chris Lattnercabe0372010-03-15 06:00:16 +000045EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
46 if (VT == MVT::iAny)
47 EnforceInteger(TP);
48 else if (VT == MVT::fAny)
49 EnforceFloatingPoint(TP);
50 else if (VT == MVT::vAny)
51 EnforceVector(TP);
52 else {
53 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
54 VT == MVT::iPTRAny) && "Not a concrete type!");
55 TypeVec.push_back(VT);
56 }
Chris Lattner8cab0212008-01-05 22:25:12 +000057}
58
Chris Lattnercabe0372010-03-15 06:00:16 +000059
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000060EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
Chris Lattnercabe0372010-03-15 06:00:16 +000061 assert(!VTList.empty() && "empty list?");
62 TypeVec.append(VTList.begin(), VTList.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +000063
Chris Lattnercabe0372010-03-15 06:00:16 +000064 if (!VTList.empty())
65 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
66 VTList[0] != MVT::fAny);
Jim Grosbach65586fe2010-12-21 16:16:00 +000067
Chris Lattner4a5f7be2010-03-27 20:32:26 +000068 // Verify no duplicates.
Chris Lattnercabe0372010-03-15 06:00:16 +000069 array_pod_sort(TypeVec.begin(), TypeVec.end());
Chris Lattner4a5f7be2010-03-27 20:32:26 +000070 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
Chris Lattner8cab0212008-01-05 22:25:12 +000071}
72
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000073/// FillWithPossibleTypes - Set to all legal types and return true, only valid
74/// on completely unknown type sets.
Chris Lattner6d765eb2010-03-19 17:41:26 +000075bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
76 bool (*Pred)(MVT::SimpleValueType),
77 const char *PredicateName) {
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000078 assert(isCompletelyUnknown());
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000079 ArrayRef<MVT::SimpleValueType> LegalTypes =
Chris Lattner6d765eb2010-03-19 17:41:26 +000080 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +000081
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000082 if (TP.hasError())
83 return false;
84
Chris Lattner6d765eb2010-03-19 17:41:26 +000085 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
86 if (Pred == 0 || Pred(LegalTypes[i]))
87 TypeVec.push_back(LegalTypes[i]);
88
89 // If we have nothing that matches the predicate, bail out.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000090 if (TypeVec.empty()) {
Chris Lattner6d765eb2010-03-19 17:41:26 +000091 TP.error("Type inference contradiction found, no " +
Jim Grosbach65586fe2010-12-21 16:16:00 +000092 std::string(PredicateName) + " types found");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000093 return false;
94 }
Chris Lattner6d765eb2010-03-19 17:41:26 +000095 // No need to sort with one element.
96 if (TypeVec.size() == 1) return true;
97
98 // Remove duplicates.
99 array_pod_sort(TypeVec.begin(), TypeVec.end());
100 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000101
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000102 return true;
103}
Chris Lattnercabe0372010-03-15 06:00:16 +0000104
105/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
106/// integer value type.
107bool EEVT::TypeSet::hasIntegerTypes() const {
108 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
109 if (isInteger(TypeVec[i]))
110 return true;
111 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000112}
Chris Lattnercabe0372010-03-15 06:00:16 +0000113
114/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
115/// a floating point value type.
116bool EEVT::TypeSet::hasFloatingPointTypes() const {
117 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
118 if (isFloatingPoint(TypeVec[i]))
119 return true;
120 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000121}
Chris Lattnercabe0372010-03-15 06:00:16 +0000122
123/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
124/// value type.
125bool EEVT::TypeSet::hasVectorTypes() const {
126 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
127 if (isVector(TypeVec[i]))
128 return true;
129 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +0000130}
Bob Wilson2cd5da82009-08-11 01:14:02 +0000131
Chris Lattnercabe0372010-03-15 06:00:16 +0000132
133std::string EEVT::TypeSet::getName() const {
Chris Lattnerda5b4ad2010-03-19 01:14:27 +0000134 if (TypeVec.empty()) return "<empty>";
Jim Grosbach65586fe2010-12-21 16:16:00 +0000135
Chris Lattnercabe0372010-03-15 06:00:16 +0000136 std::string Result;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000137
Chris Lattnercabe0372010-03-15 06:00:16 +0000138 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
139 std::string VTName = llvm::getEnumName(TypeVec[i]);
140 // Strip off MVT:: prefix if present.
141 if (VTName.substr(0,5) == "MVT::")
142 VTName = VTName.substr(5);
143 if (i) Result += ':';
144 Result += VTName;
145 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000146
Chris Lattnercabe0372010-03-15 06:00:16 +0000147 if (TypeVec.size() == 1)
148 return Result;
149 return "{" + Result + "}";
Bob Wilson2cd5da82009-08-11 01:14:02 +0000150}
Chris Lattnercabe0372010-03-15 06:00:16 +0000151
152/// MergeInTypeInfo - This merges in type information from the specified
153/// argument. If 'this' changes, it returns true. If the two types are
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000154/// contradictory (e.g. merge f32 into i32) then this flags an error.
Chris Lattnercabe0372010-03-15 06:00:16 +0000155bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000156 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
Chris Lattnercabe0372010-03-15 06:00:16 +0000157 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000158
Chris Lattnercabe0372010-03-15 06:00:16 +0000159 if (isCompletelyUnknown()) {
160 *this = InVT;
161 return true;
162 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000163
Chris Lattnercabe0372010-03-15 06:00:16 +0000164 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000165
Chris Lattnercabe0372010-03-15 06:00:16 +0000166 // Handle the abstract cases, seeing if we can resolve them better.
167 switch (TypeVec[0]) {
168 default: break;
169 case MVT::iPTR:
170 case MVT::iPTRAny:
171 if (InVT.hasIntegerTypes()) {
172 EEVT::TypeSet InCopy(InVT);
173 InCopy.EnforceInteger(TP);
174 InCopy.EnforceScalar(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000175
Chris Lattnercabe0372010-03-15 06:00:16 +0000176 if (InCopy.isConcrete()) {
177 // If the RHS has one integer type, upgrade iPTR to i32.
178 TypeVec[0] = InVT.TypeVec[0];
179 return true;
180 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000181
Chris Lattnercabe0372010-03-15 06:00:16 +0000182 // If the input has multiple scalar integers, this doesn't add any info.
183 if (!InCopy.isCompletelyUnknown())
184 return false;
185 }
186 break;
187 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000188
Chris Lattnercabe0372010-03-15 06:00:16 +0000189 // If the input constraint is iAny/iPTR and this is an integer type list,
190 // remove non-integer types from the list.
191 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
192 hasIntegerTypes()) {
193 bool MadeChange = EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000194
Chris Lattnercabe0372010-03-15 06:00:16 +0000195 // If we're merging in iPTR/iPTRAny and the node currently has a list of
196 // multiple different integer types, replace them with a single iPTR.
197 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
198 TypeVec.size() != 1) {
199 TypeVec.resize(1);
200 TypeVec[0] = InVT.TypeVec[0];
201 MadeChange = true;
202 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000203
Chris Lattnercabe0372010-03-15 06:00:16 +0000204 return MadeChange;
205 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000206
Chris Lattnercabe0372010-03-15 06:00:16 +0000207 // If this is a type list and the RHS is a typelist as well, eliminate entries
208 // from this list that aren't in the other one.
209 bool MadeChange = false;
210 TypeSet InputSet(*this);
211
212 for (unsigned i = 0; i != TypeVec.size(); ++i) {
213 bool InInVT = false;
214 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
215 if (TypeVec[i] == InVT.TypeVec[j]) {
216 InInVT = true;
217 break;
218 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000219
Chris Lattnercabe0372010-03-15 06:00:16 +0000220 if (InInVT) continue;
221 TypeVec.erase(TypeVec.begin()+i--);
222 MadeChange = true;
223 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000224
Chris Lattnercabe0372010-03-15 06:00:16 +0000225 // If we removed all of our types, we have a type contradiction.
226 if (!TypeVec.empty())
227 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000228
Chris Lattnercabe0372010-03-15 06:00:16 +0000229 // FIXME: Really want an SMLoc here!
230 TP.error("Type inference contradiction found, merging '" +
231 InVT.getName() + "' into '" + InputSet.getName() + "'");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000232 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000233}
234
235/// EnforceInteger - Remove all non-integer types from this set.
236bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000237 if (TP.hasError())
238 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000239 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000240 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000241 return FillWithPossibleTypes(TP, isInteger, "integer");
Chris Lattnercabe0372010-03-15 06:00:16 +0000242 if (!hasFloatingPointTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000243 return false;
244
245 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000246
Chris Lattnercabe0372010-03-15 06:00:16 +0000247 // Filter out all the fp types.
248 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000249 if (!isInteger(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000250 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000251
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000252 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000253 TP.error("Type inference contradiction found, '" +
254 InputSet.getName() + "' needs to be integer");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000255 return false;
256 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000257 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000258}
259
260/// EnforceFloatingPoint - Remove all integer types from this set.
261bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000262 if (TP.hasError())
263 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000264 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000265 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000266 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
267
Chris Lattnercabe0372010-03-15 06:00:16 +0000268 if (!hasIntegerTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000269 return false;
270
271 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000272
Chris Lattnercabe0372010-03-15 06:00:16 +0000273 // Filter out all the fp types.
274 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000275 if (!isFloatingPoint(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000276 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000277
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000278 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000279 TP.error("Type inference contradiction found, '" +
280 InputSet.getName() + "' needs to be floating point");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000281 return false;
282 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000283 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000284}
285
286/// EnforceScalar - Remove all vector types from this.
287bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000288 if (TP.hasError())
289 return false;
290
Chris Lattnercabe0372010-03-15 06:00:16 +0000291 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000292 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000293 return FillWithPossibleTypes(TP, isScalar, "scalar");
294
Chris Lattnercabe0372010-03-15 06:00:16 +0000295 if (!hasVectorTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000296 return false;
297
298 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000299
Chris Lattnercabe0372010-03-15 06:00:16 +0000300 // Filter out all the vector types.
301 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000302 if (!isScalar(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000303 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000304
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000305 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000306 TP.error("Type inference contradiction found, '" +
307 InputSet.getName() + "' needs to be scalar");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000308 return false;
309 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000310 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000311}
312
313/// EnforceVector - Remove all vector types from this.
314bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000315 if (TP.hasError())
316 return false;
317
Chris Lattner6d765eb2010-03-19 17:41:26 +0000318 // If we know nothing, then get the full set.
319 if (TypeVec.empty())
320 return FillWithPossibleTypes(TP, isVector, "vector");
321
Chris Lattnercabe0372010-03-15 06:00:16 +0000322 TypeSet InputSet(*this);
323 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000324
Chris Lattnercabe0372010-03-15 06:00:16 +0000325 // Filter out all the scalar types.
326 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000327 if (!isVector(TypeVec[i])) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000328 TypeVec.erase(TypeVec.begin()+i--);
Chris Lattner6d765eb2010-03-19 17:41:26 +0000329 MadeChange = true;
330 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000331
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000332 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000333 TP.error("Type inference contradiction found, '" +
334 InputSet.getName() + "' needs to be a vector");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000335 return false;
336 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000337 return MadeChange;
338}
339
340
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000341
Chris Lattnercabe0372010-03-15 06:00:16 +0000342/// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
343/// this an other based on this information.
344bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000345 if (TP.hasError())
346 return false;
347
Chris Lattnercabe0372010-03-15 06:00:16 +0000348 // Both operands must be integer or FP, but we don't care which.
349 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000350
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000351 if (isCompletelyUnknown())
352 MadeChange = FillWithPossibleTypes(TP);
353
354 if (Other.isCompletelyUnknown())
355 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000356
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000357 // If one side is known to be integer or known to be FP but the other side has
358 // no information, get at least the type integrality info in there.
359 if (!hasFloatingPointTypes())
360 MadeChange |= Other.EnforceInteger(TP);
361 else if (!hasIntegerTypes())
362 MadeChange |= Other.EnforceFloatingPoint(TP);
363 if (!Other.hasFloatingPointTypes())
364 MadeChange |= EnforceInteger(TP);
365 else if (!Other.hasIntegerTypes())
366 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000367
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000368 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
369 "Should have a type list now");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000370
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000371 // If one contains vectors but the other doesn't pull vectors out.
372 if (!hasVectorTypes())
373 MadeChange |= Other.EnforceScalar(TP);
Craig Topper6dbcb942014-01-25 05:17:38 +0000374 if (!Other.hasVectorTypes())
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000375 MadeChange |= EnforceScalar(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000376
Craig Topper5f730e82014-01-25 05:33:48 +0000377 if (isConcrete() && Other.isConcrete()) {
David Greene433c6182011-02-01 19:12:32 +0000378 // If we are down to concrete types, this code does not currently
379 // handle nodes which have multiple types, where some types are
380 // integer, and some are fp. Assert that this is not the case.
381 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
382 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
383 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
384
385 // Otherwise, if these are both vector types, either this vector
386 // must have a larger bitsize than the other, or this element type
387 // must be larger than the other.
Craig Topper5f730e82014-01-25 05:33:48 +0000388 MVT Type(getConcrete());
389 MVT OtherType(Other.getConcrete());
David Greene433c6182011-02-01 19:12:32 +0000390
391 if (hasVectorTypes() && Other.hasVectorTypes()) {
392 if (Type.getSizeInBits() >= OtherType.getSizeInBits())
393 if (Type.getVectorElementType().getSizeInBits()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000394 >= OtherType.getVectorElementType().getSizeInBits()) {
David Greene433c6182011-02-01 19:12:32 +0000395 TP.error("Type inference contradiction found, '" +
396 getName() + "' element type not smaller than '" +
397 Other.getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000398 return false;
399 }
Craig Topper9836f592013-09-24 06:21:04 +0000400 } else
David Greene433c6182011-02-01 19:12:32 +0000401 // For scalar types, the bitsize of this type must be larger
402 // than that of the other.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000403 if (Type.getSizeInBits() >= OtherType.getSizeInBits()) {
David Greene433c6182011-02-01 19:12:32 +0000404 TP.error("Type inference contradiction found, '" +
405 getName() + "' is not smaller than '" +
406 Other.getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000407 return false;
408 }
David Greene433c6182011-02-01 19:12:32 +0000409 }
410
411
412 // Handle int and fp as disjoint sets. This won't work for patterns
413 // that have mixed fp/int types but those are likely rare and would
414 // not have been accepted by this code previously.
Jim Grosbach65586fe2010-12-21 16:16:00 +0000415
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000416 // Okay, find the smallest type from the current set and remove it from the
417 // largest set.
David Greene094442d2011-02-04 17:01:53 +0000418 MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
David Greene433c6182011-02-01 19:12:32 +0000419 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
420 if (isInteger(TypeVec[i])) {
421 SmallestInt = TypeVec[i];
422 break;
423 }
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000424 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
David Greene433c6182011-02-01 19:12:32 +0000425 if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
426 SmallestInt = TypeVec[i];
427
David Greene094442d2011-02-04 17:01:53 +0000428 MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
David Greene433c6182011-02-01 19:12:32 +0000429 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
430 if (isFloatingPoint(TypeVec[i])) {
431 SmallestFP = TypeVec[i];
432 break;
433 }
434 for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
435 if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
436 SmallestFP = TypeVec[i];
437
438 int OtherIntSize = 0;
439 int OtherFPSize = 0;
Craig Topperaf0dea12013-07-04 01:31:24 +0000440 for (SmallVectorImpl<MVT::SimpleValueType>::iterator TVI =
David Greene433c6182011-02-01 19:12:32 +0000441 Other.TypeVec.begin();
442 TVI != Other.TypeVec.end();
443 /* NULL */) {
444 if (isInteger(*TVI)) {
445 ++OtherIntSize;
446 if (*TVI == SmallestInt) {
447 TVI = Other.TypeVec.erase(TVI);
448 --OtherIntSize;
449 MadeChange = true;
450 continue;
451 }
Craig Topper9836f592013-09-24 06:21:04 +0000452 } else if (isFloatingPoint(*TVI)) {
David Greene433c6182011-02-01 19:12:32 +0000453 ++OtherFPSize;
454 if (*TVI == SmallestFP) {
455 TVI = Other.TypeVec.erase(TVI);
456 --OtherFPSize;
457 MadeChange = true;
458 continue;
459 }
460 }
461 ++TVI;
462 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000463
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000464 // If this is the only type in the large set, the constraint can never be
465 // satisfied.
Craig Topper9836f592013-09-24 06:21:04 +0000466 if ((Other.hasIntegerTypes() && OtherIntSize == 0) ||
467 (Other.hasFloatingPointTypes() && OtherFPSize == 0)) {
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000468 TP.error("Type inference contradiction found, '" +
469 Other.getName() + "' has nothing larger than '" + getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000470 return false;
471 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000472
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000473 // Okay, find the largest type in the Other set and remove it from the
474 // current set.
David Greene094442d2011-02-04 17:01:53 +0000475 MVT::SimpleValueType LargestInt = MVT::Other;
David Greene433c6182011-02-01 19:12:32 +0000476 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
477 if (isInteger(Other.TypeVec[i])) {
478 LargestInt = Other.TypeVec[i];
479 break;
480 }
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000481 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
David Greene433c6182011-02-01 19:12:32 +0000482 if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
483 LargestInt = Other.TypeVec[i];
484
David Greene094442d2011-02-04 17:01:53 +0000485 MVT::SimpleValueType LargestFP = MVT::Other;
David Greene433c6182011-02-01 19:12:32 +0000486 for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
487 if (isFloatingPoint(Other.TypeVec[i])) {
488 LargestFP = Other.TypeVec[i];
489 break;
490 }
491 for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
492 if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
493 LargestFP = Other.TypeVec[i];
494
495 int IntSize = 0;
496 int FPSize = 0;
Craig Topperaf0dea12013-07-04 01:31:24 +0000497 for (SmallVectorImpl<MVT::SimpleValueType>::iterator TVI =
David Greene433c6182011-02-01 19:12:32 +0000498 TypeVec.begin();
499 TVI != TypeVec.end();
500 /* NULL */) {
501 if (isInteger(*TVI)) {
502 ++IntSize;
503 if (*TVI == LargestInt) {
504 TVI = TypeVec.erase(TVI);
505 --IntSize;
506 MadeChange = true;
507 continue;
508 }
Craig Topper9836f592013-09-24 06:21:04 +0000509 } else if (isFloatingPoint(*TVI)) {
David Greene433c6182011-02-01 19:12:32 +0000510 ++FPSize;
511 if (*TVI == LargestFP) {
512 TVI = TypeVec.erase(TVI);
513 --FPSize;
514 MadeChange = true;
515 continue;
516 }
517 }
518 ++TVI;
519 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000520
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000521 // If this is the only type in the small set, the constraint can never be
522 // satisfied.
Craig Topper9836f592013-09-24 06:21:04 +0000523 if ((hasIntegerTypes() && IntSize == 0) ||
524 (hasFloatingPointTypes() && FPSize == 0)) {
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000525 TP.error("Type inference contradiction found, '" +
526 getName() + "' has nothing smaller than '" + Other.getName()+"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000527 return false;
528 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000529
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000530 return MadeChange;
Chris Lattnercabe0372010-03-15 06:00:16 +0000531}
532
533/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
Chris Lattner57ebf632010-03-24 00:01:16 +0000534/// whose element is specified by VTOperand.
535bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattnercabe0372010-03-15 06:00:16 +0000536 TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000537 if (TP.hasError())
538 return false;
539
Chris Lattner57ebf632010-03-24 00:01:16 +0000540 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattnercabe0372010-03-15 06:00:16 +0000541 bool MadeChange = false;
Chris Lattner57ebf632010-03-24 00:01:16 +0000542 MadeChange |= EnforceVector(TP);
543 MadeChange |= VTOperand.EnforceScalar(TP);
544
545 // If we know the vector type, it forces the scalar to agree.
546 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000547 MVT IVT = getConcrete();
Chris Lattner57ebf632010-03-24 00:01:16 +0000548 IVT = IVT.getVectorElementType();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000549 return MadeChange |
Craig Topper95198f42013-09-25 06:37:18 +0000550 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
Chris Lattner57ebf632010-03-24 00:01:16 +0000551 }
552
553 // If the scalar type is known, filter out vector types whose element types
554 // disagree.
555 if (!VTOperand.isConcrete())
556 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000557
Chris Lattner57ebf632010-03-24 00:01:16 +0000558 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000559
Chris Lattner57ebf632010-03-24 00:01:16 +0000560 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000561
Chris Lattner57ebf632010-03-24 00:01:16 +0000562 // Filter out all the types which don't have the right element type.
563 for (unsigned i = 0; i != TypeVec.size(); ++i) {
564 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
Craig Topper95198f42013-09-25 06:37:18 +0000565 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000566 TypeVec.erase(TypeVec.begin()+i--);
567 MadeChange = true;
568 }
Chris Lattner57ebf632010-03-24 00:01:16 +0000569 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000570
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000571 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
Chris Lattnercabe0372010-03-15 06:00:16 +0000572 TP.error("Type inference contradiction found, forcing '" +
573 InputSet.getName() + "' to have a vector element");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000574 return false;
575 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000576 return MadeChange;
577}
578
David Greene127fd1d2011-01-24 20:53:18 +0000579/// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
580/// vector type specified by VTOperand.
581bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
582 TreePattern &TP) {
583 // "This" must be a vector and "VTOperand" must be a vector.
584 bool MadeChange = false;
585 MadeChange |= EnforceVector(TP);
586 MadeChange |= VTOperand.EnforceVector(TP);
587
588 // "This" must be larger than "VTOperand."
589 MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
590
591 // If we know the vector type, it forces the scalar types to agree.
592 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000593 MVT IVT = getConcrete();
David Greene127fd1d2011-01-24 20:53:18 +0000594 IVT = IVT.getVectorElementType();
595
Craig Topper95198f42013-09-25 06:37:18 +0000596 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000597 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
598 } else if (VTOperand.isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000599 MVT IVT = VTOperand.getConcrete();
David Greene127fd1d2011-01-24 20:53:18 +0000600 IVT = IVT.getVectorElementType();
601
Craig Topper95198f42013-09-25 06:37:18 +0000602 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000603 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
604 }
605
606 return MadeChange;
607}
608
Chris Lattnercabe0372010-03-15 06:00:16 +0000609//===----------------------------------------------------------------------===//
610// Helpers for working with extended types.
Chris Lattner8cab0212008-01-05 22:25:12 +0000611
Scott Michel94420742008-03-05 17:49:05 +0000612/// Dependent variable map for CodeGenDAGPattern variant generation
613typedef std::map<std::string, int> DepVarMap;
614
615/// Const iterator shorthand for DepVarMap
616typedef DepVarMap::const_iterator DepVarMap_citer;
617
Chris Lattner514e2922011-04-17 21:38:24 +0000618static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel94420742008-03-05 17:49:05 +0000619 if (N->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000620 if (isa<DefInit>(N->getLeafValue()))
Scott Michel94420742008-03-05 17:49:05 +0000621 DepMap[N->getName()]++;
Scott Michel94420742008-03-05 17:49:05 +0000622 } else {
623 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
624 FindDepVarsOf(N->getChild(i), DepMap);
625 }
626}
Chris Lattner514e2922011-04-17 21:38:24 +0000627
628/// Find dependent variables within child patterns
629static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000630 DepVarMap depcounts;
631 FindDepVarsOf(N, depcounts);
632 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
Chris Lattner514e2922011-04-17 21:38:24 +0000633 if (i->second > 1) // std::pair<std::string, int>
Scott Michel94420742008-03-05 17:49:05 +0000634 DepVars.insert(i->first);
Scott Michel94420742008-03-05 17:49:05 +0000635 }
636}
637
Daniel Dunbarba66a812010-10-08 02:07:22 +0000638#ifndef NDEBUG
Chris Lattner514e2922011-04-17 21:38:24 +0000639/// Dump the dependent variable set:
640static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000641 if (DepVars.empty()) {
Chris Lattner34822f62009-08-23 04:44:11 +0000642 DEBUG(errs() << "<empty set>");
Scott Michel94420742008-03-05 17:49:05 +0000643 } else {
Chris Lattner34822f62009-08-23 04:44:11 +0000644 DEBUG(errs() << "[ ");
Jim Grosbachb75d0ca2010-10-08 18:13:57 +0000645 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
646 e = DepVars.end(); i != e; ++i) {
Chris Lattner34822f62009-08-23 04:44:11 +0000647 DEBUG(errs() << (*i) << " ");
Scott Michel94420742008-03-05 17:49:05 +0000648 }
Chris Lattner34822f62009-08-23 04:44:11 +0000649 DEBUG(errs() << "]");
Scott Michel94420742008-03-05 17:49:05 +0000650 }
651}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000652#endif
653
Chris Lattner514e2922011-04-17 21:38:24 +0000654
655//===----------------------------------------------------------------------===//
656// TreePredicateFn Implementation
657//===----------------------------------------------------------------------===//
658
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000659/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
660TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
661 assert((getPredCode().empty() || getImmCode().empty()) &&
662 ".td file corrupt: can't have a node predicate *and* an imm predicate");
663}
664
Chris Lattner514e2922011-04-17 21:38:24 +0000665std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000666 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000667}
668
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000669std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000670 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000671}
672
Chris Lattner514e2922011-04-17 21:38:24 +0000673
674/// isAlwaysTrue - Return true if this is a noop predicate.
675bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000676 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000677}
678
679/// Return the name to use in the generated code to reference this, this is
680/// "Predicate_foo" if from a pattern fragment "foo".
681std::string TreePredicateFn::getFnName() const {
682 return "Predicate_" + PatFragRec->getRecord()->getName();
683}
684
685/// getCodeToRunOnSDNode - Return the code for the function body that
686/// evaluates this predicate. The argument is expected to be in "Node",
687/// not N. This handles casting and conversion to a concrete node type as
688/// appropriate.
689std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000690 // Handle immediate predicates first.
691 std::string ImmCode = getImmCode();
692 if (!ImmCode.empty()) {
693 std::string Result =
694 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000695 return Result + ImmCode;
696 }
697
698 // Handle arbitrary node predicates.
699 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000700 std::string ClassName;
701 if (PatFragRec->getOnlyTree()->isLeaf())
702 ClassName = "SDNode";
703 else {
704 Record *Op = PatFragRec->getOnlyTree()->getOperator();
705 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
706 }
707 std::string Result;
708 if (ClassName == "SDNode")
709 Result = " SDNode *N = Node;\n";
710 else
711 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
712
713 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000714}
715
Chris Lattner8cab0212008-01-05 22:25:12 +0000716//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000717// PatternToMatch implementation
718//
719
Chris Lattner05925fe2010-03-29 01:40:38 +0000720
721/// getPatternSize - Return the 'size' of this pattern. We want to match large
722/// patterns before small ones. This is used to determine the size of a
723/// pattern.
724static unsigned getPatternSize(const TreePatternNode *P,
725 const CodeGenDAGPatterns &CGP) {
726 unsigned Size = 3; // The node itself.
727 // If the root node is a ConstantSDNode, increases its size.
728 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000729 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000730 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000731
Chris Lattner05925fe2010-03-29 01:40:38 +0000732 // FIXME: This is a hack to statically increase the priority of patterns
733 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
734 // Later we can allow complexity / cost for each pattern to be (optionally)
735 // specified. To get best possible pattern match we'll need to dynamically
736 // calculate the complexity of all patterns a dag can potentially map to.
737 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
738 if (AM)
739 Size += AM->getNumOperands() * 3;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000740
Chris Lattner05925fe2010-03-29 01:40:38 +0000741 // If this node has some predicate function that must match, it adds to the
742 // complexity of this node.
743 if (!P->getPredicateFns().empty())
744 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000745
Chris Lattner05925fe2010-03-29 01:40:38 +0000746 // Count children in the count if they are also nodes.
747 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
748 TreePatternNode *Child = P->getChild(i);
749 if (!Child->isLeaf() && Child->getNumTypes() &&
750 Child->getType(0) != MVT::Other)
751 Size += getPatternSize(Child, CGP);
752 else if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000753 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000754 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
755 else if (Child->getComplexPatternInfo(CGP))
756 Size += getPatternSize(Child, CGP);
757 else if (!Child->getPredicateFns().empty())
758 ++Size;
759 }
760 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000761
Chris Lattner05925fe2010-03-29 01:40:38 +0000762 return Size;
763}
764
765/// Compute the complexity metric for the input pattern. This roughly
766/// corresponds to the number of nodes that are covered.
767unsigned PatternToMatch::
768getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
769 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
770}
771
772
Dan Gohman49e19e92008-08-22 00:20:26 +0000773/// getPredicateCheck - Return a single string containing all of this
774/// pattern's predicates concatenated with "&&" operators.
775///
776std::string PatternToMatch::getPredicateCheck() const {
777 std::string PredicateCheck;
778 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +0000779 if (DefInit *Pred = dyn_cast<DefInit>(Predicates->getElement(i))) {
Dan Gohman49e19e92008-08-22 00:20:26 +0000780 Record *Def = Pred->getDef();
781 if (!Def->isSubClassOf("Predicate")) {
782#ifndef NDEBUG
783 Def->dump();
784#endif
Craig Topperc4965bc2012-02-05 07:21:30 +0000785 llvm_unreachable("Unknown predicate type!");
Dan Gohman49e19e92008-08-22 00:20:26 +0000786 }
787 if (!PredicateCheck.empty())
788 PredicateCheck += " && ";
789 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
790 }
791 }
792
793 return PredicateCheck;
794}
795
796//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000797// SDTypeConstraint implementation
798//
799
800SDTypeConstraint::SDTypeConstraint(Record *R) {
801 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000802
Chris Lattner8cab0212008-01-05 22:25:12 +0000803 if (R->isSubClassOf("SDTCisVT")) {
804 ConstraintType = SDTCisVT;
805 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerffdac7b2010-03-28 06:04:39 +0000806 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000807 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000808
Chris Lattner8cab0212008-01-05 22:25:12 +0000809 } else if (R->isSubClassOf("SDTCisPtrTy")) {
810 ConstraintType = SDTCisPtrTy;
811 } else if (R->isSubClassOf("SDTCisInt")) {
812 ConstraintType = SDTCisInt;
813 } else if (R->isSubClassOf("SDTCisFP")) {
814 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000815 } else if (R->isSubClassOf("SDTCisVec")) {
816 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000817 } else if (R->isSubClassOf("SDTCisSameAs")) {
818 ConstraintType = SDTCisSameAs;
819 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
820 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
821 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000822 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000823 R->getValueAsInt("OtherOperandNum");
824 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
825 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000826 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000827 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000828 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
829 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000830 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000831 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
832 ConstraintType = SDTCisSubVecOfVec;
833 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
834 R->getValueAsInt("OtherOpNum");
Chris Lattner8cab0212008-01-05 22:25:12 +0000835 } else {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +0000836 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner8cab0212008-01-05 22:25:12 +0000837 exit(1);
838 }
839}
840
841/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000842/// N, and the result number in ResNo.
843static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
844 const SDNodeInfo &NodeInfo,
845 unsigned &ResNo) {
846 unsigned NumResults = NodeInfo.getNumResults();
847 if (OpNo < NumResults) {
848 ResNo = OpNo;
849 return N;
850 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000851
Chris Lattner2db7aba2010-03-19 21:56:21 +0000852 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000853
Chris Lattner2db7aba2010-03-19 21:56:21 +0000854 if (OpNo >= N->getNumChildren()) {
Jim Grosbach65586fe2010-12-21 16:16:00 +0000855 errs() << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000856 << (OpNo+NumResults) << " ";
Chris Lattner8cab0212008-01-05 22:25:12 +0000857 N->dump();
Daniel Dunbar38a22bf2009-07-03 00:10:29 +0000858 errs() << '\n';
Chris Lattner8cab0212008-01-05 22:25:12 +0000859 exit(1);
860 }
861
Chris Lattner2db7aba2010-03-19 21:56:21 +0000862 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +0000863}
864
865/// ApplyTypeConstraint - Given a node in a pattern, apply this type
866/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000867/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +0000868bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
869 const SDNodeInfo &NodeInfo,
870 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000871 if (TP.hasError())
872 return false;
873
Chris Lattner2db7aba2010-03-19 21:56:21 +0000874 unsigned ResNo = 0; // The result number being referenced.
875 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000876
Chris Lattner8cab0212008-01-05 22:25:12 +0000877 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000878 case SDTCisVT:
879 // Operand must be a particular type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000880 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000881 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +0000882 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000883 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000884 case SDTCisInt:
885 // Require it to be one of the legal integer VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000886 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000887 case SDTCisFP:
888 // Require it to be one of the legal fp VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000889 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000890 case SDTCisVec:
891 // Require it to be one of the legal vector VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000892 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000893 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000894 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000895 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000896 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +0000897 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
898 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000899 }
900 case SDTCisVTSmallerThanOp: {
901 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
902 // have an integer type that is smaller than the VT.
903 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +0000904 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +0000905 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000906 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000907 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000908 return false;
909 }
Owen Anderson9f944592009-08-11 20:47:22 +0000910 MVT::SimpleValueType VT =
David Greeneaf8ee2c2011-07-29 22:43:06 +0000911 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000912
Chris Lattner38c99662010-03-24 00:06:46 +0000913 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000914
Chris Lattner2db7aba2010-03-19 21:56:21 +0000915 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000916 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000917 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
918 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +0000919
Chris Lattner38c99662010-03-24 00:06:46 +0000920 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000921 }
922 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000923 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000924 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000925 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
926 BResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +0000927 return NodeToApply->getExtType(ResNo).
928 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000929 }
Nate Begeman17bedbc2008-02-09 01:37:05 +0000930 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000931 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +0000932 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000933 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
934 VResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000935
Chris Lattner57ebf632010-03-24 00:01:16 +0000936 // Filter vector types out of VecOperand that don't have the right element
937 // type.
938 return VecOperand->getExtType(VResNo).
939 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begeman17bedbc2008-02-09 01:37:05 +0000940 }
David Greene127fd1d2011-01-24 20:53:18 +0000941 case SDTCisSubVecOfVec: {
942 unsigned VResNo = 0;
943 TreePatternNode *BigVecOperand =
944 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
945 VResNo);
946
947 // Filter vector types out of BigVecOperand that don't have the
948 // right subvector type.
949 return BigVecOperand->getExtType(VResNo).
950 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
951 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000952 }
David Blaikiea5708dc2012-01-17 07:00:13 +0000953 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +0000954}
955
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +0000956// Update the node type to match an instruction operand or result as specified
957// in the ins or outs lists on the instruction definition. Return true if the
958// type was actually changed.
959bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
960 Record *Operand,
961 TreePattern &TP) {
962 // The 'unknown' operand indicates that types should be inferred from the
963 // context.
964 if (Operand->isSubClassOf("unknown_class"))
965 return false;
966
967 // The Operand class specifies a type directly.
968 if (Operand->isSubClassOf("Operand"))
969 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
970 TP);
971
972 // PointerLikeRegClass has a type that is determined at runtime.
973 if (Operand->isSubClassOf("PointerLikeRegClass"))
974 return UpdateNodeType(ResNo, MVT::iPTR, TP);
975
976 // Both RegisterClass and RegisterOperand operands derive their types from a
977 // register class def.
978 Record *RC = 0;
979 if (Operand->isSubClassOf("RegisterClass"))
980 RC = Operand;
981 else if (Operand->isSubClassOf("RegisterOperand"))
982 RC = Operand->getValueAsDef("RegClass");
983
984 assert(RC && "Unknown operand type");
985 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
986 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
987}
988
989
Chris Lattner8cab0212008-01-05 22:25:12 +0000990//===----------------------------------------------------------------------===//
991// SDNodeInfo implementation
992//
993SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
994 EnumName = R->getValueAsString("Opcode");
995 SDClassName = R->getValueAsString("SDClass");
996 Record *TypeProfile = R->getValueAsDef("TypeProfile");
997 NumResults = TypeProfile->getValueAsInt("NumResults");
998 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000999
Chris Lattner8cab0212008-01-05 22:25:12 +00001000 // Parse the properties.
1001 Properties = 0;
1002 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
1003 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
1004 if (PropList[i]->getName() == "SDNPCommutative") {
1005 Properties |= 1 << SDNPCommutative;
1006 } else if (PropList[i]->getName() == "SDNPAssociative") {
1007 Properties |= 1 << SDNPAssociative;
1008 } else if (PropList[i]->getName() == "SDNPHasChain") {
1009 Properties |= 1 << SDNPHasChain;
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001010 } else if (PropList[i]->getName() == "SDNPOutGlue") {
1011 Properties |= 1 << SDNPOutGlue;
1012 } else if (PropList[i]->getName() == "SDNPInGlue") {
1013 Properties |= 1 << SDNPInGlue;
1014 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
1015 Properties |= 1 << SDNPOptInGlue;
Chris Lattnera348f552008-01-06 06:44:58 +00001016 } else if (PropList[i]->getName() == "SDNPMayStore") {
1017 Properties |= 1 << SDNPMayStore;
Chris Lattner1ca20682008-01-10 04:38:57 +00001018 } else if (PropList[i]->getName() == "SDNPMayLoad") {
1019 Properties |= 1 << SDNPMayLoad;
Chris Lattner42c63ef2008-01-10 05:39:30 +00001020 } else if (PropList[i]->getName() == "SDNPSideEffect") {
1021 Properties |= 1 << SDNPSideEffect;
Mon P Wang6a490372008-06-25 08:15:39 +00001022 } else if (PropList[i]->getName() == "SDNPMemOperand") {
1023 Properties |= 1 << SDNPMemOperand;
Chris Lattner83aeaab2010-03-19 05:07:09 +00001024 } else if (PropList[i]->getName() == "SDNPVariadic") {
1025 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001026 } else {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001027 errs() << "Unknown SD Node property '" << PropList[i]->getName()
1028 << "' on node '" << R->getName() << "'!\n";
Chris Lattner8cab0212008-01-05 22:25:12 +00001029 exit(1);
1030 }
1031 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001032
1033
Chris Lattner8cab0212008-01-05 22:25:12 +00001034 // Parse the type constraints.
1035 std::vector<Record*> ConstraintList =
1036 TypeProfile->getValueAsListOfDefs("Constraints");
1037 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1038}
1039
Chris Lattner99e53b32010-02-28 00:22:30 +00001040/// getKnownType - If the type constraints on this node imply a fixed type
1041/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001042/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001043MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001044 unsigned NumResults = getNumResults();
1045 assert(NumResults <= 1 &&
1046 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001047 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001048
Chris Lattner99e53b32010-02-28 00:22:30 +00001049 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
1050 // Make sure that this applies to the correct node result.
1051 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
1052 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001053
Chris Lattner99e53b32010-02-28 00:22:30 +00001054 switch (TypeConstraints[i].ConstraintType) {
1055 default: break;
1056 case SDTypeConstraint::SDTCisVT:
1057 return TypeConstraints[i].x.SDTCisVT_Info.VT;
1058 case SDTypeConstraint::SDTCisPtrTy:
1059 return MVT::iPTR;
1060 }
1061 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001062 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001063}
1064
Chris Lattner8cab0212008-01-05 22:25:12 +00001065//===----------------------------------------------------------------------===//
1066// TreePatternNode implementation
1067//
1068
1069TreePatternNode::~TreePatternNode() {
1070#if 0 // FIXME: implement refcounted tree nodes!
1071 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1072 delete getChild(i);
1073#endif
1074}
1075
Chris Lattnerf1447252010-03-19 21:37:09 +00001076static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1077 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001078 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001079 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001080
Chris Lattner2109cb42010-03-22 20:56:36 +00001081 if (Operator->isSubClassOf("Intrinsic"))
1082 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001083
Chris Lattnerf1447252010-03-19 21:37:09 +00001084 if (Operator->isSubClassOf("SDNode"))
1085 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001086
Chris Lattnerf1447252010-03-19 21:37:09 +00001087 if (Operator->isSubClassOf("PatFrag")) {
1088 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1089 // the forward reference case where one pattern fragment references another
1090 // before it is processed.
1091 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1092 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001093
Chris Lattnerf1447252010-03-19 21:37:09 +00001094 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001095 DagInit *Tree = Operator->getValueAsDag("Fragment");
Chris Lattnerf1447252010-03-19 21:37:09 +00001096 Record *Op = 0;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001097 if (Tree)
1098 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1099 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001100 assert(Op && "Invalid Fragment");
1101 return GetNumNodeResults(Op, CDP);
1102 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001103
Chris Lattnerf1447252010-03-19 21:37:09 +00001104 if (Operator->isSubClassOf("Instruction")) {
1105 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001106
1107 // FIXME: Should allow access to all the results here.
Chris Lattnerd8adec72010-11-01 04:03:32 +00001108 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001109
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001110 // Add on one implicit def if it has a resolvable type.
1111 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1112 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001113 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001114 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001115
Chris Lattnerf1447252010-03-19 21:37:09 +00001116 if (Operator->isSubClassOf("SDNodeXForm"))
1117 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001118
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001119 if (Operator->isSubClassOf("ValueType"))
1120 return 1; // A type-cast of one result.
1121
Chris Lattnerf1447252010-03-19 21:37:09 +00001122 Operator->dump();
1123 errs() << "Unhandled node in GetNumNodeResults\n";
1124 exit(1);
1125}
1126
1127void TreePatternNode::print(raw_ostream &OS) const {
1128 if (isLeaf())
1129 OS << *getLeafValue();
1130 else
1131 OS << '(' << getOperator()->getName();
1132
1133 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1134 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001135
1136 if (!isLeaf()) {
1137 if (getNumChildren() != 0) {
1138 OS << " ";
1139 getChild(0)->print(OS);
1140 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1141 OS << ", ";
1142 getChild(i)->print(OS);
1143 }
1144 }
1145 OS << ")";
1146 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001147
Dan Gohman6e979022008-10-15 06:17:21 +00001148 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
Chris Lattner514e2922011-04-17 21:38:24 +00001149 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001150 if (TransformFn)
1151 OS << "<<X:" << TransformFn->getName() << ">>";
1152 if (!getName().empty())
1153 OS << ":$" << getName();
1154
1155}
1156void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001157 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001158}
1159
Scott Michel94420742008-03-05 17:49:05 +00001160/// isIsomorphicTo - Return true if this node is recursively
1161/// isomorphic to the specified node. For this comparison, the node's
1162/// entire state is considered. The assigned name is ignored, since
1163/// nodes with differing names are considered isomorphic. However, if
1164/// the assigned name is present in the dependent variable set, then
1165/// the assigned name is considered significant and the node is
1166/// isomorphic if the names match.
1167bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1168 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001169 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001170 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001171 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001172 getTransformFn() != N->getTransformFn())
1173 return false;
1174
1175 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001176 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1177 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001178 return ((DI->getDef() == NDI->getDef())
1179 && (DepVars.find(getName()) == DepVars.end()
1180 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001181 }
1182 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001183 return getLeafValue() == N->getLeafValue();
1184 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001185
Chris Lattner8cab0212008-01-05 22:25:12 +00001186 if (N->getOperator() != getOperator() ||
1187 N->getNumChildren() != getNumChildren()) return false;
1188 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001189 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001190 return false;
1191 return true;
1192}
1193
1194/// clone - Make a copy of this tree and all of its children.
1195///
1196TreePatternNode *TreePatternNode::clone() const {
1197 TreePatternNode *New;
1198 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001199 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001200 } else {
1201 std::vector<TreePatternNode*> CChildren;
1202 CChildren.reserve(Children.size());
1203 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1204 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001205 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001206 }
1207 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001208 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001209 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001210 New->setTransformFn(getTransformFn());
1211 return New;
1212}
1213
Chris Lattner53c39ba2010-02-14 22:22:58 +00001214/// RemoveAllTypes - Recursively strip all the types of this tree.
1215void TreePatternNode::RemoveAllTypes() {
Chris Lattnerf1447252010-03-19 21:37:09 +00001216 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1217 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner53c39ba2010-02-14 22:22:58 +00001218 if (isLeaf()) return;
1219 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1220 getChild(i)->RemoveAllTypes();
1221}
1222
1223
Chris Lattner8cab0212008-01-05 22:25:12 +00001224/// SubstituteFormalArguments - Replace the formal arguments in this tree
1225/// with actual values specified by ArgMap.
1226void TreePatternNode::
1227SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1228 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001229
Chris Lattner8cab0212008-01-05 22:25:12 +00001230 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1231 TreePatternNode *Child = getChild(i);
1232 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001233 Init *Val = Child->getLeafValue();
Sean Silva88eb8dd2012-10-10 20:24:47 +00001234 if (isa<DefInit>(Val) &&
1235 cast<DefInit>(Val)->getDef()->getName() == "node") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001236 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001237 TreePatternNode *NewChild = ArgMap[Child->getName()];
1238 assert(NewChild && "Couldn't find formal argument!");
1239 assert((Child->getPredicateFns().empty() ||
1240 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1241 "Non-empty child predicate clobbered!");
1242 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001243 }
1244 } else {
1245 getChild(i)->SubstituteFormalArguments(ArgMap);
1246 }
1247 }
1248}
1249
1250
1251/// InlinePatternFragments - If this pattern refers to any pattern
1252/// fragments, inline them into place, giving us a pattern without any
1253/// PatFrag references.
1254TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001255 if (TP.hasError())
Kaelyn Uhrain41a73b72012-10-25 21:25:08 +00001256 return 0;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001257
1258 if (isLeaf())
1259 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001260 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001261
Chris Lattner8cab0212008-01-05 22:25:12 +00001262 if (!Op->isSubClassOf("PatFrag")) {
1263 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001264 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1265 TreePatternNode *Child = getChild(i);
1266 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1267
1268 assert((Child->getPredicateFns().empty() ||
1269 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1270 "Non-empty child predicate clobbered!");
1271
1272 setChild(i, NewChild);
1273 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001274 return this;
1275 }
1276
1277 // Otherwise, we found a reference to a fragment. First, look up its
1278 // TreePattern record.
1279 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001280
Chris Lattner8cab0212008-01-05 22:25:12 +00001281 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001282 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001283 TP.error("'" + Op->getName() + "' fragment requires " +
1284 utostr(Frag->getNumArgs()) + " operands!");
Kaelyn Uhrain41a73b72012-10-25 21:25:08 +00001285 return 0;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001286 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001287
1288 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1289
Chris Lattner514e2922011-04-17 21:38:24 +00001290 TreePredicateFn PredFn(Frag);
1291 if (!PredFn.isAlwaysTrue())
1292 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001293
Chris Lattner8cab0212008-01-05 22:25:12 +00001294 // Resolve formal arguments to their actual value.
1295 if (Frag->getNumArgs()) {
1296 // Compute the map of formal to actual arguments.
1297 std::map<std::string, TreePatternNode*> ArgMap;
1298 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1299 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001300
Chris Lattner8cab0212008-01-05 22:25:12 +00001301 FragTree->SubstituteFormalArguments(ArgMap);
1302 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001303
Chris Lattner8cab0212008-01-05 22:25:12 +00001304 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001305 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1306 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001307
1308 // Transfer in the old predicates.
1309 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1310 FragTree->addPredicateFn(getPredicateFns()[i]);
1311
Chris Lattner8cab0212008-01-05 22:25:12 +00001312 // Get a new copy of this fragment to stitch into here.
1313 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001314
Chris Lattner2e253b42008-06-30 03:02:03 +00001315 // The fragment we inlined could have recursive inlining that is needed. See
1316 // if there are any pattern fragments in it and inline them as needed.
1317 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001318}
1319
1320/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001321/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001322/// references from the register file information, for example.
1323///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001324/// When Unnamed is set, return the type of a DAG operand with no name, such as
1325/// the F8RC register class argument in:
1326///
1327/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1328///
1329/// When Unnamed is false, return the type of a named DAG operand such as the
1330/// GPR:$src operand above.
1331///
Chris Lattnerf1447252010-03-19 21:37:09 +00001332static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001333 bool NotRegisters,
1334 bool Unnamed,
1335 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001336 // Check to see if this is a register operand.
1337 if (R->isSubClassOf("RegisterOperand")) {
1338 assert(ResNo == 0 && "Regoperand ref only has one result!");
1339 if (NotRegisters)
1340 return EEVT::TypeSet(); // Unknown.
1341 Record *RegClass = R->getValueAsDef("RegClass");
1342 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1343 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1344 }
1345
Chris Lattnercabe0372010-03-15 06:00:16 +00001346 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001347 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001348 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001349 // An unnamed register class represents itself as an i32 immediate, for
1350 // example on a COPY_TO_REGCLASS instruction.
1351 if (Unnamed)
1352 return EEVT::TypeSet(MVT::i32, TP);
1353
1354 // In a named operand, the register class provides the possible set of
1355 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001356 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001357 return EEVT::TypeSet(); // Unknown.
1358 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1359 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001360 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001361
Chris Lattner6070ee22010-03-23 23:50:31 +00001362 if (R->isSubClassOf("PatFrag")) {
1363 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001364 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001365 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001366 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001367
Chris Lattner6070ee22010-03-23 23:50:31 +00001368 if (R->isSubClassOf("Register")) {
1369 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001370 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001371 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001372 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001373 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001374 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001375
1376 if (R->isSubClassOf("SubRegIndex")) {
1377 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1378 return EEVT::TypeSet();
1379 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001380
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001381 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001382 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001383 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1384 //
1385 // (sext_inreg GPR:$src, i16)
1386 // ~~~
1387 if (Unnamed)
1388 return EEVT::TypeSet(MVT::Other, TP);
1389 // With a name, the ValueType simply provides the type of the named
1390 // variable.
1391 //
1392 // (sext_inreg i32:$src, i16)
1393 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001394 if (NotRegisters)
1395 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001396 return EEVT::TypeSet(getValueType(R), TP);
1397 }
1398
1399 if (R->isSubClassOf("CondCode")) {
1400 assert(ResNo == 0 && "This node only has one result!");
1401 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001402 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001403 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001404
Chris Lattner6070ee22010-03-23 23:50:31 +00001405 if (R->isSubClassOf("ComplexPattern")) {
1406 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001407 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001408 return EEVT::TypeSet(); // Unknown.
1409 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1410 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001411 }
1412 if (R->isSubClassOf("PointerLikeRegClass")) {
1413 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001414 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001415 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001416
Chris Lattner6070ee22010-03-23 23:50:31 +00001417 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1418 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001419 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001420 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001421 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001422
Chris Lattner8cab0212008-01-05 22:25:12 +00001423 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001424 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001425}
1426
Chris Lattner89c65662008-01-06 05:36:50 +00001427
1428/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1429/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1430const CodeGenIntrinsic *TreePatternNode::
1431getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1432 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1433 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1434 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1435 return 0;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001436
Sean Silva88eb8dd2012-10-10 20:24:47 +00001437 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001438 return &CDP.getIntrinsicInfo(IID);
1439}
1440
Chris Lattner53c39ba2010-02-14 22:22:58 +00001441/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1442/// return the ComplexPattern information, otherwise return null.
1443const ComplexPattern *
1444TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1445 if (!isLeaf()) return 0;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001446
Sean Silvafb509ed2012-10-10 20:24:43 +00001447 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001448 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1449 return &CGP.getComplexPattern(DI->getDef());
1450 return 0;
1451}
1452
1453/// NodeHasProperty - Return true if this node has the specified property.
1454bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001455 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001456 if (isLeaf()) {
1457 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1458 return CP->hasProperty(Property);
1459 return false;
1460 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001461
Chris Lattner53c39ba2010-02-14 22:22:58 +00001462 Record *Operator = getOperator();
1463 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001464
Chris Lattner53c39ba2010-02-14 22:22:58 +00001465 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1466}
1467
1468
1469
1470
1471/// TreeHasProperty - Return true if any node in this tree has the specified
1472/// property.
1473bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001474 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001475 if (NodeHasProperty(Property, CGP))
1476 return true;
1477 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1478 if (getChild(i)->TreeHasProperty(Property, CGP))
1479 return true;
1480 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001481}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001482
Evan Cheng49bad4c2008-06-16 20:29:38 +00001483/// isCommutativeIntrinsic - Return true if the node corresponds to a
1484/// commutative intrinsic.
1485bool
1486TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1487 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1488 return Int->isCommutative;
1489 return false;
1490}
1491
Chris Lattner89c65662008-01-06 05:36:50 +00001492
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001493/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001494/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001495/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001496bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001497 if (TP.hasError())
1498 return false;
1499
Chris Lattnerab3242f2008-01-06 01:10:31 +00001500 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001501 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001502 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001503 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001504 bool MadeChange = false;
1505 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1506 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001507 NotRegisters,
1508 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001509 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001510 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001511
Sean Silvafb509ed2012-10-10 20:24:43 +00001512 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001513 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001514
Chris Lattnerf1447252010-03-19 21:37:09 +00001515 // Int inits are always integers. :)
1516 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001517
Chris Lattnerf1447252010-03-19 21:37:09 +00001518 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001519 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001520
Chris Lattnerf1447252010-03-19 21:37:09 +00001521 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001522 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1523 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001524
Craig Topper95198f42013-09-25 06:37:18 +00001525 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001526 // Make sure that the value is representable for this type.
1527 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001528
Richard Smith228e6d42012-08-24 23:29:28 +00001529 // Check that the value doesn't use more bits than we have. It must either
1530 // be a sign- or zero-extended equivalent of the original.
1531 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1532 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001533 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001534
Richard Smith228e6d42012-08-24 23:29:28 +00001535 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001536 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001537 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001538 }
1539 return false;
1540 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001541
Chris Lattner8cab0212008-01-05 22:25:12 +00001542 // special handling for set, which isn't really an SDNode.
1543 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001544 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1545 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001546 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001547
Chris Lattnerf1447252010-03-19 21:37:09 +00001548 TreePatternNode *SetVal = getChild(NC-1);
1549 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1550
Chris Lattner8cab0212008-01-05 22:25:12 +00001551 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001552 TreePatternNode *Child = getChild(i);
1553 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001554
Chris Lattner8cab0212008-01-05 22:25:12 +00001555 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001556 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1557 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001558 }
1559 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001560 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001561
Chris Lattner5c2182e2010-03-27 02:53:27 +00001562 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001563 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1564
Chris Lattner8cab0212008-01-05 22:25:12 +00001565 bool MadeChange = false;
1566 for (unsigned i = 0; i < getNumChildren(); ++i)
1567 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001568 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001569 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001570
Chris Lattneree820ac2010-02-23 05:51:07 +00001571 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001572 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001573
Chris Lattner8cab0212008-01-05 22:25:12 +00001574 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001575 unsigned NumRetVTs = Int->IS.RetVTs.size();
1576 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001577
Bill Wendling91821472008-11-13 09:08:33 +00001578 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001579 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001580
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001581 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001582 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001583 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001584 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001585 return false;
1586 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001587
1588 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001589 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001590
Chris Lattnerf1447252010-03-19 21:37:09 +00001591 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1592 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001593
Chris Lattnerf1447252010-03-19 21:37:09 +00001594 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1595 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1596 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001597 }
1598 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001599 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001600
Chris Lattneree820ac2010-02-23 05:51:07 +00001601 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001602 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001603
Chris Lattner135091b2010-03-28 08:48:47 +00001604 // Check that the number of operands is sane. Negative operands -> varargs.
1605 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001606 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001607 TP.error(getOperator()->getName() + " node requires exactly " +
1608 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001609 return false;
1610 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001611
Chris Lattner8cab0212008-01-05 22:25:12 +00001612 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1613 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1614 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001615 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001616 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001617
Chris Lattneree820ac2010-02-23 05:51:07 +00001618 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001619 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001620 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001621 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001622
Chris Lattnerd44966f2010-03-27 19:15:02 +00001623 bool MadeChange = false;
1624
1625 // Apply the result types to the node, these come from the things in the
1626 // (outs) list of the instruction.
1627 // FIXME: Cap at one result so far.
Chris Lattnerd8adec72010-11-01 04:03:32 +00001628 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001629 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1630 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001631
Chris Lattnerd44966f2010-03-27 19:15:02 +00001632 // If the instruction has implicit defs, we apply the first one as a result.
1633 // FIXME: This sucks, it should apply all implicit defs.
1634 if (!InstInfo.ImplicitDefs.empty()) {
1635 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001636
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001637 // FIXME: Generalize to multiple possible types and multiple possible
1638 // ImplicitDefs.
1639 MVT::SimpleValueType VT =
1640 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001641
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001642 if (VT != MVT::Other)
1643 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001644 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001645
Chris Lattnercabe0372010-03-15 06:00:16 +00001646 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1647 // be the same.
1648 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001649 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1650 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1651 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001652 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001653
1654 unsigned ChildNo = 0;
1655 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1656 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001657
Chris Lattner8cab0212008-01-05 22:25:12 +00001658 // If the instruction expects a predicate or optional def operand, we
1659 // codegen this by setting the operand to it's default value if it has a
1660 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001661 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001662 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1663 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001664
Chris Lattner8cab0212008-01-05 22:25:12 +00001665 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001666 if (ChildNo >= getNumChildren()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001667 TP.error("Instruction '" + getOperator()->getName() +
1668 "' expects more operands than were provided.");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001669 return false;
1670 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001671
Chris Lattner8cab0212008-01-05 22:25:12 +00001672 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001673 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001674
1675 // If the operand has sub-operands, they may be provided by distinct
1676 // child patterns, so attempt to match each sub-operand separately.
1677 if (OperandNode->isSubClassOf("Operand")) {
1678 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1679 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1680 // But don't do that if the whole operand is being provided by
1681 // a single ComplexPattern.
1682 const ComplexPattern *AM = Child->getComplexPatternInfo(CDP);
1683 if (!AM || AM->getNumOperands() < NumArgs) {
1684 // Match first sub-operand against the child we already have.
1685 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1686 MadeChange |=
1687 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1688
1689 // And the remaining sub-operands against subsequent children.
1690 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1691 if (ChildNo >= getNumChildren()) {
1692 TP.error("Instruction '" + getOperator()->getName() +
1693 "' expects more operands than were provided.");
1694 return false;
1695 }
1696 Child = getChild(ChildNo++);
1697
1698 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1699 MadeChange |=
1700 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1701 }
1702 continue;
1703 }
1704 }
1705 }
1706
1707 // If we didn't match by pieces above, attempt to match the whole
1708 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001709 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001710 }
Christopher Lamba7312392008-03-11 09:33:47 +00001711
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001712 if (ChildNo != getNumChildren()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001713 TP.error("Instruction '" + getOperator()->getName() +
1714 "' was provided too many operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001715 return false;
1716 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001717
Ulrich Weigande618abd2013-03-19 19:51:09 +00001718 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1719 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001720 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001721 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001722
Chris Lattneree820ac2010-02-23 05:51:07 +00001723 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001724
Chris Lattneree820ac2010-02-23 05:51:07 +00001725 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001726 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001727 TP.error("Node transform '" + getOperator()->getName() +
1728 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001729 return false;
1730 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001731
Chris Lattnercabe0372010-03-15 06:00:16 +00001732 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1733
Jim Grosbach65586fe2010-12-21 16:16:00 +00001734
Chris Lattneree820ac2010-02-23 05:51:07 +00001735 // If either the output or input of the xform does not have exact
1736 // type info. We assume they must be the same. Otherwise, it is perfectly
1737 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001738#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001739 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001740 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1741 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001742 return MadeChange;
1743 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001744#endif
1745 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001746}
1747
1748/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1749/// RHS of a commutative operation, not the on LHS.
1750static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1751 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1752 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001753 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001754 return true;
1755 return false;
1756}
1757
1758
1759/// canPatternMatch - If it is impossible for this pattern to match on this
1760/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00001761/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00001762/// that can never possibly work), and to prevent the pattern permuter from
1763/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001764bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00001765 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001766 if (isLeaf()) return true;
1767
1768 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1769 if (!getChild(i)->canPatternMatch(Reason, CDP))
1770 return false;
1771
1772 // If this is an intrinsic, handle cases that would make it not match. For
1773 // example, if an operand is required to be an immediate.
1774 if (getOperator()->isSubClassOf("Intrinsic")) {
1775 // TODO:
1776 return true;
1777 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001778
Chris Lattner8cab0212008-01-05 22:25:12 +00001779 // If this node is a commutative operator, check that the LHS isn't an
1780 // immediate.
1781 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00001782 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1783 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001784 // Scan all of the operands of the node and make sure that only the last one
1785 // is a constant node, unless the RHS also is.
1786 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng49bad4c2008-06-16 20:29:38 +00001787 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1788 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00001789 if (OnlyOnRHSOfCommutative(getChild(i))) {
1790 Reason="Immediate value must be on the RHS of commutative operators!";
1791 return false;
1792 }
1793 }
1794 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001795
Chris Lattner8cab0212008-01-05 22:25:12 +00001796 return true;
1797}
1798
1799//===----------------------------------------------------------------------===//
1800// TreePattern implementation
1801//
1802
David Greeneaf8ee2c2011-07-29 22:43:06 +00001803TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001804 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1805 isInputPattern(isInput), HasError(false) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001806 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001807 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001808}
1809
David Greeneaf8ee2c2011-07-29 22:43:06 +00001810TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001811 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1812 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001813 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001814}
1815
1816TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001817 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1818 isInputPattern(isInput), HasError(false) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001819 Trees.push_back(Pat);
1820}
1821
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001822void TreePattern::error(const std::string &Msg) {
1823 if (HasError)
1824 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00001825 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001826 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1827 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00001828}
1829
Chris Lattnercabe0372010-03-15 06:00:16 +00001830void TreePattern::ComputeNamedNodes() {
1831 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1832 ComputeNamedNodes(Trees[i]);
1833}
1834
1835void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1836 if (!N->getName().empty())
1837 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001838
Chris Lattnercabe0372010-03-15 06:00:16 +00001839 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1840 ComputeNamedNodes(N->getChild(i));
1841}
1842
Chris Lattnerf1447252010-03-19 21:37:09 +00001843
David Greeneaf8ee2c2011-07-29 22:43:06 +00001844TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00001845 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001846 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001847
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001848 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00001849 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001850 /// (foo GPR, imm) -> (foo GPR, (imm))
1851 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00001852 return ParseTreePattern(
1853 DagInit::get(DI, "",
David Greeneaf8ee2c2011-07-29 22:43:06 +00001854 std::vector<std::pair<Init*, std::string> >()),
David Greenee32ebf22011-07-29 19:07:07 +00001855 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001856
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001857 // Input argument?
1858 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00001859 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001860 if (OpName.empty())
1861 error("'node' argument requires a name to match with operand list");
1862 Args.push_back(OpName);
1863 }
1864
1865 Res->setName(OpName);
1866 return Res;
1867 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001868
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00001869 // ?:$name or just $name.
1870 if (TheInit == UnsetInit::get()) {
1871 if (OpName.empty())
1872 error("'?' argument requires a name to match with operand list");
1873 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
1874 Args.push_back(OpName);
1875 Res->setName(OpName);
1876 return Res;
1877 }
1878
Sean Silvafb509ed2012-10-10 20:24:43 +00001879 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001880 if (!OpName.empty())
1881 error("Constant int argument should not have a name!");
1882 return new TreePatternNode(II, 1);
1883 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001884
Sean Silvafb509ed2012-10-10 20:24:43 +00001885 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001886 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001887 Init *II = BI->convertInitializerTo(IntRecTy::get());
Sean Silva88eb8dd2012-10-10 20:24:47 +00001888 if (II == 0 || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001889 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00001890 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001891 }
1892
Sean Silvafb509ed2012-10-10 20:24:43 +00001893 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001894 if (!Dag) {
1895 TheInit->dump();
1896 error("Pattern has unexpected init kind!");
1897 }
Sean Silvafb509ed2012-10-10 20:24:43 +00001898 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001899 if (!OpDef) error("Pattern has unexpected operator type!");
1900 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001901
Chris Lattner8cab0212008-01-05 22:25:12 +00001902 if (Operator->isSubClassOf("ValueType")) {
1903 // If the operator is a ValueType, then this must be "type cast" of a leaf
1904 // node.
1905 if (Dag->getNumArgs() != 1)
1906 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001907
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001908 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00001909
Chris Lattner8cab0212008-01-05 22:25:12 +00001910 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00001911 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1912 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001913
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001914 if (!OpName.empty())
1915 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001916 return New;
1917 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001918
Chris Lattner8cab0212008-01-05 22:25:12 +00001919 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001920 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00001921 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00001922 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001923 !Operator->isSubClassOf("SDNodeXForm") &&
1924 !Operator->isSubClassOf("Intrinsic") &&
1925 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00001926 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00001927 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001928
Chris Lattner8cab0212008-01-05 22:25:12 +00001929 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00001930 if (isInputPattern) {
1931 if (Operator->isSubClassOf("Instruction") ||
1932 Operator->isSubClassOf("SDNodeXForm"))
1933 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1934 } else {
1935 if (Operator->isSubClassOf("Intrinsic"))
1936 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001937
Chris Lattner2e9eae12010-03-28 06:57:56 +00001938 if (Operator->isSubClassOf("SDNode") &&
1939 Operator->getName() != "imm" &&
1940 Operator->getName() != "fpimm" &&
1941 Operator->getName() != "tglobaltlsaddr" &&
1942 Operator->getName() != "tconstpool" &&
1943 Operator->getName() != "tjumptable" &&
1944 Operator->getName() != "tframeindex" &&
1945 Operator->getName() != "texternalsym" &&
1946 Operator->getName() != "tblockaddress" &&
1947 Operator->getName() != "tglobaladdr" &&
1948 Operator->getName() != "bb" &&
1949 Operator->getName() != "vt")
1950 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
1951 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001952
Chris Lattner8cab0212008-01-05 22:25:12 +00001953 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001954
1955 // Parse all the operands.
1956 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
1957 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00001958
Chris Lattner8cab0212008-01-05 22:25:12 +00001959 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00001960 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00001961 // convert the intrinsic name to a number.
1962 if (Operator->isSubClassOf("Intrinsic")) {
1963 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
1964 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
1965
1966 // If this intrinsic returns void, it must have side-effects and thus a
1967 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001968 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00001969 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001970 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00001971 // Has side-effects, requires chain.
1972 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001973 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00001974 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001975
David Greenee32ebf22011-07-29 19:07:07 +00001976 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00001977 Children.insert(Children.begin(), IIDNode);
1978 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001979
Chris Lattnerf1447252010-03-19 21:37:09 +00001980 unsigned NumResults = GetNumNodeResults(Operator, CDP);
1981 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001982 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001983
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001984 if (!Dag->getName().empty()) {
1985 assert(Result->getName().empty());
1986 Result->setName(Dag->getName());
1987 }
Nate Begemandbe3f772009-03-19 05:21:56 +00001988 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00001989}
1990
Chris Lattnera787c9e2010-03-28 08:38:32 +00001991/// SimplifyTree - See if we can simplify this tree to eliminate something that
1992/// will never match in favor of something obvious that will. This is here
1993/// strictly as a convenience to target authors because it allows them to write
1994/// more type generic things and have useless type casts fold away.
1995///
1996/// This returns true if any change is made.
1997static bool SimplifyTree(TreePatternNode *&N) {
1998 if (N->isLeaf())
1999 return false;
2000
2001 // If we have a bitconvert with a resolved type and if the source and
2002 // destination types are the same, then the bitconvert is useless, remove it.
2003 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002004 N->getExtType(0).isConcrete() &&
2005 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2006 N->getName().empty()) {
2007 N = N->getChild(0);
2008 SimplifyTree(N);
2009 return true;
2010 }
2011
2012 // Walk all children.
2013 bool MadeChange = false;
2014 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2015 TreePatternNode *Child = N->getChild(i);
2016 MadeChange |= SimplifyTree(Child);
2017 N->setChild(i, Child);
2018 }
2019 return MadeChange;
2020}
2021
2022
2023
Chris Lattner8cab0212008-01-05 22:25:12 +00002024/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002025/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002026/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002027bool TreePattern::
2028InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2029 if (NamedNodes.empty())
2030 ComputeNamedNodes();
2031
Chris Lattner8cab0212008-01-05 22:25:12 +00002032 bool MadeChange = true;
2033 while (MadeChange) {
2034 MadeChange = false;
Chris Lattnera787c9e2010-03-28 08:38:32 +00002035 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002036 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002037 MadeChange |= SimplifyTree(Trees[i]);
2038 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002039
2040 // If there are constraints on our named nodes, apply them.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002041 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattnercabe0372010-03-15 06:00:16 +00002042 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
2043 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002044
Chris Lattnercabe0372010-03-15 06:00:16 +00002045 // If we have input named node types, propagate their types to the named
2046 // values here.
2047 if (InNamedTypes) {
2048 // FIXME: Should be error?
2049 assert(InNamedTypes->count(I->getKey()) &&
2050 "Named node in output pattern but not input pattern?");
2051
2052 const SmallVectorImpl<TreePatternNode*> &InNodes =
2053 InNamedTypes->find(I->getKey())->second;
2054
2055 // The input types should be fully resolved by now.
2056 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2057 // If this node is a register class, and it is the root of the pattern
2058 // then we're mapping something onto an input register. We allow
2059 // changing the type of the input register in this case. This allows
2060 // us to match things like:
2061 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2062 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002063 DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002064 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2065 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002066 continue;
2067 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002068
Daniel Dunbard177edf2010-03-21 01:38:21 +00002069 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002070 InNodes[0]->getNumTypes() == 1 &&
2071 "FIXME: cannot name multiple result nodes yet");
2072 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
2073 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002074 }
2075 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002076
Chris Lattnercabe0372010-03-15 06:00:16 +00002077 // If there are multiple nodes with the same name, they must all have the
2078 // same type.
2079 if (I->second.size() > 1) {
2080 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002081 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002082 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002083 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002084
Chris Lattnerf1447252010-03-19 21:37:09 +00002085 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2086 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002087 }
2088 }
2089 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002090 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002091
Chris Lattner8cab0212008-01-05 22:25:12 +00002092 bool HasUnresolvedTypes = false;
2093 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2094 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
2095 return !HasUnresolvedTypes;
2096}
2097
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002098void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002099 OS << getRecord()->getName();
2100 if (!Args.empty()) {
2101 OS << "(" << Args[0];
2102 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2103 OS << ", " << Args[i];
2104 OS << ")";
2105 }
2106 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002107
Chris Lattner8cab0212008-01-05 22:25:12 +00002108 if (Trees.size() > 1)
2109 OS << "[\n";
2110 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2111 OS << "\t";
2112 Trees[i]->print(OS);
2113 OS << "\n";
2114 }
2115
2116 if (Trees.size() > 1)
2117 OS << "]\n";
2118}
2119
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002120void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002121
2122//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002123// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002124//
2125
Jim Grosbach65586fe2010-12-21 16:16:00 +00002126CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002127 Records(R), Target(R) {
2128
Dale Johannesenb842d522009-02-05 01:49:45 +00002129 Intrinsics = LoadIntrinsics(Records, false);
2130 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002131 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002132 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002133 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002134 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002135 ParseDefaultOperands();
2136 ParseInstructions();
2137 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002138
Chris Lattner8cab0212008-01-05 22:25:12 +00002139 // Generate variants. For example, commutative patterns can match
2140 // multiple ways. Add them to PatternsToMatch as well.
2141 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002142
2143 // Infer instruction flags. For example, we can detect loads,
2144 // stores, and side effects in many cases by examining an
2145 // instruction's pattern.
2146 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002147
2148 // Verify that instruction flags match the patterns.
2149 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002150}
2151
Chris Lattnerab3242f2008-01-06 01:10:31 +00002152CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramerc2dbd5d2009-08-23 10:39:21 +00002153 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner8cab0212008-01-05 22:25:12 +00002154 E = PatternFragments.end(); I != E; ++I)
2155 delete I->second;
2156}
2157
2158
Chris Lattnerab3242f2008-01-06 01:10:31 +00002159Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002160 Record *N = Records.getDef(Name);
2161 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002162 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner8cab0212008-01-05 22:25:12 +00002163 exit(1);
2164 }
2165 return N;
2166}
2167
2168// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002169void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002170 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2171 while (!Nodes.empty()) {
2172 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2173 Nodes.pop_back();
2174 }
2175
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002176 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002177 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2178 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2179 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2180}
2181
2182/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2183/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002184void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002185 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2186 while (!Xforms.empty()) {
2187 Record *XFormNode = Xforms.back();
2188 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00002189 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002190 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002191
2192 Xforms.pop_back();
2193 }
2194}
2195
Chris Lattnerab3242f2008-01-06 01:10:31 +00002196void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002197 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2198 while (!AMs.empty()) {
2199 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2200 AMs.pop_back();
2201 }
2202}
2203
2204
2205/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2206/// file, building up the PatternFragments map. After we've collected them all,
2207/// inline fragments together as necessary, so that there are no references left
2208/// inside a pattern fragment to a pattern fragment.
2209///
Chris Lattnerab3242f2008-01-06 01:10:31 +00002210void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002211 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002212
Chris Lattnere7170df2008-01-05 22:43:57 +00002213 // First step, parse all of the fragments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002214 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00002215 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattner8cab0212008-01-05 22:25:12 +00002216 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2217 PatternFragments[Fragments[i]] = P;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002218
Chris Lattnere7170df2008-01-05 22:43:57 +00002219 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002220 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002221 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002222
Chris Lattnere7170df2008-01-05 22:43:57 +00002223 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002224 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002225
Chris Lattner8cab0212008-01-05 22:25:12 +00002226 // Parse the operands list.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002227 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002228 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002229 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002230 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002231 if (!OpsOp ||
2232 (OpsOp->getDef()->getName() != "ops" &&
2233 OpsOp->getDef()->getName() != "outs" &&
2234 OpsOp->getDef()->getName() != "ins"))
2235 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002236
2237 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002238 Args.clear();
2239 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002240 if (!isa<DefInit>(OpsList->getArg(j)) ||
2241 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002242 P->error("Operands list should all be 'node' values.");
2243 if (OpsList->getArgName(j).empty())
2244 P->error("Operands list should have names for each operand!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002245 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner8cab0212008-01-05 22:25:12 +00002246 P->error("'" + OpsList->getArgName(j) +
2247 "' does not occur in pattern or was multiply specified!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002248 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner8cab0212008-01-05 22:25:12 +00002249 Args.push_back(OpsList->getArgName(j));
2250 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002251
Chris Lattnere7170df2008-01-05 22:43:57 +00002252 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002253 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002254 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002255
Chris Lattnere7170df2008-01-05 22:43:57 +00002256 // If there is a code init for this fragment, keep track of the fact that
2257 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002258 TreePredicateFn PredFn(P);
2259 if (!PredFn.isAlwaysTrue())
2260 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002261
Chris Lattner8cab0212008-01-05 22:25:12 +00002262 // If there is a node transformation corresponding to this, keep track of
2263 // it.
2264 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2265 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2266 P->getOnlyTree()->setTransformFn(Transform);
2267 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002268
Chris Lattner8cab0212008-01-05 22:25:12 +00002269 // Now that we've parsed all of the tree fragments, do a closure on them so
2270 // that there are not references to PatFrags left inside of them.
Chris Lattner2e253b42008-06-30 03:02:03 +00002271 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2272 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner8cab0212008-01-05 22:25:12 +00002273 ThePat->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002274
Chris Lattner8cab0212008-01-05 22:25:12 +00002275 // Infer as many types as possible. Don't worry about it if we don't infer
2276 // all of them, some may depend on the inputs of the pattern.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002277 ThePat->InferAllTypes();
2278 ThePat->resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002279
Chris Lattner8cab0212008-01-05 22:25:12 +00002280 // If debugging, print out the pattern fragment result.
2281 DEBUG(ThePat->dump());
2282 }
2283}
2284
Chris Lattnerab3242f2008-01-06 01:10:31 +00002285void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002286 std::vector<Record*> DefaultOps;
2287 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002288
2289 // Find some SDNode.
2290 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002291 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002292
Tom Stellardb7246a72012-09-06 14:15:52 +00002293 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2294 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002295
Tom Stellardb7246a72012-09-06 14:15:52 +00002296 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2297 // SomeSDnode so that we can parse this.
2298 std::vector<std::pair<Init*, std::string> > Ops;
2299 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2300 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2301 DefaultInfo->getArgName(op)));
2302 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002303
Tom Stellardb7246a72012-09-06 14:15:52 +00002304 // Create a TreePattern to parse this.
2305 TreePattern P(DefaultOps[i], DI, false, *this);
2306 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002307
Tom Stellardb7246a72012-09-06 14:15:52 +00002308 // Copy the operands over into a DAGDefaultOperand.
2309 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002310
Tom Stellardb7246a72012-09-06 14:15:52 +00002311 TreePatternNode *T = P.getTree(0);
2312 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2313 TreePatternNode *TPN = T->getChild(op);
2314 while (TPN->ApplyTypeConstraints(P, false))
2315 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002316
Tom Stellardb7246a72012-09-06 14:15:52 +00002317 if (TPN->ContainsUnresolvedType()) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002318 PrintFatalError("Value #" + utostr(i) + " of OperandWithDefaultOps '" +
2319 DefaultOps[i]->getName() +"' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002320 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002321 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002322 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002323
2324 // Insert it into the DefaultOperands map so we can find it later.
2325 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002326 }
2327}
2328
2329/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2330/// instruction input. Return true if this is a real use.
2331static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002332 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002333 // No name -> not interesting.
2334 if (Pat->getName().empty()) {
2335 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002336 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002337 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2338 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002339 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002340 }
2341 return false;
2342 }
2343
2344 Record *Rec;
2345 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002346 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002347 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2348 Rec = DI->getDef();
2349 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002350 Rec = Pat->getOperator();
2351 }
2352
2353 // SRCVALUE nodes are ignored.
2354 if (Rec->getName() == "srcvalue")
2355 return false;
2356
2357 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2358 if (!Slot) {
2359 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002360 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002361 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002362 Record *SlotRec;
2363 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002364 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002365 } else {
2366 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2367 SlotRec = Slot->getOperator();
2368 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002369
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002370 // Ensure that the inputs agree if we've already seen this input.
2371 if (Rec != SlotRec)
2372 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002373 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002374 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002375 return true;
2376}
2377
2378/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2379/// part of "I", the instruction), computing the set of inputs and outputs of
2380/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002381void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002382FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2383 std::map<std::string, TreePatternNode*> &InstInputs,
2384 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002385 std::vector<Record*> &InstImpResults) {
2386 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002387 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002388 if (!isUse && Pat->getTransformFn())
2389 I->error("Cannot specify a transform function for a non-input value!");
2390 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002391 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002392
Chris Lattnerf2d70992010-02-17 06:53:36 +00002393 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002394 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2395 TreePatternNode *Dest = Pat->getChild(i);
2396 if (!Dest->isLeaf())
2397 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002398
Sean Silvafb509ed2012-10-10 20:24:43 +00002399 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002400 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2401 I->error("implicitly defined value should be a register!");
2402 InstImpResults.push_back(Val->getDef());
2403 }
2404 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002405 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002406
Chris Lattnerf2d70992010-02-17 06:53:36 +00002407 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002408 // If this is not a set, verify that the children nodes are not void typed,
2409 // and recurse.
2410 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002411 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002412 I->error("Cannot have void nodes inside of patterns!");
2413 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002414 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002415 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002416
Chris Lattner8cab0212008-01-05 22:25:12 +00002417 // If this is a non-leaf node with no children, treat it basically as if
2418 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002419 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002420
Chris Lattner8cab0212008-01-05 22:25:12 +00002421 if (!isUse && Pat->getTransformFn())
2422 I->error("Cannot specify a transform function for a non-input value!");
2423 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002424 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002425
Chris Lattner8cab0212008-01-05 22:25:12 +00002426 // Otherwise, this is a set, validate and collect instruction results.
2427 if (Pat->getNumChildren() == 0)
2428 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002429
Chris Lattner8cab0212008-01-05 22:25:12 +00002430 if (Pat->getTransformFn())
2431 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002432
Chris Lattner8cab0212008-01-05 22:25:12 +00002433 // Check the set destinations.
2434 unsigned NumDests = Pat->getNumChildren()-1;
2435 for (unsigned i = 0; i != NumDests; ++i) {
2436 TreePatternNode *Dest = Pat->getChild(i);
2437 if (!Dest->isLeaf())
2438 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002439
Sean Silvafb509ed2012-10-10 20:24:43 +00002440 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002441 if (!Val)
2442 I->error("set destination should be a register!");
2443
2444 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002445 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002446 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002447 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002448 if (Dest->getName().empty())
2449 I->error("set destination must have a name!");
2450 if (InstResults.count(Dest->getName()))
2451 I->error("cannot set '" + Dest->getName() +"' multiple times");
2452 InstResults[Dest->getName()] = Dest;
2453 } else if (Val->getDef()->isSubClassOf("Register")) {
2454 InstImpResults.push_back(Val->getDef());
2455 } else {
2456 I->error("set destination should be a register!");
2457 }
2458 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002459
Chris Lattner8cab0212008-01-05 22:25:12 +00002460 // Verify and collect info from the computation.
2461 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002462 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002463}
2464
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002465//===----------------------------------------------------------------------===//
2466// Instruction Analysis
2467//===----------------------------------------------------------------------===//
2468
2469class InstAnalyzer {
2470 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002471public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002472 bool hasSideEffects;
2473 bool mayStore;
2474 bool mayLoad;
2475 bool isBitcast;
2476 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002477
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002478 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2479 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2480 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002481
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002482 void Analyze(const TreePattern *Pat) {
2483 // Assume only the first tree is the pattern. The others are clobber nodes.
2484 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002485 }
2486
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002487 void Analyze(const PatternToMatch *Pat) {
2488 AnalyzeNode(Pat->getSrcPattern());
2489 }
2490
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002491private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002492 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002493 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002494 return false;
2495
2496 if (N->getNumChildren() != 2)
2497 return false;
2498
2499 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002500 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002501 return false;
2502
2503 const TreePatternNode *N1 = N->getChild(1);
2504 if (N1->isLeaf())
2505 return false;
2506 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2507 return false;
2508
2509 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2510 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2511 return false;
2512 return OpInfo.getEnumName() == "ISD::BITCAST";
2513 }
2514
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002515public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002516 void AnalyzeNode(const TreePatternNode *N) {
2517 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002518 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002519 Record *LeafRec = DI->getDef();
2520 // Handle ComplexPattern leaves.
2521 if (LeafRec->isSubClassOf("ComplexPattern")) {
2522 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2523 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2524 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002525 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002526 }
2527 }
2528 return;
2529 }
2530
2531 // Analyze children.
2532 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2533 AnalyzeNode(N->getChild(i));
2534
2535 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002536 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002537 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002538 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002539 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002540
2541 // Get information about the SDNode for the operator.
2542 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2543
2544 // Notice properties of the node.
2545 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2546 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002547 if (OpInfo.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2548 if (OpInfo.hasProperty(SDNPVariadic)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002549
2550 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2551 // If this is an intrinsic, analyze it.
2552 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2553 mayLoad = true;// These may load memory.
2554
Dan Gohmanddb2d652010-08-05 23:36:21 +00002555 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002556 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2557
Dan Gohmanddb2d652010-08-05 23:36:21 +00002558 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002559 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002560 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002561 }
2562 }
2563
2564};
2565
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002566static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002567 const InstAnalyzer &PatInfo,
2568 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002569 bool Error = false;
2570
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002571 // Remember where InstInfo got its flags.
2572 if (InstInfo.hasUndefFlags())
2573 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002574
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002575 // Check explicitly set flags for consistency.
2576 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2577 !InstInfo.hasSideEffects_Unset) {
2578 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2579 // the pattern has no side effects. That could be useful for div/rem
2580 // instructions that may trap.
2581 if (!InstInfo.hasSideEffects) {
2582 Error = true;
2583 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2584 Twine(InstInfo.hasSideEffects));
2585 }
2586 }
2587
2588 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2589 Error = true;
2590 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2591 Twine(InstInfo.mayStore));
2592 }
2593
2594 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2595 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2596 // Some targets translate imediates to loads.
2597 if (!InstInfo.mayLoad) {
2598 Error = true;
2599 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2600 Twine(InstInfo.mayLoad));
2601 }
2602 }
2603
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002604 // Transfer inferred flags.
2605 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2606 InstInfo.mayStore |= PatInfo.mayStore;
2607 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002608
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002609 // These flags are silently added without any verification.
2610 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002611
2612 // Don't infer isVariadic. This flag means something different on SDNodes and
2613 // instructions. For example, a CALL SDNode is variadic because it has the
2614 // call arguments as operands, but a CALL instruction is not variadic - it
2615 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002616
2617 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002618}
2619
Jim Grosbach514410b2012-07-17 00:47:06 +00002620/// hasNullFragReference - Return true if the DAG has any reference to the
2621/// null_frag operator.
2622static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002623 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002624 if (!OpDef) return false;
2625 Record *Operator = OpDef->getDef();
2626
2627 // If this is the null fragment, return true.
2628 if (Operator->getName() == "null_frag") return true;
2629 // If any of the arguments reference the null fragment, return true.
2630 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002631 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002632 if (Arg && hasNullFragReference(Arg))
2633 return true;
2634 }
2635
2636 return false;
2637}
2638
2639/// hasNullFragReference - Return true if any DAG in the list references
2640/// the null_frag operator.
2641static bool hasNullFragReference(ListInit *LI) {
2642 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002643 DagInit *DI = dyn_cast<DagInit>(LI->getElement(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002644 assert(DI && "non-dag in an instruction Pattern list?!");
2645 if (hasNullFragReference(DI))
2646 return true;
2647 }
2648 return false;
2649}
2650
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002651/// Get all the instructions in a tree.
2652static void
2653getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2654 if (Tree->isLeaf())
2655 return;
2656 if (Tree->getOperator()->isSubClassOf("Instruction"))
2657 Instrs.push_back(Tree->getOperator());
2658 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2659 getInstructionsInTree(Tree->getChild(i), Instrs);
2660}
2661
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002662/// Check the class of a pattern leaf node against the instruction operand it
2663/// represents.
2664static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2665 Record *Leaf) {
2666 if (OI.Rec == Leaf)
2667 return true;
2668
2669 // Allow direct value types to be used in instruction set patterns.
2670 // The type will be checked later.
2671 if (Leaf->isSubClassOf("ValueType"))
2672 return true;
2673
2674 // Patterns can also be ComplexPattern instances.
2675 if (Leaf->isSubClassOf("ComplexPattern"))
2676 return true;
2677
2678 return false;
2679}
2680
Ahmed Bougacha14107512013-10-28 18:07:21 +00002681const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2682 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002683
Ahmed Bougacha14107512013-10-28 18:07:21 +00002684 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002685
Chris Lattner8cab0212008-01-05 22:25:12 +00002686 // Parse the instruction.
Ahmed Bougacha14107512013-10-28 18:07:21 +00002687 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002688 // Inline pattern fragments into it.
2689 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002690
Chris Lattner8cab0212008-01-05 22:25:12 +00002691 // Infer as many types as possible. If we cannot infer all of them, we can
2692 // never do anything with this instruction pattern: report it to the user.
2693 if (!I->InferAllTypes())
2694 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002695
2696 // InstInputs - Keep track of all of the inputs of the instruction, along
Chris Lattner8cab0212008-01-05 22:25:12 +00002697 // with the record they are declared as.
2698 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002699
Chris Lattner8cab0212008-01-05 22:25:12 +00002700 // InstResults - Keep track of all the virtual registers that are 'set'
2701 // in the instruction, including what reg class they are.
2702 std::map<std::string, TreePatternNode*> InstResults;
2703
Chris Lattner8cab0212008-01-05 22:25:12 +00002704 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002705
Chris Lattner8cab0212008-01-05 22:25:12 +00002706 // Verify that the top-level forms in the instruction are of void type, and
2707 // fill in the InstResults map.
2708 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2709 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerf1447252010-03-19 21:37:09 +00002710 if (Pat->getNumTypes() != 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002711 I->error("Top-level forms in instruction pattern should have"
2712 " void types");
2713
2714 // Find inputs and outputs, and verify the structure of the uses/defs.
2715 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002716 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002717 }
2718
2719 // Now that we have inputs and outputs of the pattern, inspect the operands
2720 // list for the instruction. This determines the order that operands are
2721 // added to the machine instruction the node corresponds to.
2722 unsigned NumResults = InstResults.size();
2723
2724 // Parse the operands list from the (ops) list, validating it.
2725 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002726
2727 // Check that all of the results occur first in the list.
2728 std::vector<Record*> Results;
Chris Lattnerf1447252010-03-19 21:37:09 +00002729 TreePatternNode *Res0Node = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00002730 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattnerd8adec72010-11-01 04:03:32 +00002731 if (i == CGI.Operands.size())
Chris Lattner8cab0212008-01-05 22:25:12 +00002732 I->error("'" + InstResults.begin()->first +
2733 "' set but does not appear in operand list!");
Chris Lattnerd8adec72010-11-01 04:03:32 +00002734 const std::string &OpName = CGI.Operands[i].Name;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002735
Chris Lattner8cab0212008-01-05 22:25:12 +00002736 // Check that it exists in InstResults.
2737 TreePatternNode *RNode = InstResults[OpName];
2738 if (RNode == 0)
2739 I->error("Operand $" + OpName + " does not exist in operand list!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002740
Chris Lattner8cab0212008-01-05 22:25:12 +00002741 if (i == 0)
2742 Res0Node = RNode;
Sean Silva88eb8dd2012-10-10 20:24:47 +00002743 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
Chris Lattner8cab0212008-01-05 22:25:12 +00002744 if (R == 0)
2745 I->error("Operand $" + OpName + " should be a set destination: all "
2746 "outputs must occur before inputs in operand list!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002747
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002748 if (!checkOperandClass(CGI.Operands[i], R))
Chris Lattner8cab0212008-01-05 22:25:12 +00002749 I->error("Operand $" + OpName + " class mismatch!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002750
Chris Lattner8cab0212008-01-05 22:25:12 +00002751 // Remember the return type.
Chris Lattnerd8adec72010-11-01 04:03:32 +00002752 Results.push_back(CGI.Operands[i].Rec);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002753
Chris Lattner8cab0212008-01-05 22:25:12 +00002754 // Okay, this one checks out.
2755 InstResults.erase(OpName);
2756 }
2757
2758 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2759 // the copy while we're checking the inputs.
2760 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2761
2762 std::vector<TreePatternNode*> ResultNodeOperands;
2763 std::vector<Record*> Operands;
Chris Lattnerd8adec72010-11-01 04:03:32 +00002764 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2765 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
Chris Lattner8cab0212008-01-05 22:25:12 +00002766 const std::string &OpName = Op.Name;
2767 if (OpName.empty())
2768 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2769
2770 if (!InstInputsCheck.count(OpName)) {
Tom Stellardb7246a72012-09-06 14:15:52 +00002771 // If this is an operand with a DefaultOps set filled in, we can ignore
2772 // this. When we codegen it, we will do so as always executed.
2773 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002774 // Does it have a non-empty DefaultOps field? If so, ignore this
2775 // operand.
2776 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2777 continue;
2778 }
2779 I->error("Operand $" + OpName +
2780 " does not appear in the instruction pattern");
2781 }
2782 TreePatternNode *InVal = InstInputsCheck[OpName];
2783 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002784
Sean Silva88eb8dd2012-10-10 20:24:47 +00002785 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00002786 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002787 if (!checkOperandClass(Op, InRec))
Chris Lattner8cab0212008-01-05 22:25:12 +00002788 I->error("Operand $" + OpName + "'s register class disagrees"
2789 " between the operand and pattern");
2790 }
2791 Operands.push_back(Op.Rec);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002792
Chris Lattner8cab0212008-01-05 22:25:12 +00002793 // Construct the result for the dest-pattern operand list.
2794 TreePatternNode *OpNode = InVal->clone();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002795
Chris Lattner8cab0212008-01-05 22:25:12 +00002796 // No predicate is useful on the result.
Dan Gohman6e979022008-10-15 06:17:21 +00002797 OpNode->clearPredicateFns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002798
Chris Lattner8cab0212008-01-05 22:25:12 +00002799 // Promote the xform function to be an explicit node if set.
2800 if (Record *Xform = OpNode->getTransformFn()) {
2801 OpNode->setTransformFn(0);
2802 std::vector<TreePatternNode*> Children;
2803 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00002804 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00002805 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002806
Chris Lattner8cab0212008-01-05 22:25:12 +00002807 ResultNodeOperands.push_back(OpNode);
2808 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002809
Chris Lattner8cab0212008-01-05 22:25:12 +00002810 if (!InstInputsCheck.empty())
2811 I->error("Input operand $" + InstInputsCheck.begin()->first +
2812 " occurs in pattern but not in operands list!");
2813
2814 TreePatternNode *ResultPattern =
Chris Lattnerf1447252010-03-19 21:37:09 +00002815 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2816 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner8cab0212008-01-05 22:25:12 +00002817 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerf1447252010-03-19 21:37:09 +00002818 for (unsigned i = 0; i != NumResults; ++i)
2819 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner8cab0212008-01-05 22:25:12 +00002820
2821 // Create and insert the instruction.
Chris Lattner5debc332010-04-20 06:30:25 +00002822 // FIXME: InstImpResults should not be part of DAGInstruction.
Chris Lattner9dc68d32010-04-20 06:28:43 +00002823 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00002824 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
Chris Lattner8cab0212008-01-05 22:25:12 +00002825
2826 // Use a temporary tree pattern to infer all types and make sure that the
2827 // constructed result is correct. This depends on the instruction already
Ahmed Bougacha14107512013-10-28 18:07:21 +00002828 // being inserted into the DAGInsts map.
Chris Lattner8cab0212008-01-05 22:25:12 +00002829 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002830 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00002831
Ahmed Bougacha14107512013-10-28 18:07:21 +00002832 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
Chris Lattner8cab0212008-01-05 22:25:12 +00002833 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002834
Ahmed Bougacha14107512013-10-28 18:07:21 +00002835 return TheInsertedInst;
2836 }
2837
2838/// ParseInstructions - Parse all of the instructions, inlining and resolving
2839/// any fragments involved. This populates the Instructions list with fully
2840/// resolved instructions.
2841void CodeGenDAGPatterns::ParseInstructions() {
2842 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2843
2844 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2845 ListInit *LI = 0;
2846
2847 if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
2848 LI = Instrs[i]->getValueAsListInit("Pattern");
2849
2850 // If there is no pattern, only collect minimal information about the
2851 // instruction for its operand list. We have to assume that there is one
2852 // result, as we have no detailed info. A pattern which references the
2853 // null_frag operator is as-if no pattern were specified. Normally this
2854 // is from a multiclass expansion w/ a SDPatternOperator passed in as
2855 // null_frag.
2856 if (!LI || LI->getSize() == 0 || hasNullFragReference(LI)) {
2857 std::vector<Record*> Results;
2858 std::vector<Record*> Operands;
2859
2860 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2861
2862 if (InstInfo.Operands.size() != 0) {
2863 if (InstInfo.Operands.NumDefs == 0) {
2864 // These produce no results
2865 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2866 Operands.push_back(InstInfo.Operands[j].Rec);
2867 } else {
2868 // Assume the first operand is the result.
2869 Results.push_back(InstInfo.Operands[0].Rec);
2870
2871 // The rest are inputs.
2872 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2873 Operands.push_back(InstInfo.Operands[j].Rec);
2874 }
2875 }
2876
2877 // Create and insert the instruction.
2878 std::vector<Record*> ImpResults;
2879 Instructions.insert(std::make_pair(Instrs[i],
2880 DAGInstruction(0, Results, Operands, ImpResults)));
2881 continue; // no pattern.
2882 }
2883
2884 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2885 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
2886
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00002887 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00002888 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002889 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002890
Chris Lattner8cab0212008-01-05 22:25:12 +00002891 // If we can, convert the instructions to be patterns that are matched!
Sean Silvaa4e2c5f2012-09-19 01:47:00 +00002892 for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
Benjamin Kramerc2dbd5d2009-08-23 10:39:21 +00002893 Instructions.begin(),
Chris Lattner8cab0212008-01-05 22:25:12 +00002894 E = Instructions.end(); II != E; ++II) {
2895 DAGInstruction &TheInst = II->second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002896 TreePattern *I = TheInst.getPattern();
Chris Lattner8cab0212008-01-05 22:25:12 +00002897 if (I == 0) continue; // No pattern.
2898
2899 // FIXME: Assume only the first tree is the pattern. The others are clobber
2900 // nodes.
2901 TreePatternNode *Pattern = I->getTree(0);
2902 TreePatternNode *SrcPattern;
2903 if (Pattern->getOperator()->getName() == "set") {
2904 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2905 } else{
2906 // Not a set (store or something?)
2907 SrcPattern = Pattern;
2908 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002909
Chris Lattner8cab0212008-01-05 22:25:12 +00002910 Record *Instr = II->first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00002911 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00002912 PatternToMatch(Instr,
2913 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00002914 SrcPattern,
2915 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00002916 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00002917 Instr->getValueAsInt("AddedComplexity"),
2918 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00002919 }
2920}
2921
Chris Lattnera7722b62010-02-23 06:55:24 +00002922
2923typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2924
Jim Grosbach65586fe2010-12-21 16:16:00 +00002925static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00002926 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002927 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00002928 if (!P->getName().empty()) {
2929 NameRecord &Rec = Names[P->getName()];
2930 // If this is the first instance of the name, remember the node.
2931 if (Rec.second++ == 0)
2932 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00002933 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00002934 PatternTop->error("repetition of value: $" + P->getName() +
2935 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00002936 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002937
Chris Lattner94d3b0a2010-02-23 06:35:45 +00002938 if (!P->isLeaf()) {
2939 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00002940 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00002941 }
2942}
2943
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002944void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner0c0baa92010-02-23 06:16:51 +00002945 const PatternToMatch &PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00002946 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00002947 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00002948 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
2949 PrintWarning(Pattern->getRecord()->getLoc(),
2950 Twine("Pattern can never match: ") + Reason);
2951 return;
2952 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002953
Chris Lattner1e634e32010-03-01 22:29:19 +00002954 // If the source pattern's root is a complex pattern, that complex pattern
2955 // must specify the nodes it can potentially match.
2956 if (const ComplexPattern *CP =
2957 PTM.getSrcPattern()->getComplexPatternInfo(*this))
2958 if (CP->getRootNodes().empty())
2959 Pattern->error("ComplexPattern at root must specify list of opcodes it"
2960 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002961
2962
Chris Lattner94d3b0a2010-02-23 06:35:45 +00002963 // Find all of the named values in the input and output, ensure they have the
2964 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00002965 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00002966 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
2967 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00002968
2969 // Scan all of the named values in the destination pattern, rejecting them if
2970 // they don't exist in the input pattern.
Chris Lattnera7722b62010-02-23 06:55:24 +00002971 for (std::map<std::string, NameRecord>::iterator
Chris Lattner4b9225b2010-02-23 07:50:58 +00002972 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattnera7722b62010-02-23 06:55:24 +00002973 if (SrcNames[I->first].first == 0)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00002974 Pattern->error("Pattern has input without matching name in output: $" +
2975 I->first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00002976 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002977
Chris Lattnera7722b62010-02-23 06:55:24 +00002978 // Scan all of the named values in the source pattern, rejecting them if the
2979 // name isn't used in the dest, and isn't used to tie two values together.
2980 for (std::map<std::string, NameRecord>::iterator
2981 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
2982 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
2983 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002984
Chris Lattner0c0baa92010-02-23 06:16:51 +00002985 PatternsToMatch.push_back(PTM);
2986}
2987
2988
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002989
2990void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattner918be522010-03-19 00:34:35 +00002991 const std::vector<const CodeGenInstruction*> &Instructions =
2992 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002993
2994 // First try to infer flags from the primary instruction pattern, if any.
2995 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002996 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00002997 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
2998 CodeGenInstruction &InstInfo =
2999 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003000
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003001 // Treat neverHasSideEffects = 1 as the equivalent of hasSideEffects = 0.
3002 // This flag is obsolete and will be removed.
3003 if (InstInfo.neverHasSideEffects) {
3004 assert(!InstInfo.hasSideEffects);
3005 InstInfo.hasSideEffects_Unset = false;
3006 }
3007
3008 // Get the primary instruction pattern.
3009 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3010 if (!Pattern) {
3011 if (InstInfo.hasUndefFlags())
3012 Revisit.push_back(&InstInfo);
3013 continue;
3014 }
3015 InstAnalyzer PatInfo(*this);
3016 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003017 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003018 }
3019
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003020 // Second, look for single-instruction patterns defined outside the
3021 // instruction.
3022 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3023 const PatternToMatch &PTM = *I;
3024
3025 // We can only infer from single-instruction patterns, otherwise we won't
3026 // know which instruction should get the flags.
3027 SmallVector<Record*, 8> PatInstrs;
3028 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3029 if (PatInstrs.size() != 1)
3030 continue;
3031
3032 // Get the single instruction.
3033 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3034
3035 // Only infer properties from the first pattern. We'll verify the others.
3036 if (InstInfo.InferredFrom)
3037 continue;
3038
3039 InstAnalyzer PatInfo(*this);
3040 PatInfo.Analyze(&PTM);
3041 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3042 }
3043
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003044 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003045 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003046
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003047 // Revisit instructions with undefined flags and no pattern.
3048 if (Target.guessInstructionProperties()) {
3049 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3050 CodeGenInstruction &InstInfo = *Revisit[i];
3051 if (InstInfo.InferredFrom)
3052 continue;
3053 // The mayLoad and mayStore flags default to false.
3054 // Conservatively assume hasSideEffects if it wasn't explicit.
3055 if (InstInfo.hasSideEffects_Unset)
3056 InstInfo.hasSideEffects = true;
3057 }
3058 return;
3059 }
3060
3061 // Complain about any flags that are still undefined.
3062 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3063 CodeGenInstruction &InstInfo = *Revisit[i];
3064 if (InstInfo.InferredFrom)
3065 continue;
3066 if (InstInfo.hasSideEffects_Unset)
3067 PrintError(InstInfo.TheDef->getLoc(),
3068 "Can't infer hasSideEffects from patterns");
3069 if (InstInfo.mayStore_Unset)
3070 PrintError(InstInfo.TheDef->getLoc(),
3071 "Can't infer mayStore from patterns");
3072 if (InstInfo.mayLoad_Unset)
3073 PrintError(InstInfo.TheDef->getLoc(),
3074 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003075 }
3076}
3077
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003078
3079/// Verify instruction flags against pattern node properties.
3080void CodeGenDAGPatterns::VerifyInstructionFlags() {
3081 unsigned Errors = 0;
3082 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3083 const PatternToMatch &PTM = *I;
3084 SmallVector<Record*, 8> Instrs;
3085 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3086 if (Instrs.empty())
3087 continue;
3088
3089 // Count the number of instructions with each flag set.
3090 unsigned NumSideEffects = 0;
3091 unsigned NumStores = 0;
3092 unsigned NumLoads = 0;
3093 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3094 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3095 NumSideEffects += InstInfo.hasSideEffects;
3096 NumStores += InstInfo.mayStore;
3097 NumLoads += InstInfo.mayLoad;
3098 }
3099
3100 // Analyze the source pattern.
3101 InstAnalyzer PatInfo(*this);
3102 PatInfo.Analyze(&PTM);
3103
3104 // Collect error messages.
3105 SmallVector<std::string, 4> Msgs;
3106
3107 // Check for missing flags in the output.
3108 // Permit extra flags for now at least.
3109 if (PatInfo.hasSideEffects && !NumSideEffects)
3110 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3111
3112 // Don't verify store flags on instructions with side effects. At least for
3113 // intrinsics, side effects implies mayStore.
3114 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3115 Msgs.push_back("pattern may store, but mayStore isn't set");
3116
3117 // Similarly, mayStore implies mayLoad on intrinsics.
3118 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3119 Msgs.push_back("pattern may load, but mayLoad isn't set");
3120
3121 // Print error messages.
3122 if (Msgs.empty())
3123 continue;
3124 ++Errors;
3125
3126 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
3127 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
3128 (Instrs.size() == 1 ?
3129 "instruction" : "output instructions"));
3130 // Provide the location of the relevant instruction definitions.
3131 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3132 if (Instrs[i] != PTM.getSrcRecord())
3133 PrintError(Instrs[i]->getLoc(), "defined here");
3134 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3135 if (InstInfo.InferredFrom &&
3136 InstInfo.InferredFrom != InstInfo.TheDef &&
3137 InstInfo.InferredFrom != PTM.getSrcRecord())
3138 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from patttern");
3139 }
3140 }
3141 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003142 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003143}
3144
Chris Lattnercabe0372010-03-15 06:00:16 +00003145/// Given a pattern result with an unresolved type, see if we can find one
3146/// instruction with an unresolved result type. Force this result type to an
3147/// arbitrary element if it's possible types to converge results.
3148static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3149 if (N->isLeaf())
3150 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003151
Chris Lattnercabe0372010-03-15 06:00:16 +00003152 // Analyze children.
3153 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3154 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3155 return true;
3156
3157 if (!N->getOperator()->isSubClassOf("Instruction"))
3158 return false;
3159
3160 // If this type is already concrete or completely unknown we can't do
3161 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003162 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3163 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3164 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003165
Chris Lattnerf1447252010-03-19 21:37:09 +00003166 // Otherwise, force its type to the first possibility (an arbitrary choice).
3167 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3168 return true;
3169 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003170
Chris Lattnerf1447252010-03-19 21:37:09 +00003171 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003172}
3173
Chris Lattnerab3242f2008-01-06 01:10:31 +00003174void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003175 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3176
3177 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00003178 Record *CurPattern = Patterns[i];
David Greeneaf8ee2c2011-07-29 22:43:06 +00003179 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003180
3181 // If the pattern references the null_frag, there's nothing to do.
3182 if (hasNullFragReference(Tree))
3183 continue;
3184
Chris Lattner5c2182e2010-03-27 02:53:27 +00003185 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003186
3187 // Inline pattern fragments into it.
3188 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003189
David Greeneaf8ee2c2011-07-29 22:43:06 +00003190 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner8cab0212008-01-05 22:25:12 +00003191 if (LI->getSize() == 0) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003192
Chris Lattner8cab0212008-01-05 22:25:12 +00003193 // Parse the instruction.
Chris Lattnerf1447252010-03-19 21:37:09 +00003194 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003195
Chris Lattner8cab0212008-01-05 22:25:12 +00003196 // Inline pattern fragments into it.
3197 Result->InlinePatternFragments();
3198
3199 if (Result->getNumTrees() != 1)
3200 Result->error("Cannot handle instructions producing instructions "
3201 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003202
Chris Lattner8cab0212008-01-05 22:25:12 +00003203 bool IterateInference;
3204 bool InferredAllPatternTypes, InferredAllResultTypes;
3205 do {
3206 // Infer as many types as possible. If we cannot infer all of them, we
3207 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003208 InferredAllPatternTypes =
3209 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003210
Chris Lattner8cab0212008-01-05 22:25:12 +00003211 // Infer as many types as possible. If we cannot infer all of them, we
3212 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003213 InferredAllResultTypes =
3214 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003215
Chris Lattnerfdc20712010-03-18 23:15:10 +00003216 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003217
Chris Lattner8cab0212008-01-05 22:25:12 +00003218 // Apply the type of the result to the source pattern. This helps us
3219 // resolve cases where the input type is known to be a pointer type (which
3220 // is considered resolved), but the result knows it needs to be 32- or
3221 // 64-bits. Infer the other way for good measure.
Chris Lattnerf1447252010-03-19 21:37:09 +00003222 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
3223 Pattern->getTree(0)->getNumTypes());
3224 i != e; ++i) {
Chris Lattnerfdc20712010-03-18 23:15:10 +00003225 IterateInference = Pattern->getTree(0)->
Chris Lattnerf1447252010-03-19 21:37:09 +00003226 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003227 IterateInference |= Result->getTree(0)->
Chris Lattnerf1447252010-03-19 21:37:09 +00003228 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003229 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003230
Chris Lattnercabe0372010-03-15 06:00:16 +00003231 // If our iteration has converged and the input pattern's types are fully
3232 // resolved but the result pattern is not fully resolved, we may have a
3233 // situation where we have two instructions in the result pattern and
3234 // the instructions require a common register class, but don't care about
3235 // what actual MVT is used. This is actually a bug in our modelling:
3236 // output patterns should have register classes, not MVTs.
3237 //
3238 // In any case, to handle this, we just go through and disambiguate some
3239 // arbitrary types to the result pattern's nodes.
3240 if (!IterateInference && InferredAllPatternTypes &&
3241 !InferredAllResultTypes)
3242 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
3243 *Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003244 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003245
Chris Lattner8cab0212008-01-05 22:25:12 +00003246 // Verify that we inferred enough types that we can do something with the
3247 // pattern and result. If these fire the user has to add type casts.
3248 if (!InferredAllPatternTypes)
3249 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003250 if (!InferredAllResultTypes) {
3251 Pattern->dump();
Chris Lattner8cab0212008-01-05 22:25:12 +00003252 Result->error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003253 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003254
Chris Lattner8cab0212008-01-05 22:25:12 +00003255 // Validate that the input pattern is correct.
3256 std::map<std::string, TreePatternNode*> InstInputs;
3257 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003258 std::vector<Record*> InstImpResults;
3259 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3260 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3261 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003262 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003263
3264 // Promote the xform function to be an explicit node if set.
3265 TreePatternNode *DstPattern = Result->getOnlyTree();
3266 std::vector<TreePatternNode*> ResultNodeOperands;
3267 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3268 TreePatternNode *OpNode = DstPattern->getChild(ii);
3269 if (Record *Xform = OpNode->getTransformFn()) {
3270 OpNode->setTransformFn(0);
3271 std::vector<TreePatternNode*> Children;
3272 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003273 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003274 }
3275 ResultNodeOperands.push_back(OpNode);
3276 }
3277 DstPattern = Result->getOnlyTree();
3278 if (!DstPattern->isLeaf())
3279 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003280 ResultNodeOperands,
3281 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003282
Chris Lattnerf1447252010-03-19 21:37:09 +00003283 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
3284 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003285
Chris Lattner8cab0212008-01-05 22:25:12 +00003286 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
3287 Temp.InferAllTypes();
3288
Jim Grosbach65586fe2010-12-21 16:16:00 +00003289
Chris Lattner0c0baa92010-02-23 06:16:51 +00003290 AddPatternToMatch(Pattern,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003291 PatternToMatch(CurPattern,
3292 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerf1447252010-03-19 21:37:09 +00003293 Pattern->getTree(0),
3294 Temp.getOnlyTree(), InstImpResults,
3295 CurPattern->getValueAsInt("AddedComplexity"),
3296 CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003297 }
3298}
3299
3300/// CombineChildVariants - Given a bunch of permutations of each child of the
3301/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003302static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003303 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3304 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003305 CodeGenDAGPatterns &CDP,
3306 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003307 // Make sure that each operand has at least one variant to choose from.
3308 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3309 if (ChildVariants[i].empty())
3310 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003311
Chris Lattner8cab0212008-01-05 22:25:12 +00003312 // The end result is an all-pairs construction of the resultant pattern.
3313 std::vector<unsigned> Idxs;
3314 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003315 bool NotDone;
3316 do {
3317#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003318 DEBUG(if (!Idxs.empty()) {
3319 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3320 for (unsigned i = 0; i < Idxs.size(); ++i) {
3321 errs() << Idxs[i] << " ";
3322 }
3323 errs() << "]\n";
3324 });
Scott Michel94420742008-03-05 17:49:05 +00003325#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003326 // Create the variant and add it to the output list.
3327 std::vector<TreePatternNode*> NewChildren;
3328 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3329 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerf1447252010-03-19 21:37:09 +00003330 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3331 Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003332
Chris Lattner8cab0212008-01-05 22:25:12 +00003333 // Copy over properties.
3334 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003335 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003336 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003337 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3338 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003339
Scott Michel94420742008-03-05 17:49:05 +00003340 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003341 std::string ErrString;
3342 if (!R->canPatternMatch(ErrString, CDP)) {
3343 delete R;
3344 } else {
3345 bool AlreadyExists = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003346
Chris Lattner8cab0212008-01-05 22:25:12 +00003347 // Scan to see if this pattern has already been emitted. We can get
3348 // duplication due to things like commuting:
3349 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3350 // which are the same pattern. Ignore the dups.
3351 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003352 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003353 AlreadyExists = true;
3354 break;
3355 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003356
Chris Lattner8cab0212008-01-05 22:25:12 +00003357 if (AlreadyExists)
3358 delete R;
3359 else
3360 OutVariants.push_back(R);
3361 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003362
Scott Michel94420742008-03-05 17:49:05 +00003363 // Increment indices to the next permutation by incrementing the
3364 // indicies from last index backward, e.g., generate the sequence
3365 // [0, 0], [0, 1], [1, 0], [1, 1].
3366 int IdxsIdx;
3367 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3368 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3369 Idxs[IdxsIdx] = 0;
3370 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003371 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003372 }
Scott Michel94420742008-03-05 17:49:05 +00003373 NotDone = (IdxsIdx >= 0);
3374 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003375}
3376
3377/// CombineChildVariants - A helper function for binary operators.
3378///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003379static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003380 const std::vector<TreePatternNode*> &LHS,
3381 const std::vector<TreePatternNode*> &RHS,
3382 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003383 CodeGenDAGPatterns &CDP,
3384 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003385 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3386 ChildVariants.push_back(LHS);
3387 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003388 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003389}
Chris Lattner8cab0212008-01-05 22:25:12 +00003390
3391
3392static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3393 std::vector<TreePatternNode *> &Children) {
3394 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3395 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003396
Chris Lattner8cab0212008-01-05 22:25:12 +00003397 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003398 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003399 N->getTransformFn()) {
3400 Children.push_back(N);
3401 return;
3402 }
3403
3404 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3405 Children.push_back(N->getChild(0));
3406 else
3407 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3408
3409 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3410 Children.push_back(N->getChild(1));
3411 else
3412 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3413}
3414
3415/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3416/// the (potentially recursive) pattern by using algebraic laws.
3417///
3418static void GenerateVariantsOf(TreePatternNode *N,
3419 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003420 CodeGenDAGPatterns &CDP,
3421 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003422 // We cannot permute leaves.
3423 if (N->isLeaf()) {
3424 OutVariants.push_back(N);
3425 return;
3426 }
3427
3428 // Look up interesting info about the node.
3429 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3430
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003431 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003432 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003433 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003434 std::vector<TreePatternNode*> MaximalChildren;
3435 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3436
3437 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3438 // permutations.
3439 if (MaximalChildren.size() == 3) {
3440 // Find the variants of all of our maximal children.
3441 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003442 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3443 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3444 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003445
Chris Lattner8cab0212008-01-05 22:25:12 +00003446 // There are only two ways we can permute the tree:
3447 // (A op B) op C and A op (B op C)
3448 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003449
Chris Lattner8cab0212008-01-05 22:25:12 +00003450 // Generate legal pair permutations of A/B/C.
3451 std::vector<TreePatternNode*> ABVariants;
3452 std::vector<TreePatternNode*> BAVariants;
3453 std::vector<TreePatternNode*> ACVariants;
3454 std::vector<TreePatternNode*> CAVariants;
3455 std::vector<TreePatternNode*> BCVariants;
3456 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003457 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3458 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3459 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3460 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3461 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3462 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003463
3464 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003465 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3466 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3467 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3468 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3469 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3470 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003471
3472 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003473 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3474 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3475 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3476 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3477 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3478 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003479 return;
3480 }
3481 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003482
Chris Lattner8cab0212008-01-05 22:25:12 +00003483 // Compute permutations of all children.
3484 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3485 ChildVariants.resize(N->getNumChildren());
3486 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003487 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003488
3489 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003490 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003491
3492 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003493 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3494 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3495 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3496 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003497 // Don't count children which are actually register references.
3498 unsigned NC = 0;
3499 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3500 TreePatternNode *Child = N->getChild(i);
3501 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003502 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003503 Record *RR = DI->getDef();
3504 if (RR->isSubClassOf("Register"))
3505 continue;
3506 }
3507 NC++;
3508 }
3509 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003510 if (isCommIntrinsic) {
3511 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3512 // operands are the commutative operands, and there might be more operands
3513 // after those.
3514 assert(NC >= 3 &&
3515 "Commutative intrinsic should have at least 3 childrean!");
3516 std::vector<std::vector<TreePatternNode*> > Variants;
3517 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3518 Variants.push_back(ChildVariants[2]);
3519 Variants.push_back(ChildVariants[1]);
3520 for (unsigned i = 3; i != NC; ++i)
3521 Variants.push_back(ChildVariants[i]);
3522 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3523 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003524 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003525 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003526 }
3527}
3528
3529
3530// GenerateVariants - Generate variants. For example, commutative patterns can
3531// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003532void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003533 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003534
Chris Lattner8cab0212008-01-05 22:25:12 +00003535 // Loop over all of the patterns we've collected, checking to see if we can
3536 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003537 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003538 // the .td file having to contain tons of variants of instructions.
3539 //
3540 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3541 // intentionally do not reconsider these. Any variants of added patterns have
3542 // already been added.
3543 //
3544 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003545 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003546 std::vector<TreePatternNode*> Variants;
Scott Michel94420742008-03-05 17:49:05 +00003547 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003548 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003549 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003550 DEBUG(errs() << "\n");
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003551 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3552 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003553
3554 assert(!Variants.empty() && "Must create at least original variant!");
3555 Variants.erase(Variants.begin()); // Remove the original pattern.
3556
3557 if (Variants.empty()) // No variants for this pattern.
3558 continue;
3559
Chris Lattner34822f62009-08-23 04:44:11 +00003560 DEBUG(errs() << "FOUND VARIANTS OF: ";
3561 PatternsToMatch[i].getSrcPattern()->dump();
3562 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003563
3564 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3565 TreePatternNode *Variant = Variants[v];
3566
Chris Lattner34822f62009-08-23 04:44:11 +00003567 DEBUG(errs() << " VAR#" << v << ": ";
3568 Variant->dump();
3569 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003570
Chris Lattner8cab0212008-01-05 22:25:12 +00003571 // Scan to see if an instruction or explicit pattern already matches this.
3572 bool AlreadyExists = false;
3573 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003574 // Skip if the top level predicates do not match.
3575 if (PatternsToMatch[i].getPredicates() !=
3576 PatternsToMatch[p].getPredicates())
3577 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003578 // Check to see if this variant already exists.
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003579 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3580 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003581 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003582 AlreadyExists = true;
3583 break;
3584 }
3585 }
3586 // If we already have it, ignore the variant.
3587 if (AlreadyExists) continue;
3588
3589 // Otherwise, add it to the list of patterns we have.
3590 PatternsToMatch.
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003591 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3592 PatternsToMatch[i].getPredicates(),
Chris Lattner8cab0212008-01-05 22:25:12 +00003593 Variant, PatternsToMatch[i].getDstPattern(),
3594 PatternsToMatch[i].getDstRegs(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003595 PatternsToMatch[i].getAddedComplexity(),
3596 Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003597 }
3598
Chris Lattner34822f62009-08-23 04:44:11 +00003599 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003600 }
3601}