blob: c01c0d8ce3494d819272a028c489b4108766b850 [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
Chandler Carruthe96dd892014-04-21 22:55:11 +000028#define DEBUG_TYPE "dag-patterns"
29
Chris Lattner8cab0212008-01-05 22:25:12 +000030//===----------------------------------------------------------------------===//
Chris Lattnercabe0372010-03-15 06:00:16 +000031// EEVT::TypeSet Implementation
32//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +000033
Owen Anderson9f944592009-08-11 20:47:22 +000034static inline bool isInteger(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000035 return MVT(VT).isInteger();
Duncan Sands13237ac2008-06-06 12:08:01 +000036}
Owen Anderson9f944592009-08-11 20:47:22 +000037static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000038 return MVT(VT).isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000039}
Owen Anderson9f944592009-08-11 20:47:22 +000040static inline bool isVector(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000041 return MVT(VT).isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000042}
Chris Lattner6d765eb2010-03-19 17:41:26 +000043static inline bool isScalar(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000044 return !MVT(VT).isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000045}
Duncan Sands13237ac2008-06-06 12:08:01 +000046
Chris Lattnercabe0372010-03-15 06:00:16 +000047EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
48 if (VT == MVT::iAny)
49 EnforceInteger(TP);
50 else if (VT == MVT::fAny)
51 EnforceFloatingPoint(TP);
52 else if (VT == MVT::vAny)
53 EnforceVector(TP);
54 else {
55 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
Ramkumar Ramachandra75a4f352015-01-22 20:14:38 +000056 VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!");
Chris Lattnercabe0372010-03-15 06:00:16 +000057 TypeVec.push_back(VT);
58 }
Chris Lattner8cab0212008-01-05 22:25:12 +000059}
60
Chris Lattnercabe0372010-03-15 06:00:16 +000061
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000062EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
Chris Lattnercabe0372010-03-15 06:00:16 +000063 assert(!VTList.empty() && "empty list?");
64 TypeVec.append(VTList.begin(), VTList.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +000065
Chris Lattnercabe0372010-03-15 06:00:16 +000066 if (!VTList.empty())
67 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
68 VTList[0] != MVT::fAny);
Jim Grosbach65586fe2010-12-21 16:16:00 +000069
Chris Lattner4a5f7be2010-03-27 20:32:26 +000070 // Verify no duplicates.
Chris Lattnercabe0372010-03-15 06:00:16 +000071 array_pod_sort(TypeVec.begin(), TypeVec.end());
Chris Lattner4a5f7be2010-03-27 20:32:26 +000072 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
Chris Lattner8cab0212008-01-05 22:25:12 +000073}
74
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000075/// FillWithPossibleTypes - Set to all legal types and return true, only valid
76/// on completely unknown type sets.
Chris Lattner6d765eb2010-03-19 17:41:26 +000077bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
78 bool (*Pred)(MVT::SimpleValueType),
79 const char *PredicateName) {
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000080 assert(isCompletelyUnknown());
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000081 ArrayRef<MVT::SimpleValueType> LegalTypes =
Chris Lattner6d765eb2010-03-19 17:41:26 +000082 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +000083
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000084 if (TP.hasError())
85 return false;
86
Chris Lattner6d765eb2010-03-19 17:41:26 +000087 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
Craig Topper24064772014-04-15 07:20:03 +000088 if (!Pred || Pred(LegalTypes[i]))
Chris Lattner6d765eb2010-03-19 17:41:26 +000089 TypeVec.push_back(LegalTypes[i]);
90
91 // If we have nothing that matches the predicate, bail out.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000092 if (TypeVec.empty()) {
Chris Lattner6d765eb2010-03-19 17:41:26 +000093 TP.error("Type inference contradiction found, no " +
Jim Grosbach65586fe2010-12-21 16:16:00 +000094 std::string(PredicateName) + " types found");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000095 return false;
96 }
Chris Lattner6d765eb2010-03-19 17:41:26 +000097 // No need to sort with one element.
98 if (TypeVec.size() == 1) return true;
99
100 // Remove duplicates.
101 array_pod_sort(TypeVec.begin(), TypeVec.end());
102 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000103
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000104 return true;
105}
Chris Lattnercabe0372010-03-15 06:00:16 +0000106
107/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
108/// integer value type.
109bool EEVT::TypeSet::hasIntegerTypes() const {
110 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
111 if (isInteger(TypeVec[i]))
112 return true;
113 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000114}
Chris Lattnercabe0372010-03-15 06:00:16 +0000115
116/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
117/// a floating point value type.
118bool EEVT::TypeSet::hasFloatingPointTypes() const {
119 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
120 if (isFloatingPoint(TypeVec[i]))
121 return true;
122 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000123}
Chris Lattnercabe0372010-03-15 06:00:16 +0000124
Craig Topper74169dc2014-01-28 04:49:01 +0000125/// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
126bool EEVT::TypeSet::hasScalarTypes() const {
127 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
128 if (isScalar(TypeVec[i]))
129 return true;
130 return false;
131}
132
Chris Lattnercabe0372010-03-15 06:00:16 +0000133/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
134/// value type.
135bool EEVT::TypeSet::hasVectorTypes() const {
136 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
137 if (isVector(TypeVec[i]))
138 return true;
139 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +0000140}
Bob Wilson2cd5da82009-08-11 01:14:02 +0000141
Chris Lattnercabe0372010-03-15 06:00:16 +0000142
143std::string EEVT::TypeSet::getName() const {
Chris Lattnerda5b4ad2010-03-19 01:14:27 +0000144 if (TypeVec.empty()) return "<empty>";
Jim Grosbach65586fe2010-12-21 16:16:00 +0000145
Chris Lattnercabe0372010-03-15 06:00:16 +0000146 std::string Result;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000147
Chris Lattnercabe0372010-03-15 06:00:16 +0000148 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
149 std::string VTName = llvm::getEnumName(TypeVec[i]);
150 // Strip off MVT:: prefix if present.
151 if (VTName.substr(0,5) == "MVT::")
152 VTName = VTName.substr(5);
153 if (i) Result += ':';
154 Result += VTName;
155 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000156
Chris Lattnercabe0372010-03-15 06:00:16 +0000157 if (TypeVec.size() == 1)
158 return Result;
159 return "{" + Result + "}";
Bob Wilson2cd5da82009-08-11 01:14:02 +0000160}
Chris Lattnercabe0372010-03-15 06:00:16 +0000161
162/// MergeInTypeInfo - This merges in type information from the specified
163/// argument. If 'this' changes, it returns true. If the two types are
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000164/// contradictory (e.g. merge f32 into i32) then this flags an error.
Chris Lattnercabe0372010-03-15 06:00:16 +0000165bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000166 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
Chris Lattnercabe0372010-03-15 06:00:16 +0000167 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000168
Chris Lattnercabe0372010-03-15 06:00:16 +0000169 if (isCompletelyUnknown()) {
170 *this = InVT;
171 return true;
172 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000173
Chris Lattnercabe0372010-03-15 06:00:16 +0000174 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000175
Chris Lattnercabe0372010-03-15 06:00:16 +0000176 // Handle the abstract cases, seeing if we can resolve them better.
177 switch (TypeVec[0]) {
178 default: break;
179 case MVT::iPTR:
180 case MVT::iPTRAny:
181 if (InVT.hasIntegerTypes()) {
182 EEVT::TypeSet InCopy(InVT);
183 InCopy.EnforceInteger(TP);
184 InCopy.EnforceScalar(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000185
Chris Lattnercabe0372010-03-15 06:00:16 +0000186 if (InCopy.isConcrete()) {
187 // If the RHS has one integer type, upgrade iPTR to i32.
188 TypeVec[0] = InVT.TypeVec[0];
189 return true;
190 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000191
Chris Lattnercabe0372010-03-15 06:00:16 +0000192 // If the input has multiple scalar integers, this doesn't add any info.
193 if (!InCopy.isCompletelyUnknown())
194 return false;
195 }
196 break;
197 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000198
Chris Lattnercabe0372010-03-15 06:00:16 +0000199 // If the input constraint is iAny/iPTR and this is an integer type list,
200 // remove non-integer types from the list.
201 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
202 hasIntegerTypes()) {
203 bool MadeChange = EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000204
Chris Lattnercabe0372010-03-15 06:00:16 +0000205 // If we're merging in iPTR/iPTRAny and the node currently has a list of
206 // multiple different integer types, replace them with a single iPTR.
207 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
208 TypeVec.size() != 1) {
209 TypeVec.resize(1);
210 TypeVec[0] = InVT.TypeVec[0];
211 MadeChange = true;
212 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000213
Chris Lattnercabe0372010-03-15 06:00:16 +0000214 return MadeChange;
215 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000216
Chris Lattnercabe0372010-03-15 06:00:16 +0000217 // If this is a type list and the RHS is a typelist as well, eliminate entries
218 // from this list that aren't in the other one.
219 bool MadeChange = false;
220 TypeSet InputSet(*this);
221
222 for (unsigned i = 0; i != TypeVec.size(); ++i) {
223 bool InInVT = false;
224 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
225 if (TypeVec[i] == InVT.TypeVec[j]) {
226 InInVT = true;
227 break;
228 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000229
Chris Lattnercabe0372010-03-15 06:00:16 +0000230 if (InInVT) continue;
231 TypeVec.erase(TypeVec.begin()+i--);
232 MadeChange = true;
233 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000234
Chris Lattnercabe0372010-03-15 06:00:16 +0000235 // If we removed all of our types, we have a type contradiction.
236 if (!TypeVec.empty())
237 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000238
Chris Lattnercabe0372010-03-15 06:00:16 +0000239 // FIXME: Really want an SMLoc here!
240 TP.error("Type inference contradiction found, merging '" +
241 InVT.getName() + "' into '" + InputSet.getName() + "'");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000242 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000243}
244
245/// EnforceInteger - Remove all non-integer types from this set.
246bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000247 if (TP.hasError())
248 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000249 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000250 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000251 return FillWithPossibleTypes(TP, isInteger, "integer");
Chris Lattnercabe0372010-03-15 06:00:16 +0000252 if (!hasFloatingPointTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000253 return false;
254
255 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000256
Chris Lattnercabe0372010-03-15 06:00:16 +0000257 // Filter out all the fp types.
258 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000259 if (!isInteger(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000260 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000261
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000262 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000263 TP.error("Type inference contradiction found, '" +
264 InputSet.getName() + "' needs to be integer");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000265 return false;
266 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000267 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000268}
269
270/// EnforceFloatingPoint - Remove all integer types from this set.
271bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000272 if (TP.hasError())
273 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000274 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000275 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000276 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
277
Chris Lattnercabe0372010-03-15 06:00:16 +0000278 if (!hasIntegerTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000279 return false;
280
281 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000282
Chris Lattnercabe0372010-03-15 06:00:16 +0000283 // Filter out all the fp types.
284 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000285 if (!isFloatingPoint(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000286 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000287
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000288 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000289 TP.error("Type inference contradiction found, '" +
290 InputSet.getName() + "' needs to be floating point");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000291 return false;
292 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000293 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000294}
295
296/// EnforceScalar - Remove all vector types from this.
297bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000298 if (TP.hasError())
299 return false;
300
Chris Lattnercabe0372010-03-15 06:00:16 +0000301 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000302 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000303 return FillWithPossibleTypes(TP, isScalar, "scalar");
304
Chris Lattnercabe0372010-03-15 06:00:16 +0000305 if (!hasVectorTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000306 return false;
307
308 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000309
Chris Lattnercabe0372010-03-15 06:00:16 +0000310 // Filter out all the vector types.
311 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000312 if (!isScalar(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000313 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000314
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000315 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000316 TP.error("Type inference contradiction found, '" +
317 InputSet.getName() + "' needs to be scalar");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000318 return false;
319 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000320 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000321}
322
323/// EnforceVector - Remove all vector types from this.
324bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000325 if (TP.hasError())
326 return false;
327
Chris Lattner6d765eb2010-03-19 17:41:26 +0000328 // If we know nothing, then get the full set.
329 if (TypeVec.empty())
330 return FillWithPossibleTypes(TP, isVector, "vector");
331
Chris Lattnercabe0372010-03-15 06:00:16 +0000332 TypeSet InputSet(*this);
333 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000334
Chris Lattnercabe0372010-03-15 06:00:16 +0000335 // Filter out all the scalar types.
336 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000337 if (!isVector(TypeVec[i])) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000338 TypeVec.erase(TypeVec.begin()+i--);
Chris Lattner6d765eb2010-03-19 17:41:26 +0000339 MadeChange = true;
340 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000341
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000342 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000343 TP.error("Type inference contradiction found, '" +
344 InputSet.getName() + "' needs to be a vector");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000345 return false;
346 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000347 return MadeChange;
348}
349
350
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000351
Craig Topper74169dc2014-01-28 04:49:01 +0000352/// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000353/// this should be based on the element type. Update this and other based on
Craig Topper74169dc2014-01-28 04:49:01 +0000354/// this information.
Chris Lattnercabe0372010-03-15 06:00:16 +0000355bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000356 if (TP.hasError())
357 return false;
358
Chris Lattnercabe0372010-03-15 06:00:16 +0000359 // Both operands must be integer or FP, but we don't care which.
360 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000361
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000362 if (isCompletelyUnknown())
363 MadeChange = FillWithPossibleTypes(TP);
364
365 if (Other.isCompletelyUnknown())
366 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000367
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000368 // If one side is known to be integer or known to be FP but the other side has
369 // no information, get at least the type integrality info in there.
370 if (!hasFloatingPointTypes())
371 MadeChange |= Other.EnforceInteger(TP);
372 else if (!hasIntegerTypes())
373 MadeChange |= Other.EnforceFloatingPoint(TP);
374 if (!Other.hasFloatingPointTypes())
375 MadeChange |= EnforceInteger(TP);
376 else if (!Other.hasIntegerTypes())
377 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000378
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000379 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
380 "Should have a type list now");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000381
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000382 // If one contains vectors but the other doesn't pull vectors out.
383 if (!hasVectorTypes())
384 MadeChange |= Other.EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000385 else if (!hasScalarTypes())
386 MadeChange |= Other.EnforceVector(TP);
Craig Topper6dbcb942014-01-25 05:17:38 +0000387 if (!Other.hasVectorTypes())
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000388 MadeChange |= EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000389 else if (!Other.hasScalarTypes())
390 MadeChange |= EnforceVector(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000391
Craig Topper74169dc2014-01-28 04:49:01 +0000392 // This code does not currently handle nodes which have multiple types,
393 // where some types are integer, and some are fp. Assert that this is not
394 // the case.
395 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
396 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
397 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
398
399 if (TP.hasError())
400 return false;
401
Craig Topper7bbd37b2015-03-10 03:25:07 +0000402 // Okay, find the smallest type from current set and remove anything the
403 // same or smaller from the other set. We need to ensure that the scalar
404 // type size is smaller than the scalar size of the smallest type. For
405 // vectors, we also need to make sure that the total size is no larger than
406 // the size of the smallest type.
Craig Topper74169dc2014-01-28 04:49:01 +0000407 TypeSet InputSet(Other);
Craig Topper7bbd37b2015-03-10 03:25:07 +0000408 MVT Smallest = TypeVec[0];
Craig Topper74169dc2014-01-28 04:49:01 +0000409 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
Craig Topper7bbd37b2015-03-10 03:25:07 +0000410 MVT OtherVT = Other.TypeVec[i];
411 // Don't compare vector and non-vector types.
412 if (OtherVT.isVector() != Smallest.isVector())
413 continue;
414 // The getSizeInBits() check here is only needed for vectors, but is
415 // a subset of the scalar check for scalars so no need to qualify.
416 if (OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
417 OtherVT.getSizeInBits() < Smallest.getSizeInBits()) {
Craig Topper74169dc2014-01-28 04:49:01 +0000418 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
419 MadeChange = true;
420 }
421 }
422
423 if (Other.TypeVec.empty()) {
424 TP.error("Type inference contradiction found, '" + InputSet.getName() +
425 "' has nothing larger than '" + getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000426 return false;
427 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000428
Craig Topper7bbd37b2015-03-10 03:25:07 +0000429 // Okay, find the largest type from the other set and remove anything the
430 // same or smaller from the current set. We need to ensure that the scalar
431 // type size is larger than the scalar size of the largest type. For
432 // vectors, we also need to make sure that the total size is no smaller than
433 // the size of the largest type.
Craig Topper74169dc2014-01-28 04:49:01 +0000434 InputSet = TypeSet(*this);
Craig Topper7bbd37b2015-03-10 03:25:07 +0000435 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
Craig Topper74169dc2014-01-28 04:49:01 +0000436 for (unsigned i = 0; i != TypeVec.size(); ++i) {
Craig Topper7bbd37b2015-03-10 03:25:07 +0000437 MVT OtherVT = TypeVec[i];
438 // Don't compare vector and non-vector types.
439 if (OtherVT.isVector() != Largest.isVector())
440 continue;
441 // The getSizeInBits() check here is only needed for vectors, but is
442 // a subset of the scalar check for scalars so no need to qualify.
443 if (OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
444 OtherVT.getSizeInBits() > Largest.getSizeInBits()) {
Craig Topper74169dc2014-01-28 04:49:01 +0000445 TypeVec.erase(TypeVec.begin()+i--);
446 MadeChange = true;
David Greene433c6182011-02-01 19:12:32 +0000447 }
David Greene433c6182011-02-01 19:12:32 +0000448 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000449
Craig Topper74169dc2014-01-28 04:49:01 +0000450 if (TypeVec.empty()) {
451 TP.error("Type inference contradiction found, '" + InputSet.getName() +
452 "' has nothing smaller than '" + Other.getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000453 return false;
454 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000455
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000456 return MadeChange;
Chris Lattnercabe0372010-03-15 06:00:16 +0000457}
458
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000459/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Chris Lattner57ebf632010-03-24 00:01:16 +0000460/// whose element is specified by VTOperand.
Craig Topper0be34582015-03-05 07:11:34 +0000461bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
462 TreePattern &TP) {
463 bool MadeChange = false;
464
465 MadeChange |= EnforceVector(TP);
466
467 TypeSet InputSet(*this);
468
469 // Filter out all the types which don't have the right element type.
470 for (unsigned i = 0; i != TypeVec.size(); ++i) {
471 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
472 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
473 TypeVec.erase(TypeVec.begin()+i--);
474 MadeChange = true;
475 }
476 }
477
478 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
479 TP.error("Type inference contradiction found, forcing '" +
480 InputSet.getName() + "' to have a vector element");
481 return false;
482 }
483
484 return MadeChange;
485}
486
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000487/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Craig Topper0be34582015-03-05 07:11:34 +0000488/// whose element is specified by VTOperand.
Chris Lattner57ebf632010-03-24 00:01:16 +0000489bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattnercabe0372010-03-15 06:00:16 +0000490 TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000491 if (TP.hasError())
492 return false;
493
Chris Lattner57ebf632010-03-24 00:01:16 +0000494 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattnercabe0372010-03-15 06:00:16 +0000495 bool MadeChange = false;
Chris Lattner57ebf632010-03-24 00:01:16 +0000496 MadeChange |= EnforceVector(TP);
497 MadeChange |= VTOperand.EnforceScalar(TP);
498
499 // If we know the vector type, it forces the scalar to agree.
500 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000501 MVT IVT = getConcrete();
Chris Lattner57ebf632010-03-24 00:01:16 +0000502 IVT = IVT.getVectorElementType();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000503 return MadeChange |
Craig Topper95198f42013-09-25 06:37:18 +0000504 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
Chris Lattner57ebf632010-03-24 00:01:16 +0000505 }
506
507 // If the scalar type is known, filter out vector types whose element types
508 // disagree.
509 if (!VTOperand.isConcrete())
510 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000511
Chris Lattner57ebf632010-03-24 00:01:16 +0000512 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000513
Chris Lattner57ebf632010-03-24 00:01:16 +0000514 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000515
Chris Lattner57ebf632010-03-24 00:01:16 +0000516 // Filter out all the types which don't have the right element type.
517 for (unsigned i = 0; i != TypeVec.size(); ++i) {
518 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
Craig Topper95198f42013-09-25 06:37:18 +0000519 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000520 TypeVec.erase(TypeVec.begin()+i--);
521 MadeChange = true;
522 }
Chris Lattner57ebf632010-03-24 00:01:16 +0000523 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000524
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000525 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
Chris Lattnercabe0372010-03-15 06:00:16 +0000526 TP.error("Type inference contradiction found, forcing '" +
527 InputSet.getName() + "' to have a vector element");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000528 return false;
529 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000530 return MadeChange;
531}
532
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000533/// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
David Greene127fd1d2011-01-24 20:53:18 +0000534/// vector type specified by VTOperand.
535bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
536 TreePattern &TP) {
Craig Topper6e1faaf2014-01-25 17:40:33 +0000537 if (TP.hasError())
538 return false;
539
David Greene127fd1d2011-01-24 20:53:18 +0000540 // "This" must be a vector and "VTOperand" must be a vector.
541 bool MadeChange = false;
542 MadeChange |= EnforceVector(TP);
543 MadeChange |= VTOperand.EnforceVector(TP);
544
Craig Topper6e1faaf2014-01-25 17:40:33 +0000545 // If one side is known to be integer or known to be FP but the other side has
546 // no information, get at least the type integrality info in there.
547 if (!hasFloatingPointTypes())
548 MadeChange |= VTOperand.EnforceInteger(TP);
549 else if (!hasIntegerTypes())
550 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
551 if (!VTOperand.hasFloatingPointTypes())
552 MadeChange |= EnforceInteger(TP);
553 else if (!VTOperand.hasIntegerTypes())
554 MadeChange |= EnforceFloatingPoint(TP);
555
556 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
557 "Should have a type list now");
David Greene127fd1d2011-01-24 20:53:18 +0000558
559 // If we know the vector type, it forces the scalar types to agree.
Craig Topper6e1faaf2014-01-25 17:40:33 +0000560 // Also force one vector to have more elements than the other.
David Greene127fd1d2011-01-24 20:53:18 +0000561 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000562 MVT IVT = getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000563 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000564 IVT = IVT.getVectorElementType();
565
Craig Topper95198f42013-09-25 06:37:18 +0000566 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000567 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000568
569 // Only keep types that have less elements than VTOperand.
570 TypeSet InputSet(VTOperand);
571
572 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
573 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
574 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
575 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
576 MadeChange = true;
577 }
578 }
579 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
580 TP.error("Type inference contradiction found, forcing '" +
581 InputSet.getName() + "' to have less vector elements than '" +
582 getName() + "'");
583 return false;
584 }
David Greene127fd1d2011-01-24 20:53:18 +0000585 } else if (VTOperand.isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000586 MVT IVT = VTOperand.getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000587 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000588 IVT = IVT.getVectorElementType();
589
Craig Topper95198f42013-09-25 06:37:18 +0000590 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000591 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000592
593 // Only keep types that have more elements than 'this'.
594 TypeSet InputSet(*this);
595
596 for (unsigned i = 0; i != TypeVec.size(); ++i) {
597 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
598 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
599 TypeVec.erase(TypeVec.begin()+i--);
600 MadeChange = true;
601 }
602 }
603 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
604 TP.error("Type inference contradiction found, forcing '" +
605 InputSet.getName() + "' to have more vector elements than '" +
606 VTOperand.getName() + "'");
607 return false;
608 }
David Greene127fd1d2011-01-24 20:53:18 +0000609 }
610
611 return MadeChange;
612}
613
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000614/// EnforceVectorSameNumElts - 'this' is now constrained to
Craig Topper0be34582015-03-05 07:11:34 +0000615/// be a vector with same num elements as VTOperand.
616bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
617 TreePattern &TP) {
618 if (TP.hasError())
619 return false;
620
621 // "This" must be a vector and "VTOperand" must be a vector.
622 bool MadeChange = false;
623 MadeChange |= EnforceVector(TP);
624 MadeChange |= VTOperand.EnforceVector(TP);
625
626 // If we know one of the vector types, it forces the other type to agree.
627 if (isConcrete()) {
628 MVT IVT = getConcrete();
629 unsigned NumElems = IVT.getVectorNumElements();
630
631 // Only keep types that have same elements as VTOperand.
632 TypeSet InputSet(VTOperand);
633
634 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
635 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
636 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
637 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
638 MadeChange = true;
639 }
640 }
641 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
642 TP.error("Type inference contradiction found, forcing '" +
643 InputSet.getName() + "' to have same number elements as '" +
644 getName() + "'");
645 return false;
646 }
647 } else if (VTOperand.isConcrete()) {
648 MVT IVT = VTOperand.getConcrete();
649 unsigned NumElems = IVT.getVectorNumElements();
650
651 // Only keep types that have same elements as 'this'.
652 TypeSet InputSet(*this);
653
654 for (unsigned i = 0; i != TypeVec.size(); ++i) {
655 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
656 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
657 TypeVec.erase(TypeVec.begin()+i--);
658 MadeChange = true;
659 }
660 }
661 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
662 TP.error("Type inference contradiction found, forcing '" +
663 InputSet.getName() + "' to have same number elements than '" +
664 VTOperand.getName() + "'");
665 return false;
666 }
667 }
668
669 return MadeChange;
670}
671
Chris Lattnercabe0372010-03-15 06:00:16 +0000672//===----------------------------------------------------------------------===//
673// Helpers for working with extended types.
Chris Lattner8cab0212008-01-05 22:25:12 +0000674
Scott Michel94420742008-03-05 17:49:05 +0000675/// Dependent variable map for CodeGenDAGPattern variant generation
676typedef std::map<std::string, int> DepVarMap;
677
678/// Const iterator shorthand for DepVarMap
679typedef DepVarMap::const_iterator DepVarMap_citer;
680
Chris Lattner514e2922011-04-17 21:38:24 +0000681static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel94420742008-03-05 17:49:05 +0000682 if (N->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000683 if (isa<DefInit>(N->getLeafValue()))
Scott Michel94420742008-03-05 17:49:05 +0000684 DepMap[N->getName()]++;
Scott Michel94420742008-03-05 17:49:05 +0000685 } else {
686 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
687 FindDepVarsOf(N->getChild(i), DepMap);
688 }
689}
Chris Lattner514e2922011-04-17 21:38:24 +0000690
691/// Find dependent variables within child patterns
692static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000693 DepVarMap depcounts;
694 FindDepVarsOf(N, depcounts);
695 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
Chris Lattner514e2922011-04-17 21:38:24 +0000696 if (i->second > 1) // std::pair<std::string, int>
Scott Michel94420742008-03-05 17:49:05 +0000697 DepVars.insert(i->first);
Scott Michel94420742008-03-05 17:49:05 +0000698 }
699}
700
Daniel Dunbarba66a812010-10-08 02:07:22 +0000701#ifndef NDEBUG
Chris Lattner514e2922011-04-17 21:38:24 +0000702/// Dump the dependent variable set:
703static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000704 if (DepVars.empty()) {
Chris Lattner34822f62009-08-23 04:44:11 +0000705 DEBUG(errs() << "<empty set>");
Scott Michel94420742008-03-05 17:49:05 +0000706 } else {
Chris Lattner34822f62009-08-23 04:44:11 +0000707 DEBUG(errs() << "[ ");
Jim Grosbachb75d0ca2010-10-08 18:13:57 +0000708 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
709 e = DepVars.end(); i != e; ++i) {
Chris Lattner34822f62009-08-23 04:44:11 +0000710 DEBUG(errs() << (*i) << " ");
Scott Michel94420742008-03-05 17:49:05 +0000711 }
Chris Lattner34822f62009-08-23 04:44:11 +0000712 DEBUG(errs() << "]");
Scott Michel94420742008-03-05 17:49:05 +0000713 }
714}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000715#endif
716
Chris Lattner514e2922011-04-17 21:38:24 +0000717
718//===----------------------------------------------------------------------===//
719// TreePredicateFn Implementation
720//===----------------------------------------------------------------------===//
721
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000722/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
723TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
724 assert((getPredCode().empty() || getImmCode().empty()) &&
725 ".td file corrupt: can't have a node predicate *and* an imm predicate");
726}
727
Chris Lattner514e2922011-04-17 21:38:24 +0000728std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000729 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000730}
731
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000732std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000733 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000734}
735
Chris Lattner514e2922011-04-17 21:38:24 +0000736
737/// isAlwaysTrue - Return true if this is a noop predicate.
738bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000739 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000740}
741
742/// Return the name to use in the generated code to reference this, this is
743/// "Predicate_foo" if from a pattern fragment "foo".
744std::string TreePredicateFn::getFnName() const {
745 return "Predicate_" + PatFragRec->getRecord()->getName();
746}
747
748/// getCodeToRunOnSDNode - Return the code for the function body that
749/// evaluates this predicate. The argument is expected to be in "Node",
750/// not N. This handles casting and conversion to a concrete node type as
751/// appropriate.
752std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000753 // Handle immediate predicates first.
754 std::string ImmCode = getImmCode();
755 if (!ImmCode.empty()) {
756 std::string Result =
757 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000758 return Result + ImmCode;
759 }
760
761 // Handle arbitrary node predicates.
762 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000763 std::string ClassName;
764 if (PatFragRec->getOnlyTree()->isLeaf())
765 ClassName = "SDNode";
766 else {
767 Record *Op = PatFragRec->getOnlyTree()->getOperator();
768 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
769 }
770 std::string Result;
771 if (ClassName == "SDNode")
772 Result = " SDNode *N = Node;\n";
773 else
774 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
775
776 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000777}
778
Chris Lattner8cab0212008-01-05 22:25:12 +0000779//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000780// PatternToMatch implementation
781//
782
Chris Lattner05925fe2010-03-29 01:40:38 +0000783
784/// getPatternSize - Return the 'size' of this pattern. We want to match large
785/// patterns before small ones. This is used to determine the size of a
786/// pattern.
787static unsigned getPatternSize(const TreePatternNode *P,
788 const CodeGenDAGPatterns &CGP) {
789 unsigned Size = 3; // The node itself.
790 // If the root node is a ConstantSDNode, increases its size.
791 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000792 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000793 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000794
Chris Lattner05925fe2010-03-29 01:40:38 +0000795 // FIXME: This is a hack to statically increase the priority of patterns
796 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
797 // Later we can allow complexity / cost for each pattern to be (optionally)
798 // specified. To get best possible pattern match we'll need to dynamically
799 // calculate the complexity of all patterns a dag can potentially map to.
800 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000801 if (AM) {
Chris Lattner05925fe2010-03-29 01:40:38 +0000802 Size += AM->getNumOperands() * 3;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000803
Tim Northoverc807a172014-05-20 11:52:46 +0000804 // We don't want to count any children twice, so return early.
805 return Size;
806 }
807
Chris Lattner05925fe2010-03-29 01:40:38 +0000808 // If this node has some predicate function that must match, it adds to the
809 // complexity of this node.
810 if (!P->getPredicateFns().empty())
811 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000812
Chris Lattner05925fe2010-03-29 01:40:38 +0000813 // Count children in the count if they are also nodes.
814 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
815 TreePatternNode *Child = P->getChild(i);
816 if (!Child->isLeaf() && Child->getNumTypes() &&
817 Child->getType(0) != MVT::Other)
818 Size += getPatternSize(Child, CGP);
819 else if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000820 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000821 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
822 else if (Child->getComplexPatternInfo(CGP))
823 Size += getPatternSize(Child, CGP);
824 else if (!Child->getPredicateFns().empty())
825 ++Size;
826 }
827 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000828
Chris Lattner05925fe2010-03-29 01:40:38 +0000829 return Size;
830}
831
832/// Compute the complexity metric for the input pattern. This roughly
833/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000834int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000835getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
836 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
837}
838
839
Dan Gohman49e19e92008-08-22 00:20:26 +0000840/// getPredicateCheck - Return a single string containing all of this
841/// pattern's predicates concatenated with "&&" operators.
842///
843std::string PatternToMatch::getPredicateCheck() const {
844 std::string PredicateCheck;
Craig Topperef0578a2015-06-02 04:15:51 +0000845 for (Init *I : Predicates->getValues()) {
846 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
Dan Gohman49e19e92008-08-22 00:20:26 +0000847 Record *Def = Pred->getDef();
848 if (!Def->isSubClassOf("Predicate")) {
849#ifndef NDEBUG
850 Def->dump();
851#endif
Craig Topperc4965bc2012-02-05 07:21:30 +0000852 llvm_unreachable("Unknown predicate type!");
Dan Gohman49e19e92008-08-22 00:20:26 +0000853 }
854 if (!PredicateCheck.empty())
855 PredicateCheck += " && ";
856 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
857 }
858 }
859
860 return PredicateCheck;
861}
862
863//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000864// SDTypeConstraint implementation
865//
866
867SDTypeConstraint::SDTypeConstraint(Record *R) {
868 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000869
Chris Lattner8cab0212008-01-05 22:25:12 +0000870 if (R->isSubClassOf("SDTCisVT")) {
871 ConstraintType = SDTCisVT;
872 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerffdac7b2010-03-28 06:04:39 +0000873 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000874 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000875
Chris Lattner8cab0212008-01-05 22:25:12 +0000876 } else if (R->isSubClassOf("SDTCisPtrTy")) {
877 ConstraintType = SDTCisPtrTy;
878 } else if (R->isSubClassOf("SDTCisInt")) {
879 ConstraintType = SDTCisInt;
880 } else if (R->isSubClassOf("SDTCisFP")) {
881 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000882 } else if (R->isSubClassOf("SDTCisVec")) {
883 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000884 } else if (R->isSubClassOf("SDTCisSameAs")) {
885 ConstraintType = SDTCisSameAs;
886 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
887 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
888 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000889 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000890 R->getValueAsInt("OtherOperandNum");
891 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
892 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000893 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000894 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000895 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
896 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000897 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000898 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
899 ConstraintType = SDTCisSubVecOfVec;
900 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
901 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +0000902 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
903 ConstraintType = SDTCVecEltisVT;
904 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
905 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
906 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
907 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
908 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
909 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
910 "as SDTCVecEltisVT");
911 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
912 ConstraintType = SDTCisSameNumEltsAs;
913 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
914 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +0000915 } else {
James Y Knighte452e272015-05-11 22:17:13 +0000916 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +0000917 }
918}
919
920/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000921/// N, and the result number in ResNo.
922static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
923 const SDNodeInfo &NodeInfo,
924 unsigned &ResNo) {
925 unsigned NumResults = NodeInfo.getNumResults();
926 if (OpNo < NumResults) {
927 ResNo = OpNo;
928 return N;
929 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000930
Chris Lattner2db7aba2010-03-19 21:56:21 +0000931 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000932
Chris Lattner2db7aba2010-03-19 21:56:21 +0000933 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +0000934 std::string S;
935 raw_string_ostream OS(S);
936 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000937 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +0000938 N->print(OS);
939 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +0000940 }
941
Chris Lattner2db7aba2010-03-19 21:56:21 +0000942 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +0000943}
944
945/// ApplyTypeConstraint - Given a node in a pattern, apply this type
946/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000947/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +0000948bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
949 const SDNodeInfo &NodeInfo,
950 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000951 if (TP.hasError())
952 return false;
953
Chris Lattner2db7aba2010-03-19 21:56:21 +0000954 unsigned ResNo = 0; // The result number being referenced.
955 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000956
Chris Lattner8cab0212008-01-05 22:25:12 +0000957 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000958 case SDTCisVT:
959 // Operand must be a particular type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000960 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000961 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +0000962 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000963 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000964 case SDTCisInt:
965 // Require it to be one of the legal integer VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000966 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000967 case SDTCisFP:
968 // Require it to be one of the legal fp VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000969 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000970 case SDTCisVec:
971 // Require it to be one of the legal vector VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000972 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000973 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000974 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000975 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000976 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +0000977 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
978 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000979 }
980 case SDTCisVTSmallerThanOp: {
981 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
982 // have an integer type that is smaller than the VT.
983 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +0000984 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +0000985 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000986 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000987 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000988 return false;
989 }
Owen Anderson9f944592009-08-11 20:47:22 +0000990 MVT::SimpleValueType VT =
David Greeneaf8ee2c2011-07-29 22:43:06 +0000991 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000992
Chris Lattner38c99662010-03-24 00:06:46 +0000993 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000994
Chris Lattner2db7aba2010-03-19 21:56:21 +0000995 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000996 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000997 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
998 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +0000999
Chris Lattner38c99662010-03-24 00:06:46 +00001000 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001001 }
1002 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001003 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001004 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001005 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1006 BResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +00001007 return NodeToApply->getExtType(ResNo).
1008 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001009 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001010 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001011 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +00001012 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001013 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1014 VResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001015
Chris Lattner57ebf632010-03-24 00:01:16 +00001016 // Filter vector types out of VecOperand that don't have the right element
1017 // type.
1018 return VecOperand->getExtType(VResNo).
1019 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begeman17bedbc2008-02-09 01:37:05 +00001020 }
David Greene127fd1d2011-01-24 20:53:18 +00001021 case SDTCisSubVecOfVec: {
1022 unsigned VResNo = 0;
1023 TreePatternNode *BigVecOperand =
1024 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1025 VResNo);
1026
1027 // Filter vector types out of BigVecOperand that don't have the
1028 // right subvector type.
1029 return BigVecOperand->getExtType(VResNo).
1030 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1031 }
Craig Topper0be34582015-03-05 07:11:34 +00001032 case SDTCVecEltisVT: {
1033 return NodeToApply->getExtType(ResNo).
1034 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1035 }
1036 case SDTCisSameNumEltsAs: {
1037 unsigned OResNo = 0;
1038 TreePatternNode *OtherNode =
1039 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1040 N, NodeInfo, OResNo);
1041 return OtherNode->getExtType(OResNo).
1042 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1043 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001044 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001045 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001046}
1047
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001048// Update the node type to match an instruction operand or result as specified
1049// in the ins or outs lists on the instruction definition. Return true if the
1050// type was actually changed.
1051bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1052 Record *Operand,
1053 TreePattern &TP) {
1054 // The 'unknown' operand indicates that types should be inferred from the
1055 // context.
1056 if (Operand->isSubClassOf("unknown_class"))
1057 return false;
1058
1059 // The Operand class specifies a type directly.
1060 if (Operand->isSubClassOf("Operand"))
1061 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1062 TP);
1063
1064 // PointerLikeRegClass has a type that is determined at runtime.
1065 if (Operand->isSubClassOf("PointerLikeRegClass"))
1066 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1067
1068 // Both RegisterClass and RegisterOperand operands derive their types from a
1069 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001070 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001071 if (Operand->isSubClassOf("RegisterClass"))
1072 RC = Operand;
1073 else if (Operand->isSubClassOf("RegisterOperand"))
1074 RC = Operand->getValueAsDef("RegClass");
1075
1076 assert(RC && "Unknown operand type");
1077 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1078 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1079}
1080
1081
Chris Lattner8cab0212008-01-05 22:25:12 +00001082//===----------------------------------------------------------------------===//
1083// SDNodeInfo implementation
1084//
1085SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1086 EnumName = R->getValueAsString("Opcode");
1087 SDClassName = R->getValueAsString("SDClass");
1088 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1089 NumResults = TypeProfile->getValueAsInt("NumResults");
1090 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001091
Chris Lattner8cab0212008-01-05 22:25:12 +00001092 // Parse the properties.
1093 Properties = 0;
1094 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
1095 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
1096 if (PropList[i]->getName() == "SDNPCommutative") {
1097 Properties |= 1 << SDNPCommutative;
1098 } else if (PropList[i]->getName() == "SDNPAssociative") {
1099 Properties |= 1 << SDNPAssociative;
1100 } else if (PropList[i]->getName() == "SDNPHasChain") {
1101 Properties |= 1 << SDNPHasChain;
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001102 } else if (PropList[i]->getName() == "SDNPOutGlue") {
1103 Properties |= 1 << SDNPOutGlue;
1104 } else if (PropList[i]->getName() == "SDNPInGlue") {
1105 Properties |= 1 << SDNPInGlue;
1106 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
1107 Properties |= 1 << SDNPOptInGlue;
Chris Lattnera348f552008-01-06 06:44:58 +00001108 } else if (PropList[i]->getName() == "SDNPMayStore") {
1109 Properties |= 1 << SDNPMayStore;
Chris Lattner1ca20682008-01-10 04:38:57 +00001110 } else if (PropList[i]->getName() == "SDNPMayLoad") {
1111 Properties |= 1 << SDNPMayLoad;
Chris Lattner42c63ef2008-01-10 05:39:30 +00001112 } else if (PropList[i]->getName() == "SDNPSideEffect") {
1113 Properties |= 1 << SDNPSideEffect;
Mon P Wang6a490372008-06-25 08:15:39 +00001114 } else if (PropList[i]->getName() == "SDNPMemOperand") {
1115 Properties |= 1 << SDNPMemOperand;
Chris Lattner83aeaab2010-03-19 05:07:09 +00001116 } else if (PropList[i]->getName() == "SDNPVariadic") {
1117 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001118 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001119 PrintFatalError("Unknown SD Node property '" +
1120 PropList[i]->getName() + "' on node '" +
1121 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001122 }
1123 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001124
1125
Chris Lattner8cab0212008-01-05 22:25:12 +00001126 // Parse the type constraints.
1127 std::vector<Record*> ConstraintList =
1128 TypeProfile->getValueAsListOfDefs("Constraints");
1129 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1130}
1131
Chris Lattner99e53b32010-02-28 00:22:30 +00001132/// getKnownType - If the type constraints on this node imply a fixed type
1133/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001134/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001135MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001136 unsigned NumResults = getNumResults();
1137 assert(NumResults <= 1 &&
1138 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001139 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001140
Chris Lattner99e53b32010-02-28 00:22:30 +00001141 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
1142 // Make sure that this applies to the correct node result.
1143 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
1144 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001145
Chris Lattner99e53b32010-02-28 00:22:30 +00001146 switch (TypeConstraints[i].ConstraintType) {
1147 default: break;
1148 case SDTypeConstraint::SDTCisVT:
1149 return TypeConstraints[i].x.SDTCisVT_Info.VT;
1150 case SDTypeConstraint::SDTCisPtrTy:
1151 return MVT::iPTR;
1152 }
1153 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001154 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001155}
1156
Chris Lattner8cab0212008-01-05 22:25:12 +00001157//===----------------------------------------------------------------------===//
1158// TreePatternNode implementation
1159//
1160
1161TreePatternNode::~TreePatternNode() {
1162#if 0 // FIXME: implement refcounted tree nodes!
1163 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1164 delete getChild(i);
1165#endif
1166}
1167
Chris Lattnerf1447252010-03-19 21:37:09 +00001168static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1169 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001170 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001171 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001172
Chris Lattner2109cb42010-03-22 20:56:36 +00001173 if (Operator->isSubClassOf("Intrinsic"))
1174 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001175
Chris Lattnerf1447252010-03-19 21:37:09 +00001176 if (Operator->isSubClassOf("SDNode"))
1177 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001178
Chris Lattnerf1447252010-03-19 21:37:09 +00001179 if (Operator->isSubClassOf("PatFrag")) {
1180 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1181 // the forward reference case where one pattern fragment references another
1182 // before it is processed.
1183 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1184 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001185
Chris Lattnerf1447252010-03-19 21:37:09 +00001186 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001187 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001188 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001189 if (Tree)
1190 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1191 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001192 assert(Op && "Invalid Fragment");
1193 return GetNumNodeResults(Op, CDP);
1194 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001195
Chris Lattnerf1447252010-03-19 21:37:09 +00001196 if (Operator->isSubClassOf("Instruction")) {
1197 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001198
Craig Topper3a8eb892015-03-20 05:09:06 +00001199 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1200
1201 // Subtract any defaulted outputs.
1202 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1203 Record *OperandNode = InstInfo.Operands[i].Rec;
1204
1205 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1206 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1207 --NumDefsToAdd;
1208 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001209
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001210 // Add on one implicit def if it has a resolvable type.
1211 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1212 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001213 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001214 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001215
Chris Lattnerf1447252010-03-19 21:37:09 +00001216 if (Operator->isSubClassOf("SDNodeXForm"))
1217 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001218
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001219 if (Operator->isSubClassOf("ValueType"))
1220 return 1; // A type-cast of one result.
1221
Tim Northoverc807a172014-05-20 11:52:46 +00001222 if (Operator->isSubClassOf("ComplexPattern"))
1223 return 1;
1224
Chris Lattnerf1447252010-03-19 21:37:09 +00001225 Operator->dump();
James Y Knighte452e272015-05-11 22:17:13 +00001226 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001227}
1228
1229void TreePatternNode::print(raw_ostream &OS) const {
1230 if (isLeaf())
1231 OS << *getLeafValue();
1232 else
1233 OS << '(' << getOperator()->getName();
1234
1235 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1236 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001237
1238 if (!isLeaf()) {
1239 if (getNumChildren() != 0) {
1240 OS << " ";
1241 getChild(0)->print(OS);
1242 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1243 OS << ", ";
1244 getChild(i)->print(OS);
1245 }
1246 }
1247 OS << ")";
1248 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001249
Dan Gohman6e979022008-10-15 06:17:21 +00001250 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
Chris Lattner514e2922011-04-17 21:38:24 +00001251 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001252 if (TransformFn)
1253 OS << "<<X:" << TransformFn->getName() << ">>";
1254 if (!getName().empty())
1255 OS << ":$" << getName();
1256
1257}
1258void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001259 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001260}
1261
Scott Michel94420742008-03-05 17:49:05 +00001262/// isIsomorphicTo - Return true if this node is recursively
1263/// isomorphic to the specified node. For this comparison, the node's
1264/// entire state is considered. The assigned name is ignored, since
1265/// nodes with differing names are considered isomorphic. However, if
1266/// the assigned name is present in the dependent variable set, then
1267/// the assigned name is considered significant and the node is
1268/// isomorphic if the names match.
1269bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1270 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001271 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001272 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001273 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001274 getTransformFn() != N->getTransformFn())
1275 return false;
1276
1277 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001278 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1279 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001280 return ((DI->getDef() == NDI->getDef())
1281 && (DepVars.find(getName()) == DepVars.end()
1282 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001283 }
1284 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001285 return getLeafValue() == N->getLeafValue();
1286 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001287
Chris Lattner8cab0212008-01-05 22:25:12 +00001288 if (N->getOperator() != getOperator() ||
1289 N->getNumChildren() != getNumChildren()) return false;
1290 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001291 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001292 return false;
1293 return true;
1294}
1295
1296/// clone - Make a copy of this tree and all of its children.
1297///
1298TreePatternNode *TreePatternNode::clone() const {
1299 TreePatternNode *New;
1300 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001301 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001302 } else {
1303 std::vector<TreePatternNode*> CChildren;
1304 CChildren.reserve(Children.size());
1305 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1306 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001307 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001308 }
1309 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001310 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001311 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001312 New->setTransformFn(getTransformFn());
1313 return New;
1314}
1315
Chris Lattner53c39ba2010-02-14 22:22:58 +00001316/// RemoveAllTypes - Recursively strip all the types of this tree.
1317void TreePatternNode::RemoveAllTypes() {
Chris Lattnerf1447252010-03-19 21:37:09 +00001318 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1319 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner53c39ba2010-02-14 22:22:58 +00001320 if (isLeaf()) return;
1321 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1322 getChild(i)->RemoveAllTypes();
1323}
1324
1325
Chris Lattner8cab0212008-01-05 22:25:12 +00001326/// SubstituteFormalArguments - Replace the formal arguments in this tree
1327/// with actual values specified by ArgMap.
1328void TreePatternNode::
1329SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1330 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001331
Chris Lattner8cab0212008-01-05 22:25:12 +00001332 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1333 TreePatternNode *Child = getChild(i);
1334 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001335 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001336 // Note that, when substituting into an output pattern, Val might be an
1337 // UnsetInit.
1338 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1339 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001340 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001341 TreePatternNode *NewChild = ArgMap[Child->getName()];
1342 assert(NewChild && "Couldn't find formal argument!");
1343 assert((Child->getPredicateFns().empty() ||
1344 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1345 "Non-empty child predicate clobbered!");
1346 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001347 }
1348 } else {
1349 getChild(i)->SubstituteFormalArguments(ArgMap);
1350 }
1351 }
1352}
1353
1354
1355/// InlinePatternFragments - If this pattern refers to any pattern
1356/// fragments, inline them into place, giving us a pattern without any
1357/// PatFrag references.
1358TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001359 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001360 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001361
1362 if (isLeaf())
1363 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001364 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001365
Chris Lattner8cab0212008-01-05 22:25:12 +00001366 if (!Op->isSubClassOf("PatFrag")) {
1367 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001368 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1369 TreePatternNode *Child = getChild(i);
1370 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1371
1372 assert((Child->getPredicateFns().empty() ||
1373 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1374 "Non-empty child predicate clobbered!");
1375
1376 setChild(i, NewChild);
1377 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001378 return this;
1379 }
1380
1381 // Otherwise, we found a reference to a fragment. First, look up its
1382 // TreePattern record.
1383 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001384
Chris Lattner8cab0212008-01-05 22:25:12 +00001385 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001386 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001387 TP.error("'" + Op->getName() + "' fragment requires " +
1388 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001389 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001390 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001391
1392 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1393
Chris Lattner514e2922011-04-17 21:38:24 +00001394 TreePredicateFn PredFn(Frag);
1395 if (!PredFn.isAlwaysTrue())
1396 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001397
Chris Lattner8cab0212008-01-05 22:25:12 +00001398 // Resolve formal arguments to their actual value.
1399 if (Frag->getNumArgs()) {
1400 // Compute the map of formal to actual arguments.
1401 std::map<std::string, TreePatternNode*> ArgMap;
1402 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1403 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001404
Chris Lattner8cab0212008-01-05 22:25:12 +00001405 FragTree->SubstituteFormalArguments(ArgMap);
1406 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001407
Chris Lattner8cab0212008-01-05 22:25:12 +00001408 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001409 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1410 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001411
1412 // Transfer in the old predicates.
1413 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1414 FragTree->addPredicateFn(getPredicateFns()[i]);
1415
Chris Lattner8cab0212008-01-05 22:25:12 +00001416 // Get a new copy of this fragment to stitch into here.
1417 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001418
Chris Lattner2e253b42008-06-30 03:02:03 +00001419 // The fragment we inlined could have recursive inlining that is needed. See
1420 // if there are any pattern fragments in it and inline them as needed.
1421 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001422}
1423
1424/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001425/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001426/// references from the register file information, for example.
1427///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001428/// When Unnamed is set, return the type of a DAG operand with no name, such as
1429/// the F8RC register class argument in:
1430///
1431/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1432///
1433/// When Unnamed is false, return the type of a named DAG operand such as the
1434/// GPR:$src operand above.
1435///
Chris Lattnerf1447252010-03-19 21:37:09 +00001436static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001437 bool NotRegisters,
1438 bool Unnamed,
1439 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001440 // Check to see if this is a register operand.
1441 if (R->isSubClassOf("RegisterOperand")) {
1442 assert(ResNo == 0 && "Regoperand ref only has one result!");
1443 if (NotRegisters)
1444 return EEVT::TypeSet(); // Unknown.
1445 Record *RegClass = R->getValueAsDef("RegClass");
1446 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1447 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1448 }
1449
Chris Lattnercabe0372010-03-15 06:00:16 +00001450 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001451 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001452 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001453 // An unnamed register class represents itself as an i32 immediate, for
1454 // example on a COPY_TO_REGCLASS instruction.
1455 if (Unnamed)
1456 return EEVT::TypeSet(MVT::i32, TP);
1457
1458 // In a named operand, the register class provides the possible set of
1459 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001460 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001461 return EEVT::TypeSet(); // Unknown.
1462 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1463 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001464 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001465
Chris Lattner6070ee22010-03-23 23:50:31 +00001466 if (R->isSubClassOf("PatFrag")) {
1467 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001468 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001469 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001470 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001471
Chris Lattner6070ee22010-03-23 23:50:31 +00001472 if (R->isSubClassOf("Register")) {
1473 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001474 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001475 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001476 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001477 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001478 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001479
1480 if (R->isSubClassOf("SubRegIndex")) {
1481 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00001482 return EEVT::TypeSet(MVT::i32, TP);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001483 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001484
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001485 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001486 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001487 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1488 //
1489 // (sext_inreg GPR:$src, i16)
1490 // ~~~
1491 if (Unnamed)
1492 return EEVT::TypeSet(MVT::Other, TP);
1493 // With a name, the ValueType simply provides the type of the named
1494 // variable.
1495 //
1496 // (sext_inreg i32:$src, i16)
1497 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001498 if (NotRegisters)
1499 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001500 return EEVT::TypeSet(getValueType(R), TP);
1501 }
1502
1503 if (R->isSubClassOf("CondCode")) {
1504 assert(ResNo == 0 && "This node only has one result!");
1505 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001506 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001507 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001508
Chris Lattner6070ee22010-03-23 23:50:31 +00001509 if (R->isSubClassOf("ComplexPattern")) {
1510 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001511 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001512 return EEVT::TypeSet(); // Unknown.
1513 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1514 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001515 }
1516 if (R->isSubClassOf("PointerLikeRegClass")) {
1517 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001518 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001519 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001520
Chris Lattner6070ee22010-03-23 23:50:31 +00001521 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1522 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001523 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001524 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001525 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001526
Tim Northoverc807a172014-05-20 11:52:46 +00001527 if (R->isSubClassOf("Operand"))
1528 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1529
Chris Lattner8cab0212008-01-05 22:25:12 +00001530 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001531 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001532}
1533
Chris Lattner89c65662008-01-06 05:36:50 +00001534
1535/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1536/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1537const CodeGenIntrinsic *TreePatternNode::
1538getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1539 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1540 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1541 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001542 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001543
Sean Silva88eb8dd2012-10-10 20:24:47 +00001544 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001545 return &CDP.getIntrinsicInfo(IID);
1546}
1547
Chris Lattner53c39ba2010-02-14 22:22:58 +00001548/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1549/// return the ComplexPattern information, otherwise return null.
1550const ComplexPattern *
1551TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001552 Record *Rec;
1553 if (isLeaf()) {
1554 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1555 if (!DI)
1556 return nullptr;
1557 Rec = DI->getDef();
1558 } else
1559 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001560
Tim Northoverc807a172014-05-20 11:52:46 +00001561 if (!Rec->isSubClassOf("ComplexPattern"))
1562 return nullptr;
1563 return &CGP.getComplexPattern(Rec);
1564}
1565
1566unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1567 // A ComplexPattern specifically declares how many results it fills in.
1568 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1569 return CP->getNumOperands();
1570
1571 // If MIOperandInfo is specified, that gives the count.
1572 if (isLeaf()) {
1573 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1574 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1575 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1576 if (MIOps->getNumArgs())
1577 return MIOps->getNumArgs();
1578 }
1579 }
1580
1581 // Otherwise there is just one result.
1582 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001583}
1584
1585/// NodeHasProperty - Return true if this node has the specified property.
1586bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001587 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001588 if (isLeaf()) {
1589 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1590 return CP->hasProperty(Property);
1591 return false;
1592 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001593
Chris Lattner53c39ba2010-02-14 22:22:58 +00001594 Record *Operator = getOperator();
1595 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001596
Chris Lattner53c39ba2010-02-14 22:22:58 +00001597 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1598}
1599
1600
1601
1602
1603/// TreeHasProperty - Return true if any node in this tree has the specified
1604/// property.
1605bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001606 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001607 if (NodeHasProperty(Property, CGP))
1608 return true;
1609 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1610 if (getChild(i)->TreeHasProperty(Property, CGP))
1611 return true;
1612 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001613}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001614
Evan Cheng49bad4c2008-06-16 20:29:38 +00001615/// isCommutativeIntrinsic - Return true if the node corresponds to a
1616/// commutative intrinsic.
1617bool
1618TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1619 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1620 return Int->isCommutative;
1621 return false;
1622}
1623
Matt Arsenaulteb492162014-11-02 23:46:51 +00001624static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1625 if (!N->isLeaf())
1626 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001627
Matt Arsenaulteb492162014-11-02 23:46:51 +00001628 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1629 if (DI && DI->getDef()->isSubClassOf(Class))
1630 return true;
1631
1632 return false;
1633}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001634
1635static void emitTooManyOperandsError(TreePattern &TP,
1636 StringRef InstName,
1637 unsigned Expected,
1638 unsigned Actual) {
1639 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1640 " operands but expected only " + Twine(Expected) + "!");
1641}
1642
1643static void emitTooFewOperandsError(TreePattern &TP,
1644 StringRef InstName,
1645 unsigned Actual) {
1646 TP.error("Instruction '" + InstName +
1647 "' expects more than the provided " + Twine(Actual) + " operands!");
1648}
1649
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001650/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001651/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001652/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001653bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001654 if (TP.hasError())
1655 return false;
1656
Chris Lattnerab3242f2008-01-06 01:10:31 +00001657 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001658 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001659 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001660 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001661 bool MadeChange = false;
1662 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1663 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001664 NotRegisters,
1665 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001666 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001667 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001668
Sean Silvafb509ed2012-10-10 20:24:43 +00001669 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001670 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001671
Chris Lattnerf1447252010-03-19 21:37:09 +00001672 // Int inits are always integers. :)
1673 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001674
Chris Lattnerf1447252010-03-19 21:37:09 +00001675 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001676 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001677
Chris Lattnerf1447252010-03-19 21:37:09 +00001678 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001679 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1680 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001681
Craig Topper95198f42013-09-25 06:37:18 +00001682 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001683 // Make sure that the value is representable for this type.
1684 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001685
Richard Smith228e6d42012-08-24 23:29:28 +00001686 // Check that the value doesn't use more bits than we have. It must either
1687 // be a sign- or zero-extended equivalent of the original.
1688 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1689 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001690 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001691
Richard Smith228e6d42012-08-24 23:29:28 +00001692 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001693 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001694 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001695 }
1696 return false;
1697 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001698
Chris Lattner8cab0212008-01-05 22:25:12 +00001699 // special handling for set, which isn't really an SDNode.
1700 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001701 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1702 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001703 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001704
Chris Lattnerf1447252010-03-19 21:37:09 +00001705 TreePatternNode *SetVal = getChild(NC-1);
1706 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1707
Elena Demikhovsky09954792015-03-01 08:23:41 +00001708 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001709 TreePatternNode *Child = getChild(i);
1710 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001711
Chris Lattner8cab0212008-01-05 22:25:12 +00001712 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001713 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1714 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001715 }
1716 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001717 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001718
Chris Lattner5c2182e2010-03-27 02:53:27 +00001719 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001720 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1721
Chris Lattner8cab0212008-01-05 22:25:12 +00001722 bool MadeChange = false;
1723 for (unsigned i = 0; i < getNumChildren(); ++i)
1724 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001725 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001726 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001727
Chris Lattneree820ac2010-02-23 05:51:07 +00001728 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001729 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001730
Chris Lattner8cab0212008-01-05 22:25:12 +00001731 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001732 unsigned NumRetVTs = Int->IS.RetVTs.size();
1733 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001734
Bill Wendling91821472008-11-13 09:08:33 +00001735 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001736 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001737
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001738 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001739 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001740 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001741 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001742 return false;
1743 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001744
1745 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001746 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001747
Chris Lattnerf1447252010-03-19 21:37:09 +00001748 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1749 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001750
Chris Lattnerf1447252010-03-19 21:37:09 +00001751 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1752 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1753 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001754 }
1755 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001756 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001757
Chris Lattneree820ac2010-02-23 05:51:07 +00001758 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001759 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001760
Chris Lattner135091b2010-03-28 08:48:47 +00001761 // Check that the number of operands is sane. Negative operands -> varargs.
1762 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001763 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001764 TP.error(getOperator()->getName() + " node requires exactly " +
1765 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001766 return false;
1767 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001768
Chris Lattner8cab0212008-01-05 22:25:12 +00001769 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1770 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1771 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001772 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001773 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001774
Chris Lattneree820ac2010-02-23 05:51:07 +00001775 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001776 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001777 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001778 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001779
Chris Lattnerd44966f2010-03-27 19:15:02 +00001780 bool MadeChange = false;
1781
1782 // Apply the result types to the node, these come from the things in the
1783 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00001784 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1785 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001786 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1787 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001788
Chris Lattnerd44966f2010-03-27 19:15:02 +00001789 // If the instruction has implicit defs, we apply the first one as a result.
1790 // FIXME: This sucks, it should apply all implicit defs.
1791 if (!InstInfo.ImplicitDefs.empty()) {
1792 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001793
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001794 // FIXME: Generalize to multiple possible types and multiple possible
1795 // ImplicitDefs.
1796 MVT::SimpleValueType VT =
1797 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001798
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001799 if (VT != MVT::Other)
1800 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001801 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001802
Chris Lattnercabe0372010-03-15 06:00:16 +00001803 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1804 // be the same.
1805 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001806 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1807 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1808 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00001809 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1810 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1811 // variadic.
1812
1813 unsigned NChild = getNumChildren();
1814 if (NChild < 3) {
1815 TP.error("REG_SEQUENCE requires at least 3 operands!");
1816 return false;
1817 }
1818
1819 if (NChild % 2 == 0) {
1820 TP.error("REG_SEQUENCE requires an odd number of operands!");
1821 return false;
1822 }
1823
1824 if (!isOperandClass(getChild(0), "RegisterClass")) {
1825 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1826 return false;
1827 }
1828
1829 for (unsigned I = 1; I < NChild; I += 2) {
1830 TreePatternNode *SubIdxChild = getChild(I + 1);
1831 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1832 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1833 itostr(I + 1) + "!");
1834 return false;
1835 }
1836 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001837 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001838
1839 unsigned ChildNo = 0;
1840 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1841 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001842
Chris Lattner8cab0212008-01-05 22:25:12 +00001843 // If the instruction expects a predicate or optional def operand, we
1844 // codegen this by setting the operand to it's default value if it has a
1845 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001846 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001847 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1848 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001849
Chris Lattner8cab0212008-01-05 22:25:12 +00001850 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001851 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001852 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001853 return false;
1854 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001855
Chris Lattner8cab0212008-01-05 22:25:12 +00001856 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001857 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001858
1859 // If the operand has sub-operands, they may be provided by distinct
1860 // child patterns, so attempt to match each sub-operand separately.
1861 if (OperandNode->isSubClassOf("Operand")) {
1862 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1863 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1864 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00001865 // a single ComplexPattern-related Operand.
1866
1867 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00001868 // Match first sub-operand against the child we already have.
1869 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1870 MadeChange |=
1871 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1872
1873 // And the remaining sub-operands against subsequent children.
1874 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1875 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001876 emitTooFewOperandsError(TP, getOperator()->getName(),
1877 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00001878 return false;
1879 }
1880 Child = getChild(ChildNo++);
1881
1882 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1883 MadeChange |=
1884 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1885 }
1886 continue;
1887 }
1888 }
1889 }
1890
1891 // If we didn't match by pieces above, attempt to match the whole
1892 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001893 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001894 }
Christopher Lamba7312392008-03-11 09:33:47 +00001895
Matt Arsenaulteb492162014-11-02 23:46:51 +00001896 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001897 emitTooManyOperandsError(TP, getOperator()->getName(),
1898 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001899 return false;
1900 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001901
Ulrich Weigande618abd2013-03-19 19:51:09 +00001902 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1903 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001904 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001905 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001906
Tim Northoverc807a172014-05-20 11:52:46 +00001907 if (getOperator()->isSubClassOf("ComplexPattern")) {
1908 bool MadeChange = false;
1909
1910 for (unsigned i = 0; i < getNumChildren(); ++i)
1911 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1912
1913 return MadeChange;
1914 }
1915
Chris Lattneree820ac2010-02-23 05:51:07 +00001916 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001917
Chris Lattneree820ac2010-02-23 05:51:07 +00001918 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001919 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001920 TP.error("Node transform '" + getOperator()->getName() +
1921 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001922 return false;
1923 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001924
Chris Lattnercabe0372010-03-15 06:00:16 +00001925 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1926
Jim Grosbach65586fe2010-12-21 16:16:00 +00001927
Chris Lattneree820ac2010-02-23 05:51:07 +00001928 // If either the output or input of the xform does not have exact
1929 // type info. We assume they must be the same. Otherwise, it is perfectly
1930 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001931#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001932 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001933 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1934 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001935 return MadeChange;
1936 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001937#endif
1938 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001939}
1940
1941/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1942/// RHS of a commutative operation, not the on LHS.
1943static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1944 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1945 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001946 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001947 return true;
1948 return false;
1949}
1950
1951
1952/// canPatternMatch - If it is impossible for this pattern to match on this
1953/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00001954/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00001955/// that can never possibly work), and to prevent the pattern permuter from
1956/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001957bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00001958 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001959 if (isLeaf()) return true;
1960
1961 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1962 if (!getChild(i)->canPatternMatch(Reason, CDP))
1963 return false;
1964
1965 // If this is an intrinsic, handle cases that would make it not match. For
1966 // example, if an operand is required to be an immediate.
1967 if (getOperator()->isSubClassOf("Intrinsic")) {
1968 // TODO:
1969 return true;
1970 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001971
Tim Northoverc807a172014-05-20 11:52:46 +00001972 if (getOperator()->isSubClassOf("ComplexPattern"))
1973 return true;
1974
Chris Lattner8cab0212008-01-05 22:25:12 +00001975 // If this node is a commutative operator, check that the LHS isn't an
1976 // immediate.
1977 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00001978 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1979 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001980 // Scan all of the operands of the node and make sure that only the last one
1981 // is a constant node, unless the RHS also is.
1982 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng49bad4c2008-06-16 20:29:38 +00001983 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1984 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00001985 if (OnlyOnRHSOfCommutative(getChild(i))) {
1986 Reason="Immediate value must be on the RHS of commutative operators!";
1987 return false;
1988 }
1989 }
1990 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001991
Chris Lattner8cab0212008-01-05 22:25:12 +00001992 return true;
1993}
1994
1995//===----------------------------------------------------------------------===//
1996// TreePattern implementation
1997//
1998
David Greeneaf8ee2c2011-07-29 22:43:06 +00001999TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002000 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2001 isInputPattern(isInput), HasError(false) {
Craig Topperef0578a2015-06-02 04:15:51 +00002002 for (Init *I : RawPat->getValues())
2003 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002004}
2005
David Greeneaf8ee2c2011-07-29 22:43:06 +00002006TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002007 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2008 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002009 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002010}
2011
David Blaikiecf195302014-11-17 22:55:41 +00002012TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002013 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2014 isInputPattern(isInput), HasError(false) {
David Blaikiecf195302014-11-17 22:55:41 +00002015 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002016}
2017
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002018void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002019 if (HasError)
2020 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002021 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002022 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2023 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002024}
2025
Chris Lattnercabe0372010-03-15 06:00:16 +00002026void TreePattern::ComputeNamedNodes() {
2027 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002028 ComputeNamedNodes(Trees[i]);
Chris Lattnercabe0372010-03-15 06:00:16 +00002029}
2030
2031void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2032 if (!N->getName().empty())
2033 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002034
Chris Lattnercabe0372010-03-15 06:00:16 +00002035 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2036 ComputeNamedNodes(N->getChild(i));
2037}
2038
David Blaikiecf195302014-11-17 22:55:41 +00002039
2040TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002041 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002042 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002043
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002044 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002045 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002046 /// (foo GPR, imm) -> (foo GPR, (imm))
2047 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002048 return ParseTreePattern(
2049 DagInit::get(DI, "",
David Greeneaf8ee2c2011-07-29 22:43:06 +00002050 std::vector<std::pair<Init*, std::string> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002051 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002052
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002053 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002054 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002055 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002056 if (OpName.empty())
2057 error("'node' argument requires a name to match with operand list");
2058 Args.push_back(OpName);
2059 }
2060
2061 Res->setName(OpName);
2062 return Res;
2063 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002064
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002065 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002066 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002067 if (OpName.empty())
2068 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002069 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002070 Args.push_back(OpName);
2071 Res->setName(OpName);
2072 return Res;
2073 }
2074
Sean Silvafb509ed2012-10-10 20:24:43 +00002075 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002076 if (!OpName.empty())
2077 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002078 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002079 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002080
Sean Silvafb509ed2012-10-10 20:24:43 +00002081 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002082 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002083 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002084 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002085 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002086 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002087 }
2088
Sean Silvafb509ed2012-10-10 20:24:43 +00002089 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002090 if (!Dag) {
2091 TheInit->dump();
2092 error("Pattern has unexpected init kind!");
2093 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002094 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002095 if (!OpDef) error("Pattern has unexpected operator type!");
2096 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002097
Chris Lattner8cab0212008-01-05 22:25:12 +00002098 if (Operator->isSubClassOf("ValueType")) {
2099 // If the operator is a ValueType, then this must be "type cast" of a leaf
2100 // node.
2101 if (Dag->getNumArgs() != 1)
2102 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002103
David Blaikiecf195302014-11-17 22:55:41 +00002104 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002105
Chris Lattner8cab0212008-01-05 22:25:12 +00002106 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002107 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2108 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002109
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002110 if (!OpName.empty())
2111 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002112 return New;
2113 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002114
Chris Lattner8cab0212008-01-05 22:25:12 +00002115 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002116 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002117 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002118 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002119 !Operator->isSubClassOf("SDNodeXForm") &&
2120 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002121 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002122 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002123 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002124 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002125
Chris Lattner8cab0212008-01-05 22:25:12 +00002126 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002127 if (isInputPattern) {
2128 if (Operator->isSubClassOf("Instruction") ||
2129 Operator->isSubClassOf("SDNodeXForm"))
2130 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2131 } else {
2132 if (Operator->isSubClassOf("Intrinsic"))
2133 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002134
Chris Lattner2e9eae12010-03-28 06:57:56 +00002135 if (Operator->isSubClassOf("SDNode") &&
2136 Operator->getName() != "imm" &&
2137 Operator->getName() != "fpimm" &&
2138 Operator->getName() != "tglobaltlsaddr" &&
2139 Operator->getName() != "tconstpool" &&
2140 Operator->getName() != "tjumptable" &&
2141 Operator->getName() != "tframeindex" &&
2142 Operator->getName() != "texternalsym" &&
2143 Operator->getName() != "tblockaddress" &&
2144 Operator->getName() != "tglobaladdr" &&
2145 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002146 Operator->getName() != "vt" &&
2147 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002148 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2149 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002150
Chris Lattner8cab0212008-01-05 22:25:12 +00002151 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002152
2153 // Parse all the operands.
2154 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002155 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002156
Chris Lattner8cab0212008-01-05 22:25:12 +00002157 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002158 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002159 // convert the intrinsic name to a number.
2160 if (Operator->isSubClassOf("Intrinsic")) {
2161 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2162 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2163
2164 // If this intrinsic returns void, it must have side-effects and thus a
2165 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002166 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002167 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002168 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002169 // Has side-effects, requires chain.
2170 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002171 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002172 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002173
David Greenee32ebf22011-07-29 19:07:07 +00002174 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002175 Children.insert(Children.begin(), IIDNode);
2176 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002177
Tim Northoverc807a172014-05-20 11:52:46 +00002178 if (Operator->isSubClassOf("ComplexPattern")) {
2179 for (unsigned i = 0; i < Children.size(); ++i) {
2180 TreePatternNode *Child = Children[i];
2181
2182 if (Child->getName().empty())
2183 error("All arguments to a ComplexPattern must be named");
2184
2185 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2186 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2187 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2188 auto OperandId = std::make_pair(Operator, i);
2189 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2190 if (PrevOp != ComplexPatternOperands.end()) {
2191 if (PrevOp->getValue() != OperandId)
2192 error("All ComplexPattern operands must appear consistently: "
2193 "in the same order in just one ComplexPattern instance.");
2194 } else
2195 ComplexPatternOperands[Child->getName()] = OperandId;
2196 }
2197 }
2198
Chris Lattnerf1447252010-03-19 21:37:09 +00002199 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002200 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002201 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002202
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002203 if (!Dag->getName().empty()) {
2204 assert(Result->getName().empty());
2205 Result->setName(Dag->getName());
2206 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002207 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002208}
2209
Chris Lattnera787c9e2010-03-28 08:38:32 +00002210/// SimplifyTree - See if we can simplify this tree to eliminate something that
2211/// will never match in favor of something obvious that will. This is here
2212/// strictly as a convenience to target authors because it allows them to write
2213/// more type generic things and have useless type casts fold away.
2214///
2215/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002216static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002217 if (N->isLeaf())
2218 return false;
2219
2220 // If we have a bitconvert with a resolved type and if the source and
2221 // destination types are the same, then the bitconvert is useless, remove it.
2222 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002223 N->getExtType(0).isConcrete() &&
2224 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2225 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002226 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002227 SimplifyTree(N);
2228 return true;
2229 }
2230
2231 // Walk all children.
2232 bool MadeChange = false;
2233 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002234 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002235 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002236 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002237 }
2238 return MadeChange;
2239}
2240
2241
2242
Chris Lattner8cab0212008-01-05 22:25:12 +00002243/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002244/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002245/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002246bool TreePattern::
2247InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2248 if (NamedNodes.empty())
2249 ComputeNamedNodes();
2250
Chris Lattner8cab0212008-01-05 22:25:12 +00002251 bool MadeChange = true;
2252 while (MadeChange) {
2253 MadeChange = false;
Chris Lattnera787c9e2010-03-28 08:38:32 +00002254 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002255 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002256 MadeChange |= SimplifyTree(Trees[i]);
2257 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002258
2259 // If there are constraints on our named nodes, apply them.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002260 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattnercabe0372010-03-15 06:00:16 +00002261 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
2262 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002263
Chris Lattnercabe0372010-03-15 06:00:16 +00002264 // If we have input named node types, propagate their types to the named
2265 // values here.
2266 if (InNamedTypes) {
Jim Grosbach37b80932014-07-09 18:55:49 +00002267 if (!InNamedTypes->count(I->getKey())) {
2268 error("Node '" + std::string(I->getKey()) +
2269 "' in output pattern but not input pattern");
2270 return true;
2271 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002272
2273 const SmallVectorImpl<TreePatternNode*> &InNodes =
2274 InNamedTypes->find(I->getKey())->second;
2275
2276 // The input types should be fully resolved by now.
2277 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2278 // If this node is a register class, and it is the root of the pattern
2279 // then we're mapping something onto an input register. We allow
2280 // changing the type of the input register in this case. This allows
2281 // us to match things like:
2282 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
David Blaikiecf195302014-11-17 22:55:41 +00002283 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002284 DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002285 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2286 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002287 continue;
2288 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002289
Daniel Dunbard177edf2010-03-21 01:38:21 +00002290 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002291 InNodes[0]->getNumTypes() == 1 &&
2292 "FIXME: cannot name multiple result nodes yet");
2293 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
2294 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002295 }
2296 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002297
Chris Lattnercabe0372010-03-15 06:00:16 +00002298 // If there are multiple nodes with the same name, they must all have the
2299 // same type.
2300 if (I->second.size() > 1) {
2301 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002302 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002303 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002304 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002305
Chris Lattnerf1447252010-03-19 21:37:09 +00002306 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2307 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002308 }
2309 }
2310 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002311 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002312
Chris Lattner8cab0212008-01-05 22:25:12 +00002313 bool HasUnresolvedTypes = false;
2314 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2315 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
2316 return !HasUnresolvedTypes;
2317}
2318
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002319void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002320 OS << getRecord()->getName();
2321 if (!Args.empty()) {
2322 OS << "(" << Args[0];
2323 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2324 OS << ", " << Args[i];
2325 OS << ")";
2326 }
2327 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002328
Chris Lattner8cab0212008-01-05 22:25:12 +00002329 if (Trees.size() > 1)
2330 OS << "[\n";
2331 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2332 OS << "\t";
2333 Trees[i]->print(OS);
2334 OS << "\n";
2335 }
2336
2337 if (Trees.size() > 1)
2338 OS << "]\n";
2339}
2340
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002341void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002342
2343//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002344// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002345//
2346
Jim Grosbach65586fe2010-12-21 16:16:00 +00002347CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002348 Records(R), Target(R) {
2349
Dale Johannesenb842d522009-02-05 01:49:45 +00002350 Intrinsics = LoadIntrinsics(Records, false);
2351 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002352 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002353 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002354 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002355 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002356 ParseDefaultOperands();
2357 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002358 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002359 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002360
Chris Lattner8cab0212008-01-05 22:25:12 +00002361 // Generate variants. For example, commutative patterns can match
2362 // multiple ways. Add them to PatternsToMatch as well.
2363 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002364
2365 // Infer instruction flags. For example, we can detect loads,
2366 // stores, and side effects in many cases by examining an
2367 // instruction's pattern.
2368 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002369
2370 // Verify that instruction flags match the patterns.
2371 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002372}
2373
Chris Lattnerab3242f2008-01-06 01:10:31 +00002374Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002375 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002376 if (!N || !N->isSubClassOf("SDNode"))
2377 PrintFatalError("Error getting SDNode '" + Name + "'!");
2378
Chris Lattner8cab0212008-01-05 22:25:12 +00002379 return N;
2380}
2381
2382// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002383void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002384 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2385 while (!Nodes.empty()) {
2386 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2387 Nodes.pop_back();
2388 }
2389
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002390 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002391 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2392 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2393 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2394}
2395
2396/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2397/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002398void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002399 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2400 while (!Xforms.empty()) {
2401 Record *XFormNode = Xforms.back();
2402 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00002403 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002404 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002405
2406 Xforms.pop_back();
2407 }
2408}
2409
Chris Lattnerab3242f2008-01-06 01:10:31 +00002410void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002411 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2412 while (!AMs.empty()) {
2413 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2414 AMs.pop_back();
2415 }
2416}
2417
2418
2419/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2420/// file, building up the PatternFragments map. After we've collected them all,
2421/// inline fragments together as necessary, so that there are no references left
2422/// inside a pattern fragment to a pattern fragment.
2423///
Hal Finkel2756dc12014-02-28 00:26:56 +00002424void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002425 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002426
Chris Lattnere7170df2008-01-05 22:43:57 +00002427 // First step, parse all of the fragments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002428 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Hal Finkel2756dc12014-02-28 00:26:56 +00002429 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2430 continue;
2431
David Greeneaf8ee2c2011-07-29 22:43:06 +00002432 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002433 TreePattern *P =
David Blaikie3c6ca232014-11-13 21:40:02 +00002434 (PatternFragments[Fragments[i]] = llvm::make_unique<TreePattern>(
2435 Fragments[i], Tree, !Fragments[i]->isSubClassOf("OutPatFrag"),
2436 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002437
Chris Lattnere7170df2008-01-05 22:43:57 +00002438 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002439 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002440 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002441
Chris Lattnere7170df2008-01-05 22:43:57 +00002442 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002443 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002444
Chris Lattner8cab0212008-01-05 22:25:12 +00002445 // Parse the operands list.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002446 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002447 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002448 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002449 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002450 if (!OpsOp ||
2451 (OpsOp->getDef()->getName() != "ops" &&
2452 OpsOp->getDef()->getName() != "outs" &&
2453 OpsOp->getDef()->getName() != "ins"))
2454 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002455
2456 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002457 Args.clear();
2458 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002459 if (!isa<DefInit>(OpsList->getArg(j)) ||
2460 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002461 P->error("Operands list should all be 'node' values.");
2462 if (OpsList->getArgName(j).empty())
2463 P->error("Operands list should have names for each operand!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002464 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner8cab0212008-01-05 22:25:12 +00002465 P->error("'" + OpsList->getArgName(j) +
2466 "' does not occur in pattern or was multiply specified!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002467 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner8cab0212008-01-05 22:25:12 +00002468 Args.push_back(OpsList->getArgName(j));
2469 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002470
Chris Lattnere7170df2008-01-05 22:43:57 +00002471 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002472 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002473 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002474
Chris Lattnere7170df2008-01-05 22:43:57 +00002475 // If there is a code init for this fragment, keep track of the fact that
2476 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002477 TreePredicateFn PredFn(P);
2478 if (!PredFn.isAlwaysTrue())
2479 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002480
Chris Lattner8cab0212008-01-05 22:25:12 +00002481 // If there is a node transformation corresponding to this, keep track of
2482 // it.
2483 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2484 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2485 P->getOnlyTree()->setTransformFn(Transform);
2486 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002487
Chris Lattner8cab0212008-01-05 22:25:12 +00002488 // Now that we've parsed all of the tree fragments, do a closure on them so
2489 // that there are not references to PatFrags left inside of them.
Chris Lattner2e253b42008-06-30 03:02:03 +00002490 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Hal Finkel2756dc12014-02-28 00:26:56 +00002491 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2492 continue;
2493
David Blaikie3c6ca232014-11-13 21:40:02 +00002494 TreePattern &ThePat = *PatternFragments[Fragments[i]];
2495 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002496
Chris Lattner8cab0212008-01-05 22:25:12 +00002497 // Infer as many types as possible. Don't worry about it if we don't infer
2498 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002499 ThePat.InferAllTypes();
2500 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002501
Chris Lattner8cab0212008-01-05 22:25:12 +00002502 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002503 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002504 }
2505}
2506
Chris Lattnerab3242f2008-01-06 01:10:31 +00002507void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002508 std::vector<Record*> DefaultOps;
2509 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002510
2511 // Find some SDNode.
2512 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002513 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002514
Tom Stellardb7246a72012-09-06 14:15:52 +00002515 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2516 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002517
Tom Stellardb7246a72012-09-06 14:15:52 +00002518 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2519 // SomeSDnode so that we can parse this.
2520 std::vector<std::pair<Init*, std::string> > Ops;
2521 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2522 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2523 DefaultInfo->getArgName(op)));
2524 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002525
Tom Stellardb7246a72012-09-06 14:15:52 +00002526 // Create a TreePattern to parse this.
2527 TreePattern P(DefaultOps[i], DI, false, *this);
2528 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002529
Tom Stellardb7246a72012-09-06 14:15:52 +00002530 // Copy the operands over into a DAGDefaultOperand.
2531 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002532
Tom Stellardb7246a72012-09-06 14:15:52 +00002533 TreePatternNode *T = P.getTree(0);
2534 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2535 TreePatternNode *TPN = T->getChild(op);
2536 while (TPN->ApplyTypeConstraints(P, false))
2537 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002538
Tom Stellardb7246a72012-09-06 14:15:52 +00002539 if (TPN->ContainsUnresolvedType()) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002540 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2541 DefaultOps[i]->getName() +
2542 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002543 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002544 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002545 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002546
2547 // Insert it into the DefaultOperands map so we can find it later.
2548 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002549 }
2550}
2551
2552/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2553/// instruction input. Return true if this is a real use.
2554static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002555 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002556 // No name -> not interesting.
2557 if (Pat->getName().empty()) {
2558 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002559 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002560 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2561 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002562 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002563 }
2564 return false;
2565 }
2566
2567 Record *Rec;
2568 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002569 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002570 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2571 Rec = DI->getDef();
2572 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002573 Rec = Pat->getOperator();
2574 }
2575
2576 // SRCVALUE nodes are ignored.
2577 if (Rec->getName() == "srcvalue")
2578 return false;
2579
2580 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2581 if (!Slot) {
2582 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002583 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002584 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002585 Record *SlotRec;
2586 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002587 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002588 } else {
2589 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2590 SlotRec = Slot->getOperator();
2591 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002592
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002593 // Ensure that the inputs agree if we've already seen this input.
2594 if (Rec != SlotRec)
2595 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002596 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002597 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002598 return true;
2599}
2600
2601/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2602/// part of "I", the instruction), computing the set of inputs and outputs of
2603/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002604void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002605FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2606 std::map<std::string, TreePatternNode*> &InstInputs,
2607 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002608 std::vector<Record*> &InstImpResults) {
2609 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002610 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002611 if (!isUse && Pat->getTransformFn())
2612 I->error("Cannot specify a transform function for a non-input value!");
2613 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002614 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002615
Chris Lattnerf2d70992010-02-17 06:53:36 +00002616 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002617 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2618 TreePatternNode *Dest = Pat->getChild(i);
2619 if (!Dest->isLeaf())
2620 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002621
Sean Silvafb509ed2012-10-10 20:24:43 +00002622 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002623 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2624 I->error("implicitly defined value should be a register!");
2625 InstImpResults.push_back(Val->getDef());
2626 }
2627 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002628 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002629
Chris Lattnerf2d70992010-02-17 06:53:36 +00002630 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002631 // If this is not a set, verify that the children nodes are not void typed,
2632 // and recurse.
2633 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002634 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002635 I->error("Cannot have void nodes inside of patterns!");
2636 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002637 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002638 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002639
Chris Lattner8cab0212008-01-05 22:25:12 +00002640 // If this is a non-leaf node with no children, treat it basically as if
2641 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002642 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002643
Chris Lattner8cab0212008-01-05 22:25:12 +00002644 if (!isUse && Pat->getTransformFn())
2645 I->error("Cannot specify a transform function for a non-input value!");
2646 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002647 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002648
Chris Lattner8cab0212008-01-05 22:25:12 +00002649 // Otherwise, this is a set, validate and collect instruction results.
2650 if (Pat->getNumChildren() == 0)
2651 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002652
Chris Lattner8cab0212008-01-05 22:25:12 +00002653 if (Pat->getTransformFn())
2654 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002655
Chris Lattner8cab0212008-01-05 22:25:12 +00002656 // Check the set destinations.
2657 unsigned NumDests = Pat->getNumChildren()-1;
2658 for (unsigned i = 0; i != NumDests; ++i) {
2659 TreePatternNode *Dest = Pat->getChild(i);
2660 if (!Dest->isLeaf())
2661 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002662
Sean Silvafb509ed2012-10-10 20:24:43 +00002663 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002664 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002665 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002666 continue;
2667 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002668
2669 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002670 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002671 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002672 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002673 if (Dest->getName().empty())
2674 I->error("set destination must have a name!");
2675 if (InstResults.count(Dest->getName()))
2676 I->error("cannot set '" + Dest->getName() +"' multiple times");
2677 InstResults[Dest->getName()] = Dest;
2678 } else if (Val->getDef()->isSubClassOf("Register")) {
2679 InstImpResults.push_back(Val->getDef());
2680 } else {
2681 I->error("set destination should be a register!");
2682 }
2683 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002684
Chris Lattner8cab0212008-01-05 22:25:12 +00002685 // Verify and collect info from the computation.
2686 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002687 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002688}
2689
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002690//===----------------------------------------------------------------------===//
2691// Instruction Analysis
2692//===----------------------------------------------------------------------===//
2693
2694class InstAnalyzer {
2695 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002696public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002697 bool hasSideEffects;
2698 bool mayStore;
2699 bool mayLoad;
2700 bool isBitcast;
2701 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002702
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002703 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2704 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2705 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002706
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002707 void Analyze(const TreePattern *Pat) {
2708 // Assume only the first tree is the pattern. The others are clobber nodes.
2709 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002710 }
2711
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002712 void Analyze(const PatternToMatch *Pat) {
2713 AnalyzeNode(Pat->getSrcPattern());
2714 }
2715
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002716private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002717 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002718 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002719 return false;
2720
2721 if (N->getNumChildren() != 2)
2722 return false;
2723
2724 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002725 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002726 return false;
2727
2728 const TreePatternNode *N1 = N->getChild(1);
2729 if (N1->isLeaf())
2730 return false;
2731 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2732 return false;
2733
2734 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2735 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2736 return false;
2737 return OpInfo.getEnumName() == "ISD::BITCAST";
2738 }
2739
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002740public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002741 void AnalyzeNode(const TreePatternNode *N) {
2742 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002743 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002744 Record *LeafRec = DI->getDef();
2745 // Handle ComplexPattern leaves.
2746 if (LeafRec->isSubClassOf("ComplexPattern")) {
2747 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2748 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2749 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002750 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002751 }
2752 }
2753 return;
2754 }
2755
2756 // Analyze children.
2757 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2758 AnalyzeNode(N->getChild(i));
2759
2760 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002761 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002762 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002763 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002764 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002765
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002766 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002767 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2768 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2769 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2770 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002771
2772 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2773 // If this is an intrinsic, analyze it.
2774 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2775 mayLoad = true;// These may load memory.
2776
Dan Gohmanddb2d652010-08-05 23:36:21 +00002777 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002778 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2779
Dan Gohmanddb2d652010-08-05 23:36:21 +00002780 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002781 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002782 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002783 }
2784 }
2785
2786};
2787
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002788static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002789 const InstAnalyzer &PatInfo,
2790 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002791 bool Error = false;
2792
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002793 // Remember where InstInfo got its flags.
2794 if (InstInfo.hasUndefFlags())
2795 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002796
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002797 // Check explicitly set flags for consistency.
2798 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2799 !InstInfo.hasSideEffects_Unset) {
2800 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2801 // the pattern has no side effects. That could be useful for div/rem
2802 // instructions that may trap.
2803 if (!InstInfo.hasSideEffects) {
2804 Error = true;
2805 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2806 Twine(InstInfo.hasSideEffects));
2807 }
2808 }
2809
2810 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2811 Error = true;
2812 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2813 Twine(InstInfo.mayStore));
2814 }
2815
2816 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2817 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00002818 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002819 if (!InstInfo.mayLoad) {
2820 Error = true;
2821 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2822 Twine(InstInfo.mayLoad));
2823 }
2824 }
2825
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002826 // Transfer inferred flags.
2827 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2828 InstInfo.mayStore |= PatInfo.mayStore;
2829 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002830
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002831 // These flags are silently added without any verification.
2832 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002833
2834 // Don't infer isVariadic. This flag means something different on SDNodes and
2835 // instructions. For example, a CALL SDNode is variadic because it has the
2836 // call arguments as operands, but a CALL instruction is not variadic - it
2837 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002838
2839 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002840}
2841
Jim Grosbach514410b2012-07-17 00:47:06 +00002842/// hasNullFragReference - Return true if the DAG has any reference to the
2843/// null_frag operator.
2844static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002845 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002846 if (!OpDef) return false;
2847 Record *Operator = OpDef->getDef();
2848
2849 // If this is the null fragment, return true.
2850 if (Operator->getName() == "null_frag") return true;
2851 // If any of the arguments reference the null fragment, return true.
2852 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002853 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002854 if (Arg && hasNullFragReference(Arg))
2855 return true;
2856 }
2857
2858 return false;
2859}
2860
2861/// hasNullFragReference - Return true if any DAG in the list references
2862/// the null_frag operator.
2863static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00002864 for (Init *I : LI->getValues()) {
2865 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00002866 assert(DI && "non-dag in an instruction Pattern list?!");
2867 if (hasNullFragReference(DI))
2868 return true;
2869 }
2870 return false;
2871}
2872
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002873/// Get all the instructions in a tree.
2874static void
2875getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2876 if (Tree->isLeaf())
2877 return;
2878 if (Tree->getOperator()->isSubClassOf("Instruction"))
2879 Instrs.push_back(Tree->getOperator());
2880 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2881 getInstructionsInTree(Tree->getChild(i), Instrs);
2882}
2883
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002884/// Check the class of a pattern leaf node against the instruction operand it
2885/// represents.
2886static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2887 Record *Leaf) {
2888 if (OI.Rec == Leaf)
2889 return true;
2890
2891 // Allow direct value types to be used in instruction set patterns.
2892 // The type will be checked later.
2893 if (Leaf->isSubClassOf("ValueType"))
2894 return true;
2895
2896 // Patterns can also be ComplexPattern instances.
2897 if (Leaf->isSubClassOf("ComplexPattern"))
2898 return true;
2899
2900 return false;
2901}
2902
Ahmed Bougacha14107512013-10-28 18:07:21 +00002903const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2904 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002905
Craig Topper0d1fb902015-03-10 03:25:04 +00002906 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002907
Craig Topper0d1fb902015-03-10 03:25:04 +00002908 // Parse the instruction.
2909 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2910 // Inline pattern fragments into it.
2911 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002912
Craig Topper0d1fb902015-03-10 03:25:04 +00002913 // Infer as many types as possible. If we cannot infer all of them, we can
2914 // never do anything with this instruction pattern: report it to the user.
2915 if (!I->InferAllTypes())
2916 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002917
Craig Topper0d1fb902015-03-10 03:25:04 +00002918 // InstInputs - Keep track of all of the inputs of the instruction, along
2919 // with the record they are declared as.
2920 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002921
Craig Topper0d1fb902015-03-10 03:25:04 +00002922 // InstResults - Keep track of all the virtual registers that are 'set'
2923 // in the instruction, including what reg class they are.
2924 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00002925
Craig Topper0d1fb902015-03-10 03:25:04 +00002926 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002927
Craig Topper0d1fb902015-03-10 03:25:04 +00002928 // Verify that the top-level forms in the instruction are of void type, and
2929 // fill in the InstResults map.
2930 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2931 TreePatternNode *Pat = I->getTree(j);
2932 if (Pat->getNumTypes() != 0)
2933 I->error("Top-level forms in instruction pattern should have"
2934 " void types");
Chris Lattner8cab0212008-01-05 22:25:12 +00002935
Craig Topper0d1fb902015-03-10 03:25:04 +00002936 // Find inputs and outputs, and verify the structure of the uses/defs.
2937 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2938 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00002939 }
2940
Craig Topper0d1fb902015-03-10 03:25:04 +00002941 // Now that we have inputs and outputs of the pattern, inspect the operands
2942 // list for the instruction. This determines the order that operands are
2943 // added to the machine instruction the node corresponds to.
2944 unsigned NumResults = InstResults.size();
2945
2946 // Parse the operands list from the (ops) list, validating it.
2947 assert(I->getArgList().empty() && "Args list should still be empty here!");
2948
2949 // Check that all of the results occur first in the list.
2950 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00002951 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00002952 for (unsigned i = 0; i != NumResults; ++i) {
2953 if (i == CGI.Operands.size())
2954 I->error("'" + InstResults.begin()->first +
2955 "' set but does not appear in operand list!");
2956 const std::string &OpName = CGI.Operands[i].Name;
2957
2958 // Check that it exists in InstResults.
2959 TreePatternNode *RNode = InstResults[OpName];
2960 if (!RNode)
2961 I->error("Operand $" + OpName + " does not exist in operand list!");
2962
Craig Topper3a8eb892015-03-20 05:09:06 +00002963 ResNodes.push_back(RNode);
2964
Craig Topper0d1fb902015-03-10 03:25:04 +00002965 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2966 if (!R)
2967 I->error("Operand $" + OpName + " should be a set destination: all "
2968 "outputs must occur before inputs in operand list!");
2969
2970 if (!checkOperandClass(CGI.Operands[i], R))
2971 I->error("Operand $" + OpName + " class mismatch!");
2972
2973 // Remember the return type.
2974 Results.push_back(CGI.Operands[i].Rec);
2975
2976 // Okay, this one checks out.
2977 InstResults.erase(OpName);
2978 }
2979
2980 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2981 // the copy while we're checking the inputs.
2982 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2983
2984 std::vector<TreePatternNode*> ResultNodeOperands;
2985 std::vector<Record*> Operands;
2986 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2987 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2988 const std::string &OpName = Op.Name;
2989 if (OpName.empty())
2990 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2991
2992 if (!InstInputsCheck.count(OpName)) {
2993 // If this is an operand with a DefaultOps set filled in, we can ignore
2994 // this. When we codegen it, we will do so as always executed.
2995 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2996 // Does it have a non-empty DefaultOps field? If so, ignore this
2997 // operand.
2998 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2999 continue;
3000 }
3001 I->error("Operand $" + OpName +
3002 " does not appear in the instruction pattern");
3003 }
3004 TreePatternNode *InVal = InstInputsCheck[OpName];
3005 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3006
3007 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3008 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3009 if (!checkOperandClass(Op, InRec))
3010 I->error("Operand $" + OpName + "'s register class disagrees"
3011 " between the operand and pattern");
3012 }
3013 Operands.push_back(Op.Rec);
3014
3015 // Construct the result for the dest-pattern operand list.
3016 TreePatternNode *OpNode = InVal->clone();
3017
3018 // No predicate is useful on the result.
3019 OpNode->clearPredicateFns();
3020
3021 // Promote the xform function to be an explicit node if set.
3022 if (Record *Xform = OpNode->getTransformFn()) {
3023 OpNode->setTransformFn(nullptr);
3024 std::vector<TreePatternNode*> Children;
3025 Children.push_back(OpNode);
3026 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3027 }
3028
3029 ResultNodeOperands.push_back(OpNode);
3030 }
3031
3032 if (!InstInputsCheck.empty())
3033 I->error("Input operand $" + InstInputsCheck.begin()->first +
3034 " occurs in pattern but not in operands list!");
3035
3036 TreePatternNode *ResultPattern =
3037 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3038 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003039 // Copy fully inferred output node types to instruction result pattern.
3040 for (unsigned i = 0; i != NumResults; ++i) {
3041 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3042 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3043 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003044
3045 // Create and insert the instruction.
3046 // FIXME: InstImpResults should not be part of DAGInstruction.
3047 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3048 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3049
3050 // Use a temporary tree pattern to infer all types and make sure that the
3051 // constructed result is correct. This depends on the instruction already
3052 // being inserted into the DAGInsts map.
3053 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3054 Temp.InferAllTypes(&I->getNamedNodesMap());
3055
3056 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3057 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3058
3059 return TheInsertedInst;
3060}
3061
Ahmed Bougacha14107512013-10-28 18:07:21 +00003062/// ParseInstructions - Parse all of the instructions, inlining and resolving
3063/// any fragments involved. This populates the Instructions list with fully
3064/// resolved instructions.
3065void CodeGenDAGPatterns::ParseInstructions() {
3066 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3067
3068 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Craig Topper24064772014-04-15 07:20:03 +00003069 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003070
3071 if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
3072 LI = Instrs[i]->getValueAsListInit("Pattern");
3073
3074 // If there is no pattern, only collect minimal information about the
3075 // instruction for its operand list. We have to assume that there is one
3076 // result, as we have no detailed info. A pattern which references the
3077 // null_frag operator is as-if no pattern were specified. Normally this
3078 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3079 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003080 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003081 std::vector<Record*> Results;
3082 std::vector<Record*> Operands;
3083
3084 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3085
3086 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003087 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3088 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003089
Craig Topper3a8eb892015-03-20 05:09:06 +00003090 // The rest are inputs.
3091 for (unsigned j = InstInfo.Operands.NumDefs,
3092 e = InstInfo.Operands.size(); j < e; ++j)
3093 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003094 }
3095
3096 // Create and insert the instruction.
3097 std::vector<Record*> ImpResults;
3098 Instructions.insert(std::make_pair(Instrs[i],
Craig Topper24064772014-04-15 07:20:03 +00003099 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003100 continue; // no pattern.
3101 }
3102
3103 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
3104 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3105
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003106 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003107 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003108 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003109
Chris Lattner8cab0212008-01-05 22:25:12 +00003110 // If we can, convert the instructions to be patterns that are matched!
Sean Silvaa4e2c5f2012-09-19 01:47:00 +00003111 for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
Benjamin Kramerc2dbd5d2009-08-23 10:39:21 +00003112 Instructions.begin(),
Chris Lattner8cab0212008-01-05 22:25:12 +00003113 E = Instructions.end(); II != E; ++II) {
3114 DAGInstruction &TheInst = II->second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003115 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003116 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003117
3118 // FIXME: Assume only the first tree is the pattern. The others are clobber
3119 // nodes.
3120 TreePatternNode *Pattern = I->getTree(0);
3121 TreePatternNode *SrcPattern;
3122 if (Pattern->getOperator()->getName() == "set") {
3123 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3124 } else{
3125 // Not a set (store or something?)
3126 SrcPattern = Pattern;
3127 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003128
Chris Lattner8cab0212008-01-05 22:25:12 +00003129 Record *Instr = II->first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00003130 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003131 PatternToMatch(Instr,
3132 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003133 SrcPattern,
3134 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00003135 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003136 Instr->getValueAsInt("AddedComplexity"),
3137 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003138 }
3139}
3140
Chris Lattnera7722b62010-02-23 06:55:24 +00003141
3142typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3143
Jim Grosbach65586fe2010-12-21 16:16:00 +00003144static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003145 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003146 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003147 if (!P->getName().empty()) {
3148 NameRecord &Rec = Names[P->getName()];
3149 // If this is the first instance of the name, remember the node.
3150 if (Rec.second++ == 0)
3151 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003152 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003153 PatternTop->error("repetition of value: $" + P->getName() +
3154 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003155 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003156
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003157 if (!P->isLeaf()) {
3158 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003159 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003160 }
3161}
3162
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003163void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner0c0baa92010-02-23 06:16:51 +00003164 const PatternToMatch &PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003165 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003166 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003167 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3168 PrintWarning(Pattern->getRecord()->getLoc(),
3169 Twine("Pattern can never match: ") + Reason);
3170 return;
3171 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003172
Chris Lattner1e634e32010-03-01 22:29:19 +00003173 // If the source pattern's root is a complex pattern, that complex pattern
3174 // must specify the nodes it can potentially match.
3175 if (const ComplexPattern *CP =
3176 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3177 if (CP->getRootNodes().empty())
3178 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3179 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003180
3181
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003182 // Find all of the named values in the input and output, ensure they have the
3183 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003184 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003185 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3186 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003187
3188 // Scan all of the named values in the destination pattern, rejecting them if
3189 // they don't exist in the input pattern.
Chris Lattnera7722b62010-02-23 06:55:24 +00003190 for (std::map<std::string, NameRecord>::iterator
Chris Lattner4b9225b2010-02-23 07:50:58 +00003191 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Craig Topper24064772014-04-15 07:20:03 +00003192 if (SrcNames[I->first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003193 Pattern->error("Pattern has input without matching name in output: $" +
3194 I->first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003195 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003196
Chris Lattnera7722b62010-02-23 06:55:24 +00003197 // Scan all of the named values in the source pattern, rejecting them if the
3198 // name isn't used in the dest, and isn't used to tie two values together.
3199 for (std::map<std::string, NameRecord>::iterator
3200 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
Craig Topper24064772014-04-15 07:20:03 +00003201 if (DstNames[I->first].first == nullptr && SrcNames[I->first].second == 1)
Chris Lattnera7722b62010-02-23 06:55:24 +00003202 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003203
Chris Lattner0c0baa92010-02-23 06:16:51 +00003204 PatternsToMatch.push_back(PTM);
3205}
3206
3207
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003208
3209void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattner918be522010-03-19 00:34:35 +00003210 const std::vector<const CodeGenInstruction*> &Instructions =
3211 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003212
3213 // First try to infer flags from the primary instruction pattern, if any.
3214 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003215 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003216 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3217 CodeGenInstruction &InstInfo =
3218 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003219
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003220 // Get the primary instruction pattern.
3221 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3222 if (!Pattern) {
3223 if (InstInfo.hasUndefFlags())
3224 Revisit.push_back(&InstInfo);
3225 continue;
3226 }
3227 InstAnalyzer PatInfo(*this);
3228 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003229 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003230 }
3231
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003232 // Second, look for single-instruction patterns defined outside the
3233 // instruction.
3234 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3235 const PatternToMatch &PTM = *I;
3236
3237 // We can only infer from single-instruction patterns, otherwise we won't
3238 // know which instruction should get the flags.
3239 SmallVector<Record*, 8> PatInstrs;
3240 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3241 if (PatInstrs.size() != 1)
3242 continue;
3243
3244 // Get the single instruction.
3245 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3246
3247 // Only infer properties from the first pattern. We'll verify the others.
3248 if (InstInfo.InferredFrom)
3249 continue;
3250
3251 InstAnalyzer PatInfo(*this);
3252 PatInfo.Analyze(&PTM);
3253 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3254 }
3255
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003256 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003257 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003258
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003259 // Revisit instructions with undefined flags and no pattern.
3260 if (Target.guessInstructionProperties()) {
3261 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3262 CodeGenInstruction &InstInfo = *Revisit[i];
3263 if (InstInfo.InferredFrom)
3264 continue;
3265 // The mayLoad and mayStore flags default to false.
3266 // Conservatively assume hasSideEffects if it wasn't explicit.
3267 if (InstInfo.hasSideEffects_Unset)
3268 InstInfo.hasSideEffects = true;
3269 }
3270 return;
3271 }
3272
3273 // Complain about any flags that are still undefined.
3274 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3275 CodeGenInstruction &InstInfo = *Revisit[i];
3276 if (InstInfo.InferredFrom)
3277 continue;
3278 if (InstInfo.hasSideEffects_Unset)
3279 PrintError(InstInfo.TheDef->getLoc(),
3280 "Can't infer hasSideEffects from patterns");
3281 if (InstInfo.mayStore_Unset)
3282 PrintError(InstInfo.TheDef->getLoc(),
3283 "Can't infer mayStore from patterns");
3284 if (InstInfo.mayLoad_Unset)
3285 PrintError(InstInfo.TheDef->getLoc(),
3286 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003287 }
3288}
3289
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003290
3291/// Verify instruction flags against pattern node properties.
3292void CodeGenDAGPatterns::VerifyInstructionFlags() {
3293 unsigned Errors = 0;
3294 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3295 const PatternToMatch &PTM = *I;
3296 SmallVector<Record*, 8> Instrs;
3297 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3298 if (Instrs.empty())
3299 continue;
3300
3301 // Count the number of instructions with each flag set.
3302 unsigned NumSideEffects = 0;
3303 unsigned NumStores = 0;
3304 unsigned NumLoads = 0;
3305 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3306 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3307 NumSideEffects += InstInfo.hasSideEffects;
3308 NumStores += InstInfo.mayStore;
3309 NumLoads += InstInfo.mayLoad;
3310 }
3311
3312 // Analyze the source pattern.
3313 InstAnalyzer PatInfo(*this);
3314 PatInfo.Analyze(&PTM);
3315
3316 // Collect error messages.
3317 SmallVector<std::string, 4> Msgs;
3318
3319 // Check for missing flags in the output.
3320 // Permit extra flags for now at least.
3321 if (PatInfo.hasSideEffects && !NumSideEffects)
3322 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3323
3324 // Don't verify store flags on instructions with side effects. At least for
3325 // intrinsics, side effects implies mayStore.
3326 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3327 Msgs.push_back("pattern may store, but mayStore isn't set");
3328
3329 // Similarly, mayStore implies mayLoad on intrinsics.
3330 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3331 Msgs.push_back("pattern may load, but mayLoad isn't set");
3332
3333 // Print error messages.
3334 if (Msgs.empty())
3335 continue;
3336 ++Errors;
3337
3338 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
3339 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
3340 (Instrs.size() == 1 ?
3341 "instruction" : "output instructions"));
3342 // Provide the location of the relevant instruction definitions.
3343 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3344 if (Instrs[i] != PTM.getSrcRecord())
3345 PrintError(Instrs[i]->getLoc(), "defined here");
3346 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3347 if (InstInfo.InferredFrom &&
3348 InstInfo.InferredFrom != InstInfo.TheDef &&
3349 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003350 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003351 }
3352 }
3353 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003354 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003355}
3356
Chris Lattnercabe0372010-03-15 06:00:16 +00003357/// Given a pattern result with an unresolved type, see if we can find one
3358/// instruction with an unresolved result type. Force this result type to an
3359/// arbitrary element if it's possible types to converge results.
3360static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3361 if (N->isLeaf())
3362 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003363
Chris Lattnercabe0372010-03-15 06:00:16 +00003364 // Analyze children.
3365 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3366 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3367 return true;
3368
3369 if (!N->getOperator()->isSubClassOf("Instruction"))
3370 return false;
3371
3372 // If this type is already concrete or completely unknown we can't do
3373 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003374 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3375 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3376 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003377
Chris Lattnerf1447252010-03-19 21:37:09 +00003378 // Otherwise, force its type to the first possibility (an arbitrary choice).
3379 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3380 return true;
3381 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003382
Chris Lattnerf1447252010-03-19 21:37:09 +00003383 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003384}
3385
Chris Lattnerab3242f2008-01-06 01:10:31 +00003386void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003387 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3388
3389 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00003390 Record *CurPattern = Patterns[i];
David Greeneaf8ee2c2011-07-29 22:43:06 +00003391 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003392
3393 // If the pattern references the null_frag, there's nothing to do.
3394 if (hasNullFragReference(Tree))
3395 continue;
3396
Chris Lattner5c2182e2010-03-27 02:53:27 +00003397 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003398
3399 // Inline pattern fragments into it.
3400 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003401
David Greeneaf8ee2c2011-07-29 22:43:06 +00003402 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003403 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003404
Chris Lattner8cab0212008-01-05 22:25:12 +00003405 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003406 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003407
Chris Lattner8cab0212008-01-05 22:25:12 +00003408 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003409 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003410
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003411 if (Result.getNumTrees() != 1)
3412 Result.error("Cannot handle instructions producing instructions "
3413 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003414
Chris Lattner8cab0212008-01-05 22:25:12 +00003415 bool IterateInference;
3416 bool InferredAllPatternTypes, InferredAllResultTypes;
3417 do {
3418 // Infer as many types as possible. If we cannot infer all of them, we
3419 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003420 InferredAllPatternTypes =
3421 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003422
Chris Lattner8cab0212008-01-05 22:25:12 +00003423 // Infer as many types as possible. If we cannot infer all of them, we
3424 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003425 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003426 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003427
Chris Lattnerfdc20712010-03-18 23:15:10 +00003428 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003429
Chris Lattner8cab0212008-01-05 22:25:12 +00003430 // Apply the type of the result to the source pattern. This helps us
3431 // resolve cases where the input type is known to be a pointer type (which
3432 // is considered resolved), but the result knows it needs to be 32- or
3433 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003434 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003435 Pattern->getTree(0)->getNumTypes());
3436 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003437 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3438 i, Result.getTree(0)->getExtType(i), Result);
3439 IterateInference |= Result.getTree(0)->UpdateNodeType(
3440 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003441 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003442
Chris Lattnercabe0372010-03-15 06:00:16 +00003443 // If our iteration has converged and the input pattern's types are fully
3444 // resolved but the result pattern is not fully resolved, we may have a
3445 // situation where we have two instructions in the result pattern and
3446 // the instructions require a common register class, but don't care about
3447 // what actual MVT is used. This is actually a bug in our modelling:
3448 // output patterns should have register classes, not MVTs.
3449 //
3450 // In any case, to handle this, we just go through and disambiguate some
3451 // arbitrary types to the result pattern's nodes.
3452 if (!IterateInference && InferredAllPatternTypes &&
3453 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003454 IterateInference =
3455 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003456 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003457
Chris Lattner8cab0212008-01-05 22:25:12 +00003458 // Verify that we inferred enough types that we can do something with the
3459 // pattern and result. If these fire the user has to add type casts.
3460 if (!InferredAllPatternTypes)
3461 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003462 if (!InferredAllResultTypes) {
3463 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003464 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003465 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003466
Chris Lattner8cab0212008-01-05 22:25:12 +00003467 // Validate that the input pattern is correct.
3468 std::map<std::string, TreePatternNode*> InstInputs;
3469 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003470 std::vector<Record*> InstImpResults;
3471 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3472 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3473 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003474 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003475
3476 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003477 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003478 std::vector<TreePatternNode*> ResultNodeOperands;
3479 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3480 TreePatternNode *OpNode = DstPattern->getChild(ii);
3481 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003482 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003483 std::vector<TreePatternNode*> Children;
3484 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003485 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003486 }
3487 ResultNodeOperands.push_back(OpNode);
3488 }
David Blaikiecf195302014-11-17 22:55:41 +00003489 DstPattern = Result.getOnlyTree();
3490 if (!DstPattern->isLeaf())
3491 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3492 ResultNodeOperands,
3493 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003494
David Blaikiecf195302014-11-17 22:55:41 +00003495 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3496 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3497
3498 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003499 Temp.InferAllTypes();
3500
Jim Grosbach65586fe2010-12-21 16:16:00 +00003501
Chris Lattner0c0baa92010-02-23 06:16:51 +00003502 AddPatternToMatch(Pattern,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003503 PatternToMatch(CurPattern,
3504 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerf1447252010-03-19 21:37:09 +00003505 Pattern->getTree(0),
David Blaikiecf195302014-11-17 22:55:41 +00003506 Temp.getOnlyTree(), InstImpResults,
Chris Lattnerf1447252010-03-19 21:37:09 +00003507 CurPattern->getValueAsInt("AddedComplexity"),
3508 CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003509 }
3510}
3511
3512/// CombineChildVariants - Given a bunch of permutations of each child of the
3513/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003514static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003515 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3516 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003517 CodeGenDAGPatterns &CDP,
3518 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003519 // Make sure that each operand has at least one variant to choose from.
3520 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3521 if (ChildVariants[i].empty())
3522 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003523
Chris Lattner8cab0212008-01-05 22:25:12 +00003524 // The end result is an all-pairs construction of the resultant pattern.
3525 std::vector<unsigned> Idxs;
3526 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003527 bool NotDone;
3528 do {
3529#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003530 DEBUG(if (!Idxs.empty()) {
3531 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3532 for (unsigned i = 0; i < Idxs.size(); ++i) {
3533 errs() << Idxs[i] << " ";
3534 }
3535 errs() << "]\n";
3536 });
Scott Michel94420742008-03-05 17:49:05 +00003537#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003538 // Create the variant and add it to the output list.
3539 std::vector<TreePatternNode*> NewChildren;
3540 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3541 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerf1447252010-03-19 21:37:09 +00003542 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3543 Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003544
Chris Lattner8cab0212008-01-05 22:25:12 +00003545 // Copy over properties.
3546 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003547 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003548 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003549 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3550 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003551
Scott Michel94420742008-03-05 17:49:05 +00003552 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003553 std::string ErrString;
3554 if (!R->canPatternMatch(ErrString, CDP)) {
3555 delete R;
3556 } else {
3557 bool AlreadyExists = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003558
Chris Lattner8cab0212008-01-05 22:25:12 +00003559 // Scan to see if this pattern has already been emitted. We can get
3560 // duplication due to things like commuting:
3561 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3562 // which are the same pattern. Ignore the dups.
3563 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003564 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003565 AlreadyExists = true;
3566 break;
3567 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003568
Chris Lattner8cab0212008-01-05 22:25:12 +00003569 if (AlreadyExists)
3570 delete R;
3571 else
3572 OutVariants.push_back(R);
3573 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003574
Scott Michel94420742008-03-05 17:49:05 +00003575 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003576 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00003577 // [0, 0], [0, 1], [1, 0], [1, 1].
3578 int IdxsIdx;
3579 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3580 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3581 Idxs[IdxsIdx] = 0;
3582 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003583 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003584 }
Scott Michel94420742008-03-05 17:49:05 +00003585 NotDone = (IdxsIdx >= 0);
3586 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003587}
3588
3589/// CombineChildVariants - A helper function for binary operators.
3590///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003591static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003592 const std::vector<TreePatternNode*> &LHS,
3593 const std::vector<TreePatternNode*> &RHS,
3594 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003595 CodeGenDAGPatterns &CDP,
3596 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003597 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3598 ChildVariants.push_back(LHS);
3599 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003600 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003601}
Chris Lattner8cab0212008-01-05 22:25:12 +00003602
3603
3604static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3605 std::vector<TreePatternNode *> &Children) {
3606 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3607 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003608
Chris Lattner8cab0212008-01-05 22:25:12 +00003609 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003610 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003611 N->getTransformFn()) {
3612 Children.push_back(N);
3613 return;
3614 }
3615
3616 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3617 Children.push_back(N->getChild(0));
3618 else
3619 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3620
3621 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3622 Children.push_back(N->getChild(1));
3623 else
3624 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3625}
3626
3627/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3628/// the (potentially recursive) pattern by using algebraic laws.
3629///
3630static void GenerateVariantsOf(TreePatternNode *N,
3631 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003632 CodeGenDAGPatterns &CDP,
3633 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003634 // We cannot permute leaves or ComplexPattern uses.
3635 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003636 OutVariants.push_back(N);
3637 return;
3638 }
3639
3640 // Look up interesting info about the node.
3641 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3642
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003643 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003644 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003645 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003646 std::vector<TreePatternNode*> MaximalChildren;
3647 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3648
3649 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3650 // permutations.
3651 if (MaximalChildren.size() == 3) {
3652 // Find the variants of all of our maximal children.
3653 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003654 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3655 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3656 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003657
Chris Lattner8cab0212008-01-05 22:25:12 +00003658 // There are only two ways we can permute the tree:
3659 // (A op B) op C and A op (B op C)
3660 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003661
Chris Lattner8cab0212008-01-05 22:25:12 +00003662 // Generate legal pair permutations of A/B/C.
3663 std::vector<TreePatternNode*> ABVariants;
3664 std::vector<TreePatternNode*> BAVariants;
3665 std::vector<TreePatternNode*> ACVariants;
3666 std::vector<TreePatternNode*> CAVariants;
3667 std::vector<TreePatternNode*> BCVariants;
3668 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003669 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3670 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3671 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3672 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3673 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3674 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003675
3676 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003677 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3678 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3679 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3680 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3681 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3682 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003683
3684 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003685 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3686 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3687 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3688 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3689 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3690 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003691 return;
3692 }
3693 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003694
Chris Lattner8cab0212008-01-05 22:25:12 +00003695 // Compute permutations of all children.
3696 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3697 ChildVariants.resize(N->getNumChildren());
3698 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003699 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003700
3701 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003702 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003703
3704 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003705 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3706 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3707 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3708 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003709 // Don't count children which are actually register references.
3710 unsigned NC = 0;
3711 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3712 TreePatternNode *Child = N->getChild(i);
3713 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003714 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003715 Record *RR = DI->getDef();
3716 if (RR->isSubClassOf("Register"))
3717 continue;
3718 }
3719 NC++;
3720 }
3721 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003722 if (isCommIntrinsic) {
3723 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3724 // operands are the commutative operands, and there might be more operands
3725 // after those.
3726 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003727 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00003728 std::vector<std::vector<TreePatternNode*> > Variants;
3729 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3730 Variants.push_back(ChildVariants[2]);
3731 Variants.push_back(ChildVariants[1]);
3732 for (unsigned i = 3; i != NC; ++i)
3733 Variants.push_back(ChildVariants[i]);
3734 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3735 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003736 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003737 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003738 }
3739}
3740
3741
3742// GenerateVariants - Generate variants. For example, commutative patterns can
3743// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003744void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003745 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003746
Chris Lattner8cab0212008-01-05 22:25:12 +00003747 // Loop over all of the patterns we've collected, checking to see if we can
3748 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003749 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003750 // the .td file having to contain tons of variants of instructions.
3751 //
3752 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3753 // intentionally do not reconsider these. Any variants of added patterns have
3754 // already been added.
3755 //
3756 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003757 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003758 std::vector<TreePatternNode*> Variants;
Scott Michel94420742008-03-05 17:49:05 +00003759 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003760 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003761 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003762 DEBUG(errs() << "\n");
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003763 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3764 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003765
3766 assert(!Variants.empty() && "Must create at least original variant!");
3767 Variants.erase(Variants.begin()); // Remove the original pattern.
3768
3769 if (Variants.empty()) // No variants for this pattern.
3770 continue;
3771
Chris Lattner34822f62009-08-23 04:44:11 +00003772 DEBUG(errs() << "FOUND VARIANTS OF: ";
3773 PatternsToMatch[i].getSrcPattern()->dump();
3774 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003775
3776 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3777 TreePatternNode *Variant = Variants[v];
3778
Chris Lattner34822f62009-08-23 04:44:11 +00003779 DEBUG(errs() << " VAR#" << v << ": ";
3780 Variant->dump();
3781 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003782
Chris Lattner8cab0212008-01-05 22:25:12 +00003783 // Scan to see if an instruction or explicit pattern already matches this.
3784 bool AlreadyExists = false;
3785 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003786 // Skip if the top level predicates do not match.
3787 if (PatternsToMatch[i].getPredicates() !=
3788 PatternsToMatch[p].getPredicates())
3789 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003790 // Check to see if this variant already exists.
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003791 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3792 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003793 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003794 AlreadyExists = true;
3795 break;
3796 }
3797 }
3798 // If we already have it, ignore the variant.
3799 if (AlreadyExists) continue;
3800
3801 // Otherwise, add it to the list of patterns we have.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00003802 PatternsToMatch.emplace_back(
3803 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3804 Variant, PatternsToMatch[i].getDstPattern(),
3805 PatternsToMatch[i].getDstRegs(),
3806 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
Chris Lattner8cab0212008-01-05 22:25:12 +00003807 }
3808
Chris Lattner34822f62009-08-23 04:44:11 +00003809 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003810 }
3811}