blob: 358334f06227796d03ff9f74c382b5a337c29434 [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) {
Craig Topper6e1faaf2014-01-25 17:40:33 +0000583 if (TP.hasError())
584 return false;
585
David Greene127fd1d2011-01-24 20:53:18 +0000586 // "This" must be a vector and "VTOperand" must be a vector.
587 bool MadeChange = false;
588 MadeChange |= EnforceVector(TP);
589 MadeChange |= VTOperand.EnforceVector(TP);
590
Craig Topper6e1faaf2014-01-25 17:40:33 +0000591 // If one side is known to be integer or known to be FP but the other side has
592 // no information, get at least the type integrality info in there.
593 if (!hasFloatingPointTypes())
594 MadeChange |= VTOperand.EnforceInteger(TP);
595 else if (!hasIntegerTypes())
596 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
597 if (!VTOperand.hasFloatingPointTypes())
598 MadeChange |= EnforceInteger(TP);
599 else if (!VTOperand.hasIntegerTypes())
600 MadeChange |= EnforceFloatingPoint(TP);
601
602 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
603 "Should have a type list now");
David Greene127fd1d2011-01-24 20:53:18 +0000604
605 // If we know the vector type, it forces the scalar types to agree.
Craig Topper6e1faaf2014-01-25 17:40:33 +0000606 // Also force one vector to have more elements than the other.
David Greene127fd1d2011-01-24 20:53:18 +0000607 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000608 MVT IVT = getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000609 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000610 IVT = IVT.getVectorElementType();
611
Craig Topper95198f42013-09-25 06:37:18 +0000612 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000613 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000614
615 // Only keep types that have less elements than VTOperand.
616 TypeSet InputSet(VTOperand);
617
618 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
619 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
620 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
621 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
622 MadeChange = true;
623 }
624 }
625 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
626 TP.error("Type inference contradiction found, forcing '" +
627 InputSet.getName() + "' to have less vector elements than '" +
628 getName() + "'");
629 return false;
630 }
David Greene127fd1d2011-01-24 20:53:18 +0000631 } else if (VTOperand.isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000632 MVT IVT = VTOperand.getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000633 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000634 IVT = IVT.getVectorElementType();
635
Craig Topper95198f42013-09-25 06:37:18 +0000636 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000637 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000638
639 // Only keep types that have more elements than 'this'.
640 TypeSet InputSet(*this);
641
642 for (unsigned i = 0; i != TypeVec.size(); ++i) {
643 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
644 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
645 TypeVec.erase(TypeVec.begin()+i--);
646 MadeChange = true;
647 }
648 }
649 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
650 TP.error("Type inference contradiction found, forcing '" +
651 InputSet.getName() + "' to have more vector elements than '" +
652 VTOperand.getName() + "'");
653 return false;
654 }
David Greene127fd1d2011-01-24 20:53:18 +0000655 }
656
657 return MadeChange;
658}
659
Chris Lattnercabe0372010-03-15 06:00:16 +0000660//===----------------------------------------------------------------------===//
661// Helpers for working with extended types.
Chris Lattner8cab0212008-01-05 22:25:12 +0000662
Scott Michel94420742008-03-05 17:49:05 +0000663/// Dependent variable map for CodeGenDAGPattern variant generation
664typedef std::map<std::string, int> DepVarMap;
665
666/// Const iterator shorthand for DepVarMap
667typedef DepVarMap::const_iterator DepVarMap_citer;
668
Chris Lattner514e2922011-04-17 21:38:24 +0000669static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel94420742008-03-05 17:49:05 +0000670 if (N->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000671 if (isa<DefInit>(N->getLeafValue()))
Scott Michel94420742008-03-05 17:49:05 +0000672 DepMap[N->getName()]++;
Scott Michel94420742008-03-05 17:49:05 +0000673 } else {
674 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
675 FindDepVarsOf(N->getChild(i), DepMap);
676 }
677}
Chris Lattner514e2922011-04-17 21:38:24 +0000678
679/// Find dependent variables within child patterns
680static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000681 DepVarMap depcounts;
682 FindDepVarsOf(N, depcounts);
683 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
Chris Lattner514e2922011-04-17 21:38:24 +0000684 if (i->second > 1) // std::pair<std::string, int>
Scott Michel94420742008-03-05 17:49:05 +0000685 DepVars.insert(i->first);
Scott Michel94420742008-03-05 17:49:05 +0000686 }
687}
688
Daniel Dunbarba66a812010-10-08 02:07:22 +0000689#ifndef NDEBUG
Chris Lattner514e2922011-04-17 21:38:24 +0000690/// Dump the dependent variable set:
691static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000692 if (DepVars.empty()) {
Chris Lattner34822f62009-08-23 04:44:11 +0000693 DEBUG(errs() << "<empty set>");
Scott Michel94420742008-03-05 17:49:05 +0000694 } else {
Chris Lattner34822f62009-08-23 04:44:11 +0000695 DEBUG(errs() << "[ ");
Jim Grosbachb75d0ca2010-10-08 18:13:57 +0000696 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
697 e = DepVars.end(); i != e; ++i) {
Chris Lattner34822f62009-08-23 04:44:11 +0000698 DEBUG(errs() << (*i) << " ");
Scott Michel94420742008-03-05 17:49:05 +0000699 }
Chris Lattner34822f62009-08-23 04:44:11 +0000700 DEBUG(errs() << "]");
Scott Michel94420742008-03-05 17:49:05 +0000701 }
702}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000703#endif
704
Chris Lattner514e2922011-04-17 21:38:24 +0000705
706//===----------------------------------------------------------------------===//
707// TreePredicateFn Implementation
708//===----------------------------------------------------------------------===//
709
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000710/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
711TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
712 assert((getPredCode().empty() || getImmCode().empty()) &&
713 ".td file corrupt: can't have a node predicate *and* an imm predicate");
714}
715
Chris Lattner514e2922011-04-17 21:38:24 +0000716std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000717 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000718}
719
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000720std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000721 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000722}
723
Chris Lattner514e2922011-04-17 21:38:24 +0000724
725/// isAlwaysTrue - Return true if this is a noop predicate.
726bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000727 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000728}
729
730/// Return the name to use in the generated code to reference this, this is
731/// "Predicate_foo" if from a pattern fragment "foo".
732std::string TreePredicateFn::getFnName() const {
733 return "Predicate_" + PatFragRec->getRecord()->getName();
734}
735
736/// getCodeToRunOnSDNode - Return the code for the function body that
737/// evaluates this predicate. The argument is expected to be in "Node",
738/// not N. This handles casting and conversion to a concrete node type as
739/// appropriate.
740std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000741 // Handle immediate predicates first.
742 std::string ImmCode = getImmCode();
743 if (!ImmCode.empty()) {
744 std::string Result =
745 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000746 return Result + ImmCode;
747 }
748
749 // Handle arbitrary node predicates.
750 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000751 std::string ClassName;
752 if (PatFragRec->getOnlyTree()->isLeaf())
753 ClassName = "SDNode";
754 else {
755 Record *Op = PatFragRec->getOnlyTree()->getOperator();
756 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
757 }
758 std::string Result;
759 if (ClassName == "SDNode")
760 Result = " SDNode *N = Node;\n";
761 else
762 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
763
764 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000765}
766
Chris Lattner8cab0212008-01-05 22:25:12 +0000767//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000768// PatternToMatch implementation
769//
770
Chris Lattner05925fe2010-03-29 01:40:38 +0000771
772/// getPatternSize - Return the 'size' of this pattern. We want to match large
773/// patterns before small ones. This is used to determine the size of a
774/// pattern.
775static unsigned getPatternSize(const TreePatternNode *P,
776 const CodeGenDAGPatterns &CGP) {
777 unsigned Size = 3; // The node itself.
778 // If the root node is a ConstantSDNode, increases its size.
779 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000780 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000781 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000782
Chris Lattner05925fe2010-03-29 01:40:38 +0000783 // FIXME: This is a hack to statically increase the priority of patterns
784 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
785 // Later we can allow complexity / cost for each pattern to be (optionally)
786 // specified. To get best possible pattern match we'll need to dynamically
787 // calculate the complexity of all patterns a dag can potentially map to.
788 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
789 if (AM)
790 Size += AM->getNumOperands() * 3;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000791
Chris Lattner05925fe2010-03-29 01:40:38 +0000792 // If this node has some predicate function that must match, it adds to the
793 // complexity of this node.
794 if (!P->getPredicateFns().empty())
795 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000796
Chris Lattner05925fe2010-03-29 01:40:38 +0000797 // Count children in the count if they are also nodes.
798 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
799 TreePatternNode *Child = P->getChild(i);
800 if (!Child->isLeaf() && Child->getNumTypes() &&
801 Child->getType(0) != MVT::Other)
802 Size += getPatternSize(Child, CGP);
803 else if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000804 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000805 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
806 else if (Child->getComplexPatternInfo(CGP))
807 Size += getPatternSize(Child, CGP);
808 else if (!Child->getPredicateFns().empty())
809 ++Size;
810 }
811 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000812
Chris Lattner05925fe2010-03-29 01:40:38 +0000813 return Size;
814}
815
816/// Compute the complexity metric for the input pattern. This roughly
817/// corresponds to the number of nodes that are covered.
818unsigned PatternToMatch::
819getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
820 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
821}
822
823
Dan Gohman49e19e92008-08-22 00:20:26 +0000824/// getPredicateCheck - Return a single string containing all of this
825/// pattern's predicates concatenated with "&&" operators.
826///
827std::string PatternToMatch::getPredicateCheck() const {
828 std::string PredicateCheck;
829 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +0000830 if (DefInit *Pred = dyn_cast<DefInit>(Predicates->getElement(i))) {
Dan Gohman49e19e92008-08-22 00:20:26 +0000831 Record *Def = Pred->getDef();
832 if (!Def->isSubClassOf("Predicate")) {
833#ifndef NDEBUG
834 Def->dump();
835#endif
Craig Topperc4965bc2012-02-05 07:21:30 +0000836 llvm_unreachable("Unknown predicate type!");
Dan Gohman49e19e92008-08-22 00:20:26 +0000837 }
838 if (!PredicateCheck.empty())
839 PredicateCheck += " && ";
840 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
841 }
842 }
843
844 return PredicateCheck;
845}
846
847//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000848// SDTypeConstraint implementation
849//
850
851SDTypeConstraint::SDTypeConstraint(Record *R) {
852 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000853
Chris Lattner8cab0212008-01-05 22:25:12 +0000854 if (R->isSubClassOf("SDTCisVT")) {
855 ConstraintType = SDTCisVT;
856 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerffdac7b2010-03-28 06:04:39 +0000857 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000858 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000859
Chris Lattner8cab0212008-01-05 22:25:12 +0000860 } else if (R->isSubClassOf("SDTCisPtrTy")) {
861 ConstraintType = SDTCisPtrTy;
862 } else if (R->isSubClassOf("SDTCisInt")) {
863 ConstraintType = SDTCisInt;
864 } else if (R->isSubClassOf("SDTCisFP")) {
865 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000866 } else if (R->isSubClassOf("SDTCisVec")) {
867 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000868 } else if (R->isSubClassOf("SDTCisSameAs")) {
869 ConstraintType = SDTCisSameAs;
870 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
871 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
872 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000873 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000874 R->getValueAsInt("OtherOperandNum");
875 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
876 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000877 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000878 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000879 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
880 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000881 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000882 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
883 ConstraintType = SDTCisSubVecOfVec;
884 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
885 R->getValueAsInt("OtherOpNum");
Chris Lattner8cab0212008-01-05 22:25:12 +0000886 } else {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +0000887 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner8cab0212008-01-05 22:25:12 +0000888 exit(1);
889 }
890}
891
892/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000893/// N, and the result number in ResNo.
894static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
895 const SDNodeInfo &NodeInfo,
896 unsigned &ResNo) {
897 unsigned NumResults = NodeInfo.getNumResults();
898 if (OpNo < NumResults) {
899 ResNo = OpNo;
900 return N;
901 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000902
Chris Lattner2db7aba2010-03-19 21:56:21 +0000903 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000904
Chris Lattner2db7aba2010-03-19 21:56:21 +0000905 if (OpNo >= N->getNumChildren()) {
Jim Grosbach65586fe2010-12-21 16:16:00 +0000906 errs() << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000907 << (OpNo+NumResults) << " ";
Chris Lattner8cab0212008-01-05 22:25:12 +0000908 N->dump();
Daniel Dunbar38a22bf2009-07-03 00:10:29 +0000909 errs() << '\n';
Chris Lattner8cab0212008-01-05 22:25:12 +0000910 exit(1);
911 }
912
Chris Lattner2db7aba2010-03-19 21:56:21 +0000913 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +0000914}
915
916/// ApplyTypeConstraint - Given a node in a pattern, apply this type
917/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000918/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +0000919bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
920 const SDNodeInfo &NodeInfo,
921 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000922 if (TP.hasError())
923 return false;
924
Chris Lattner2db7aba2010-03-19 21:56:21 +0000925 unsigned ResNo = 0; // The result number being referenced.
926 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000927
Chris Lattner8cab0212008-01-05 22:25:12 +0000928 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000929 case SDTCisVT:
930 // Operand must be a particular type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000931 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000932 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +0000933 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000934 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000935 case SDTCisInt:
936 // Require it to be one of the legal integer VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000937 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000938 case SDTCisFP:
939 // Require it to be one of the legal fp VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000940 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000941 case SDTCisVec:
942 // Require it to be one of the legal vector VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000943 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000944 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000945 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000946 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000947 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +0000948 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
949 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000950 }
951 case SDTCisVTSmallerThanOp: {
952 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
953 // have an integer type that is smaller than the VT.
954 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +0000955 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +0000956 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000957 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000958 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000959 return false;
960 }
Owen Anderson9f944592009-08-11 20:47:22 +0000961 MVT::SimpleValueType VT =
David Greeneaf8ee2c2011-07-29 22:43:06 +0000962 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000963
Chris Lattner38c99662010-03-24 00:06:46 +0000964 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000965
Chris Lattner2db7aba2010-03-19 21:56:21 +0000966 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000967 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000968 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
969 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +0000970
Chris Lattner38c99662010-03-24 00:06:46 +0000971 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000972 }
973 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000974 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000975 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000976 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
977 BResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +0000978 return NodeToApply->getExtType(ResNo).
979 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000980 }
Nate Begeman17bedbc2008-02-09 01:37:05 +0000981 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000982 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +0000983 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000984 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
985 VResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000986
Chris Lattner57ebf632010-03-24 00:01:16 +0000987 // Filter vector types out of VecOperand that don't have the right element
988 // type.
989 return VecOperand->getExtType(VResNo).
990 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begeman17bedbc2008-02-09 01:37:05 +0000991 }
David Greene127fd1d2011-01-24 20:53:18 +0000992 case SDTCisSubVecOfVec: {
993 unsigned VResNo = 0;
994 TreePatternNode *BigVecOperand =
995 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
996 VResNo);
997
998 // Filter vector types out of BigVecOperand that don't have the
999 // right subvector type.
1000 return BigVecOperand->getExtType(VResNo).
1001 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1002 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001003 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001004 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001005}
1006
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001007// Update the node type to match an instruction operand or result as specified
1008// in the ins or outs lists on the instruction definition. Return true if the
1009// type was actually changed.
1010bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1011 Record *Operand,
1012 TreePattern &TP) {
1013 // The 'unknown' operand indicates that types should be inferred from the
1014 // context.
1015 if (Operand->isSubClassOf("unknown_class"))
1016 return false;
1017
1018 // The Operand class specifies a type directly.
1019 if (Operand->isSubClassOf("Operand"))
1020 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1021 TP);
1022
1023 // PointerLikeRegClass has a type that is determined at runtime.
1024 if (Operand->isSubClassOf("PointerLikeRegClass"))
1025 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1026
1027 // Both RegisterClass and RegisterOperand operands derive their types from a
1028 // register class def.
1029 Record *RC = 0;
1030 if (Operand->isSubClassOf("RegisterClass"))
1031 RC = Operand;
1032 else if (Operand->isSubClassOf("RegisterOperand"))
1033 RC = Operand->getValueAsDef("RegClass");
1034
1035 assert(RC && "Unknown operand type");
1036 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1037 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1038}
1039
1040
Chris Lattner8cab0212008-01-05 22:25:12 +00001041//===----------------------------------------------------------------------===//
1042// SDNodeInfo implementation
1043//
1044SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1045 EnumName = R->getValueAsString("Opcode");
1046 SDClassName = R->getValueAsString("SDClass");
1047 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1048 NumResults = TypeProfile->getValueAsInt("NumResults");
1049 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001050
Chris Lattner8cab0212008-01-05 22:25:12 +00001051 // Parse the properties.
1052 Properties = 0;
1053 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
1054 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
1055 if (PropList[i]->getName() == "SDNPCommutative") {
1056 Properties |= 1 << SDNPCommutative;
1057 } else if (PropList[i]->getName() == "SDNPAssociative") {
1058 Properties |= 1 << SDNPAssociative;
1059 } else if (PropList[i]->getName() == "SDNPHasChain") {
1060 Properties |= 1 << SDNPHasChain;
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001061 } else if (PropList[i]->getName() == "SDNPOutGlue") {
1062 Properties |= 1 << SDNPOutGlue;
1063 } else if (PropList[i]->getName() == "SDNPInGlue") {
1064 Properties |= 1 << SDNPInGlue;
1065 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
1066 Properties |= 1 << SDNPOptInGlue;
Chris Lattnera348f552008-01-06 06:44:58 +00001067 } else if (PropList[i]->getName() == "SDNPMayStore") {
1068 Properties |= 1 << SDNPMayStore;
Chris Lattner1ca20682008-01-10 04:38:57 +00001069 } else if (PropList[i]->getName() == "SDNPMayLoad") {
1070 Properties |= 1 << SDNPMayLoad;
Chris Lattner42c63ef2008-01-10 05:39:30 +00001071 } else if (PropList[i]->getName() == "SDNPSideEffect") {
1072 Properties |= 1 << SDNPSideEffect;
Mon P Wang6a490372008-06-25 08:15:39 +00001073 } else if (PropList[i]->getName() == "SDNPMemOperand") {
1074 Properties |= 1 << SDNPMemOperand;
Chris Lattner83aeaab2010-03-19 05:07:09 +00001075 } else if (PropList[i]->getName() == "SDNPVariadic") {
1076 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001077 } else {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001078 errs() << "Unknown SD Node property '" << PropList[i]->getName()
1079 << "' on node '" << R->getName() << "'!\n";
Chris Lattner8cab0212008-01-05 22:25:12 +00001080 exit(1);
1081 }
1082 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001083
1084
Chris Lattner8cab0212008-01-05 22:25:12 +00001085 // Parse the type constraints.
1086 std::vector<Record*> ConstraintList =
1087 TypeProfile->getValueAsListOfDefs("Constraints");
1088 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1089}
1090
Chris Lattner99e53b32010-02-28 00:22:30 +00001091/// getKnownType - If the type constraints on this node imply a fixed type
1092/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001093/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001094MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001095 unsigned NumResults = getNumResults();
1096 assert(NumResults <= 1 &&
1097 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001098 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001099
Chris Lattner99e53b32010-02-28 00:22:30 +00001100 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
1101 // Make sure that this applies to the correct node result.
1102 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
1103 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001104
Chris Lattner99e53b32010-02-28 00:22:30 +00001105 switch (TypeConstraints[i].ConstraintType) {
1106 default: break;
1107 case SDTypeConstraint::SDTCisVT:
1108 return TypeConstraints[i].x.SDTCisVT_Info.VT;
1109 case SDTypeConstraint::SDTCisPtrTy:
1110 return MVT::iPTR;
1111 }
1112 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001113 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001114}
1115
Chris Lattner8cab0212008-01-05 22:25:12 +00001116//===----------------------------------------------------------------------===//
1117// TreePatternNode implementation
1118//
1119
1120TreePatternNode::~TreePatternNode() {
1121#if 0 // FIXME: implement refcounted tree nodes!
1122 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1123 delete getChild(i);
1124#endif
1125}
1126
Chris Lattnerf1447252010-03-19 21:37:09 +00001127static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1128 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001129 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001130 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001131
Chris Lattner2109cb42010-03-22 20:56:36 +00001132 if (Operator->isSubClassOf("Intrinsic"))
1133 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001134
Chris Lattnerf1447252010-03-19 21:37:09 +00001135 if (Operator->isSubClassOf("SDNode"))
1136 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001137
Chris Lattnerf1447252010-03-19 21:37:09 +00001138 if (Operator->isSubClassOf("PatFrag")) {
1139 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1140 // the forward reference case where one pattern fragment references another
1141 // before it is processed.
1142 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1143 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001144
Chris Lattnerf1447252010-03-19 21:37:09 +00001145 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001146 DagInit *Tree = Operator->getValueAsDag("Fragment");
Chris Lattnerf1447252010-03-19 21:37:09 +00001147 Record *Op = 0;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001148 if (Tree)
1149 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1150 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001151 assert(Op && "Invalid Fragment");
1152 return GetNumNodeResults(Op, CDP);
1153 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001154
Chris Lattnerf1447252010-03-19 21:37:09 +00001155 if (Operator->isSubClassOf("Instruction")) {
1156 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001157
1158 // FIXME: Should allow access to all the results here.
Chris Lattnerd8adec72010-11-01 04:03:32 +00001159 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001160
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001161 // Add on one implicit def if it has a resolvable type.
1162 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1163 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001164 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001165 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001166
Chris Lattnerf1447252010-03-19 21:37:09 +00001167 if (Operator->isSubClassOf("SDNodeXForm"))
1168 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001169
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001170 if (Operator->isSubClassOf("ValueType"))
1171 return 1; // A type-cast of one result.
1172
Chris Lattnerf1447252010-03-19 21:37:09 +00001173 Operator->dump();
1174 errs() << "Unhandled node in GetNumNodeResults\n";
1175 exit(1);
1176}
1177
1178void TreePatternNode::print(raw_ostream &OS) const {
1179 if (isLeaf())
1180 OS << *getLeafValue();
1181 else
1182 OS << '(' << getOperator()->getName();
1183
1184 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1185 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001186
1187 if (!isLeaf()) {
1188 if (getNumChildren() != 0) {
1189 OS << " ";
1190 getChild(0)->print(OS);
1191 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1192 OS << ", ";
1193 getChild(i)->print(OS);
1194 }
1195 }
1196 OS << ")";
1197 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001198
Dan Gohman6e979022008-10-15 06:17:21 +00001199 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
Chris Lattner514e2922011-04-17 21:38:24 +00001200 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001201 if (TransformFn)
1202 OS << "<<X:" << TransformFn->getName() << ">>";
1203 if (!getName().empty())
1204 OS << ":$" << getName();
1205
1206}
1207void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001208 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001209}
1210
Scott Michel94420742008-03-05 17:49:05 +00001211/// isIsomorphicTo - Return true if this node is recursively
1212/// isomorphic to the specified node. For this comparison, the node's
1213/// entire state is considered. The assigned name is ignored, since
1214/// nodes with differing names are considered isomorphic. However, if
1215/// the assigned name is present in the dependent variable set, then
1216/// the assigned name is considered significant and the node is
1217/// isomorphic if the names match.
1218bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1219 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001220 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001221 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001222 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001223 getTransformFn() != N->getTransformFn())
1224 return false;
1225
1226 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001227 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1228 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001229 return ((DI->getDef() == NDI->getDef())
1230 && (DepVars.find(getName()) == DepVars.end()
1231 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001232 }
1233 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001234 return getLeafValue() == N->getLeafValue();
1235 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001236
Chris Lattner8cab0212008-01-05 22:25:12 +00001237 if (N->getOperator() != getOperator() ||
1238 N->getNumChildren() != getNumChildren()) return false;
1239 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001240 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001241 return false;
1242 return true;
1243}
1244
1245/// clone - Make a copy of this tree and all of its children.
1246///
1247TreePatternNode *TreePatternNode::clone() const {
1248 TreePatternNode *New;
1249 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001250 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001251 } else {
1252 std::vector<TreePatternNode*> CChildren;
1253 CChildren.reserve(Children.size());
1254 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1255 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001256 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001257 }
1258 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001259 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001260 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001261 New->setTransformFn(getTransformFn());
1262 return New;
1263}
1264
Chris Lattner53c39ba2010-02-14 22:22:58 +00001265/// RemoveAllTypes - Recursively strip all the types of this tree.
1266void TreePatternNode::RemoveAllTypes() {
Chris Lattnerf1447252010-03-19 21:37:09 +00001267 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1268 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner53c39ba2010-02-14 22:22:58 +00001269 if (isLeaf()) return;
1270 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1271 getChild(i)->RemoveAllTypes();
1272}
1273
1274
Chris Lattner8cab0212008-01-05 22:25:12 +00001275/// SubstituteFormalArguments - Replace the formal arguments in this tree
1276/// with actual values specified by ArgMap.
1277void TreePatternNode::
1278SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1279 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001280
Chris Lattner8cab0212008-01-05 22:25:12 +00001281 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1282 TreePatternNode *Child = getChild(i);
1283 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001284 Init *Val = Child->getLeafValue();
Sean Silva88eb8dd2012-10-10 20:24:47 +00001285 if (isa<DefInit>(Val) &&
1286 cast<DefInit>(Val)->getDef()->getName() == "node") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001287 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001288 TreePatternNode *NewChild = ArgMap[Child->getName()];
1289 assert(NewChild && "Couldn't find formal argument!");
1290 assert((Child->getPredicateFns().empty() ||
1291 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1292 "Non-empty child predicate clobbered!");
1293 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001294 }
1295 } else {
1296 getChild(i)->SubstituteFormalArguments(ArgMap);
1297 }
1298 }
1299}
1300
1301
1302/// InlinePatternFragments - If this pattern refers to any pattern
1303/// fragments, inline them into place, giving us a pattern without any
1304/// PatFrag references.
1305TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001306 if (TP.hasError())
Kaelyn Uhrain41a73b72012-10-25 21:25:08 +00001307 return 0;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001308
1309 if (isLeaf())
1310 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001311 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001312
Chris Lattner8cab0212008-01-05 22:25:12 +00001313 if (!Op->isSubClassOf("PatFrag")) {
1314 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001315 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1316 TreePatternNode *Child = getChild(i);
1317 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1318
1319 assert((Child->getPredicateFns().empty() ||
1320 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1321 "Non-empty child predicate clobbered!");
1322
1323 setChild(i, NewChild);
1324 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001325 return this;
1326 }
1327
1328 // Otherwise, we found a reference to a fragment. First, look up its
1329 // TreePattern record.
1330 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001331
Chris Lattner8cab0212008-01-05 22:25:12 +00001332 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001333 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001334 TP.error("'" + Op->getName() + "' fragment requires " +
1335 utostr(Frag->getNumArgs()) + " operands!");
Kaelyn Uhrain41a73b72012-10-25 21:25:08 +00001336 return 0;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001337 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001338
1339 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1340
Chris Lattner514e2922011-04-17 21:38:24 +00001341 TreePredicateFn PredFn(Frag);
1342 if (!PredFn.isAlwaysTrue())
1343 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001344
Chris Lattner8cab0212008-01-05 22:25:12 +00001345 // Resolve formal arguments to their actual value.
1346 if (Frag->getNumArgs()) {
1347 // Compute the map of formal to actual arguments.
1348 std::map<std::string, TreePatternNode*> ArgMap;
1349 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1350 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001351
Chris Lattner8cab0212008-01-05 22:25:12 +00001352 FragTree->SubstituteFormalArguments(ArgMap);
1353 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001354
Chris Lattner8cab0212008-01-05 22:25:12 +00001355 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001356 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1357 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001358
1359 // Transfer in the old predicates.
1360 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1361 FragTree->addPredicateFn(getPredicateFns()[i]);
1362
Chris Lattner8cab0212008-01-05 22:25:12 +00001363 // Get a new copy of this fragment to stitch into here.
1364 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001365
Chris Lattner2e253b42008-06-30 03:02:03 +00001366 // The fragment we inlined could have recursive inlining that is needed. See
1367 // if there are any pattern fragments in it and inline them as needed.
1368 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001369}
1370
1371/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001372/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001373/// references from the register file information, for example.
1374///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001375/// When Unnamed is set, return the type of a DAG operand with no name, such as
1376/// the F8RC register class argument in:
1377///
1378/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1379///
1380/// When Unnamed is false, return the type of a named DAG operand such as the
1381/// GPR:$src operand above.
1382///
Chris Lattnerf1447252010-03-19 21:37:09 +00001383static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001384 bool NotRegisters,
1385 bool Unnamed,
1386 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001387 // Check to see if this is a register operand.
1388 if (R->isSubClassOf("RegisterOperand")) {
1389 assert(ResNo == 0 && "Regoperand ref only has one result!");
1390 if (NotRegisters)
1391 return EEVT::TypeSet(); // Unknown.
1392 Record *RegClass = R->getValueAsDef("RegClass");
1393 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1394 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1395 }
1396
Chris Lattnercabe0372010-03-15 06:00:16 +00001397 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001398 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001399 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001400 // An unnamed register class represents itself as an i32 immediate, for
1401 // example on a COPY_TO_REGCLASS instruction.
1402 if (Unnamed)
1403 return EEVT::TypeSet(MVT::i32, TP);
1404
1405 // In a named operand, the register class provides the possible set of
1406 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001407 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001408 return EEVT::TypeSet(); // Unknown.
1409 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1410 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001411 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001412
Chris Lattner6070ee22010-03-23 23:50:31 +00001413 if (R->isSubClassOf("PatFrag")) {
1414 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001415 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001416 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001417 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001418
Chris Lattner6070ee22010-03-23 23:50:31 +00001419 if (R->isSubClassOf("Register")) {
1420 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001421 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001422 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001423 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001424 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001425 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001426
1427 if (R->isSubClassOf("SubRegIndex")) {
1428 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1429 return EEVT::TypeSet();
1430 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001431
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001432 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001433 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001434 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1435 //
1436 // (sext_inreg GPR:$src, i16)
1437 // ~~~
1438 if (Unnamed)
1439 return EEVT::TypeSet(MVT::Other, TP);
1440 // With a name, the ValueType simply provides the type of the named
1441 // variable.
1442 //
1443 // (sext_inreg i32:$src, i16)
1444 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001445 if (NotRegisters)
1446 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001447 return EEVT::TypeSet(getValueType(R), TP);
1448 }
1449
1450 if (R->isSubClassOf("CondCode")) {
1451 assert(ResNo == 0 && "This node only has one result!");
1452 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001453 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001454 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001455
Chris Lattner6070ee22010-03-23 23:50:31 +00001456 if (R->isSubClassOf("ComplexPattern")) {
1457 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001458 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001459 return EEVT::TypeSet(); // Unknown.
1460 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1461 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001462 }
1463 if (R->isSubClassOf("PointerLikeRegClass")) {
1464 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001465 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001466 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001467
Chris Lattner6070ee22010-03-23 23:50:31 +00001468 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1469 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001470 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001471 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001472 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001473
Chris Lattner8cab0212008-01-05 22:25:12 +00001474 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001475 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001476}
1477
Chris Lattner89c65662008-01-06 05:36:50 +00001478
1479/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1480/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1481const CodeGenIntrinsic *TreePatternNode::
1482getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1483 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1484 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1485 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
1486 return 0;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001487
Sean Silva88eb8dd2012-10-10 20:24:47 +00001488 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001489 return &CDP.getIntrinsicInfo(IID);
1490}
1491
Chris Lattner53c39ba2010-02-14 22:22:58 +00001492/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1493/// return the ComplexPattern information, otherwise return null.
1494const ComplexPattern *
1495TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
1496 if (!isLeaf()) return 0;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001497
Sean Silvafb509ed2012-10-10 20:24:43 +00001498 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001499 if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
1500 return &CGP.getComplexPattern(DI->getDef());
1501 return 0;
1502}
1503
1504/// NodeHasProperty - Return true if this node has the specified property.
1505bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001506 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001507 if (isLeaf()) {
1508 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1509 return CP->hasProperty(Property);
1510 return false;
1511 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001512
Chris Lattner53c39ba2010-02-14 22:22:58 +00001513 Record *Operator = getOperator();
1514 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001515
Chris Lattner53c39ba2010-02-14 22:22:58 +00001516 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1517}
1518
1519
1520
1521
1522/// TreeHasProperty - Return true if any node in this tree has the specified
1523/// property.
1524bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001525 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001526 if (NodeHasProperty(Property, CGP))
1527 return true;
1528 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1529 if (getChild(i)->TreeHasProperty(Property, CGP))
1530 return true;
1531 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001532}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001533
Evan Cheng49bad4c2008-06-16 20:29:38 +00001534/// isCommutativeIntrinsic - Return true if the node corresponds to a
1535/// commutative intrinsic.
1536bool
1537TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1538 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1539 return Int->isCommutative;
1540 return false;
1541}
1542
Chris Lattner89c65662008-01-06 05:36:50 +00001543
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001544/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001545/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001546/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001547bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001548 if (TP.hasError())
1549 return false;
1550
Chris Lattnerab3242f2008-01-06 01:10:31 +00001551 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001552 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001553 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001554 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001555 bool MadeChange = false;
1556 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1557 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001558 NotRegisters,
1559 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001560 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001561 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001562
Sean Silvafb509ed2012-10-10 20:24:43 +00001563 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001564 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001565
Chris Lattnerf1447252010-03-19 21:37:09 +00001566 // Int inits are always integers. :)
1567 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001568
Chris Lattnerf1447252010-03-19 21:37:09 +00001569 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001570 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001571
Chris Lattnerf1447252010-03-19 21:37:09 +00001572 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001573 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1574 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001575
Craig Topper95198f42013-09-25 06:37:18 +00001576 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001577 // Make sure that the value is representable for this type.
1578 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001579
Richard Smith228e6d42012-08-24 23:29:28 +00001580 // Check that the value doesn't use more bits than we have. It must either
1581 // be a sign- or zero-extended equivalent of the original.
1582 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1583 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001584 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001585
Richard Smith228e6d42012-08-24 23:29:28 +00001586 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001587 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001588 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001589 }
1590 return false;
1591 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001592
Chris Lattner8cab0212008-01-05 22:25:12 +00001593 // special handling for set, which isn't really an SDNode.
1594 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001595 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1596 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001597 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001598
Chris Lattnerf1447252010-03-19 21:37:09 +00001599 TreePatternNode *SetVal = getChild(NC-1);
1600 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1601
Chris Lattner8cab0212008-01-05 22:25:12 +00001602 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001603 TreePatternNode *Child = getChild(i);
1604 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001605
Chris Lattner8cab0212008-01-05 22:25:12 +00001606 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001607 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1608 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001609 }
1610 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001611 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001612
Chris Lattner5c2182e2010-03-27 02:53:27 +00001613 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001614 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1615
Chris Lattner8cab0212008-01-05 22:25:12 +00001616 bool MadeChange = false;
1617 for (unsigned i = 0; i < getNumChildren(); ++i)
1618 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001619 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001620 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001621
Chris Lattneree820ac2010-02-23 05:51:07 +00001622 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001623 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001624
Chris Lattner8cab0212008-01-05 22:25:12 +00001625 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001626 unsigned NumRetVTs = Int->IS.RetVTs.size();
1627 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001628
Bill Wendling91821472008-11-13 09:08:33 +00001629 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001630 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001631
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001632 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001633 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001634 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001635 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001636 return false;
1637 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001638
1639 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001640 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001641
Chris Lattnerf1447252010-03-19 21:37:09 +00001642 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1643 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001644
Chris Lattnerf1447252010-03-19 21:37:09 +00001645 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1646 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1647 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001648 }
1649 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001650 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001651
Chris Lattneree820ac2010-02-23 05:51:07 +00001652 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001653 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001654
Chris Lattner135091b2010-03-28 08:48:47 +00001655 // Check that the number of operands is sane. Negative operands -> varargs.
1656 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001657 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001658 TP.error(getOperator()->getName() + " node requires exactly " +
1659 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001660 return false;
1661 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001662
Chris Lattner8cab0212008-01-05 22:25:12 +00001663 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1664 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1665 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001666 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001667 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001668
Chris Lattneree820ac2010-02-23 05:51:07 +00001669 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001670 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001671 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001672 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001673
Chris Lattnerd44966f2010-03-27 19:15:02 +00001674 bool MadeChange = false;
1675
1676 // Apply the result types to the node, these come from the things in the
1677 // (outs) list of the instruction.
1678 // FIXME: Cap at one result so far.
Chris Lattnerd8adec72010-11-01 04:03:32 +00001679 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001680 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1681 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001682
Chris Lattnerd44966f2010-03-27 19:15:02 +00001683 // If the instruction has implicit defs, we apply the first one as a result.
1684 // FIXME: This sucks, it should apply all implicit defs.
1685 if (!InstInfo.ImplicitDefs.empty()) {
1686 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001687
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001688 // FIXME: Generalize to multiple possible types and multiple possible
1689 // ImplicitDefs.
1690 MVT::SimpleValueType VT =
1691 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001692
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001693 if (VT != MVT::Other)
1694 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001695 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001696
Chris Lattnercabe0372010-03-15 06:00:16 +00001697 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1698 // be the same.
1699 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001700 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1701 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1702 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001703 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001704
1705 unsigned ChildNo = 0;
1706 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1707 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001708
Chris Lattner8cab0212008-01-05 22:25:12 +00001709 // If the instruction expects a predicate or optional def operand, we
1710 // codegen this by setting the operand to it's default value if it has a
1711 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001712 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001713 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1714 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001715
Chris Lattner8cab0212008-01-05 22:25:12 +00001716 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001717 if (ChildNo >= getNumChildren()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001718 TP.error("Instruction '" + getOperator()->getName() +
1719 "' expects more operands than were provided.");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001720 return false;
1721 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001722
Chris Lattner8cab0212008-01-05 22:25:12 +00001723 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001724 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001725
1726 // If the operand has sub-operands, they may be provided by distinct
1727 // child patterns, so attempt to match each sub-operand separately.
1728 if (OperandNode->isSubClassOf("Operand")) {
1729 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1730 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1731 // But don't do that if the whole operand is being provided by
1732 // a single ComplexPattern.
1733 const ComplexPattern *AM = Child->getComplexPatternInfo(CDP);
1734 if (!AM || AM->getNumOperands() < NumArgs) {
1735 // Match first sub-operand against the child we already have.
1736 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1737 MadeChange |=
1738 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1739
1740 // And the remaining sub-operands against subsequent children.
1741 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1742 if (ChildNo >= getNumChildren()) {
1743 TP.error("Instruction '" + getOperator()->getName() +
1744 "' expects more operands than were provided.");
1745 return false;
1746 }
1747 Child = getChild(ChildNo++);
1748
1749 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1750 MadeChange |=
1751 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1752 }
1753 continue;
1754 }
1755 }
1756 }
1757
1758 // If we didn't match by pieces above, attempt to match the whole
1759 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001760 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001761 }
Christopher Lamba7312392008-03-11 09:33:47 +00001762
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001763 if (ChildNo != getNumChildren()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001764 TP.error("Instruction '" + getOperator()->getName() +
1765 "' was provided too many operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001766 return false;
1767 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001768
Ulrich Weigande618abd2013-03-19 19:51:09 +00001769 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1770 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001771 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001772 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001773
Chris Lattneree820ac2010-02-23 05:51:07 +00001774 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001775
Chris Lattneree820ac2010-02-23 05:51:07 +00001776 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001777 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001778 TP.error("Node transform '" + getOperator()->getName() +
1779 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001780 return false;
1781 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001782
Chris Lattnercabe0372010-03-15 06:00:16 +00001783 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1784
Jim Grosbach65586fe2010-12-21 16:16:00 +00001785
Chris Lattneree820ac2010-02-23 05:51:07 +00001786 // If either the output or input of the xform does not have exact
1787 // type info. We assume they must be the same. Otherwise, it is perfectly
1788 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001789#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001790 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001791 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1792 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001793 return MadeChange;
1794 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001795#endif
1796 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001797}
1798
1799/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1800/// RHS of a commutative operation, not the on LHS.
1801static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1802 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1803 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001804 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001805 return true;
1806 return false;
1807}
1808
1809
1810/// canPatternMatch - If it is impossible for this pattern to match on this
1811/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00001812/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00001813/// that can never possibly work), and to prevent the pattern permuter from
1814/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001815bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00001816 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001817 if (isLeaf()) return true;
1818
1819 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1820 if (!getChild(i)->canPatternMatch(Reason, CDP))
1821 return false;
1822
1823 // If this is an intrinsic, handle cases that would make it not match. For
1824 // example, if an operand is required to be an immediate.
1825 if (getOperator()->isSubClassOf("Intrinsic")) {
1826 // TODO:
1827 return true;
1828 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001829
Chris Lattner8cab0212008-01-05 22:25:12 +00001830 // If this node is a commutative operator, check that the LHS isn't an
1831 // immediate.
1832 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00001833 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1834 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001835 // Scan all of the operands of the node and make sure that only the last one
1836 // is a constant node, unless the RHS also is.
1837 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng49bad4c2008-06-16 20:29:38 +00001838 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1839 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00001840 if (OnlyOnRHSOfCommutative(getChild(i))) {
1841 Reason="Immediate value must be on the RHS of commutative operators!";
1842 return false;
1843 }
1844 }
1845 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001846
Chris Lattner8cab0212008-01-05 22:25:12 +00001847 return true;
1848}
1849
1850//===----------------------------------------------------------------------===//
1851// TreePattern implementation
1852//
1853
David Greeneaf8ee2c2011-07-29 22:43:06 +00001854TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001855 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1856 isInputPattern(isInput), HasError(false) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001857 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001858 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001859}
1860
David Greeneaf8ee2c2011-07-29 22:43:06 +00001861TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001862 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1863 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001864 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001865}
1866
1867TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001868 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1869 isInputPattern(isInput), HasError(false) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001870 Trees.push_back(Pat);
1871}
1872
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001873void TreePattern::error(const std::string &Msg) {
1874 if (HasError)
1875 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00001876 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001877 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1878 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00001879}
1880
Chris Lattnercabe0372010-03-15 06:00:16 +00001881void TreePattern::ComputeNamedNodes() {
1882 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1883 ComputeNamedNodes(Trees[i]);
1884}
1885
1886void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1887 if (!N->getName().empty())
1888 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001889
Chris Lattnercabe0372010-03-15 06:00:16 +00001890 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1891 ComputeNamedNodes(N->getChild(i));
1892}
1893
Chris Lattnerf1447252010-03-19 21:37:09 +00001894
David Greeneaf8ee2c2011-07-29 22:43:06 +00001895TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00001896 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001897 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001898
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001899 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00001900 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001901 /// (foo GPR, imm) -> (foo GPR, (imm))
1902 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00001903 return ParseTreePattern(
1904 DagInit::get(DI, "",
David Greeneaf8ee2c2011-07-29 22:43:06 +00001905 std::vector<std::pair<Init*, std::string> >()),
David Greenee32ebf22011-07-29 19:07:07 +00001906 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001907
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001908 // Input argument?
1909 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00001910 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001911 if (OpName.empty())
1912 error("'node' argument requires a name to match with operand list");
1913 Args.push_back(OpName);
1914 }
1915
1916 Res->setName(OpName);
1917 return Res;
1918 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001919
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00001920 // ?:$name or just $name.
1921 if (TheInit == UnsetInit::get()) {
1922 if (OpName.empty())
1923 error("'?' argument requires a name to match with operand list");
1924 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
1925 Args.push_back(OpName);
1926 Res->setName(OpName);
1927 return Res;
1928 }
1929
Sean Silvafb509ed2012-10-10 20:24:43 +00001930 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001931 if (!OpName.empty())
1932 error("Constant int argument should not have a name!");
1933 return new TreePatternNode(II, 1);
1934 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001935
Sean Silvafb509ed2012-10-10 20:24:43 +00001936 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001937 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001938 Init *II = BI->convertInitializerTo(IntRecTy::get());
Sean Silva88eb8dd2012-10-10 20:24:47 +00001939 if (II == 0 || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001940 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00001941 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001942 }
1943
Sean Silvafb509ed2012-10-10 20:24:43 +00001944 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001945 if (!Dag) {
1946 TheInit->dump();
1947 error("Pattern has unexpected init kind!");
1948 }
Sean Silvafb509ed2012-10-10 20:24:43 +00001949 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001950 if (!OpDef) error("Pattern has unexpected operator type!");
1951 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001952
Chris Lattner8cab0212008-01-05 22:25:12 +00001953 if (Operator->isSubClassOf("ValueType")) {
1954 // If the operator is a ValueType, then this must be "type cast" of a leaf
1955 // node.
1956 if (Dag->getNumArgs() != 1)
1957 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001958
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001959 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00001960
Chris Lattner8cab0212008-01-05 22:25:12 +00001961 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00001962 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1963 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001964
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001965 if (!OpName.empty())
1966 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001967 return New;
1968 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001969
Chris Lattner8cab0212008-01-05 22:25:12 +00001970 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001971 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00001972 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00001973 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001974 !Operator->isSubClassOf("SDNodeXForm") &&
1975 !Operator->isSubClassOf("Intrinsic") &&
1976 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00001977 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00001978 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001979
Chris Lattner8cab0212008-01-05 22:25:12 +00001980 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00001981 if (isInputPattern) {
1982 if (Operator->isSubClassOf("Instruction") ||
1983 Operator->isSubClassOf("SDNodeXForm"))
1984 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1985 } else {
1986 if (Operator->isSubClassOf("Intrinsic"))
1987 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001988
Chris Lattner2e9eae12010-03-28 06:57:56 +00001989 if (Operator->isSubClassOf("SDNode") &&
1990 Operator->getName() != "imm" &&
1991 Operator->getName() != "fpimm" &&
1992 Operator->getName() != "tglobaltlsaddr" &&
1993 Operator->getName() != "tconstpool" &&
1994 Operator->getName() != "tjumptable" &&
1995 Operator->getName() != "tframeindex" &&
1996 Operator->getName() != "texternalsym" &&
1997 Operator->getName() != "tblockaddress" &&
1998 Operator->getName() != "tglobaladdr" &&
1999 Operator->getName() != "bb" &&
2000 Operator->getName() != "vt")
2001 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2002 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002003
Chris Lattner8cab0212008-01-05 22:25:12 +00002004 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002005
2006 // Parse all the operands.
2007 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2008 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002009
Chris Lattner8cab0212008-01-05 22:25:12 +00002010 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002011 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002012 // convert the intrinsic name to a number.
2013 if (Operator->isSubClassOf("Intrinsic")) {
2014 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2015 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2016
2017 // If this intrinsic returns void, it must have side-effects and thus a
2018 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002019 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002020 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002021 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002022 // Has side-effects, requires chain.
2023 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002024 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002025 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002026
David Greenee32ebf22011-07-29 19:07:07 +00002027 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002028 Children.insert(Children.begin(), IIDNode);
2029 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002030
Chris Lattnerf1447252010-03-19 21:37:09 +00002031 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2032 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002033 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002034
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002035 if (!Dag->getName().empty()) {
2036 assert(Result->getName().empty());
2037 Result->setName(Dag->getName());
2038 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002039 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002040}
2041
Chris Lattnera787c9e2010-03-28 08:38:32 +00002042/// SimplifyTree - See if we can simplify this tree to eliminate something that
2043/// will never match in favor of something obvious that will. This is here
2044/// strictly as a convenience to target authors because it allows them to write
2045/// more type generic things and have useless type casts fold away.
2046///
2047/// This returns true if any change is made.
2048static bool SimplifyTree(TreePatternNode *&N) {
2049 if (N->isLeaf())
2050 return false;
2051
2052 // If we have a bitconvert with a resolved type and if the source and
2053 // destination types are the same, then the bitconvert is useless, remove it.
2054 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002055 N->getExtType(0).isConcrete() &&
2056 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2057 N->getName().empty()) {
2058 N = N->getChild(0);
2059 SimplifyTree(N);
2060 return true;
2061 }
2062
2063 // Walk all children.
2064 bool MadeChange = false;
2065 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2066 TreePatternNode *Child = N->getChild(i);
2067 MadeChange |= SimplifyTree(Child);
2068 N->setChild(i, Child);
2069 }
2070 return MadeChange;
2071}
2072
2073
2074
Chris Lattner8cab0212008-01-05 22:25:12 +00002075/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002076/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002077/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002078bool TreePattern::
2079InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2080 if (NamedNodes.empty())
2081 ComputeNamedNodes();
2082
Chris Lattner8cab0212008-01-05 22:25:12 +00002083 bool MadeChange = true;
2084 while (MadeChange) {
2085 MadeChange = false;
Chris Lattnera787c9e2010-03-28 08:38:32 +00002086 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002087 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002088 MadeChange |= SimplifyTree(Trees[i]);
2089 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002090
2091 // If there are constraints on our named nodes, apply them.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002092 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattnercabe0372010-03-15 06:00:16 +00002093 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
2094 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002095
Chris Lattnercabe0372010-03-15 06:00:16 +00002096 // If we have input named node types, propagate their types to the named
2097 // values here.
2098 if (InNamedTypes) {
2099 // FIXME: Should be error?
2100 assert(InNamedTypes->count(I->getKey()) &&
2101 "Named node in output pattern but not input pattern?");
2102
2103 const SmallVectorImpl<TreePatternNode*> &InNodes =
2104 InNamedTypes->find(I->getKey())->second;
2105
2106 // The input types should be fully resolved by now.
2107 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2108 // If this node is a register class, and it is the root of the pattern
2109 // then we're mapping something onto an input register. We allow
2110 // changing the type of the input register in this case. This allows
2111 // us to match things like:
2112 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2113 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002114 DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002115 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2116 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002117 continue;
2118 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002119
Daniel Dunbard177edf2010-03-21 01:38:21 +00002120 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002121 InNodes[0]->getNumTypes() == 1 &&
2122 "FIXME: cannot name multiple result nodes yet");
2123 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
2124 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002125 }
2126 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002127
Chris Lattnercabe0372010-03-15 06:00:16 +00002128 // If there are multiple nodes with the same name, they must all have the
2129 // same type.
2130 if (I->second.size() > 1) {
2131 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002132 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002133 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002134 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002135
Chris Lattnerf1447252010-03-19 21:37:09 +00002136 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2137 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002138 }
2139 }
2140 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002141 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002142
Chris Lattner8cab0212008-01-05 22:25:12 +00002143 bool HasUnresolvedTypes = false;
2144 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2145 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
2146 return !HasUnresolvedTypes;
2147}
2148
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002149void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002150 OS << getRecord()->getName();
2151 if (!Args.empty()) {
2152 OS << "(" << Args[0];
2153 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2154 OS << ", " << Args[i];
2155 OS << ")";
2156 }
2157 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002158
Chris Lattner8cab0212008-01-05 22:25:12 +00002159 if (Trees.size() > 1)
2160 OS << "[\n";
2161 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2162 OS << "\t";
2163 Trees[i]->print(OS);
2164 OS << "\n";
2165 }
2166
2167 if (Trees.size() > 1)
2168 OS << "]\n";
2169}
2170
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002171void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002172
2173//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002174// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002175//
2176
Jim Grosbach65586fe2010-12-21 16:16:00 +00002177CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002178 Records(R), Target(R) {
2179
Dale Johannesenb842d522009-02-05 01:49:45 +00002180 Intrinsics = LoadIntrinsics(Records, false);
2181 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002182 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002183 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002184 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002185 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002186 ParseDefaultOperands();
2187 ParseInstructions();
2188 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002189
Chris Lattner8cab0212008-01-05 22:25:12 +00002190 // Generate variants. For example, commutative patterns can match
2191 // multiple ways. Add them to PatternsToMatch as well.
2192 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002193
2194 // Infer instruction flags. For example, we can detect loads,
2195 // stores, and side effects in many cases by examining an
2196 // instruction's pattern.
2197 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002198
2199 // Verify that instruction flags match the patterns.
2200 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002201}
2202
Chris Lattnerab3242f2008-01-06 01:10:31 +00002203CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramerc2dbd5d2009-08-23 10:39:21 +00002204 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner8cab0212008-01-05 22:25:12 +00002205 E = PatternFragments.end(); I != E; ++I)
2206 delete I->second;
2207}
2208
2209
Chris Lattnerab3242f2008-01-06 01:10:31 +00002210Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002211 Record *N = Records.getDef(Name);
2212 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002213 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner8cab0212008-01-05 22:25:12 +00002214 exit(1);
2215 }
2216 return N;
2217}
2218
2219// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002220void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002221 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2222 while (!Nodes.empty()) {
2223 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2224 Nodes.pop_back();
2225 }
2226
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002227 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002228 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2229 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2230 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2231}
2232
2233/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2234/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002235void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002236 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2237 while (!Xforms.empty()) {
2238 Record *XFormNode = Xforms.back();
2239 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00002240 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002241 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002242
2243 Xforms.pop_back();
2244 }
2245}
2246
Chris Lattnerab3242f2008-01-06 01:10:31 +00002247void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002248 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2249 while (!AMs.empty()) {
2250 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2251 AMs.pop_back();
2252 }
2253}
2254
2255
2256/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2257/// file, building up the PatternFragments map. After we've collected them all,
2258/// inline fragments together as necessary, so that there are no references left
2259/// inside a pattern fragment to a pattern fragment.
2260///
Chris Lattnerab3242f2008-01-06 01:10:31 +00002261void CodeGenDAGPatterns::ParsePatternFragments() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002262 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002263
Chris Lattnere7170df2008-01-05 22:43:57 +00002264 // First step, parse all of the fragments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002265 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00002266 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Chris Lattner8cab0212008-01-05 22:25:12 +00002267 TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
2268 PatternFragments[Fragments[i]] = P;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002269
Chris Lattnere7170df2008-01-05 22:43:57 +00002270 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002271 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002272 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002273
Chris Lattnere7170df2008-01-05 22:43:57 +00002274 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002275 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002276
Chris Lattner8cab0212008-01-05 22:25:12 +00002277 // Parse the operands list.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002278 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002279 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002280 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002281 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002282 if (!OpsOp ||
2283 (OpsOp->getDef()->getName() != "ops" &&
2284 OpsOp->getDef()->getName() != "outs" &&
2285 OpsOp->getDef()->getName() != "ins"))
2286 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002287
2288 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002289 Args.clear();
2290 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002291 if (!isa<DefInit>(OpsList->getArg(j)) ||
2292 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002293 P->error("Operands list should all be 'node' values.");
2294 if (OpsList->getArgName(j).empty())
2295 P->error("Operands list should have names for each operand!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002296 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner8cab0212008-01-05 22:25:12 +00002297 P->error("'" + OpsList->getArgName(j) +
2298 "' does not occur in pattern or was multiply specified!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002299 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner8cab0212008-01-05 22:25:12 +00002300 Args.push_back(OpsList->getArgName(j));
2301 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002302
Chris Lattnere7170df2008-01-05 22:43:57 +00002303 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002304 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002305 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002306
Chris Lattnere7170df2008-01-05 22:43:57 +00002307 // If there is a code init for this fragment, keep track of the fact that
2308 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002309 TreePredicateFn PredFn(P);
2310 if (!PredFn.isAlwaysTrue())
2311 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002312
Chris Lattner8cab0212008-01-05 22:25:12 +00002313 // If there is a node transformation corresponding to this, keep track of
2314 // it.
2315 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2316 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2317 P->getOnlyTree()->setTransformFn(Transform);
2318 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002319
Chris Lattner8cab0212008-01-05 22:25:12 +00002320 // Now that we've parsed all of the tree fragments, do a closure on them so
2321 // that there are not references to PatFrags left inside of them.
Chris Lattner2e253b42008-06-30 03:02:03 +00002322 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
2323 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner8cab0212008-01-05 22:25:12 +00002324 ThePat->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002325
Chris Lattner8cab0212008-01-05 22:25:12 +00002326 // Infer as many types as possible. Don't worry about it if we don't infer
2327 // all of them, some may depend on the inputs of the pattern.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002328 ThePat->InferAllTypes();
2329 ThePat->resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002330
Chris Lattner8cab0212008-01-05 22:25:12 +00002331 // If debugging, print out the pattern fragment result.
2332 DEBUG(ThePat->dump());
2333 }
2334}
2335
Chris Lattnerab3242f2008-01-06 01:10:31 +00002336void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002337 std::vector<Record*> DefaultOps;
2338 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002339
2340 // Find some SDNode.
2341 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002342 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002343
Tom Stellardb7246a72012-09-06 14:15:52 +00002344 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2345 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002346
Tom Stellardb7246a72012-09-06 14:15:52 +00002347 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2348 // SomeSDnode so that we can parse this.
2349 std::vector<std::pair<Init*, std::string> > Ops;
2350 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2351 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2352 DefaultInfo->getArgName(op)));
2353 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002354
Tom Stellardb7246a72012-09-06 14:15:52 +00002355 // Create a TreePattern to parse this.
2356 TreePattern P(DefaultOps[i], DI, false, *this);
2357 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002358
Tom Stellardb7246a72012-09-06 14:15:52 +00002359 // Copy the operands over into a DAGDefaultOperand.
2360 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002361
Tom Stellardb7246a72012-09-06 14:15:52 +00002362 TreePatternNode *T = P.getTree(0);
2363 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2364 TreePatternNode *TPN = T->getChild(op);
2365 while (TPN->ApplyTypeConstraints(P, false))
2366 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002367
Tom Stellardb7246a72012-09-06 14:15:52 +00002368 if (TPN->ContainsUnresolvedType()) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002369 PrintFatalError("Value #" + utostr(i) + " of OperandWithDefaultOps '" +
2370 DefaultOps[i]->getName() +"' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002371 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002372 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002373 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002374
2375 // Insert it into the DefaultOperands map so we can find it later.
2376 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002377 }
2378}
2379
2380/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2381/// instruction input. Return true if this is a real use.
2382static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002383 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002384 // No name -> not interesting.
2385 if (Pat->getName().empty()) {
2386 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002387 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002388 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2389 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002390 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002391 }
2392 return false;
2393 }
2394
2395 Record *Rec;
2396 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002397 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002398 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2399 Rec = DI->getDef();
2400 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002401 Rec = Pat->getOperator();
2402 }
2403
2404 // SRCVALUE nodes are ignored.
2405 if (Rec->getName() == "srcvalue")
2406 return false;
2407
2408 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2409 if (!Slot) {
2410 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002411 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002412 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002413 Record *SlotRec;
2414 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002415 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002416 } else {
2417 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2418 SlotRec = Slot->getOperator();
2419 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002420
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002421 // Ensure that the inputs agree if we've already seen this input.
2422 if (Rec != SlotRec)
2423 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002424 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002425 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002426 return true;
2427}
2428
2429/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2430/// part of "I", the instruction), computing the set of inputs and outputs of
2431/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002432void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002433FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2434 std::map<std::string, TreePatternNode*> &InstInputs,
2435 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002436 std::vector<Record*> &InstImpResults) {
2437 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002438 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002439 if (!isUse && Pat->getTransformFn())
2440 I->error("Cannot specify a transform function for a non-input value!");
2441 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002442 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002443
Chris Lattnerf2d70992010-02-17 06:53:36 +00002444 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002445 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2446 TreePatternNode *Dest = Pat->getChild(i);
2447 if (!Dest->isLeaf())
2448 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002449
Sean Silvafb509ed2012-10-10 20:24:43 +00002450 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002451 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2452 I->error("implicitly defined value should be a register!");
2453 InstImpResults.push_back(Val->getDef());
2454 }
2455 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002456 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002457
Chris Lattnerf2d70992010-02-17 06:53:36 +00002458 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002459 // If this is not a set, verify that the children nodes are not void typed,
2460 // and recurse.
2461 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002462 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002463 I->error("Cannot have void nodes inside of patterns!");
2464 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002465 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002466 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002467
Chris Lattner8cab0212008-01-05 22:25:12 +00002468 // If this is a non-leaf node with no children, treat it basically as if
2469 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002470 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002471
Chris Lattner8cab0212008-01-05 22:25:12 +00002472 if (!isUse && Pat->getTransformFn())
2473 I->error("Cannot specify a transform function for a non-input value!");
2474 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002475 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002476
Chris Lattner8cab0212008-01-05 22:25:12 +00002477 // Otherwise, this is a set, validate and collect instruction results.
2478 if (Pat->getNumChildren() == 0)
2479 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002480
Chris Lattner8cab0212008-01-05 22:25:12 +00002481 if (Pat->getTransformFn())
2482 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002483
Chris Lattner8cab0212008-01-05 22:25:12 +00002484 // Check the set destinations.
2485 unsigned NumDests = Pat->getNumChildren()-1;
2486 for (unsigned i = 0; i != NumDests; ++i) {
2487 TreePatternNode *Dest = Pat->getChild(i);
2488 if (!Dest->isLeaf())
2489 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002490
Sean Silvafb509ed2012-10-10 20:24:43 +00002491 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002492 if (!Val)
2493 I->error("set destination should be a register!");
2494
2495 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002496 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002497 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002498 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002499 if (Dest->getName().empty())
2500 I->error("set destination must have a name!");
2501 if (InstResults.count(Dest->getName()))
2502 I->error("cannot set '" + Dest->getName() +"' multiple times");
2503 InstResults[Dest->getName()] = Dest;
2504 } else if (Val->getDef()->isSubClassOf("Register")) {
2505 InstImpResults.push_back(Val->getDef());
2506 } else {
2507 I->error("set destination should be a register!");
2508 }
2509 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002510
Chris Lattner8cab0212008-01-05 22:25:12 +00002511 // Verify and collect info from the computation.
2512 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002513 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002514}
2515
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002516//===----------------------------------------------------------------------===//
2517// Instruction Analysis
2518//===----------------------------------------------------------------------===//
2519
2520class InstAnalyzer {
2521 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002522public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002523 bool hasSideEffects;
2524 bool mayStore;
2525 bool mayLoad;
2526 bool isBitcast;
2527 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002528
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002529 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2530 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2531 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002532
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002533 void Analyze(const TreePattern *Pat) {
2534 // Assume only the first tree is the pattern. The others are clobber nodes.
2535 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002536 }
2537
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002538 void Analyze(const PatternToMatch *Pat) {
2539 AnalyzeNode(Pat->getSrcPattern());
2540 }
2541
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002542private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002543 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002544 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002545 return false;
2546
2547 if (N->getNumChildren() != 2)
2548 return false;
2549
2550 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002551 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002552 return false;
2553
2554 const TreePatternNode *N1 = N->getChild(1);
2555 if (N1->isLeaf())
2556 return false;
2557 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2558 return false;
2559
2560 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2561 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2562 return false;
2563 return OpInfo.getEnumName() == "ISD::BITCAST";
2564 }
2565
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002566public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002567 void AnalyzeNode(const TreePatternNode *N) {
2568 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002569 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002570 Record *LeafRec = DI->getDef();
2571 // Handle ComplexPattern leaves.
2572 if (LeafRec->isSubClassOf("ComplexPattern")) {
2573 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2574 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2575 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002576 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002577 }
2578 }
2579 return;
2580 }
2581
2582 // Analyze children.
2583 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2584 AnalyzeNode(N->getChild(i));
2585
2586 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002587 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002588 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002589 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002590 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002591
2592 // Get information about the SDNode for the operator.
2593 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
2594
2595 // Notice properties of the node.
2596 if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
2597 if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002598 if (OpInfo.hasProperty(SDNPSideEffect)) hasSideEffects = true;
2599 if (OpInfo.hasProperty(SDNPVariadic)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002600
2601 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2602 // If this is an intrinsic, analyze it.
2603 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2604 mayLoad = true;// These may load memory.
2605
Dan Gohmanddb2d652010-08-05 23:36:21 +00002606 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002607 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2608
Dan Gohmanddb2d652010-08-05 23:36:21 +00002609 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002610 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002611 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002612 }
2613 }
2614
2615};
2616
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002617static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002618 const InstAnalyzer &PatInfo,
2619 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002620 bool Error = false;
2621
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002622 // Remember where InstInfo got its flags.
2623 if (InstInfo.hasUndefFlags())
2624 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002625
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002626 // Check explicitly set flags for consistency.
2627 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2628 !InstInfo.hasSideEffects_Unset) {
2629 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2630 // the pattern has no side effects. That could be useful for div/rem
2631 // instructions that may trap.
2632 if (!InstInfo.hasSideEffects) {
2633 Error = true;
2634 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2635 Twine(InstInfo.hasSideEffects));
2636 }
2637 }
2638
2639 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2640 Error = true;
2641 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2642 Twine(InstInfo.mayStore));
2643 }
2644
2645 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2646 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2647 // Some targets translate imediates to loads.
2648 if (!InstInfo.mayLoad) {
2649 Error = true;
2650 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2651 Twine(InstInfo.mayLoad));
2652 }
2653 }
2654
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002655 // Transfer inferred flags.
2656 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2657 InstInfo.mayStore |= PatInfo.mayStore;
2658 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002659
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002660 // These flags are silently added without any verification.
2661 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002662
2663 // Don't infer isVariadic. This flag means something different on SDNodes and
2664 // instructions. For example, a CALL SDNode is variadic because it has the
2665 // call arguments as operands, but a CALL instruction is not variadic - it
2666 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002667
2668 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002669}
2670
Jim Grosbach514410b2012-07-17 00:47:06 +00002671/// hasNullFragReference - Return true if the DAG has any reference to the
2672/// null_frag operator.
2673static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002674 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002675 if (!OpDef) return false;
2676 Record *Operator = OpDef->getDef();
2677
2678 // If this is the null fragment, return true.
2679 if (Operator->getName() == "null_frag") return true;
2680 // If any of the arguments reference the null fragment, return true.
2681 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002682 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002683 if (Arg && hasNullFragReference(Arg))
2684 return true;
2685 }
2686
2687 return false;
2688}
2689
2690/// hasNullFragReference - Return true if any DAG in the list references
2691/// the null_frag operator.
2692static bool hasNullFragReference(ListInit *LI) {
2693 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002694 DagInit *DI = dyn_cast<DagInit>(LI->getElement(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002695 assert(DI && "non-dag in an instruction Pattern list?!");
2696 if (hasNullFragReference(DI))
2697 return true;
2698 }
2699 return false;
2700}
2701
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002702/// Get all the instructions in a tree.
2703static void
2704getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2705 if (Tree->isLeaf())
2706 return;
2707 if (Tree->getOperator()->isSubClassOf("Instruction"))
2708 Instrs.push_back(Tree->getOperator());
2709 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2710 getInstructionsInTree(Tree->getChild(i), Instrs);
2711}
2712
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002713/// Check the class of a pattern leaf node against the instruction operand it
2714/// represents.
2715static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2716 Record *Leaf) {
2717 if (OI.Rec == Leaf)
2718 return true;
2719
2720 // Allow direct value types to be used in instruction set patterns.
2721 // The type will be checked later.
2722 if (Leaf->isSubClassOf("ValueType"))
2723 return true;
2724
2725 // Patterns can also be ComplexPattern instances.
2726 if (Leaf->isSubClassOf("ComplexPattern"))
2727 return true;
2728
2729 return false;
2730}
2731
Ahmed Bougacha14107512013-10-28 18:07:21 +00002732const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2733 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002734
Ahmed Bougacha14107512013-10-28 18:07:21 +00002735 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002736
Chris Lattner8cab0212008-01-05 22:25:12 +00002737 // Parse the instruction.
Ahmed Bougacha14107512013-10-28 18:07:21 +00002738 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002739 // Inline pattern fragments into it.
2740 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002741
Chris Lattner8cab0212008-01-05 22:25:12 +00002742 // Infer as many types as possible. If we cannot infer all of them, we can
2743 // never do anything with this instruction pattern: report it to the user.
2744 if (!I->InferAllTypes())
2745 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002746
2747 // InstInputs - Keep track of all of the inputs of the instruction, along
Chris Lattner8cab0212008-01-05 22:25:12 +00002748 // with the record they are declared as.
2749 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002750
Chris Lattner8cab0212008-01-05 22:25:12 +00002751 // InstResults - Keep track of all the virtual registers that are 'set'
2752 // in the instruction, including what reg class they are.
2753 std::map<std::string, TreePatternNode*> InstResults;
2754
Chris Lattner8cab0212008-01-05 22:25:12 +00002755 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002756
Chris Lattner8cab0212008-01-05 22:25:12 +00002757 // Verify that the top-level forms in the instruction are of void type, and
2758 // fill in the InstResults map.
2759 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2760 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerf1447252010-03-19 21:37:09 +00002761 if (Pat->getNumTypes() != 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002762 I->error("Top-level forms in instruction pattern should have"
2763 " void types");
2764
2765 // Find inputs and outputs, and verify the structure of the uses/defs.
2766 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002767 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002768 }
2769
2770 // Now that we have inputs and outputs of the pattern, inspect the operands
2771 // list for the instruction. This determines the order that operands are
2772 // added to the machine instruction the node corresponds to.
2773 unsigned NumResults = InstResults.size();
2774
2775 // Parse the operands list from the (ops) list, validating it.
2776 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002777
2778 // Check that all of the results occur first in the list.
2779 std::vector<Record*> Results;
Chris Lattnerf1447252010-03-19 21:37:09 +00002780 TreePatternNode *Res0Node = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00002781 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattnerd8adec72010-11-01 04:03:32 +00002782 if (i == CGI.Operands.size())
Chris Lattner8cab0212008-01-05 22:25:12 +00002783 I->error("'" + InstResults.begin()->first +
2784 "' set but does not appear in operand list!");
Chris Lattnerd8adec72010-11-01 04:03:32 +00002785 const std::string &OpName = CGI.Operands[i].Name;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002786
Chris Lattner8cab0212008-01-05 22:25:12 +00002787 // Check that it exists in InstResults.
2788 TreePatternNode *RNode = InstResults[OpName];
2789 if (RNode == 0)
2790 I->error("Operand $" + OpName + " does not exist in operand list!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002791
Chris Lattner8cab0212008-01-05 22:25:12 +00002792 if (i == 0)
2793 Res0Node = RNode;
Sean Silva88eb8dd2012-10-10 20:24:47 +00002794 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
Chris Lattner8cab0212008-01-05 22:25:12 +00002795 if (R == 0)
2796 I->error("Operand $" + OpName + " should be a set destination: all "
2797 "outputs must occur before inputs in operand list!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002798
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002799 if (!checkOperandClass(CGI.Operands[i], R))
Chris Lattner8cab0212008-01-05 22:25:12 +00002800 I->error("Operand $" + OpName + " class mismatch!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002801
Chris Lattner8cab0212008-01-05 22:25:12 +00002802 // Remember the return type.
Chris Lattnerd8adec72010-11-01 04:03:32 +00002803 Results.push_back(CGI.Operands[i].Rec);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002804
Chris Lattner8cab0212008-01-05 22:25:12 +00002805 // Okay, this one checks out.
2806 InstResults.erase(OpName);
2807 }
2808
2809 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2810 // the copy while we're checking the inputs.
2811 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2812
2813 std::vector<TreePatternNode*> ResultNodeOperands;
2814 std::vector<Record*> Operands;
Chris Lattnerd8adec72010-11-01 04:03:32 +00002815 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2816 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
Chris Lattner8cab0212008-01-05 22:25:12 +00002817 const std::string &OpName = Op.Name;
2818 if (OpName.empty())
2819 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2820
2821 if (!InstInputsCheck.count(OpName)) {
Tom Stellardb7246a72012-09-06 14:15:52 +00002822 // If this is an operand with a DefaultOps set filled in, we can ignore
2823 // this. When we codegen it, we will do so as always executed.
2824 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002825 // Does it have a non-empty DefaultOps field? If so, ignore this
2826 // operand.
2827 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2828 continue;
2829 }
2830 I->error("Operand $" + OpName +
2831 " does not appear in the instruction pattern");
2832 }
2833 TreePatternNode *InVal = InstInputsCheck[OpName];
2834 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002835
Sean Silva88eb8dd2012-10-10 20:24:47 +00002836 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00002837 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002838 if (!checkOperandClass(Op, InRec))
Chris Lattner8cab0212008-01-05 22:25:12 +00002839 I->error("Operand $" + OpName + "'s register class disagrees"
2840 " between the operand and pattern");
2841 }
2842 Operands.push_back(Op.Rec);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002843
Chris Lattner8cab0212008-01-05 22:25:12 +00002844 // Construct the result for the dest-pattern operand list.
2845 TreePatternNode *OpNode = InVal->clone();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002846
Chris Lattner8cab0212008-01-05 22:25:12 +00002847 // No predicate is useful on the result.
Dan Gohman6e979022008-10-15 06:17:21 +00002848 OpNode->clearPredicateFns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002849
Chris Lattner8cab0212008-01-05 22:25:12 +00002850 // Promote the xform function to be an explicit node if set.
2851 if (Record *Xform = OpNode->getTransformFn()) {
2852 OpNode->setTransformFn(0);
2853 std::vector<TreePatternNode*> Children;
2854 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00002855 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00002856 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002857
Chris Lattner8cab0212008-01-05 22:25:12 +00002858 ResultNodeOperands.push_back(OpNode);
2859 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002860
Chris Lattner8cab0212008-01-05 22:25:12 +00002861 if (!InstInputsCheck.empty())
2862 I->error("Input operand $" + InstInputsCheck.begin()->first +
2863 " occurs in pattern but not in operands list!");
2864
2865 TreePatternNode *ResultPattern =
Chris Lattnerf1447252010-03-19 21:37:09 +00002866 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2867 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner8cab0212008-01-05 22:25:12 +00002868 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerf1447252010-03-19 21:37:09 +00002869 for (unsigned i = 0; i != NumResults; ++i)
2870 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner8cab0212008-01-05 22:25:12 +00002871
2872 // Create and insert the instruction.
Chris Lattner5debc332010-04-20 06:30:25 +00002873 // FIXME: InstImpResults should not be part of DAGInstruction.
Chris Lattner9dc68d32010-04-20 06:28:43 +00002874 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00002875 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
Chris Lattner8cab0212008-01-05 22:25:12 +00002876
2877 // Use a temporary tree pattern to infer all types and make sure that the
2878 // constructed result is correct. This depends on the instruction already
Ahmed Bougacha14107512013-10-28 18:07:21 +00002879 // being inserted into the DAGInsts map.
Chris Lattner8cab0212008-01-05 22:25:12 +00002880 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002881 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00002882
Ahmed Bougacha14107512013-10-28 18:07:21 +00002883 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
Chris Lattner8cab0212008-01-05 22:25:12 +00002884 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002885
Ahmed Bougacha14107512013-10-28 18:07:21 +00002886 return TheInsertedInst;
2887 }
2888
2889/// ParseInstructions - Parse all of the instructions, inlining and resolving
2890/// any fragments involved. This populates the Instructions list with fully
2891/// resolved instructions.
2892void CodeGenDAGPatterns::ParseInstructions() {
2893 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2894
2895 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
2896 ListInit *LI = 0;
2897
2898 if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
2899 LI = Instrs[i]->getValueAsListInit("Pattern");
2900
2901 // If there is no pattern, only collect minimal information about the
2902 // instruction for its operand list. We have to assume that there is one
2903 // result, as we have no detailed info. A pattern which references the
2904 // null_frag operator is as-if no pattern were specified. Normally this
2905 // is from a multiclass expansion w/ a SDPatternOperator passed in as
2906 // null_frag.
2907 if (!LI || LI->getSize() == 0 || hasNullFragReference(LI)) {
2908 std::vector<Record*> Results;
2909 std::vector<Record*> Operands;
2910
2911 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2912
2913 if (InstInfo.Operands.size() != 0) {
2914 if (InstInfo.Operands.NumDefs == 0) {
2915 // These produce no results
2916 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2917 Operands.push_back(InstInfo.Operands[j].Rec);
2918 } else {
2919 // Assume the first operand is the result.
2920 Results.push_back(InstInfo.Operands[0].Rec);
2921
2922 // The rest are inputs.
2923 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2924 Operands.push_back(InstInfo.Operands[j].Rec);
2925 }
2926 }
2927
2928 // Create and insert the instruction.
2929 std::vector<Record*> ImpResults;
2930 Instructions.insert(std::make_pair(Instrs[i],
2931 DAGInstruction(0, Results, Operands, ImpResults)));
2932 continue; // no pattern.
2933 }
2934
2935 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2936 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
2937
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00002938 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00002939 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002940 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002941
Chris Lattner8cab0212008-01-05 22:25:12 +00002942 // If we can, convert the instructions to be patterns that are matched!
Sean Silvaa4e2c5f2012-09-19 01:47:00 +00002943 for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
Benjamin Kramerc2dbd5d2009-08-23 10:39:21 +00002944 Instructions.begin(),
Chris Lattner8cab0212008-01-05 22:25:12 +00002945 E = Instructions.end(); II != E; ++II) {
2946 DAGInstruction &TheInst = II->second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002947 TreePattern *I = TheInst.getPattern();
Chris Lattner8cab0212008-01-05 22:25:12 +00002948 if (I == 0) continue; // No pattern.
2949
2950 // FIXME: Assume only the first tree is the pattern. The others are clobber
2951 // nodes.
2952 TreePatternNode *Pattern = I->getTree(0);
2953 TreePatternNode *SrcPattern;
2954 if (Pattern->getOperator()->getName() == "set") {
2955 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2956 } else{
2957 // Not a set (store or something?)
2958 SrcPattern = Pattern;
2959 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002960
Chris Lattner8cab0212008-01-05 22:25:12 +00002961 Record *Instr = II->first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00002962 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00002963 PatternToMatch(Instr,
2964 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00002965 SrcPattern,
2966 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00002967 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00002968 Instr->getValueAsInt("AddedComplexity"),
2969 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00002970 }
2971}
2972
Chris Lattnera7722b62010-02-23 06:55:24 +00002973
2974typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
2975
Jim Grosbach65586fe2010-12-21 16:16:00 +00002976static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00002977 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002978 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00002979 if (!P->getName().empty()) {
2980 NameRecord &Rec = Names[P->getName()];
2981 // If this is the first instance of the name, remember the node.
2982 if (Rec.second++ == 0)
2983 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00002984 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00002985 PatternTop->error("repetition of value: $" + P->getName() +
2986 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00002987 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002988
Chris Lattner94d3b0a2010-02-23 06:35:45 +00002989 if (!P->isLeaf()) {
2990 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00002991 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00002992 }
2993}
2994
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002995void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner0c0baa92010-02-23 06:16:51 +00002996 const PatternToMatch &PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00002997 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00002998 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00002999 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3000 PrintWarning(Pattern->getRecord()->getLoc(),
3001 Twine("Pattern can never match: ") + Reason);
3002 return;
3003 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003004
Chris Lattner1e634e32010-03-01 22:29:19 +00003005 // If the source pattern's root is a complex pattern, that complex pattern
3006 // must specify the nodes it can potentially match.
3007 if (const ComplexPattern *CP =
3008 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3009 if (CP->getRootNodes().empty())
3010 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3011 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003012
3013
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003014 // Find all of the named values in the input and output, ensure they have the
3015 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003016 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003017 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3018 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003019
3020 // Scan all of the named values in the destination pattern, rejecting them if
3021 // they don't exist in the input pattern.
Chris Lattnera7722b62010-02-23 06:55:24 +00003022 for (std::map<std::string, NameRecord>::iterator
Chris Lattner4b9225b2010-02-23 07:50:58 +00003023 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003024 if (SrcNames[I->first].first == 0)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003025 Pattern->error("Pattern has input without matching name in output: $" +
3026 I->first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003027 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003028
Chris Lattnera7722b62010-02-23 06:55:24 +00003029 // Scan all of the named values in the source pattern, rejecting them if the
3030 // name isn't used in the dest, and isn't used to tie two values together.
3031 for (std::map<std::string, NameRecord>::iterator
3032 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
3033 if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
3034 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003035
Chris Lattner0c0baa92010-02-23 06:16:51 +00003036 PatternsToMatch.push_back(PTM);
3037}
3038
3039
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003040
3041void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattner918be522010-03-19 00:34:35 +00003042 const std::vector<const CodeGenInstruction*> &Instructions =
3043 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003044
3045 // First try to infer flags from the primary instruction pattern, if any.
3046 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003047 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003048 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3049 CodeGenInstruction &InstInfo =
3050 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003051
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003052 // Treat neverHasSideEffects = 1 as the equivalent of hasSideEffects = 0.
3053 // This flag is obsolete and will be removed.
3054 if (InstInfo.neverHasSideEffects) {
3055 assert(!InstInfo.hasSideEffects);
3056 InstInfo.hasSideEffects_Unset = false;
3057 }
3058
3059 // Get the primary instruction pattern.
3060 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3061 if (!Pattern) {
3062 if (InstInfo.hasUndefFlags())
3063 Revisit.push_back(&InstInfo);
3064 continue;
3065 }
3066 InstAnalyzer PatInfo(*this);
3067 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003068 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003069 }
3070
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003071 // Second, look for single-instruction patterns defined outside the
3072 // instruction.
3073 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3074 const PatternToMatch &PTM = *I;
3075
3076 // We can only infer from single-instruction patterns, otherwise we won't
3077 // know which instruction should get the flags.
3078 SmallVector<Record*, 8> PatInstrs;
3079 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3080 if (PatInstrs.size() != 1)
3081 continue;
3082
3083 // Get the single instruction.
3084 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3085
3086 // Only infer properties from the first pattern. We'll verify the others.
3087 if (InstInfo.InferredFrom)
3088 continue;
3089
3090 InstAnalyzer PatInfo(*this);
3091 PatInfo.Analyze(&PTM);
3092 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3093 }
3094
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003095 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003096 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003097
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003098 // Revisit instructions with undefined flags and no pattern.
3099 if (Target.guessInstructionProperties()) {
3100 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3101 CodeGenInstruction &InstInfo = *Revisit[i];
3102 if (InstInfo.InferredFrom)
3103 continue;
3104 // The mayLoad and mayStore flags default to false.
3105 // Conservatively assume hasSideEffects if it wasn't explicit.
3106 if (InstInfo.hasSideEffects_Unset)
3107 InstInfo.hasSideEffects = true;
3108 }
3109 return;
3110 }
3111
3112 // Complain about any flags that are still undefined.
3113 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3114 CodeGenInstruction &InstInfo = *Revisit[i];
3115 if (InstInfo.InferredFrom)
3116 continue;
3117 if (InstInfo.hasSideEffects_Unset)
3118 PrintError(InstInfo.TheDef->getLoc(),
3119 "Can't infer hasSideEffects from patterns");
3120 if (InstInfo.mayStore_Unset)
3121 PrintError(InstInfo.TheDef->getLoc(),
3122 "Can't infer mayStore from patterns");
3123 if (InstInfo.mayLoad_Unset)
3124 PrintError(InstInfo.TheDef->getLoc(),
3125 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003126 }
3127}
3128
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003129
3130/// Verify instruction flags against pattern node properties.
3131void CodeGenDAGPatterns::VerifyInstructionFlags() {
3132 unsigned Errors = 0;
3133 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3134 const PatternToMatch &PTM = *I;
3135 SmallVector<Record*, 8> Instrs;
3136 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3137 if (Instrs.empty())
3138 continue;
3139
3140 // Count the number of instructions with each flag set.
3141 unsigned NumSideEffects = 0;
3142 unsigned NumStores = 0;
3143 unsigned NumLoads = 0;
3144 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3145 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3146 NumSideEffects += InstInfo.hasSideEffects;
3147 NumStores += InstInfo.mayStore;
3148 NumLoads += InstInfo.mayLoad;
3149 }
3150
3151 // Analyze the source pattern.
3152 InstAnalyzer PatInfo(*this);
3153 PatInfo.Analyze(&PTM);
3154
3155 // Collect error messages.
3156 SmallVector<std::string, 4> Msgs;
3157
3158 // Check for missing flags in the output.
3159 // Permit extra flags for now at least.
3160 if (PatInfo.hasSideEffects && !NumSideEffects)
3161 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3162
3163 // Don't verify store flags on instructions with side effects. At least for
3164 // intrinsics, side effects implies mayStore.
3165 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3166 Msgs.push_back("pattern may store, but mayStore isn't set");
3167
3168 // Similarly, mayStore implies mayLoad on intrinsics.
3169 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3170 Msgs.push_back("pattern may load, but mayLoad isn't set");
3171
3172 // Print error messages.
3173 if (Msgs.empty())
3174 continue;
3175 ++Errors;
3176
3177 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
3178 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
3179 (Instrs.size() == 1 ?
3180 "instruction" : "output instructions"));
3181 // Provide the location of the relevant instruction definitions.
3182 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3183 if (Instrs[i] != PTM.getSrcRecord())
3184 PrintError(Instrs[i]->getLoc(), "defined here");
3185 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3186 if (InstInfo.InferredFrom &&
3187 InstInfo.InferredFrom != InstInfo.TheDef &&
3188 InstInfo.InferredFrom != PTM.getSrcRecord())
3189 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from patttern");
3190 }
3191 }
3192 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003193 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003194}
3195
Chris Lattnercabe0372010-03-15 06:00:16 +00003196/// Given a pattern result with an unresolved type, see if we can find one
3197/// instruction with an unresolved result type. Force this result type to an
3198/// arbitrary element if it's possible types to converge results.
3199static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3200 if (N->isLeaf())
3201 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003202
Chris Lattnercabe0372010-03-15 06:00:16 +00003203 // Analyze children.
3204 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3205 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3206 return true;
3207
3208 if (!N->getOperator()->isSubClassOf("Instruction"))
3209 return false;
3210
3211 // If this type is already concrete or completely unknown we can't do
3212 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003213 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3214 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3215 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003216
Chris Lattnerf1447252010-03-19 21:37:09 +00003217 // Otherwise, force its type to the first possibility (an arbitrary choice).
3218 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3219 return true;
3220 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003221
Chris Lattnerf1447252010-03-19 21:37:09 +00003222 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003223}
3224
Chris Lattnerab3242f2008-01-06 01:10:31 +00003225void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003226 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3227
3228 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00003229 Record *CurPattern = Patterns[i];
David Greeneaf8ee2c2011-07-29 22:43:06 +00003230 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003231
3232 // If the pattern references the null_frag, there's nothing to do.
3233 if (hasNullFragReference(Tree))
3234 continue;
3235
Chris Lattner5c2182e2010-03-27 02:53:27 +00003236 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003237
3238 // Inline pattern fragments into it.
3239 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003240
David Greeneaf8ee2c2011-07-29 22:43:06 +00003241 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner8cab0212008-01-05 22:25:12 +00003242 if (LI->getSize() == 0) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003243
Chris Lattner8cab0212008-01-05 22:25:12 +00003244 // Parse the instruction.
Chris Lattnerf1447252010-03-19 21:37:09 +00003245 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003246
Chris Lattner8cab0212008-01-05 22:25:12 +00003247 // Inline pattern fragments into it.
3248 Result->InlinePatternFragments();
3249
3250 if (Result->getNumTrees() != 1)
3251 Result->error("Cannot handle instructions producing instructions "
3252 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003253
Chris Lattner8cab0212008-01-05 22:25:12 +00003254 bool IterateInference;
3255 bool InferredAllPatternTypes, InferredAllResultTypes;
3256 do {
3257 // Infer as many types as possible. If we cannot infer all of them, we
3258 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003259 InferredAllPatternTypes =
3260 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003261
Chris Lattner8cab0212008-01-05 22:25:12 +00003262 // Infer as many types as possible. If we cannot infer all of them, we
3263 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003264 InferredAllResultTypes =
3265 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003266
Chris Lattnerfdc20712010-03-18 23:15:10 +00003267 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003268
Chris Lattner8cab0212008-01-05 22:25:12 +00003269 // Apply the type of the result to the source pattern. This helps us
3270 // resolve cases where the input type is known to be a pointer type (which
3271 // is considered resolved), but the result knows it needs to be 32- or
3272 // 64-bits. Infer the other way for good measure.
Chris Lattnerf1447252010-03-19 21:37:09 +00003273 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
3274 Pattern->getTree(0)->getNumTypes());
3275 i != e; ++i) {
Chris Lattnerfdc20712010-03-18 23:15:10 +00003276 IterateInference = Pattern->getTree(0)->
Chris Lattnerf1447252010-03-19 21:37:09 +00003277 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003278 IterateInference |= Result->getTree(0)->
Chris Lattnerf1447252010-03-19 21:37:09 +00003279 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003280 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003281
Chris Lattnercabe0372010-03-15 06:00:16 +00003282 // If our iteration has converged and the input pattern's types are fully
3283 // resolved but the result pattern is not fully resolved, we may have a
3284 // situation where we have two instructions in the result pattern and
3285 // the instructions require a common register class, but don't care about
3286 // what actual MVT is used. This is actually a bug in our modelling:
3287 // output patterns should have register classes, not MVTs.
3288 //
3289 // In any case, to handle this, we just go through and disambiguate some
3290 // arbitrary types to the result pattern's nodes.
3291 if (!IterateInference && InferredAllPatternTypes &&
3292 !InferredAllResultTypes)
3293 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
3294 *Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003295 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003296
Chris Lattner8cab0212008-01-05 22:25:12 +00003297 // Verify that we inferred enough types that we can do something with the
3298 // pattern and result. If these fire the user has to add type casts.
3299 if (!InferredAllPatternTypes)
3300 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003301 if (!InferredAllResultTypes) {
3302 Pattern->dump();
Chris Lattner8cab0212008-01-05 22:25:12 +00003303 Result->error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003304 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003305
Chris Lattner8cab0212008-01-05 22:25:12 +00003306 // Validate that the input pattern is correct.
3307 std::map<std::string, TreePatternNode*> InstInputs;
3308 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003309 std::vector<Record*> InstImpResults;
3310 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3311 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3312 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003313 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003314
3315 // Promote the xform function to be an explicit node if set.
3316 TreePatternNode *DstPattern = Result->getOnlyTree();
3317 std::vector<TreePatternNode*> ResultNodeOperands;
3318 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3319 TreePatternNode *OpNode = DstPattern->getChild(ii);
3320 if (Record *Xform = OpNode->getTransformFn()) {
3321 OpNode->setTransformFn(0);
3322 std::vector<TreePatternNode*> Children;
3323 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003324 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003325 }
3326 ResultNodeOperands.push_back(OpNode);
3327 }
3328 DstPattern = Result->getOnlyTree();
3329 if (!DstPattern->isLeaf())
3330 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003331 ResultNodeOperands,
3332 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003333
Chris Lattnerf1447252010-03-19 21:37:09 +00003334 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
3335 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003336
Chris Lattner8cab0212008-01-05 22:25:12 +00003337 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
3338 Temp.InferAllTypes();
3339
Jim Grosbach65586fe2010-12-21 16:16:00 +00003340
Chris Lattner0c0baa92010-02-23 06:16:51 +00003341 AddPatternToMatch(Pattern,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003342 PatternToMatch(CurPattern,
3343 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerf1447252010-03-19 21:37:09 +00003344 Pattern->getTree(0),
3345 Temp.getOnlyTree(), InstImpResults,
3346 CurPattern->getValueAsInt("AddedComplexity"),
3347 CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003348 }
3349}
3350
3351/// CombineChildVariants - Given a bunch of permutations of each child of the
3352/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003353static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003354 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3355 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003356 CodeGenDAGPatterns &CDP,
3357 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003358 // Make sure that each operand has at least one variant to choose from.
3359 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3360 if (ChildVariants[i].empty())
3361 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003362
Chris Lattner8cab0212008-01-05 22:25:12 +00003363 // The end result is an all-pairs construction of the resultant pattern.
3364 std::vector<unsigned> Idxs;
3365 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003366 bool NotDone;
3367 do {
3368#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003369 DEBUG(if (!Idxs.empty()) {
3370 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3371 for (unsigned i = 0; i < Idxs.size(); ++i) {
3372 errs() << Idxs[i] << " ";
3373 }
3374 errs() << "]\n";
3375 });
Scott Michel94420742008-03-05 17:49:05 +00003376#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003377 // Create the variant and add it to the output list.
3378 std::vector<TreePatternNode*> NewChildren;
3379 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3380 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerf1447252010-03-19 21:37:09 +00003381 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3382 Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003383
Chris Lattner8cab0212008-01-05 22:25:12 +00003384 // Copy over properties.
3385 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003386 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003387 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003388 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3389 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003390
Scott Michel94420742008-03-05 17:49:05 +00003391 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003392 std::string ErrString;
3393 if (!R->canPatternMatch(ErrString, CDP)) {
3394 delete R;
3395 } else {
3396 bool AlreadyExists = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003397
Chris Lattner8cab0212008-01-05 22:25:12 +00003398 // Scan to see if this pattern has already been emitted. We can get
3399 // duplication due to things like commuting:
3400 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3401 // which are the same pattern. Ignore the dups.
3402 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003403 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003404 AlreadyExists = true;
3405 break;
3406 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003407
Chris Lattner8cab0212008-01-05 22:25:12 +00003408 if (AlreadyExists)
3409 delete R;
3410 else
3411 OutVariants.push_back(R);
3412 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003413
Scott Michel94420742008-03-05 17:49:05 +00003414 // Increment indices to the next permutation by incrementing the
3415 // indicies from last index backward, e.g., generate the sequence
3416 // [0, 0], [0, 1], [1, 0], [1, 1].
3417 int IdxsIdx;
3418 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3419 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3420 Idxs[IdxsIdx] = 0;
3421 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003422 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003423 }
Scott Michel94420742008-03-05 17:49:05 +00003424 NotDone = (IdxsIdx >= 0);
3425 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003426}
3427
3428/// CombineChildVariants - A helper function for binary operators.
3429///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003430static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003431 const std::vector<TreePatternNode*> &LHS,
3432 const std::vector<TreePatternNode*> &RHS,
3433 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003434 CodeGenDAGPatterns &CDP,
3435 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003436 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3437 ChildVariants.push_back(LHS);
3438 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003439 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003440}
Chris Lattner8cab0212008-01-05 22:25:12 +00003441
3442
3443static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3444 std::vector<TreePatternNode *> &Children) {
3445 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3446 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003447
Chris Lattner8cab0212008-01-05 22:25:12 +00003448 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003449 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003450 N->getTransformFn()) {
3451 Children.push_back(N);
3452 return;
3453 }
3454
3455 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3456 Children.push_back(N->getChild(0));
3457 else
3458 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3459
3460 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3461 Children.push_back(N->getChild(1));
3462 else
3463 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3464}
3465
3466/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3467/// the (potentially recursive) pattern by using algebraic laws.
3468///
3469static void GenerateVariantsOf(TreePatternNode *N,
3470 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003471 CodeGenDAGPatterns &CDP,
3472 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003473 // We cannot permute leaves.
3474 if (N->isLeaf()) {
3475 OutVariants.push_back(N);
3476 return;
3477 }
3478
3479 // Look up interesting info about the node.
3480 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3481
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003482 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003483 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003484 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003485 std::vector<TreePatternNode*> MaximalChildren;
3486 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3487
3488 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3489 // permutations.
3490 if (MaximalChildren.size() == 3) {
3491 // Find the variants of all of our maximal children.
3492 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003493 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3494 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3495 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003496
Chris Lattner8cab0212008-01-05 22:25:12 +00003497 // There are only two ways we can permute the tree:
3498 // (A op B) op C and A op (B op C)
3499 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003500
Chris Lattner8cab0212008-01-05 22:25:12 +00003501 // Generate legal pair permutations of A/B/C.
3502 std::vector<TreePatternNode*> ABVariants;
3503 std::vector<TreePatternNode*> BAVariants;
3504 std::vector<TreePatternNode*> ACVariants;
3505 std::vector<TreePatternNode*> CAVariants;
3506 std::vector<TreePatternNode*> BCVariants;
3507 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003508 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3509 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3510 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3511 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3512 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3513 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003514
3515 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003516 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3517 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3518 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3519 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3520 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3521 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003522
3523 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003524 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3525 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3526 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3527 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3528 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3529 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003530 return;
3531 }
3532 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003533
Chris Lattner8cab0212008-01-05 22:25:12 +00003534 // Compute permutations of all children.
3535 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3536 ChildVariants.resize(N->getNumChildren());
3537 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003538 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003539
3540 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003541 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003542
3543 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003544 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3545 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3546 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3547 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003548 // Don't count children which are actually register references.
3549 unsigned NC = 0;
3550 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3551 TreePatternNode *Child = N->getChild(i);
3552 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003553 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003554 Record *RR = DI->getDef();
3555 if (RR->isSubClassOf("Register"))
3556 continue;
3557 }
3558 NC++;
3559 }
3560 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003561 if (isCommIntrinsic) {
3562 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3563 // operands are the commutative operands, and there might be more operands
3564 // after those.
3565 assert(NC >= 3 &&
3566 "Commutative intrinsic should have at least 3 childrean!");
3567 std::vector<std::vector<TreePatternNode*> > Variants;
3568 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3569 Variants.push_back(ChildVariants[2]);
3570 Variants.push_back(ChildVariants[1]);
3571 for (unsigned i = 3; i != NC; ++i)
3572 Variants.push_back(ChildVariants[i]);
3573 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3574 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003575 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003576 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003577 }
3578}
3579
3580
3581// GenerateVariants - Generate variants. For example, commutative patterns can
3582// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003583void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003584 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003585
Chris Lattner8cab0212008-01-05 22:25:12 +00003586 // Loop over all of the patterns we've collected, checking to see if we can
3587 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003588 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003589 // the .td file having to contain tons of variants of instructions.
3590 //
3591 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3592 // intentionally do not reconsider these. Any variants of added patterns have
3593 // already been added.
3594 //
3595 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003596 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003597 std::vector<TreePatternNode*> Variants;
Scott Michel94420742008-03-05 17:49:05 +00003598 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003599 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003600 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003601 DEBUG(errs() << "\n");
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003602 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3603 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003604
3605 assert(!Variants.empty() && "Must create at least original variant!");
3606 Variants.erase(Variants.begin()); // Remove the original pattern.
3607
3608 if (Variants.empty()) // No variants for this pattern.
3609 continue;
3610
Chris Lattner34822f62009-08-23 04:44:11 +00003611 DEBUG(errs() << "FOUND VARIANTS OF: ";
3612 PatternsToMatch[i].getSrcPattern()->dump();
3613 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003614
3615 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3616 TreePatternNode *Variant = Variants[v];
3617
Chris Lattner34822f62009-08-23 04:44:11 +00003618 DEBUG(errs() << " VAR#" << v << ": ";
3619 Variant->dump();
3620 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003621
Chris Lattner8cab0212008-01-05 22:25:12 +00003622 // Scan to see if an instruction or explicit pattern already matches this.
3623 bool AlreadyExists = false;
3624 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003625 // Skip if the top level predicates do not match.
3626 if (PatternsToMatch[i].getPredicates() !=
3627 PatternsToMatch[p].getPredicates())
3628 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003629 // Check to see if this variant already exists.
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003630 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3631 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003632 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003633 AlreadyExists = true;
3634 break;
3635 }
3636 }
3637 // If we already have it, ignore the variant.
3638 if (AlreadyExists) continue;
3639
3640 // Otherwise, add it to the list of patterns we have.
3641 PatternsToMatch.
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003642 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3643 PatternsToMatch[i].getPredicates(),
Chris Lattner8cab0212008-01-05 22:25:12 +00003644 Variant, PatternsToMatch[i].getDstPattern(),
3645 PatternsToMatch[i].getDstRegs(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003646 PatternsToMatch[i].getAddedComplexity(),
3647 Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003648 }
3649
Chris Lattner34822f62009-08-23 04:44:11 +00003650 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003651 }
3652}