blob: 307a95373c9d0802b6f0ec0033ca2d6b7345f46a [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"
Craig Topper3522ab32015-11-28 08:23:02 +000017#include "llvm/ADT/SmallString.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000018#include "llvm/ADT/StringExtras.h"
Jim Grosbach3ae48a62012-04-18 17:46:41 +000019#include "llvm/ADT/Twine.h"
Chris Lattner8cab0212008-01-05 22:25:12 +000020#include "llvm/Support/Debug.h"
David Blaikieb48ed1a2012-01-17 04:43:56 +000021#include "llvm/Support/ErrorHandling.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000022#include "llvm/TableGen/Error.h"
23#include "llvm/TableGen/Record.h"
Chuck Rose IIIfe2714f2008-01-15 21:43:17 +000024#include <algorithm>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000025#include <cstdio>
26#include <set>
Chris Lattner8cab0212008-01-05 22:25:12 +000027using namespace llvm;
28
Chandler Carruthe96dd892014-04-21 22:55:11 +000029#define DEBUG_TYPE "dag-patterns"
30
Chris Lattner8cab0212008-01-05 22:25:12 +000031//===----------------------------------------------------------------------===//
Chris Lattnercabe0372010-03-15 06:00:16 +000032// EEVT::TypeSet Implementation
33//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +000034
Owen Anderson9f944592009-08-11 20:47:22 +000035static inline bool isInteger(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000036 return MVT(VT).isInteger();
Duncan Sands13237ac2008-06-06 12:08:01 +000037}
Owen Anderson9f944592009-08-11 20:47:22 +000038static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000039 return MVT(VT).isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000040}
Owen Anderson9f944592009-08-11 20:47:22 +000041static inline bool isVector(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000042 return MVT(VT).isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000043}
Chris Lattner6d765eb2010-03-19 17:41:26 +000044static inline bool isScalar(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000045 return !MVT(VT).isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000046}
Duncan Sands13237ac2008-06-06 12:08:01 +000047
Chris Lattnercabe0372010-03-15 06:00:16 +000048EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
49 if (VT == MVT::iAny)
50 EnforceInteger(TP);
51 else if (VT == MVT::fAny)
52 EnforceFloatingPoint(TP);
53 else if (VT == MVT::vAny)
54 EnforceVector(TP);
55 else {
56 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
Ramkumar Ramachandra75a4f352015-01-22 20:14:38 +000057 VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!");
Chris Lattnercabe0372010-03-15 06:00:16 +000058 TypeVec.push_back(VT);
59 }
Chris Lattner8cab0212008-01-05 22:25:12 +000060}
61
Chris Lattnercabe0372010-03-15 06:00:16 +000062
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000063EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
Chris Lattnercabe0372010-03-15 06:00:16 +000064 assert(!VTList.empty() && "empty list?");
65 TypeVec.append(VTList.begin(), VTList.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +000066
Chris Lattnercabe0372010-03-15 06:00:16 +000067 if (!VTList.empty())
68 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
69 VTList[0] != MVT::fAny);
Jim Grosbach65586fe2010-12-21 16:16:00 +000070
Chris Lattner4a5f7be2010-03-27 20:32:26 +000071 // Verify no duplicates.
Chris Lattnercabe0372010-03-15 06:00:16 +000072 array_pod_sort(TypeVec.begin(), TypeVec.end());
Chris Lattner4a5f7be2010-03-27 20:32:26 +000073 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
Chris Lattner8cab0212008-01-05 22:25:12 +000074}
75
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000076/// FillWithPossibleTypes - Set to all legal types and return true, only valid
77/// on completely unknown type sets.
Chris Lattner6d765eb2010-03-19 17:41:26 +000078bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
79 bool (*Pred)(MVT::SimpleValueType),
80 const char *PredicateName) {
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000081 assert(isCompletelyUnknown());
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000082 ArrayRef<MVT::SimpleValueType> LegalTypes =
Chris Lattner6d765eb2010-03-19 17:41:26 +000083 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +000084
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000085 if (TP.hasError())
86 return false;
87
Craig Topper306cb122015-11-22 20:46:24 +000088 for (MVT::SimpleValueType VT : LegalTypes)
89 if (!Pred || Pred(VT))
90 TypeVec.push_back(VT);
Chris Lattner6d765eb2010-03-19 17:41:26 +000091
92 // If we have nothing that matches the predicate, bail out.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000093 if (TypeVec.empty()) {
Chris Lattner6d765eb2010-03-19 17:41:26 +000094 TP.error("Type inference contradiction found, no " +
Jim Grosbach65586fe2010-12-21 16:16:00 +000095 std::string(PredicateName) + " types found");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000096 return false;
97 }
Chris Lattner6d765eb2010-03-19 17:41:26 +000098 // No need to sort with one element.
99 if (TypeVec.size() == 1) return true;
100
101 // Remove duplicates.
102 array_pod_sort(TypeVec.begin(), TypeVec.end());
103 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000104
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000105 return true;
106}
Chris Lattnercabe0372010-03-15 06:00:16 +0000107
108/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
109/// integer value type.
110bool EEVT::TypeSet::hasIntegerTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000111 return std::any_of(TypeVec.begin(), TypeVec.end(), isInteger);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000112}
Chris Lattnercabe0372010-03-15 06:00:16 +0000113
114/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
115/// a floating point value type.
116bool EEVT::TypeSet::hasFloatingPointTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000117 return std::any_of(TypeVec.begin(), TypeVec.end(), isFloatingPoint);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000118}
Chris Lattnercabe0372010-03-15 06:00:16 +0000119
Craig Topper74169dc2014-01-28 04:49:01 +0000120/// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
121bool EEVT::TypeSet::hasScalarTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000122 return std::any_of(TypeVec.begin(), TypeVec.end(), isScalar);
Craig Topper74169dc2014-01-28 04:49:01 +0000123}
124
Chris Lattnercabe0372010-03-15 06:00:16 +0000125/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
126/// value type.
127bool EEVT::TypeSet::hasVectorTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000128 return std::any_of(TypeVec.begin(), TypeVec.end(), isVector);
Chris Lattner8cab0212008-01-05 22:25:12 +0000129}
Bob Wilson2cd5da82009-08-11 01:14:02 +0000130
Chris Lattnercabe0372010-03-15 06:00:16 +0000131
132std::string EEVT::TypeSet::getName() const {
Chris Lattnerda5b4ad2010-03-19 01:14:27 +0000133 if (TypeVec.empty()) return "<empty>";
Jim Grosbach65586fe2010-12-21 16:16:00 +0000134
Chris Lattnercabe0372010-03-15 06:00:16 +0000135 std::string Result;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000136
Chris Lattnercabe0372010-03-15 06:00:16 +0000137 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
138 std::string VTName = llvm::getEnumName(TypeVec[i]);
139 // Strip off MVT:: prefix if present.
140 if (VTName.substr(0,5) == "MVT::")
141 VTName = VTName.substr(5);
142 if (i) Result += ':';
143 Result += VTName;
144 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000145
Chris Lattnercabe0372010-03-15 06:00:16 +0000146 if (TypeVec.size() == 1)
147 return Result;
148 return "{" + Result + "}";
Bob Wilson2cd5da82009-08-11 01:14:02 +0000149}
Chris Lattnercabe0372010-03-15 06:00:16 +0000150
151/// MergeInTypeInfo - This merges in type information from the specified
152/// argument. If 'this' changes, it returns true. If the two types are
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000153/// contradictory (e.g. merge f32 into i32) then this flags an error.
Chris Lattnercabe0372010-03-15 06:00:16 +0000154bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000155 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
Chris Lattnercabe0372010-03-15 06:00:16 +0000156 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000157
Chris Lattnercabe0372010-03-15 06:00:16 +0000158 if (isCompletelyUnknown()) {
159 *this = InVT;
160 return true;
161 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000162
Craig Topperd2177de2015-11-23 07:19:08 +0000163 assert(!TypeVec.empty() && !InVT.TypeVec.empty() && "No unknowns");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000164
Chris Lattnercabe0372010-03-15 06:00:16 +0000165 // Handle the abstract cases, seeing if we can resolve them better.
166 switch (TypeVec[0]) {
167 default: break;
168 case MVT::iPTR:
169 case MVT::iPTRAny:
170 if (InVT.hasIntegerTypes()) {
171 EEVT::TypeSet InCopy(InVT);
172 InCopy.EnforceInteger(TP);
173 InCopy.EnforceScalar(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000174
Chris Lattnercabe0372010-03-15 06:00:16 +0000175 if (InCopy.isConcrete()) {
176 // If the RHS has one integer type, upgrade iPTR to i32.
177 TypeVec[0] = InVT.TypeVec[0];
178 return true;
179 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000180
Chris Lattnercabe0372010-03-15 06:00:16 +0000181 // If the input has multiple scalar integers, this doesn't add any info.
182 if (!InCopy.isCompletelyUnknown())
183 return false;
184 }
185 break;
186 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000187
Chris Lattnercabe0372010-03-15 06:00:16 +0000188 // If the input constraint is iAny/iPTR and this is an integer type list,
189 // remove non-integer types from the list.
190 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
191 hasIntegerTypes()) {
192 bool MadeChange = EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000193
Chris Lattnercabe0372010-03-15 06:00:16 +0000194 // If we're merging in iPTR/iPTRAny and the node currently has a list of
195 // multiple different integer types, replace them with a single iPTR.
196 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
197 TypeVec.size() != 1) {
Craig Topper4856c812015-11-24 08:20:41 +0000198 TypeVec.assign(1, InVT.TypeVec[0]);
Chris Lattnercabe0372010-03-15 06:00:16 +0000199 MadeChange = true;
200 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000201
Chris Lattnercabe0372010-03-15 06:00:16 +0000202 return MadeChange;
203 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000204
Chris Lattnercabe0372010-03-15 06:00:16 +0000205 // If this is a type list and the RHS is a typelist as well, eliminate entries
206 // from this list that aren't in the other one.
Chris Lattnercabe0372010-03-15 06:00:16 +0000207 TypeSet InputSet(*this);
208
Craig Topperfef745c2015-11-24 08:20:42 +0000209 TypeVec.clear();
210 std::set_intersection(InputSet.TypeVec.begin(), InputSet.TypeVec.end(),
211 InVT.TypeVec.begin(), InVT.TypeVec.end(),
212 std::back_inserter(TypeVec));
Jim Grosbach65586fe2010-12-21 16:16:00 +0000213
Craig Topperfef745c2015-11-24 08:20:42 +0000214 // If the intersection is the same size as the original set then we're done.
215 if (TypeVec.size() == InputSet.TypeVec.size())
216 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000217
Chris Lattnercabe0372010-03-15 06:00:16 +0000218 // If we removed all of our types, we have a type contradiction.
219 if (!TypeVec.empty())
Craig Topperfef745c2015-11-24 08:20:42 +0000220 return true;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000221
Chris Lattnercabe0372010-03-15 06:00:16 +0000222 // FIXME: Really want an SMLoc here!
223 TP.error("Type inference contradiction found, merging '" +
224 InVT.getName() + "' into '" + InputSet.getName() + "'");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000225 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000226}
227
228/// EnforceInteger - Remove all non-integer types from this set.
229bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000230 if (TP.hasError())
231 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000232 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000233 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000234 return FillWithPossibleTypes(TP, isInteger, "integer");
Craig Topperd2177de2015-11-23 07:19:08 +0000235
Chris Lattnercabe0372010-03-15 06:00:16 +0000236 if (!hasFloatingPointTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000237 return false;
238
239 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000240
Chris Lattnercabe0372010-03-15 06:00:16 +0000241 // Filter out all the fp types.
Craig Topperde2d7592015-11-23 07:19:10 +0000242 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
243 std::not1(std::ptr_fun(isInteger))),
244 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000245
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000246 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000247 TP.error("Type inference contradiction found, '" +
248 InputSet.getName() + "' needs to be integer");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000249 return false;
250 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000251 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000252}
253
254/// EnforceFloatingPoint - Remove all integer types from this set.
255bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000256 if (TP.hasError())
257 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000258 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000259 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000260 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
261
Chris Lattnercabe0372010-03-15 06:00:16 +0000262 if (!hasIntegerTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000263 return false;
264
265 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000266
Craig Topperde2d7592015-11-23 07:19:10 +0000267 // Filter out all the integer types.
268 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
269 std::not1(std::ptr_fun(isFloatingPoint))),
270 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000271
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000272 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000273 TP.error("Type inference contradiction found, '" +
274 InputSet.getName() + "' needs to be floating point");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000275 return false;
276 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000277 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000278}
279
280/// EnforceScalar - Remove all vector types from this.
281bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000282 if (TP.hasError())
283 return false;
284
Chris Lattnercabe0372010-03-15 06:00:16 +0000285 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000286 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000287 return FillWithPossibleTypes(TP, isScalar, "scalar");
288
Chris Lattnercabe0372010-03-15 06:00:16 +0000289 if (!hasVectorTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000290 return false;
291
292 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000293
Chris Lattnercabe0372010-03-15 06:00:16 +0000294 // Filter out all the vector types.
Craig Topperde2d7592015-11-23 07:19:10 +0000295 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
296 std::not1(std::ptr_fun(isScalar))),
297 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000298
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000299 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000300 TP.error("Type inference contradiction found, '" +
301 InputSet.getName() + "' needs to be scalar");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000302 return false;
303 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000304 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000305}
306
307/// EnforceVector - Remove all vector types from this.
308bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000309 if (TP.hasError())
310 return false;
311
Chris Lattner6d765eb2010-03-19 17:41:26 +0000312 // If we know nothing, then get the full set.
313 if (TypeVec.empty())
314 return FillWithPossibleTypes(TP, isVector, "vector");
315
Chris Lattnercabe0372010-03-15 06:00:16 +0000316 TypeSet InputSet(*this);
317 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000318
Chris Lattnercabe0372010-03-15 06:00:16 +0000319 // Filter out all the scalar types.
Craig Topperde2d7592015-11-23 07:19:10 +0000320 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
321 std::not1(std::ptr_fun(isVector))),
322 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000323
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000324 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000325 TP.error("Type inference contradiction found, '" +
326 InputSet.getName() + "' needs to be a vector");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000327 return false;
328 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000329 return MadeChange;
330}
331
332
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000333
Craig Topper74169dc2014-01-28 04:49:01 +0000334/// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000335/// this should be based on the element type. Update this and other based on
Craig Topper74169dc2014-01-28 04:49:01 +0000336/// this information.
Chris Lattnercabe0372010-03-15 06:00:16 +0000337bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000338 if (TP.hasError())
339 return false;
340
Chris Lattnercabe0372010-03-15 06:00:16 +0000341 // Both operands must be integer or FP, but we don't care which.
342 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000343
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000344 if (isCompletelyUnknown())
345 MadeChange = FillWithPossibleTypes(TP);
346
347 if (Other.isCompletelyUnknown())
348 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000349
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000350 // If one side is known to be integer or known to be FP but the other side has
351 // no information, get at least the type integrality info in there.
352 if (!hasFloatingPointTypes())
353 MadeChange |= Other.EnforceInteger(TP);
354 else if (!hasIntegerTypes())
355 MadeChange |= Other.EnforceFloatingPoint(TP);
356 if (!Other.hasFloatingPointTypes())
357 MadeChange |= EnforceInteger(TP);
358 else if (!Other.hasIntegerTypes())
359 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000360
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000361 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
362 "Should have a type list now");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000363
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000364 // If one contains vectors but the other doesn't pull vectors out.
365 if (!hasVectorTypes())
366 MadeChange |= Other.EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000367 else if (!hasScalarTypes())
368 MadeChange |= Other.EnforceVector(TP);
Craig Topper6dbcb942014-01-25 05:17:38 +0000369 if (!Other.hasVectorTypes())
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000370 MadeChange |= EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000371 else if (!Other.hasScalarTypes())
372 MadeChange |= EnforceVector(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000373
Craig Topper74169dc2014-01-28 04:49:01 +0000374 // This code does not currently handle nodes which have multiple types,
375 // where some types are integer, and some are fp. Assert that this is not
376 // the case.
377 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
378 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
379 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
380
381 if (TP.hasError())
382 return false;
383
Craig Topper7bbd37b2015-03-10 03:25:07 +0000384 // Okay, find the smallest type from current set and remove anything the
385 // same or smaller from the other set. We need to ensure that the scalar
386 // type size is smaller than the scalar size of the smallest type. For
387 // vectors, we also need to make sure that the total size is no larger than
388 // the size of the smallest type.
Craig Topper5712d462015-11-24 08:20:47 +0000389 {
390 TypeSet InputSet(Other);
Craig Topper1282df52015-12-03 05:57:37 +0000391 MVT Smallest = *std::min_element(TypeVec.begin(), TypeVec.end(),
392 [](MVT A, MVT B) {
393 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
394 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
395 A.getSizeInBits() < B.getSizeInBits());
396 });
397
Craig Topper5712d462015-11-24 08:20:47 +0000398 auto I = std::remove_if(Other.TypeVec.begin(), Other.TypeVec.end(),
399 [Smallest](MVT OtherVT) {
400 // Don't compare vector and non-vector types.
401 if (OtherVT.isVector() != Smallest.isVector())
402 return false;
403 // The getSizeInBits() check here is only needed for vectors, but is
404 // a subset of the scalar check for scalars so no need to qualify.
405 return OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits()||
406 OtherVT.getSizeInBits() < Smallest.getSizeInBits();
407 });
408 MadeChange |= I != Other.TypeVec.end(); // If we're about to remove types.
409 Other.TypeVec.erase(I, Other.TypeVec.end());
Craig Topper74169dc2014-01-28 04:49:01 +0000410
Craig Topper5712d462015-11-24 08:20:47 +0000411 if (Other.TypeVec.empty()) {
412 TP.error("Type inference contradiction found, '" + InputSet.getName() +
413 "' has nothing larger than '" + getName() +"'!");
414 return false;
415 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000416 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000417
Craig Topper7bbd37b2015-03-10 03:25:07 +0000418 // Okay, find the largest type from the other set and remove anything the
419 // same or smaller from the current set. We need to ensure that the scalar
420 // type size is larger than the scalar size of the largest type. For
421 // vectors, we also need to make sure that the total size is no smaller than
422 // the size of the largest type.
Craig Topper5712d462015-11-24 08:20:47 +0000423 {
424 TypeSet InputSet(*this);
Craig Topper1282df52015-12-03 05:57:37 +0000425 MVT Largest = *std::max_element(Other.TypeVec.begin(), Other.TypeVec.end(),
426 [](MVT A, MVT B) {
427 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
428 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
429 A.getSizeInBits() < B.getSizeInBits());
430 });
Craig Topper5712d462015-11-24 08:20:47 +0000431 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
432 [Largest](MVT OtherVT) {
433 // Don't compare vector and non-vector types.
434 if (OtherVT.isVector() != Largest.isVector())
435 return false;
436 return OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
437 OtherVT.getSizeInBits() > Largest.getSizeInBits();
438 });
439 MadeChange |= I != TypeVec.end(); // If we're about to remove types.
440 TypeVec.erase(I, TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000441
Craig Topper5712d462015-11-24 08:20:47 +0000442 if (TypeVec.empty()) {
443 TP.error("Type inference contradiction found, '" + InputSet.getName() +
444 "' has nothing smaller than '" + Other.getName() +"'!");
445 return false;
446 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000447 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000448
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000449 return MadeChange;
Chris Lattnercabe0372010-03-15 06:00:16 +0000450}
451
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000452/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Chris Lattner57ebf632010-03-24 00:01:16 +0000453/// whose element is specified by VTOperand.
Craig Topper0be34582015-03-05 07:11:34 +0000454bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
455 TreePattern &TP) {
456 bool MadeChange = false;
457
458 MadeChange |= EnforceVector(TP);
459
460 TypeSet InputSet(*this);
461
462 // Filter out all the types which don't have the right element type.
Craig Topper5712d462015-11-24 08:20:47 +0000463 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
464 [VT](MVT VVT) {
465 return VVT.getVectorElementType().SimpleTy != VT;
466 });
467 MadeChange |= I != TypeVec.end();
468 TypeVec.erase(I, TypeVec.end());
Craig Topper0be34582015-03-05 07:11:34 +0000469
470 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
471 TP.error("Type inference contradiction found, forcing '" +
Craig Topper5712d462015-11-24 08:20:47 +0000472 InputSet.getName() + "' to have a vector element of type " +
473 getEnumName(VT));
Craig Topper0be34582015-03-05 07:11:34 +0000474 return false;
475 }
476
477 return MadeChange;
478}
479
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000480/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Craig Topper0be34582015-03-05 07:11:34 +0000481/// whose element is specified by VTOperand.
Chris Lattner57ebf632010-03-24 00:01:16 +0000482bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattnercabe0372010-03-15 06:00:16 +0000483 TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000484 if (TP.hasError())
485 return false;
486
Chris Lattner57ebf632010-03-24 00:01:16 +0000487 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattnercabe0372010-03-15 06:00:16 +0000488 bool MadeChange = false;
Chris Lattner57ebf632010-03-24 00:01:16 +0000489 MadeChange |= EnforceVector(TP);
490 MadeChange |= VTOperand.EnforceScalar(TP);
491
492 // If we know the vector type, it forces the scalar to agree.
493 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000494 MVT IVT = getConcrete();
Chris Lattner57ebf632010-03-24 00:01:16 +0000495 IVT = IVT.getVectorElementType();
Craig Topperdbfcc102015-11-24 08:20:44 +0000496 return MadeChange || VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
Chris Lattner57ebf632010-03-24 00:01:16 +0000497 }
498
499 // If the scalar type is known, filter out vector types whose element types
500 // disagree.
501 if (!VTOperand.isConcrete())
502 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000503
Chris Lattner57ebf632010-03-24 00:01:16 +0000504 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000505
Craig Topper16f1cbd2015-11-24 08:20:45 +0000506 MadeChange |= EnforceVectorEltTypeIs(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000507
Chris Lattnercabe0372010-03-15 06:00:16 +0000508 return MadeChange;
509}
510
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000511/// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
David Greene127fd1d2011-01-24 20:53:18 +0000512/// vector type specified by VTOperand.
513bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
514 TreePattern &TP) {
Craig Topper6e1faaf2014-01-25 17:40:33 +0000515 if (TP.hasError())
516 return false;
517
David Greene127fd1d2011-01-24 20:53:18 +0000518 // "This" must be a vector and "VTOperand" must be a vector.
519 bool MadeChange = false;
520 MadeChange |= EnforceVector(TP);
521 MadeChange |= VTOperand.EnforceVector(TP);
522
Craig Topper6e1faaf2014-01-25 17:40:33 +0000523 // If one side is known to be integer or known to be FP but the other side has
524 // no information, get at least the type integrality info in there.
525 if (!hasFloatingPointTypes())
526 MadeChange |= VTOperand.EnforceInteger(TP);
527 else if (!hasIntegerTypes())
528 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
529 if (!VTOperand.hasFloatingPointTypes())
530 MadeChange |= EnforceInteger(TP);
531 else if (!VTOperand.hasIntegerTypes())
532 MadeChange |= EnforceFloatingPoint(TP);
533
534 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
535 "Should have a type list now");
David Greene127fd1d2011-01-24 20:53:18 +0000536
537 // If we know the vector type, it forces the scalar types to agree.
Craig Topper6e1faaf2014-01-25 17:40:33 +0000538 // Also force one vector to have more elements than the other.
David Greene127fd1d2011-01-24 20:53:18 +0000539 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000540 MVT IVT = getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000541 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000542 IVT = IVT.getVectorElementType();
543
Craig Topper95198f42013-09-25 06:37:18 +0000544 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000545 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000546
547 // Only keep types that have less elements than VTOperand.
548 TypeSet InputSet(VTOperand);
549
Craig Topper5712d462015-11-24 08:20:47 +0000550 auto I = std::remove_if(VTOperand.TypeVec.begin(), VTOperand.TypeVec.end(),
551 [NumElems](MVT VVT) {
552 return VVT.getVectorNumElements() >= NumElems;
553 });
554 MadeChange |= I != VTOperand.TypeVec.end();
555 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
556
Craig Topper6e1faaf2014-01-25 17:40:33 +0000557 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
558 TP.error("Type inference contradiction found, forcing '" +
559 InputSet.getName() + "' to have less vector elements than '" +
560 getName() + "'");
561 return false;
562 }
David Greene127fd1d2011-01-24 20:53:18 +0000563 } else if (VTOperand.isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000564 MVT IVT = VTOperand.getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000565 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000566 IVT = IVT.getVectorElementType();
567
Craig Topper95198f42013-09-25 06:37:18 +0000568 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000569 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000570
571 // Only keep types that have more elements than 'this'.
572 TypeSet InputSet(*this);
573
Craig Topper5712d462015-11-24 08:20:47 +0000574 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
575 [NumElems](MVT VVT) {
576 return VVT.getVectorNumElements() <= NumElems;
577 });
578 MadeChange |= I != TypeVec.end();
579 TypeVec.erase(I, TypeVec.end());
580
Craig Topper6e1faaf2014-01-25 17:40:33 +0000581 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
582 TP.error("Type inference contradiction found, forcing '" +
583 InputSet.getName() + "' to have more vector elements than '" +
584 VTOperand.getName() + "'");
585 return false;
586 }
David Greene127fd1d2011-01-24 20:53:18 +0000587 }
588
589 return MadeChange;
590}
591
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000592/// EnforceVectorSameNumElts - 'this' is now constrained to
Craig Topper0be34582015-03-05 07:11:34 +0000593/// be a vector with same num elements as VTOperand.
594bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
595 TreePattern &TP) {
596 if (TP.hasError())
597 return false;
598
599 // "This" must be a vector and "VTOperand" must be a vector.
600 bool MadeChange = false;
601 MadeChange |= EnforceVector(TP);
602 MadeChange |= VTOperand.EnforceVector(TP);
603
604 // If we know one of the vector types, it forces the other type to agree.
605 if (isConcrete()) {
606 MVT IVT = getConcrete();
607 unsigned NumElems = IVT.getVectorNumElements();
608
Craig Topper25ce6b82015-11-26 06:30:40 +0000609 // Only keep types that have same elements as 'this'.
Craig Topper0be34582015-03-05 07:11:34 +0000610 TypeSet InputSet(VTOperand);
611
Craig Topper5712d462015-11-24 08:20:47 +0000612 auto I = std::remove_if(VTOperand.TypeVec.begin(), VTOperand.TypeVec.end(),
613 [NumElems](MVT VVT) {
614 return VVT.getVectorNumElements() != NumElems;
615 });
616 MadeChange |= I != VTOperand.TypeVec.end();
617 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
618
Craig Topper0be34582015-03-05 07:11:34 +0000619 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
620 TP.error("Type inference contradiction found, forcing '" +
621 InputSet.getName() + "' to have same number elements as '" +
622 getName() + "'");
623 return false;
624 }
625 } else if (VTOperand.isConcrete()) {
626 MVT IVT = VTOperand.getConcrete();
627 unsigned NumElems = IVT.getVectorNumElements();
628
Craig Topper25ce6b82015-11-26 06:30:40 +0000629 // Only keep types that have same elements as VTOperand.
Craig Topper0be34582015-03-05 07:11:34 +0000630 TypeSet InputSet(*this);
631
Craig Topper5712d462015-11-24 08:20:47 +0000632 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
633 [NumElems](MVT VVT) {
634 return VVT.getVectorNumElements() != NumElems;
635 });
636 MadeChange |= I != TypeVec.end();
637 TypeVec.erase(I, TypeVec.end());
638
Craig Topper0be34582015-03-05 07:11:34 +0000639 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
640 TP.error("Type inference contradiction found, forcing '" +
641 InputSet.getName() + "' to have same number elements than '" +
642 VTOperand.getName() + "'");
643 return false;
644 }
645 }
646
647 return MadeChange;
648}
649
Craig Topper9a44b3f2015-11-26 07:02:18 +0000650/// EnforceSameSize - 'this' is now constrained to be same size as VTOperand.
651bool EEVT::TypeSet::EnforceSameSize(EEVT::TypeSet &VTOperand,
652 TreePattern &TP) {
653 if (TP.hasError())
654 return false;
655
656 bool MadeChange = false;
657
658 // If we know one of the types, it forces the other type agree.
659 if (isConcrete()) {
660 MVT IVT = getConcrete();
661 unsigned Size = IVT.getSizeInBits();
662
663 // Only keep types that have the same size as 'this'.
664 TypeSet InputSet(VTOperand);
665
666 auto I = std::remove_if(VTOperand.TypeVec.begin(), VTOperand.TypeVec.end(),
667 [&](MVT VT) {
668 return VT.getSizeInBits() != Size;
669 });
670 MadeChange |= I != VTOperand.TypeVec.end();
671 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end());
672
673 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
674 TP.error("Type inference contradiction found, forcing '" +
675 InputSet.getName() + "' to have same size as '" +
676 getName() + "'");
677 return false;
678 }
679 } else if (VTOperand.isConcrete()) {
680 MVT IVT = VTOperand.getConcrete();
681 unsigned Size = IVT.getSizeInBits();
682
683 // Only keep types that have the same size as VTOperand.
684 TypeSet InputSet(*this);
685
686 auto I = std::remove_if(TypeVec.begin(), TypeVec.end(),
687 [&](MVT VT) {
688 return VT.getSizeInBits() != Size;
689 });
690 MadeChange |= I != TypeVec.end();
691 TypeVec.erase(I, TypeVec.end());
692
693 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
694 TP.error("Type inference contradiction found, forcing '" +
695 InputSet.getName() + "' to have same size as '" +
696 VTOperand.getName() + "'");
697 return false;
698 }
699 }
700
701 return MadeChange;
702}
703
Chris Lattnercabe0372010-03-15 06:00:16 +0000704//===----------------------------------------------------------------------===//
705// Helpers for working with extended types.
Chris Lattner8cab0212008-01-05 22:25:12 +0000706
Scott Michel94420742008-03-05 17:49:05 +0000707/// Dependent variable map for CodeGenDAGPattern variant generation
708typedef std::map<std::string, int> DepVarMap;
709
Chris Lattner514e2922011-04-17 21:38:24 +0000710static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel94420742008-03-05 17:49:05 +0000711 if (N->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000712 if (isa<DefInit>(N->getLeafValue()))
Scott Michel94420742008-03-05 17:49:05 +0000713 DepMap[N->getName()]++;
Scott Michel94420742008-03-05 17:49:05 +0000714 } else {
715 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
716 FindDepVarsOf(N->getChild(i), DepMap);
717 }
718}
Chris Lattner514e2922011-04-17 21:38:24 +0000719
720/// Find dependent variables within child patterns
721static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000722 DepVarMap depcounts;
723 FindDepVarsOf(N, depcounts);
Craig Topper306cb122015-11-22 20:46:24 +0000724 for (const std::pair<std::string, int> &Pair : depcounts) {
725 if (Pair.second > 1)
726 DepVars.insert(Pair.first);
Scott Michel94420742008-03-05 17:49:05 +0000727 }
728}
729
Daniel Dunbarba66a812010-10-08 02:07:22 +0000730#ifndef NDEBUG
Chris Lattner514e2922011-04-17 21:38:24 +0000731/// Dump the dependent variable set:
732static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000733 if (DepVars.empty()) {
Chris Lattner34822f62009-08-23 04:44:11 +0000734 DEBUG(errs() << "<empty set>");
Scott Michel94420742008-03-05 17:49:05 +0000735 } else {
Chris Lattner34822f62009-08-23 04:44:11 +0000736 DEBUG(errs() << "[ ");
Craig Topper306cb122015-11-22 20:46:24 +0000737 for (const std::string &DepVar : DepVars) {
738 DEBUG(errs() << DepVar << " ");
Scott Michel94420742008-03-05 17:49:05 +0000739 }
Chris Lattner34822f62009-08-23 04:44:11 +0000740 DEBUG(errs() << "]");
Scott Michel94420742008-03-05 17:49:05 +0000741 }
742}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000743#endif
744
Chris Lattner514e2922011-04-17 21:38:24 +0000745
746//===----------------------------------------------------------------------===//
747// TreePredicateFn Implementation
748//===----------------------------------------------------------------------===//
749
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000750/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
751TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
752 assert((getPredCode().empty() || getImmCode().empty()) &&
753 ".td file corrupt: can't have a node predicate *and* an imm predicate");
754}
755
Chris Lattner514e2922011-04-17 21:38:24 +0000756std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000757 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000758}
759
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000760std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000761 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000762}
763
Chris Lattner514e2922011-04-17 21:38:24 +0000764
765/// isAlwaysTrue - Return true if this is a noop predicate.
766bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000767 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000768}
769
770/// Return the name to use in the generated code to reference this, this is
771/// "Predicate_foo" if from a pattern fragment "foo".
772std::string TreePredicateFn::getFnName() const {
773 return "Predicate_" + PatFragRec->getRecord()->getName();
774}
775
776/// getCodeToRunOnSDNode - Return the code for the function body that
777/// evaluates this predicate. The argument is expected to be in "Node",
778/// not N. This handles casting and conversion to a concrete node type as
779/// appropriate.
780std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000781 // Handle immediate predicates first.
782 std::string ImmCode = getImmCode();
783 if (!ImmCode.empty()) {
784 std::string Result =
785 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000786 return Result + ImmCode;
787 }
788
789 // Handle arbitrary node predicates.
790 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000791 std::string ClassName;
792 if (PatFragRec->getOnlyTree()->isLeaf())
793 ClassName = "SDNode";
794 else {
795 Record *Op = PatFragRec->getOnlyTree()->getOperator();
796 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
797 }
798 std::string Result;
799 if (ClassName == "SDNode")
800 Result = " SDNode *N = Node;\n";
801 else
Craig Topper5b0f57d2015-10-11 16:59:29 +0000802 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
Chris Lattner514e2922011-04-17 21:38:24 +0000803
804 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000805}
806
Chris Lattner8cab0212008-01-05 22:25:12 +0000807//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000808// PatternToMatch implementation
809//
810
Chris Lattner05925fe2010-03-29 01:40:38 +0000811
812/// getPatternSize - Return the 'size' of this pattern. We want to match large
813/// patterns before small ones. This is used to determine the size of a
814/// pattern.
815static unsigned getPatternSize(const TreePatternNode *P,
816 const CodeGenDAGPatterns &CGP) {
817 unsigned Size = 3; // The node itself.
818 // If the root node is a ConstantSDNode, increases its size.
819 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000820 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000821 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000822
Chris Lattner05925fe2010-03-29 01:40:38 +0000823 // FIXME: This is a hack to statically increase the priority of patterns
824 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
825 // Later we can allow complexity / cost for each pattern to be (optionally)
826 // specified. To get best possible pattern match we'll need to dynamically
827 // calculate the complexity of all patterns a dag can potentially map to.
828 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000829 if (AM) {
Chris Lattner05925fe2010-03-29 01:40:38 +0000830 Size += AM->getNumOperands() * 3;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000831
Tim Northoverc807a172014-05-20 11:52:46 +0000832 // We don't want to count any children twice, so return early.
833 return Size;
834 }
835
Chris Lattner05925fe2010-03-29 01:40:38 +0000836 // If this node has some predicate function that must match, it adds to the
837 // complexity of this node.
838 if (!P->getPredicateFns().empty())
839 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000840
Chris Lattner05925fe2010-03-29 01:40:38 +0000841 // Count children in the count if they are also nodes.
842 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
843 TreePatternNode *Child = P->getChild(i);
844 if (!Child->isLeaf() && Child->getNumTypes() &&
845 Child->getType(0) != MVT::Other)
846 Size += getPatternSize(Child, CGP);
847 else if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000848 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000849 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
850 else if (Child->getComplexPatternInfo(CGP))
851 Size += getPatternSize(Child, CGP);
852 else if (!Child->getPredicateFns().empty())
853 ++Size;
854 }
855 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000856
Chris Lattner05925fe2010-03-29 01:40:38 +0000857 return Size;
858}
859
860/// Compute the complexity metric for the input pattern. This roughly
861/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000862int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000863getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
864 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
865}
866
867
Dan Gohman49e19e92008-08-22 00:20:26 +0000868/// getPredicateCheck - Return a single string containing all of this
869/// pattern's predicates concatenated with "&&" operators.
870///
871std::string PatternToMatch::getPredicateCheck() const {
Craig Topper8985efe2015-11-27 05:44:04 +0000872 SmallVector<Record *, 4> PredicateRecs;
Craig Topperef0578a2015-06-02 04:15:51 +0000873 for (Init *I : Predicates->getValues()) {
874 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
Dan Gohman49e19e92008-08-22 00:20:26 +0000875 Record *Def = Pred->getDef();
876 if (!Def->isSubClassOf("Predicate")) {
877#ifndef NDEBUG
878 Def->dump();
879#endif
Craig Topperc4965bc2012-02-05 07:21:30 +0000880 llvm_unreachable("Unknown predicate type!");
Dan Gohman49e19e92008-08-22 00:20:26 +0000881 }
Craig Topper8985efe2015-11-27 05:44:04 +0000882 PredicateRecs.push_back(Def);
Dan Gohman49e19e92008-08-22 00:20:26 +0000883 }
884 }
Craig Topper8985efe2015-11-27 05:44:04 +0000885 // Sort so that different orders get canonicalized to the same string.
886 std::sort(PredicateRecs.begin(), PredicateRecs.end(), LessRecord());
887
Craig Topper3522ab32015-11-28 08:23:02 +0000888 SmallString<128> PredicateCheck;
Craig Topper8985efe2015-11-27 05:44:04 +0000889 for (Record *Pred : PredicateRecs) {
890 if (!PredicateCheck.empty())
891 PredicateCheck += " && ";
892 PredicateCheck += "(" + Pred->getValueAsString("CondString") + ")";
893 }
Dan Gohman49e19e92008-08-22 00:20:26 +0000894
Craig Topper3522ab32015-11-28 08:23:02 +0000895 return PredicateCheck.str();
Dan Gohman49e19e92008-08-22 00:20:26 +0000896}
897
898//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000899// SDTypeConstraint implementation
900//
901
902SDTypeConstraint::SDTypeConstraint(Record *R) {
903 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000904
Chris Lattner8cab0212008-01-05 22:25:12 +0000905 if (R->isSubClassOf("SDTCisVT")) {
906 ConstraintType = SDTCisVT;
907 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerffdac7b2010-03-28 06:04:39 +0000908 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000909 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000910
Chris Lattner8cab0212008-01-05 22:25:12 +0000911 } else if (R->isSubClassOf("SDTCisPtrTy")) {
912 ConstraintType = SDTCisPtrTy;
913 } else if (R->isSubClassOf("SDTCisInt")) {
914 ConstraintType = SDTCisInt;
915 } else if (R->isSubClassOf("SDTCisFP")) {
916 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000917 } else if (R->isSubClassOf("SDTCisVec")) {
918 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000919 } else if (R->isSubClassOf("SDTCisSameAs")) {
920 ConstraintType = SDTCisSameAs;
921 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
922 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
923 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000924 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000925 R->getValueAsInt("OtherOperandNum");
926 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
927 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000928 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000929 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000930 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
931 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000932 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000933 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
934 ConstraintType = SDTCisSubVecOfVec;
935 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
936 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +0000937 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
938 ConstraintType = SDTCVecEltisVT;
939 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
940 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
941 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
942 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
943 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
944 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
945 "as SDTCVecEltisVT");
946 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
947 ConstraintType = SDTCisSameNumEltsAs;
948 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
949 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +0000950 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
951 ConstraintType = SDTCisSameSizeAs;
952 x.SDTCisSameSizeAs_Info.OtherOperandNum =
953 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +0000954 } else {
James Y Knighte452e272015-05-11 22:17:13 +0000955 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +0000956 }
957}
958
959/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000960/// N, and the result number in ResNo.
961static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
962 const SDNodeInfo &NodeInfo,
963 unsigned &ResNo) {
964 unsigned NumResults = NodeInfo.getNumResults();
965 if (OpNo < NumResults) {
966 ResNo = OpNo;
967 return N;
968 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000969
Chris Lattner2db7aba2010-03-19 21:56:21 +0000970 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000971
Chris Lattner2db7aba2010-03-19 21:56:21 +0000972 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +0000973 std::string S;
974 raw_string_ostream OS(S);
975 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000976 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +0000977 N->print(OS);
978 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +0000979 }
980
Chris Lattner2db7aba2010-03-19 21:56:21 +0000981 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +0000982}
983
984/// ApplyTypeConstraint - Given a node in a pattern, apply this type
985/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000986/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +0000987bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
988 const SDNodeInfo &NodeInfo,
989 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000990 if (TP.hasError())
991 return false;
992
Chris Lattner2db7aba2010-03-19 21:56:21 +0000993 unsigned ResNo = 0; // The result number being referenced.
994 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000995
Chris Lattner8cab0212008-01-05 22:25:12 +0000996 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000997 case SDTCisVT:
998 // Operand must be a particular type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000999 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001000 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001001 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001002 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001003 case SDTCisInt:
1004 // Require it to be one of the legal integer VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +00001005 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001006 case SDTCisFP:
1007 // Require it to be one of the legal fp VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +00001008 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001009 case SDTCisVec:
1010 // Require it to be one of the legal vector VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +00001011 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001012 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001013 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001014 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001015 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +00001016 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1017 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001018 }
1019 case SDTCisVTSmallerThanOp: {
1020 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1021 // have an integer type that is smaller than the VT.
1022 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +00001023 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +00001024 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001025 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001026 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001027 return false;
1028 }
Owen Anderson9f944592009-08-11 20:47:22 +00001029 MVT::SimpleValueType VT =
David Greeneaf8ee2c2011-07-29 22:43:06 +00001030 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001031
Chris Lattner38c99662010-03-24 00:06:46 +00001032 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001033
Chris Lattner2db7aba2010-03-19 21:56:21 +00001034 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001035 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001036 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1037 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001038
Chris Lattner38c99662010-03-24 00:06:46 +00001039 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001040 }
1041 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001042 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001043 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001044 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1045 BResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +00001046 return NodeToApply->getExtType(ResNo).
1047 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001048 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001049 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001050 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +00001051 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001052 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1053 VResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001054
Chris Lattner57ebf632010-03-24 00:01:16 +00001055 // Filter vector types out of VecOperand that don't have the right element
1056 // type.
1057 return VecOperand->getExtType(VResNo).
1058 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begeman17bedbc2008-02-09 01:37:05 +00001059 }
David Greene127fd1d2011-01-24 20:53:18 +00001060 case SDTCisSubVecOfVec: {
1061 unsigned VResNo = 0;
1062 TreePatternNode *BigVecOperand =
1063 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1064 VResNo);
1065
1066 // Filter vector types out of BigVecOperand that don't have the
1067 // right subvector type.
1068 return BigVecOperand->getExtType(VResNo).
1069 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1070 }
Craig Topper0be34582015-03-05 07:11:34 +00001071 case SDTCVecEltisVT: {
1072 return NodeToApply->getExtType(ResNo).
1073 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1074 }
1075 case SDTCisSameNumEltsAs: {
1076 unsigned OResNo = 0;
1077 TreePatternNode *OtherNode =
1078 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1079 N, NodeInfo, OResNo);
1080 return OtherNode->getExtType(OResNo).
1081 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1082 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001083 case SDTCisSameSizeAs: {
1084 unsigned OResNo = 0;
1085 TreePatternNode *OtherNode =
1086 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1087 N, NodeInfo, OResNo);
1088 return OtherNode->getExtType(OResNo).
1089 EnforceSameSize(NodeToApply->getExtType(ResNo), TP);
1090 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001091 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001092 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001093}
1094
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001095// Update the node type to match an instruction operand or result as specified
1096// in the ins or outs lists on the instruction definition. Return true if the
1097// type was actually changed.
1098bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1099 Record *Operand,
1100 TreePattern &TP) {
1101 // The 'unknown' operand indicates that types should be inferred from the
1102 // context.
1103 if (Operand->isSubClassOf("unknown_class"))
1104 return false;
1105
1106 // The Operand class specifies a type directly.
1107 if (Operand->isSubClassOf("Operand"))
1108 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1109 TP);
1110
1111 // PointerLikeRegClass has a type that is determined at runtime.
1112 if (Operand->isSubClassOf("PointerLikeRegClass"))
1113 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1114
1115 // Both RegisterClass and RegisterOperand operands derive their types from a
1116 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001117 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001118 if (Operand->isSubClassOf("RegisterClass"))
1119 RC = Operand;
1120 else if (Operand->isSubClassOf("RegisterOperand"))
1121 RC = Operand->getValueAsDef("RegClass");
1122
1123 assert(RC && "Unknown operand type");
1124 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1125 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1126}
1127
1128
Chris Lattner8cab0212008-01-05 22:25:12 +00001129//===----------------------------------------------------------------------===//
1130// SDNodeInfo implementation
1131//
1132SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1133 EnumName = R->getValueAsString("Opcode");
1134 SDClassName = R->getValueAsString("SDClass");
1135 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1136 NumResults = TypeProfile->getValueAsInt("NumResults");
1137 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001138
Chris Lattner8cab0212008-01-05 22:25:12 +00001139 // Parse the properties.
1140 Properties = 0;
Craig Topper306cb122015-11-22 20:46:24 +00001141 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1142 if (Property->getName() == "SDNPCommutative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001143 Properties |= 1 << SDNPCommutative;
Craig Topper306cb122015-11-22 20:46:24 +00001144 } else if (Property->getName() == "SDNPAssociative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001145 Properties |= 1 << SDNPAssociative;
Craig Topper306cb122015-11-22 20:46:24 +00001146 } else if (Property->getName() == "SDNPHasChain") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001147 Properties |= 1 << SDNPHasChain;
Craig Topper306cb122015-11-22 20:46:24 +00001148 } else if (Property->getName() == "SDNPOutGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001149 Properties |= 1 << SDNPOutGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001150 } else if (Property->getName() == "SDNPInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001151 Properties |= 1 << SDNPInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001152 } else if (Property->getName() == "SDNPOptInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001153 Properties |= 1 << SDNPOptInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001154 } else if (Property->getName() == "SDNPMayStore") {
Chris Lattnera348f552008-01-06 06:44:58 +00001155 Properties |= 1 << SDNPMayStore;
Craig Topper306cb122015-11-22 20:46:24 +00001156 } else if (Property->getName() == "SDNPMayLoad") {
Chris Lattner1ca20682008-01-10 04:38:57 +00001157 Properties |= 1 << SDNPMayLoad;
Craig Topper306cb122015-11-22 20:46:24 +00001158 } else if (Property->getName() == "SDNPSideEffect") {
Chris Lattner42c63ef2008-01-10 05:39:30 +00001159 Properties |= 1 << SDNPSideEffect;
Craig Topper306cb122015-11-22 20:46:24 +00001160 } else if (Property->getName() == "SDNPMemOperand") {
Mon P Wang6a490372008-06-25 08:15:39 +00001161 Properties |= 1 << SDNPMemOperand;
Craig Topper306cb122015-11-22 20:46:24 +00001162 } else if (Property->getName() == "SDNPVariadic") {
Chris Lattner83aeaab2010-03-19 05:07:09 +00001163 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001164 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001165 PrintFatalError("Unknown SD Node property '" +
Craig Topper306cb122015-11-22 20:46:24 +00001166 Property->getName() + "' on node '" +
James Y Knighte452e272015-05-11 22:17:13 +00001167 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001168 }
1169 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001170
1171
Chris Lattner8cab0212008-01-05 22:25:12 +00001172 // Parse the type constraints.
1173 std::vector<Record*> ConstraintList =
1174 TypeProfile->getValueAsListOfDefs("Constraints");
1175 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1176}
1177
Chris Lattner99e53b32010-02-28 00:22:30 +00001178/// getKnownType - If the type constraints on this node imply a fixed type
1179/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001180/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001181MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001182 unsigned NumResults = getNumResults();
1183 assert(NumResults <= 1 &&
1184 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001185 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001186
Craig Topper306cb122015-11-22 20:46:24 +00001187 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001188 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001189 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001190 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001191
Craig Topper306cb122015-11-22 20:46:24 +00001192 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001193 default: break;
1194 case SDTypeConstraint::SDTCisVT:
Craig Topper306cb122015-11-22 20:46:24 +00001195 return Constraint.x.SDTCisVT_Info.VT;
Chris Lattner99e53b32010-02-28 00:22:30 +00001196 case SDTypeConstraint::SDTCisPtrTy:
1197 return MVT::iPTR;
1198 }
1199 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001200 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001201}
1202
Chris Lattner8cab0212008-01-05 22:25:12 +00001203//===----------------------------------------------------------------------===//
1204// TreePatternNode implementation
1205//
1206
1207TreePatternNode::~TreePatternNode() {
1208#if 0 // FIXME: implement refcounted tree nodes!
1209 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1210 delete getChild(i);
1211#endif
1212}
1213
Chris Lattnerf1447252010-03-19 21:37:09 +00001214static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1215 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001216 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001217 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001218
Chris Lattner2109cb42010-03-22 20:56:36 +00001219 if (Operator->isSubClassOf("Intrinsic"))
1220 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001221
Chris Lattnerf1447252010-03-19 21:37:09 +00001222 if (Operator->isSubClassOf("SDNode"))
1223 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001224
Chris Lattnerf1447252010-03-19 21:37:09 +00001225 if (Operator->isSubClassOf("PatFrag")) {
1226 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1227 // the forward reference case where one pattern fragment references another
1228 // before it is processed.
1229 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1230 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001231
Chris Lattnerf1447252010-03-19 21:37:09 +00001232 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001233 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001234 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001235 if (Tree)
1236 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1237 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001238 assert(Op && "Invalid Fragment");
1239 return GetNumNodeResults(Op, CDP);
1240 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001241
Chris Lattnerf1447252010-03-19 21:37:09 +00001242 if (Operator->isSubClassOf("Instruction")) {
1243 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001244
Craig Topper3a8eb892015-03-20 05:09:06 +00001245 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1246
1247 // Subtract any defaulted outputs.
1248 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1249 Record *OperandNode = InstInfo.Operands[i].Rec;
1250
1251 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1252 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1253 --NumDefsToAdd;
1254 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001255
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001256 // Add on one implicit def if it has a resolvable type.
1257 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1258 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001259 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001260 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001261
Chris Lattnerf1447252010-03-19 21:37:09 +00001262 if (Operator->isSubClassOf("SDNodeXForm"))
1263 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001264
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001265 if (Operator->isSubClassOf("ValueType"))
1266 return 1; // A type-cast of one result.
1267
Tim Northoverc807a172014-05-20 11:52:46 +00001268 if (Operator->isSubClassOf("ComplexPattern"))
1269 return 1;
1270
Chris Lattnerf1447252010-03-19 21:37:09 +00001271 Operator->dump();
James Y Knighte452e272015-05-11 22:17:13 +00001272 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001273}
1274
1275void TreePatternNode::print(raw_ostream &OS) const {
1276 if (isLeaf())
1277 OS << *getLeafValue();
1278 else
1279 OS << '(' << getOperator()->getName();
1280
1281 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1282 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001283
1284 if (!isLeaf()) {
1285 if (getNumChildren() != 0) {
1286 OS << " ";
1287 getChild(0)->print(OS);
1288 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1289 OS << ", ";
1290 getChild(i)->print(OS);
1291 }
1292 }
1293 OS << ")";
1294 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001295
Craig Topper306cb122015-11-22 20:46:24 +00001296 for (const TreePredicateFn &Pred : PredicateFns)
1297 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001298 if (TransformFn)
1299 OS << "<<X:" << TransformFn->getName() << ">>";
1300 if (!getName().empty())
1301 OS << ":$" << getName();
1302
1303}
1304void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001305 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001306}
1307
Scott Michel94420742008-03-05 17:49:05 +00001308/// isIsomorphicTo - Return true if this node is recursively
1309/// isomorphic to the specified node. For this comparison, the node's
1310/// entire state is considered. The assigned name is ignored, since
1311/// nodes with differing names are considered isomorphic. However, if
1312/// the assigned name is present in the dependent variable set, then
1313/// the assigned name is considered significant and the node is
1314/// isomorphic if the names match.
1315bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1316 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001317 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001318 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001319 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001320 getTransformFn() != N->getTransformFn())
1321 return false;
1322
1323 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001324 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1325 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001326 return ((DI->getDef() == NDI->getDef())
1327 && (DepVars.find(getName()) == DepVars.end()
1328 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001329 }
1330 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001331 return getLeafValue() == N->getLeafValue();
1332 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001333
Chris Lattner8cab0212008-01-05 22:25:12 +00001334 if (N->getOperator() != getOperator() ||
1335 N->getNumChildren() != getNumChildren()) return false;
1336 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001337 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001338 return false;
1339 return true;
1340}
1341
1342/// clone - Make a copy of this tree and all of its children.
1343///
1344TreePatternNode *TreePatternNode::clone() const {
1345 TreePatternNode *New;
1346 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001347 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001348 } else {
1349 std::vector<TreePatternNode*> CChildren;
1350 CChildren.reserve(Children.size());
1351 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1352 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001353 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001354 }
1355 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001356 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001357 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001358 New->setTransformFn(getTransformFn());
1359 return New;
1360}
1361
Chris Lattner53c39ba2010-02-14 22:22:58 +00001362/// RemoveAllTypes - Recursively strip all the types of this tree.
1363void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001364 // Reset to unknown type.
1365 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001366 if (isLeaf()) return;
1367 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1368 getChild(i)->RemoveAllTypes();
1369}
1370
1371
Chris Lattner8cab0212008-01-05 22:25:12 +00001372/// SubstituteFormalArguments - Replace the formal arguments in this tree
1373/// with actual values specified by ArgMap.
1374void TreePatternNode::
1375SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1376 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001377
Chris Lattner8cab0212008-01-05 22:25:12 +00001378 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1379 TreePatternNode *Child = getChild(i);
1380 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001381 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001382 // Note that, when substituting into an output pattern, Val might be an
1383 // UnsetInit.
1384 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1385 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001386 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001387 TreePatternNode *NewChild = ArgMap[Child->getName()];
1388 assert(NewChild && "Couldn't find formal argument!");
1389 assert((Child->getPredicateFns().empty() ||
1390 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1391 "Non-empty child predicate clobbered!");
1392 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001393 }
1394 } else {
1395 getChild(i)->SubstituteFormalArguments(ArgMap);
1396 }
1397 }
1398}
1399
1400
1401/// InlinePatternFragments - If this pattern refers to any pattern
1402/// fragments, inline them into place, giving us a pattern without any
1403/// PatFrag references.
1404TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001405 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001406 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001407
1408 if (isLeaf())
1409 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001410 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001411
Chris Lattner8cab0212008-01-05 22:25:12 +00001412 if (!Op->isSubClassOf("PatFrag")) {
1413 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001414 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1415 TreePatternNode *Child = getChild(i);
1416 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1417
1418 assert((Child->getPredicateFns().empty() ||
1419 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1420 "Non-empty child predicate clobbered!");
1421
1422 setChild(i, NewChild);
1423 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001424 return this;
1425 }
1426
1427 // Otherwise, we found a reference to a fragment. First, look up its
1428 // TreePattern record.
1429 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001430
Chris Lattner8cab0212008-01-05 22:25:12 +00001431 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001432 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001433 TP.error("'" + Op->getName() + "' fragment requires " +
1434 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001435 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001436 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001437
1438 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1439
Chris Lattner514e2922011-04-17 21:38:24 +00001440 TreePredicateFn PredFn(Frag);
1441 if (!PredFn.isAlwaysTrue())
1442 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001443
Chris Lattner8cab0212008-01-05 22:25:12 +00001444 // Resolve formal arguments to their actual value.
1445 if (Frag->getNumArgs()) {
1446 // Compute the map of formal to actual arguments.
1447 std::map<std::string, TreePatternNode*> ArgMap;
1448 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1449 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001450
Chris Lattner8cab0212008-01-05 22:25:12 +00001451 FragTree->SubstituteFormalArguments(ArgMap);
1452 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001453
Chris Lattner8cab0212008-01-05 22:25:12 +00001454 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001455 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1456 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001457
1458 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001459 for (const TreePredicateFn &Pred : getPredicateFns())
1460 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001461
Chris Lattner8cab0212008-01-05 22:25:12 +00001462 // Get a new copy of this fragment to stitch into here.
1463 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001464
Chris Lattner2e253b42008-06-30 03:02:03 +00001465 // The fragment we inlined could have recursive inlining that is needed. See
1466 // if there are any pattern fragments in it and inline them as needed.
1467 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001468}
1469
1470/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001471/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001472/// references from the register file information, for example.
1473///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001474/// When Unnamed is set, return the type of a DAG operand with no name, such as
1475/// the F8RC register class argument in:
1476///
1477/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1478///
1479/// When Unnamed is false, return the type of a named DAG operand such as the
1480/// GPR:$src operand above.
1481///
Chris Lattnerf1447252010-03-19 21:37:09 +00001482static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001483 bool NotRegisters,
1484 bool Unnamed,
1485 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001486 // Check to see if this is a register operand.
1487 if (R->isSubClassOf("RegisterOperand")) {
1488 assert(ResNo == 0 && "Regoperand ref only has one result!");
1489 if (NotRegisters)
1490 return EEVT::TypeSet(); // Unknown.
1491 Record *RegClass = R->getValueAsDef("RegClass");
1492 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1493 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1494 }
1495
Chris Lattnercabe0372010-03-15 06:00:16 +00001496 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001497 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001498 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001499 // An unnamed register class represents itself as an i32 immediate, for
1500 // example on a COPY_TO_REGCLASS instruction.
1501 if (Unnamed)
1502 return EEVT::TypeSet(MVT::i32, TP);
1503
1504 // In a named operand, the register class provides the possible set of
1505 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001506 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001507 return EEVT::TypeSet(); // Unknown.
1508 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1509 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001510 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001511
Chris Lattner6070ee22010-03-23 23:50:31 +00001512 if (R->isSubClassOf("PatFrag")) {
1513 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001514 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001515 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001516 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001517
Chris Lattner6070ee22010-03-23 23:50:31 +00001518 if (R->isSubClassOf("Register")) {
1519 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001520 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001521 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001522 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001523 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001524 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001525
1526 if (R->isSubClassOf("SubRegIndex")) {
1527 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00001528 return EEVT::TypeSet(MVT::i32, TP);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001529 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001530
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001531 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001532 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001533 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1534 //
1535 // (sext_inreg GPR:$src, i16)
1536 // ~~~
1537 if (Unnamed)
1538 return EEVT::TypeSet(MVT::Other, TP);
1539 // With a name, the ValueType simply provides the type of the named
1540 // variable.
1541 //
1542 // (sext_inreg i32:$src, i16)
1543 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001544 if (NotRegisters)
1545 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001546 return EEVT::TypeSet(getValueType(R), TP);
1547 }
1548
1549 if (R->isSubClassOf("CondCode")) {
1550 assert(ResNo == 0 && "This node only has one result!");
1551 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001552 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001553 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001554
Chris Lattner6070ee22010-03-23 23:50:31 +00001555 if (R->isSubClassOf("ComplexPattern")) {
1556 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001557 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001558 return EEVT::TypeSet(); // Unknown.
1559 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1560 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001561 }
1562 if (R->isSubClassOf("PointerLikeRegClass")) {
1563 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001564 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001565 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001566
Chris Lattner6070ee22010-03-23 23:50:31 +00001567 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1568 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001569 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001570 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001571 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001572
Tim Northoverc807a172014-05-20 11:52:46 +00001573 if (R->isSubClassOf("Operand"))
1574 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1575
Chris Lattner8cab0212008-01-05 22:25:12 +00001576 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001577 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001578}
1579
Chris Lattner89c65662008-01-06 05:36:50 +00001580
1581/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1582/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1583const CodeGenIntrinsic *TreePatternNode::
1584getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1585 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1586 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1587 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001588 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001589
Sean Silva88eb8dd2012-10-10 20:24:47 +00001590 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001591 return &CDP.getIntrinsicInfo(IID);
1592}
1593
Chris Lattner53c39ba2010-02-14 22:22:58 +00001594/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1595/// return the ComplexPattern information, otherwise return null.
1596const ComplexPattern *
1597TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001598 Record *Rec;
1599 if (isLeaf()) {
1600 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1601 if (!DI)
1602 return nullptr;
1603 Rec = DI->getDef();
1604 } else
1605 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001606
Tim Northoverc807a172014-05-20 11:52:46 +00001607 if (!Rec->isSubClassOf("ComplexPattern"))
1608 return nullptr;
1609 return &CGP.getComplexPattern(Rec);
1610}
1611
1612unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1613 // A ComplexPattern specifically declares how many results it fills in.
1614 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1615 return CP->getNumOperands();
1616
1617 // If MIOperandInfo is specified, that gives the count.
1618 if (isLeaf()) {
1619 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1620 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1621 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1622 if (MIOps->getNumArgs())
1623 return MIOps->getNumArgs();
1624 }
1625 }
1626
1627 // Otherwise there is just one result.
1628 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001629}
1630
1631/// NodeHasProperty - Return true if this node has the specified property.
1632bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001633 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001634 if (isLeaf()) {
1635 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1636 return CP->hasProperty(Property);
1637 return false;
1638 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001639
Chris Lattner53c39ba2010-02-14 22:22:58 +00001640 Record *Operator = getOperator();
1641 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001642
Chris Lattner53c39ba2010-02-14 22:22:58 +00001643 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1644}
1645
1646
1647
1648
1649/// TreeHasProperty - Return true if any node in this tree has the specified
1650/// property.
1651bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001652 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001653 if (NodeHasProperty(Property, CGP))
1654 return true;
1655 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1656 if (getChild(i)->TreeHasProperty(Property, CGP))
1657 return true;
1658 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001659}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001660
Evan Cheng49bad4c2008-06-16 20:29:38 +00001661/// isCommutativeIntrinsic - Return true if the node corresponds to a
1662/// commutative intrinsic.
1663bool
1664TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1665 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1666 return Int->isCommutative;
1667 return false;
1668}
1669
Matt Arsenaulteb492162014-11-02 23:46:51 +00001670static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1671 if (!N->isLeaf())
1672 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001673
Matt Arsenaulteb492162014-11-02 23:46:51 +00001674 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1675 if (DI && DI->getDef()->isSubClassOf(Class))
1676 return true;
1677
1678 return false;
1679}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001680
1681static void emitTooManyOperandsError(TreePattern &TP,
1682 StringRef InstName,
1683 unsigned Expected,
1684 unsigned Actual) {
1685 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1686 " operands but expected only " + Twine(Expected) + "!");
1687}
1688
1689static void emitTooFewOperandsError(TreePattern &TP,
1690 StringRef InstName,
1691 unsigned Actual) {
1692 TP.error("Instruction '" + InstName +
1693 "' expects more than the provided " + Twine(Actual) + " operands!");
1694}
1695
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001696/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001697/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001698/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001699bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001700 if (TP.hasError())
1701 return false;
1702
Chris Lattnerab3242f2008-01-06 01:10:31 +00001703 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001704 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001705 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001706 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001707 bool MadeChange = false;
1708 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1709 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001710 NotRegisters,
1711 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001712 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001713 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001714
Sean Silvafb509ed2012-10-10 20:24:43 +00001715 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001716 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001717
Chris Lattnerf1447252010-03-19 21:37:09 +00001718 // Int inits are always integers. :)
1719 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001720
Chris Lattnerf1447252010-03-19 21:37:09 +00001721 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001722 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001723
Chris Lattnerf1447252010-03-19 21:37:09 +00001724 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001725 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1726 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001727
Craig Topper95198f42013-09-25 06:37:18 +00001728 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001729 // Make sure that the value is representable for this type.
1730 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001731
Richard Smith228e6d42012-08-24 23:29:28 +00001732 // Check that the value doesn't use more bits than we have. It must either
1733 // be a sign- or zero-extended equivalent of the original.
1734 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1735 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001736 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001737
Richard Smith228e6d42012-08-24 23:29:28 +00001738 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001739 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001740 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001741 }
1742 return false;
1743 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001744
Chris Lattner8cab0212008-01-05 22:25:12 +00001745 // special handling for set, which isn't really an SDNode.
1746 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001747 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1748 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001749 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001750
Chris Lattnerf1447252010-03-19 21:37:09 +00001751 TreePatternNode *SetVal = getChild(NC-1);
1752 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1753
Elena Demikhovsky09954792015-03-01 08:23:41 +00001754 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001755 TreePatternNode *Child = getChild(i);
1756 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001757
Chris Lattner8cab0212008-01-05 22:25:12 +00001758 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001759 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1760 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001761 }
1762 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001763 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001764
Chris Lattner5c2182e2010-03-27 02:53:27 +00001765 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001766 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1767
Chris Lattner8cab0212008-01-05 22:25:12 +00001768 bool MadeChange = false;
1769 for (unsigned i = 0; i < getNumChildren(); ++i)
1770 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001771 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001772 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001773
Chris Lattneree820ac2010-02-23 05:51:07 +00001774 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001775 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001776
Chris Lattner8cab0212008-01-05 22:25:12 +00001777 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001778 unsigned NumRetVTs = Int->IS.RetVTs.size();
1779 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001780
Bill Wendling91821472008-11-13 09:08:33 +00001781 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001782 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001783
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001784 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001785 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001786 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001787 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001788 return false;
1789 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001790
1791 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001792 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001793
Chris Lattnerf1447252010-03-19 21:37:09 +00001794 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1795 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001796
Chris Lattnerf1447252010-03-19 21:37:09 +00001797 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1798 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1799 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001800 }
1801 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001802 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001803
Chris Lattneree820ac2010-02-23 05:51:07 +00001804 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001805 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001806
Chris Lattner135091b2010-03-28 08:48:47 +00001807 // Check that the number of operands is sane. Negative operands -> varargs.
1808 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001809 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001810 TP.error(getOperator()->getName() + " node requires exactly " +
1811 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001812 return false;
1813 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001814
Chris Lattner8cab0212008-01-05 22:25:12 +00001815 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1816 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1817 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001818 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001819 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001820
Chris Lattneree820ac2010-02-23 05:51:07 +00001821 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001822 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001823 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001824 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001825
Chris Lattnerd44966f2010-03-27 19:15:02 +00001826 bool MadeChange = false;
1827
1828 // Apply the result types to the node, these come from the things in the
1829 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00001830 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1831 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001832 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1833 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001834
Chris Lattnerd44966f2010-03-27 19:15:02 +00001835 // If the instruction has implicit defs, we apply the first one as a result.
1836 // FIXME: This sucks, it should apply all implicit defs.
1837 if (!InstInfo.ImplicitDefs.empty()) {
1838 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001839
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001840 // FIXME: Generalize to multiple possible types and multiple possible
1841 // ImplicitDefs.
1842 MVT::SimpleValueType VT =
1843 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001844
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001845 if (VT != MVT::Other)
1846 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001847 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001848
Chris Lattnercabe0372010-03-15 06:00:16 +00001849 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1850 // be the same.
1851 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001852 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1853 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1854 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00001855 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1856 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1857 // variadic.
1858
1859 unsigned NChild = getNumChildren();
1860 if (NChild < 3) {
1861 TP.error("REG_SEQUENCE requires at least 3 operands!");
1862 return false;
1863 }
1864
1865 if (NChild % 2 == 0) {
1866 TP.error("REG_SEQUENCE requires an odd number of operands!");
1867 return false;
1868 }
1869
1870 if (!isOperandClass(getChild(0), "RegisterClass")) {
1871 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1872 return false;
1873 }
1874
1875 for (unsigned I = 1; I < NChild; I += 2) {
1876 TreePatternNode *SubIdxChild = getChild(I + 1);
1877 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1878 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1879 itostr(I + 1) + "!");
1880 return false;
1881 }
1882 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001883 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001884
1885 unsigned ChildNo = 0;
1886 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1887 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001888
Chris Lattner8cab0212008-01-05 22:25:12 +00001889 // If the instruction expects a predicate or optional def operand, we
1890 // codegen this by setting the operand to it's default value if it has a
1891 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001892 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001893 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1894 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001895
Chris Lattner8cab0212008-01-05 22:25:12 +00001896 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001897 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001898 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001899 return false;
1900 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001901
Chris Lattner8cab0212008-01-05 22:25:12 +00001902 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001903 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001904
1905 // If the operand has sub-operands, they may be provided by distinct
1906 // child patterns, so attempt to match each sub-operand separately.
1907 if (OperandNode->isSubClassOf("Operand")) {
1908 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1909 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1910 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00001911 // a single ComplexPattern-related Operand.
1912
1913 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00001914 // Match first sub-operand against the child we already have.
1915 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1916 MadeChange |=
1917 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1918
1919 // And the remaining sub-operands against subsequent children.
1920 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1921 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001922 emitTooFewOperandsError(TP, getOperator()->getName(),
1923 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00001924 return false;
1925 }
1926 Child = getChild(ChildNo++);
1927
1928 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1929 MadeChange |=
1930 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1931 }
1932 continue;
1933 }
1934 }
1935 }
1936
1937 // If we didn't match by pieces above, attempt to match the whole
1938 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001939 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001940 }
Christopher Lamba7312392008-03-11 09:33:47 +00001941
Matt Arsenaulteb492162014-11-02 23:46:51 +00001942 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001943 emitTooManyOperandsError(TP, getOperator()->getName(),
1944 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001945 return false;
1946 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001947
Ulrich Weigande618abd2013-03-19 19:51:09 +00001948 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1949 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001950 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001951 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001952
Tim Northoverc807a172014-05-20 11:52:46 +00001953 if (getOperator()->isSubClassOf("ComplexPattern")) {
1954 bool MadeChange = false;
1955
1956 for (unsigned i = 0; i < getNumChildren(); ++i)
1957 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1958
1959 return MadeChange;
1960 }
1961
Chris Lattneree820ac2010-02-23 05:51:07 +00001962 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001963
Chris Lattneree820ac2010-02-23 05:51:07 +00001964 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001965 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001966 TP.error("Node transform '" + getOperator()->getName() +
1967 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001968 return false;
1969 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001970
Chris Lattnercabe0372010-03-15 06:00:16 +00001971 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1972
Jim Grosbach65586fe2010-12-21 16:16:00 +00001973
Chris Lattneree820ac2010-02-23 05:51:07 +00001974 // If either the output or input of the xform does not have exact
1975 // type info. We assume they must be the same. Otherwise, it is perfectly
1976 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001977#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001978 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001979 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1980 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001981 return MadeChange;
1982 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001983#endif
1984 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001985}
1986
1987/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1988/// RHS of a commutative operation, not the on LHS.
1989static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1990 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1991 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001992 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001993 return true;
1994 return false;
1995}
1996
1997
1998/// canPatternMatch - If it is impossible for this pattern to match on this
1999/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002000/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002001/// that can never possibly work), and to prevent the pattern permuter from
2002/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002003bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002004 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002005 if (isLeaf()) return true;
2006
2007 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2008 if (!getChild(i)->canPatternMatch(Reason, CDP))
2009 return false;
2010
2011 // If this is an intrinsic, handle cases that would make it not match. For
2012 // example, if an operand is required to be an immediate.
2013 if (getOperator()->isSubClassOf("Intrinsic")) {
2014 // TODO:
2015 return true;
2016 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002017
Tim Northoverc807a172014-05-20 11:52:46 +00002018 if (getOperator()->isSubClassOf("ComplexPattern"))
2019 return true;
2020
Chris Lattner8cab0212008-01-05 22:25:12 +00002021 // If this node is a commutative operator, check that the LHS isn't an
2022 // immediate.
2023 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002024 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2025 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002026 // Scan all of the operands of the node and make sure that only the last one
2027 // is a constant node, unless the RHS also is.
2028 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng49bad4c2008-06-16 20:29:38 +00002029 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2030 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002031 if (OnlyOnRHSOfCommutative(getChild(i))) {
2032 Reason="Immediate value must be on the RHS of commutative operators!";
2033 return false;
2034 }
2035 }
2036 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002037
Chris Lattner8cab0212008-01-05 22:25:12 +00002038 return true;
2039}
2040
2041//===----------------------------------------------------------------------===//
2042// TreePattern implementation
2043//
2044
David Greeneaf8ee2c2011-07-29 22:43:06 +00002045TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002046 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2047 isInputPattern(isInput), HasError(false) {
Craig Topperef0578a2015-06-02 04:15:51 +00002048 for (Init *I : RawPat->getValues())
2049 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002050}
2051
David Greeneaf8ee2c2011-07-29 22:43:06 +00002052TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002053 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2054 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002055 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002056}
2057
David Blaikiecf195302014-11-17 22:55:41 +00002058TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002059 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
2060 isInputPattern(isInput), HasError(false) {
David Blaikiecf195302014-11-17 22:55:41 +00002061 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002062}
2063
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002064void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002065 if (HasError)
2066 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002067 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002068 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2069 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002070}
2071
Chris Lattnercabe0372010-03-15 06:00:16 +00002072void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00002073 for (TreePatternNode *Tree : Trees)
2074 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00002075}
2076
2077void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2078 if (!N->getName().empty())
2079 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002080
Chris Lattnercabe0372010-03-15 06:00:16 +00002081 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2082 ComputeNamedNodes(N->getChild(i));
2083}
2084
David Blaikiecf195302014-11-17 22:55:41 +00002085
2086TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002087 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002088 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002089
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002090 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002091 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002092 /// (foo GPR, imm) -> (foo GPR, (imm))
2093 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002094 return ParseTreePattern(
2095 DagInit::get(DI, "",
David Greeneaf8ee2c2011-07-29 22:43:06 +00002096 std::vector<std::pair<Init*, std::string> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002097 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002098
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002099 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002100 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002101 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002102 if (OpName.empty())
2103 error("'node' argument requires a name to match with operand list");
2104 Args.push_back(OpName);
2105 }
2106
2107 Res->setName(OpName);
2108 return Res;
2109 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002110
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002111 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002112 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002113 if (OpName.empty())
2114 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002115 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002116 Args.push_back(OpName);
2117 Res->setName(OpName);
2118 return Res;
2119 }
2120
Sean Silvafb509ed2012-10-10 20:24:43 +00002121 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002122 if (!OpName.empty())
2123 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002124 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002125 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002126
Sean Silvafb509ed2012-10-10 20:24:43 +00002127 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002128 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002129 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002130 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002131 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002132 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002133 }
2134
Sean Silvafb509ed2012-10-10 20:24:43 +00002135 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002136 if (!Dag) {
2137 TheInit->dump();
2138 error("Pattern has unexpected init kind!");
2139 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002140 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002141 if (!OpDef) error("Pattern has unexpected operator type!");
2142 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002143
Chris Lattner8cab0212008-01-05 22:25:12 +00002144 if (Operator->isSubClassOf("ValueType")) {
2145 // If the operator is a ValueType, then this must be "type cast" of a leaf
2146 // node.
2147 if (Dag->getNumArgs() != 1)
2148 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002149
David Blaikiecf195302014-11-17 22:55:41 +00002150 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002151
Chris Lattner8cab0212008-01-05 22:25:12 +00002152 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002153 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2154 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002155
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002156 if (!OpName.empty())
2157 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002158 return New;
2159 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002160
Chris Lattner8cab0212008-01-05 22:25:12 +00002161 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002162 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002163 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002164 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002165 !Operator->isSubClassOf("SDNodeXForm") &&
2166 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002167 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002168 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002169 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002170 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002171
Chris Lattner8cab0212008-01-05 22:25:12 +00002172 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002173 if (isInputPattern) {
2174 if (Operator->isSubClassOf("Instruction") ||
2175 Operator->isSubClassOf("SDNodeXForm"))
2176 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2177 } else {
2178 if (Operator->isSubClassOf("Intrinsic"))
2179 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002180
Chris Lattner2e9eae12010-03-28 06:57:56 +00002181 if (Operator->isSubClassOf("SDNode") &&
2182 Operator->getName() != "imm" &&
2183 Operator->getName() != "fpimm" &&
2184 Operator->getName() != "tglobaltlsaddr" &&
2185 Operator->getName() != "tconstpool" &&
2186 Operator->getName() != "tjumptable" &&
2187 Operator->getName() != "tframeindex" &&
2188 Operator->getName() != "texternalsym" &&
2189 Operator->getName() != "tblockaddress" &&
2190 Operator->getName() != "tglobaladdr" &&
2191 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002192 Operator->getName() != "vt" &&
2193 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002194 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2195 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002196
Chris Lattner8cab0212008-01-05 22:25:12 +00002197 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002198
2199 // Parse all the operands.
2200 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002201 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002202
Chris Lattner8cab0212008-01-05 22:25:12 +00002203 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002204 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002205 // convert the intrinsic name to a number.
2206 if (Operator->isSubClassOf("Intrinsic")) {
2207 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2208 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2209
2210 // If this intrinsic returns void, it must have side-effects and thus a
2211 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002212 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002213 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002214 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002215 // Has side-effects, requires chain.
2216 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002217 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002218 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002219
David Greenee32ebf22011-07-29 19:07:07 +00002220 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002221 Children.insert(Children.begin(), IIDNode);
2222 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002223
Tim Northoverc807a172014-05-20 11:52:46 +00002224 if (Operator->isSubClassOf("ComplexPattern")) {
2225 for (unsigned i = 0; i < Children.size(); ++i) {
2226 TreePatternNode *Child = Children[i];
2227
2228 if (Child->getName().empty())
2229 error("All arguments to a ComplexPattern must be named");
2230
2231 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2232 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2233 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2234 auto OperandId = std::make_pair(Operator, i);
2235 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2236 if (PrevOp != ComplexPatternOperands.end()) {
2237 if (PrevOp->getValue() != OperandId)
2238 error("All ComplexPattern operands must appear consistently: "
2239 "in the same order in just one ComplexPattern instance.");
2240 } else
2241 ComplexPatternOperands[Child->getName()] = OperandId;
2242 }
2243 }
2244
Chris Lattnerf1447252010-03-19 21:37:09 +00002245 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002246 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002247 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002248
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002249 if (!Dag->getName().empty()) {
2250 assert(Result->getName().empty());
2251 Result->setName(Dag->getName());
2252 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002253 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002254}
2255
Chris Lattnera787c9e2010-03-28 08:38:32 +00002256/// SimplifyTree - See if we can simplify this tree to eliminate something that
2257/// will never match in favor of something obvious that will. This is here
2258/// strictly as a convenience to target authors because it allows them to write
2259/// more type generic things and have useless type casts fold away.
2260///
2261/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002262static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002263 if (N->isLeaf())
2264 return false;
2265
2266 // If we have a bitconvert with a resolved type and if the source and
2267 // destination types are the same, then the bitconvert is useless, remove it.
2268 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002269 N->getExtType(0).isConcrete() &&
2270 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2271 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002272 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002273 SimplifyTree(N);
2274 return true;
2275 }
2276
2277 // Walk all children.
2278 bool MadeChange = false;
2279 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002280 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002281 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002282 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002283 }
2284 return MadeChange;
2285}
2286
2287
2288
Chris Lattner8cab0212008-01-05 22:25:12 +00002289/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002290/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002291/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002292bool TreePattern::
2293InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2294 if (NamedNodes.empty())
2295 ComputeNamedNodes();
2296
Chris Lattner8cab0212008-01-05 22:25:12 +00002297 bool MadeChange = true;
2298 while (MadeChange) {
2299 MadeChange = false;
Craig Topper306cb122015-11-22 20:46:24 +00002300 for (TreePatternNode *Tree : Trees) {
2301 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2302 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002303 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002304
2305 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002306 for (auto &Entry : NamedNodes) {
2307 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002308
Chris Lattnercabe0372010-03-15 06:00:16 +00002309 // If we have input named node types, propagate their types to the named
2310 // values here.
2311 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002312 if (!InNamedTypes->count(Entry.getKey())) {
2313 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002314 "' in output pattern but not input pattern");
2315 return true;
2316 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002317
2318 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002319 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002320
2321 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002322 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002323 // If this node is a register class, and it is the root of the pattern
2324 // then we're mapping something onto an input register. We allow
2325 // changing the type of the input register in this case. This allows
2326 // us to match things like:
2327 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002328 if (Node == Trees[0] && Node->isLeaf()) {
2329 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002330 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2331 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002332 continue;
2333 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002334
Craig Topper306cb122015-11-22 20:46:24 +00002335 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002336 InNodes[0]->getNumTypes() == 1 &&
2337 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002338 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2339 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002340 }
2341 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002342
Chris Lattnercabe0372010-03-15 06:00:16 +00002343 // If there are multiple nodes with the same name, they must all have the
2344 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002345 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002346 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002347 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002348 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002349 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002350
Chris Lattnerf1447252010-03-19 21:37:09 +00002351 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2352 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002353 }
2354 }
2355 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002356 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002357
Chris Lattner8cab0212008-01-05 22:25:12 +00002358 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002359 for (const TreePatternNode *Tree : Trees)
2360 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
Chris Lattner8cab0212008-01-05 22:25:12 +00002361 return !HasUnresolvedTypes;
2362}
2363
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002364void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002365 OS << getRecord()->getName();
2366 if (!Args.empty()) {
2367 OS << "(" << Args[0];
2368 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2369 OS << ", " << Args[i];
2370 OS << ")";
2371 }
2372 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002373
Chris Lattner8cab0212008-01-05 22:25:12 +00002374 if (Trees.size() > 1)
2375 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002376 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002377 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002378 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002379 OS << "\n";
2380 }
2381
2382 if (Trees.size() > 1)
2383 OS << "]\n";
2384}
2385
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002386void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002387
2388//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002389// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002390//
2391
Jim Grosbach65586fe2010-12-21 16:16:00 +00002392CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002393 Records(R), Target(R) {
2394
Justin Bogner92a8c612016-07-15 16:31:37 +00002395 Intrinsics = CodeGenIntrinsicTable(Records, false);
2396 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002397 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002398 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002399 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002400 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002401 ParseDefaultOperands();
2402 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002403 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002404 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002405
Chris Lattner8cab0212008-01-05 22:25:12 +00002406 // Generate variants. For example, commutative patterns can match
2407 // multiple ways. Add them to PatternsToMatch as well.
2408 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002409
2410 // Infer instruction flags. For example, we can detect loads,
2411 // stores, and side effects in many cases by examining an
2412 // instruction's pattern.
2413 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002414
2415 // Verify that instruction flags match the patterns.
2416 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002417}
2418
Chris Lattnerab3242f2008-01-06 01:10:31 +00002419Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002420 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002421 if (!N || !N->isSubClassOf("SDNode"))
2422 PrintFatalError("Error getting SDNode '" + Name + "'!");
2423
Chris Lattner8cab0212008-01-05 22:25:12 +00002424 return N;
2425}
2426
2427// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002428void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002429 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2430 while (!Nodes.empty()) {
2431 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2432 Nodes.pop_back();
2433 }
2434
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002435 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002436 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2437 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2438 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2439}
2440
2441/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2442/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002443void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002444 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2445 while (!Xforms.empty()) {
2446 Record *XFormNode = Xforms.back();
2447 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00002448 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002449 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002450
2451 Xforms.pop_back();
2452 }
2453}
2454
Chris Lattnerab3242f2008-01-06 01:10:31 +00002455void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002456 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2457 while (!AMs.empty()) {
2458 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2459 AMs.pop_back();
2460 }
2461}
2462
2463
2464/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2465/// file, building up the PatternFragments map. After we've collected them all,
2466/// inline fragments together as necessary, so that there are no references left
2467/// inside a pattern fragment to a pattern fragment.
2468///
Hal Finkel2756dc12014-02-28 00:26:56 +00002469void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002470 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002471
Chris Lattnere7170df2008-01-05 22:43:57 +00002472 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002473 for (Record *Frag : Fragments) {
2474 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002475 continue;
2476
Craig Topper306cb122015-11-22 20:46:24 +00002477 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002478 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002479 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2480 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002481 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002482
Chris Lattnere7170df2008-01-05 22:43:57 +00002483 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002484 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002485 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002486
Chris Lattnere7170df2008-01-05 22:43:57 +00002487 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002488 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002489
Chris Lattner8cab0212008-01-05 22:25:12 +00002490 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002491 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002492 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002493 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002494 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002495 if (!OpsOp ||
2496 (OpsOp->getDef()->getName() != "ops" &&
2497 OpsOp->getDef()->getName() != "outs" &&
2498 OpsOp->getDef()->getName() != "ins"))
2499 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002500
2501 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002502 Args.clear();
2503 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002504 if (!isa<DefInit>(OpsList->getArg(j)) ||
2505 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002506 P->error("Operands list should all be 'node' values.");
2507 if (OpsList->getArgName(j).empty())
2508 P->error("Operands list should have names for each operand!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002509 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner8cab0212008-01-05 22:25:12 +00002510 P->error("'" + OpsList->getArgName(j) +
2511 "' does not occur in pattern or was multiply specified!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002512 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner8cab0212008-01-05 22:25:12 +00002513 Args.push_back(OpsList->getArgName(j));
2514 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002515
Chris Lattnere7170df2008-01-05 22:43:57 +00002516 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002517 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002518 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002519
Chris Lattnere7170df2008-01-05 22:43:57 +00002520 // If there is a code init for this fragment, keep track of the fact that
2521 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002522 TreePredicateFn PredFn(P);
2523 if (!PredFn.isAlwaysTrue())
2524 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002525
Chris Lattner8cab0212008-01-05 22:25:12 +00002526 // If there is a node transformation corresponding to this, keep track of
2527 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002528 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002529 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2530 P->getOnlyTree()->setTransformFn(Transform);
2531 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002532
Chris Lattner8cab0212008-01-05 22:25:12 +00002533 // Now that we've parsed all of the tree fragments, do a closure on them so
2534 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002535 for (Record *Frag : Fragments) {
2536 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002537 continue;
2538
Craig Topper306cb122015-11-22 20:46:24 +00002539 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002540 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002541
Chris Lattner8cab0212008-01-05 22:25:12 +00002542 // Infer as many types as possible. Don't worry about it if we don't infer
2543 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002544 ThePat.InferAllTypes();
2545 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002546
Chris Lattner8cab0212008-01-05 22:25:12 +00002547 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002548 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002549 }
2550}
2551
Chris Lattnerab3242f2008-01-06 01:10:31 +00002552void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002553 std::vector<Record*> DefaultOps;
2554 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002555
2556 // Find some SDNode.
2557 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002558 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002559
Tom Stellardb7246a72012-09-06 14:15:52 +00002560 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2561 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002562
Tom Stellardb7246a72012-09-06 14:15:52 +00002563 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2564 // SomeSDnode so that we can parse this.
2565 std::vector<std::pair<Init*, std::string> > Ops;
2566 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2567 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2568 DefaultInfo->getArgName(op)));
2569 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002570
Tom Stellardb7246a72012-09-06 14:15:52 +00002571 // Create a TreePattern to parse this.
2572 TreePattern P(DefaultOps[i], DI, false, *this);
2573 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002574
Tom Stellardb7246a72012-09-06 14:15:52 +00002575 // Copy the operands over into a DAGDefaultOperand.
2576 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002577
Tom Stellardb7246a72012-09-06 14:15:52 +00002578 TreePatternNode *T = P.getTree(0);
2579 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2580 TreePatternNode *TPN = T->getChild(op);
2581 while (TPN->ApplyTypeConstraints(P, false))
2582 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002583
Tom Stellardb7246a72012-09-06 14:15:52 +00002584 if (TPN->ContainsUnresolvedType()) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002585 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2586 DefaultOps[i]->getName() +
2587 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002588 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002589 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002590 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002591
2592 // Insert it into the DefaultOperands map so we can find it later.
2593 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002594 }
2595}
2596
2597/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2598/// instruction input. Return true if this is a real use.
2599static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002600 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002601 // No name -> not interesting.
2602 if (Pat->getName().empty()) {
2603 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002604 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002605 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2606 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002607 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002608 }
2609 return false;
2610 }
2611
2612 Record *Rec;
2613 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002614 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002615 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2616 Rec = DI->getDef();
2617 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002618 Rec = Pat->getOperator();
2619 }
2620
2621 // SRCVALUE nodes are ignored.
2622 if (Rec->getName() == "srcvalue")
2623 return false;
2624
2625 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2626 if (!Slot) {
2627 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002628 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002629 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002630 Record *SlotRec;
2631 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002632 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002633 } else {
2634 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2635 SlotRec = Slot->getOperator();
2636 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002637
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002638 // Ensure that the inputs agree if we've already seen this input.
2639 if (Rec != SlotRec)
2640 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002641 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002642 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002643 return true;
2644}
2645
2646/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2647/// part of "I", the instruction), computing the set of inputs and outputs of
2648/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002649void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002650FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2651 std::map<std::string, TreePatternNode*> &InstInputs,
2652 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002653 std::vector<Record*> &InstImpResults) {
2654 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002655 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002656 if (!isUse && Pat->getTransformFn())
2657 I->error("Cannot specify a transform function for a non-input value!");
2658 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002659 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002660
Chris Lattnerf2d70992010-02-17 06:53:36 +00002661 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002662 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2663 TreePatternNode *Dest = Pat->getChild(i);
2664 if (!Dest->isLeaf())
2665 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002666
Sean Silvafb509ed2012-10-10 20:24:43 +00002667 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002668 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2669 I->error("implicitly defined value should be a register!");
2670 InstImpResults.push_back(Val->getDef());
2671 }
2672 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002673 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002674
Chris Lattnerf2d70992010-02-17 06:53:36 +00002675 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002676 // If this is not a set, verify that the children nodes are not void typed,
2677 // and recurse.
2678 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002679 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002680 I->error("Cannot have void nodes inside of patterns!");
2681 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002682 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002683 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002684
Chris Lattner8cab0212008-01-05 22:25:12 +00002685 // If this is a non-leaf node with no children, treat it basically as if
2686 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002687 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002688
Chris Lattner8cab0212008-01-05 22:25:12 +00002689 if (!isUse && Pat->getTransformFn())
2690 I->error("Cannot specify a transform function for a non-input value!");
2691 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002692 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002693
Chris Lattner8cab0212008-01-05 22:25:12 +00002694 // Otherwise, this is a set, validate and collect instruction results.
2695 if (Pat->getNumChildren() == 0)
2696 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002697
Chris Lattner8cab0212008-01-05 22:25:12 +00002698 if (Pat->getTransformFn())
2699 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002700
Chris Lattner8cab0212008-01-05 22:25:12 +00002701 // Check the set destinations.
2702 unsigned NumDests = Pat->getNumChildren()-1;
2703 for (unsigned i = 0; i != NumDests; ++i) {
2704 TreePatternNode *Dest = Pat->getChild(i);
2705 if (!Dest->isLeaf())
2706 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002707
Sean Silvafb509ed2012-10-10 20:24:43 +00002708 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002709 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002710 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002711 continue;
2712 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002713
2714 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002715 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002716 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002717 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002718 if (Dest->getName().empty())
2719 I->error("set destination must have a name!");
2720 if (InstResults.count(Dest->getName()))
2721 I->error("cannot set '" + Dest->getName() +"' multiple times");
2722 InstResults[Dest->getName()] = Dest;
2723 } else if (Val->getDef()->isSubClassOf("Register")) {
2724 InstImpResults.push_back(Val->getDef());
2725 } else {
2726 I->error("set destination should be a register!");
2727 }
2728 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002729
Chris Lattner8cab0212008-01-05 22:25:12 +00002730 // Verify and collect info from the computation.
2731 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002732 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002733}
2734
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002735//===----------------------------------------------------------------------===//
2736// Instruction Analysis
2737//===----------------------------------------------------------------------===//
2738
2739class InstAnalyzer {
2740 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002741public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002742 bool hasSideEffects;
2743 bool mayStore;
2744 bool mayLoad;
2745 bool isBitcast;
2746 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002747
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002748 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2749 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2750 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002751
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002752 void Analyze(const TreePattern *Pat) {
2753 // Assume only the first tree is the pattern. The others are clobber nodes.
2754 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002755 }
2756
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002757 void Analyze(const PatternToMatch *Pat) {
2758 AnalyzeNode(Pat->getSrcPattern());
2759 }
2760
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002761private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002762 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002763 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002764 return false;
2765
2766 if (N->getNumChildren() != 2)
2767 return false;
2768
2769 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002770 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002771 return false;
2772
2773 const TreePatternNode *N1 = N->getChild(1);
2774 if (N1->isLeaf())
2775 return false;
2776 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2777 return false;
2778
2779 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2780 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2781 return false;
2782 return OpInfo.getEnumName() == "ISD::BITCAST";
2783 }
2784
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002785public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002786 void AnalyzeNode(const TreePatternNode *N) {
2787 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002788 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002789 Record *LeafRec = DI->getDef();
2790 // Handle ComplexPattern leaves.
2791 if (LeafRec->isSubClassOf("ComplexPattern")) {
2792 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2793 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2794 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002795 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002796 }
2797 }
2798 return;
2799 }
2800
2801 // Analyze children.
2802 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2803 AnalyzeNode(N->getChild(i));
2804
2805 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002806 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002807 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002808 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002809 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002810
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002811 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002812 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2813 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2814 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2815 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002816
2817 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2818 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002819 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002820 mayLoad = true;// These may load memory.
2821
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002822 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002823 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2824
Dan Gohmanddb2d652010-08-05 23:36:21 +00002825 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002826 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002827 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002828 }
2829 }
2830
2831};
2832
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002833static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002834 const InstAnalyzer &PatInfo,
2835 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002836 bool Error = false;
2837
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002838 // Remember where InstInfo got its flags.
2839 if (InstInfo.hasUndefFlags())
2840 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002841
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002842 // Check explicitly set flags for consistency.
2843 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2844 !InstInfo.hasSideEffects_Unset) {
2845 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2846 // the pattern has no side effects. That could be useful for div/rem
2847 // instructions that may trap.
2848 if (!InstInfo.hasSideEffects) {
2849 Error = true;
2850 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2851 Twine(InstInfo.hasSideEffects));
2852 }
2853 }
2854
2855 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2856 Error = true;
2857 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2858 Twine(InstInfo.mayStore));
2859 }
2860
2861 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2862 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00002863 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002864 if (!InstInfo.mayLoad) {
2865 Error = true;
2866 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2867 Twine(InstInfo.mayLoad));
2868 }
2869 }
2870
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002871 // Transfer inferred flags.
2872 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2873 InstInfo.mayStore |= PatInfo.mayStore;
2874 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002875
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002876 // These flags are silently added without any verification.
2877 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002878
2879 // Don't infer isVariadic. This flag means something different on SDNodes and
2880 // instructions. For example, a CALL SDNode is variadic because it has the
2881 // call arguments as operands, but a CALL instruction is not variadic - it
2882 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002883
2884 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002885}
2886
Jim Grosbach514410b2012-07-17 00:47:06 +00002887/// hasNullFragReference - Return true if the DAG has any reference to the
2888/// null_frag operator.
2889static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002890 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002891 if (!OpDef) return false;
2892 Record *Operator = OpDef->getDef();
2893
2894 // If this is the null fragment, return true.
2895 if (Operator->getName() == "null_frag") return true;
2896 // If any of the arguments reference the null fragment, return true.
2897 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002898 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002899 if (Arg && hasNullFragReference(Arg))
2900 return true;
2901 }
2902
2903 return false;
2904}
2905
2906/// hasNullFragReference - Return true if any DAG in the list references
2907/// the null_frag operator.
2908static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00002909 for (Init *I : LI->getValues()) {
2910 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00002911 assert(DI && "non-dag in an instruction Pattern list?!");
2912 if (hasNullFragReference(DI))
2913 return true;
2914 }
2915 return false;
2916}
2917
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002918/// Get all the instructions in a tree.
2919static void
2920getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2921 if (Tree->isLeaf())
2922 return;
2923 if (Tree->getOperator()->isSubClassOf("Instruction"))
2924 Instrs.push_back(Tree->getOperator());
2925 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2926 getInstructionsInTree(Tree->getChild(i), Instrs);
2927}
2928
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002929/// Check the class of a pattern leaf node against the instruction operand it
2930/// represents.
2931static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2932 Record *Leaf) {
2933 if (OI.Rec == Leaf)
2934 return true;
2935
2936 // Allow direct value types to be used in instruction set patterns.
2937 // The type will be checked later.
2938 if (Leaf->isSubClassOf("ValueType"))
2939 return true;
2940
2941 // Patterns can also be ComplexPattern instances.
2942 if (Leaf->isSubClassOf("ComplexPattern"))
2943 return true;
2944
2945 return false;
2946}
2947
Ahmed Bougacha14107512013-10-28 18:07:21 +00002948const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2949 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002950
Craig Topper0d1fb902015-03-10 03:25:04 +00002951 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002952
Craig Topper0d1fb902015-03-10 03:25:04 +00002953 // Parse the instruction.
2954 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2955 // Inline pattern fragments into it.
2956 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002957
Craig Topper0d1fb902015-03-10 03:25:04 +00002958 // Infer as many types as possible. If we cannot infer all of them, we can
2959 // never do anything with this instruction pattern: report it to the user.
2960 if (!I->InferAllTypes())
2961 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002962
Craig Topper0d1fb902015-03-10 03:25:04 +00002963 // InstInputs - Keep track of all of the inputs of the instruction, along
2964 // with the record they are declared as.
2965 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002966
Craig Topper0d1fb902015-03-10 03:25:04 +00002967 // InstResults - Keep track of all the virtual registers that are 'set'
2968 // in the instruction, including what reg class they are.
2969 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00002970
Craig Topper0d1fb902015-03-10 03:25:04 +00002971 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002972
Craig Topper0d1fb902015-03-10 03:25:04 +00002973 // Verify that the top-level forms in the instruction are of void type, and
2974 // fill in the InstResults map.
2975 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2976 TreePatternNode *Pat = I->getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00002977 if (Pat->getNumTypes() != 0) {
2978 std::string Types;
2979 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
2980 if (k > 0)
2981 Types += ", ";
2982 Types += Pat->getExtType(k).getName();
2983 }
Craig Topper0d1fb902015-03-10 03:25:04 +00002984 I->error("Top-level forms in instruction pattern should have"
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00002985 " void types, has types " + Types);
2986 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002987
Craig Topper0d1fb902015-03-10 03:25:04 +00002988 // Find inputs and outputs, and verify the structure of the uses/defs.
2989 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2990 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00002991 }
2992
Craig Topper0d1fb902015-03-10 03:25:04 +00002993 // Now that we have inputs and outputs of the pattern, inspect the operands
2994 // list for the instruction. This determines the order that operands are
2995 // added to the machine instruction the node corresponds to.
2996 unsigned NumResults = InstResults.size();
2997
2998 // Parse the operands list from the (ops) list, validating it.
2999 assert(I->getArgList().empty() && "Args list should still be empty here!");
3000
3001 // Check that all of the results occur first in the list.
3002 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00003003 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003004 for (unsigned i = 0; i != NumResults; ++i) {
3005 if (i == CGI.Operands.size())
3006 I->error("'" + InstResults.begin()->first +
3007 "' set but does not appear in operand list!");
3008 const std::string &OpName = CGI.Operands[i].Name;
3009
3010 // Check that it exists in InstResults.
3011 TreePatternNode *RNode = InstResults[OpName];
3012 if (!RNode)
3013 I->error("Operand $" + OpName + " does not exist in operand list!");
3014
Craig Topper3a8eb892015-03-20 05:09:06 +00003015 ResNodes.push_back(RNode);
3016
Craig Topper0d1fb902015-03-10 03:25:04 +00003017 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3018 if (!R)
3019 I->error("Operand $" + OpName + " should be a set destination: all "
3020 "outputs must occur before inputs in operand list!");
3021
3022 if (!checkOperandClass(CGI.Operands[i], R))
3023 I->error("Operand $" + OpName + " class mismatch!");
3024
3025 // Remember the return type.
3026 Results.push_back(CGI.Operands[i].Rec);
3027
3028 // Okay, this one checks out.
3029 InstResults.erase(OpName);
3030 }
3031
3032 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3033 // the copy while we're checking the inputs.
3034 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3035
3036 std::vector<TreePatternNode*> ResultNodeOperands;
3037 std::vector<Record*> Operands;
3038 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3039 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3040 const std::string &OpName = Op.Name;
3041 if (OpName.empty())
3042 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3043
3044 if (!InstInputsCheck.count(OpName)) {
3045 // If this is an operand with a DefaultOps set filled in, we can ignore
3046 // this. When we codegen it, we will do so as always executed.
3047 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3048 // Does it have a non-empty DefaultOps field? If so, ignore this
3049 // operand.
3050 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3051 continue;
3052 }
3053 I->error("Operand $" + OpName +
3054 " does not appear in the instruction pattern");
3055 }
3056 TreePatternNode *InVal = InstInputsCheck[OpName];
3057 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3058
3059 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3060 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3061 if (!checkOperandClass(Op, InRec))
3062 I->error("Operand $" + OpName + "'s register class disagrees"
3063 " between the operand and pattern");
3064 }
3065 Operands.push_back(Op.Rec);
3066
3067 // Construct the result for the dest-pattern operand list.
3068 TreePatternNode *OpNode = InVal->clone();
3069
3070 // No predicate is useful on the result.
3071 OpNode->clearPredicateFns();
3072
3073 // Promote the xform function to be an explicit node if set.
3074 if (Record *Xform = OpNode->getTransformFn()) {
3075 OpNode->setTransformFn(nullptr);
3076 std::vector<TreePatternNode*> Children;
3077 Children.push_back(OpNode);
3078 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3079 }
3080
3081 ResultNodeOperands.push_back(OpNode);
3082 }
3083
3084 if (!InstInputsCheck.empty())
3085 I->error("Input operand $" + InstInputsCheck.begin()->first +
3086 " occurs in pattern but not in operands list!");
3087
3088 TreePatternNode *ResultPattern =
3089 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3090 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003091 // Copy fully inferred output node types to instruction result pattern.
3092 for (unsigned i = 0; i != NumResults; ++i) {
3093 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3094 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3095 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003096
3097 // Create and insert the instruction.
3098 // FIXME: InstImpResults should not be part of DAGInstruction.
3099 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3100 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3101
3102 // Use a temporary tree pattern to infer all types and make sure that the
3103 // constructed result is correct. This depends on the instruction already
3104 // being inserted into the DAGInsts map.
3105 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3106 Temp.InferAllTypes(&I->getNamedNodesMap());
3107
3108 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3109 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3110
3111 return TheInsertedInst;
3112}
3113
Ahmed Bougacha14107512013-10-28 18:07:21 +00003114/// ParseInstructions - Parse all of the instructions, inlining and resolving
3115/// any fragments involved. This populates the Instructions list with fully
3116/// resolved instructions.
3117void CodeGenDAGPatterns::ParseInstructions() {
3118 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3119
Craig Topper306cb122015-11-22 20:46:24 +00003120 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003121 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003122
Craig Topper306cb122015-11-22 20:46:24 +00003123 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3124 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003125
3126 // If there is no pattern, only collect minimal information about the
3127 // instruction for its operand list. We have to assume that there is one
3128 // result, as we have no detailed info. A pattern which references the
3129 // null_frag operator is as-if no pattern were specified. Normally this
3130 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3131 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003132 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003133 std::vector<Record*> Results;
3134 std::vector<Record*> Operands;
3135
Craig Topper306cb122015-11-22 20:46:24 +00003136 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003137
3138 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003139 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3140 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003141
Craig Topper3a8eb892015-03-20 05:09:06 +00003142 // The rest are inputs.
3143 for (unsigned j = InstInfo.Operands.NumDefs,
3144 e = InstInfo.Operands.size(); j < e; ++j)
3145 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003146 }
3147
3148 // Create and insert the instruction.
3149 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003150 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003151 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003152 continue; // no pattern.
3153 }
3154
Craig Topper306cb122015-11-22 20:46:24 +00003155 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003156 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3157
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003158 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003159 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003160 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003161
Chris Lattner8cab0212008-01-05 22:25:12 +00003162 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003163 for (auto &Entry : Instructions) {
3164 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003165 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003166 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003167
3168 // FIXME: Assume only the first tree is the pattern. The others are clobber
3169 // nodes.
3170 TreePatternNode *Pattern = I->getTree(0);
3171 TreePatternNode *SrcPattern;
3172 if (Pattern->getOperator()->getName() == "set") {
3173 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3174 } else{
3175 // Not a set (store or something?)
3176 SrcPattern = Pattern;
3177 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003178
Craig Topper306cb122015-11-22 20:46:24 +00003179 Record *Instr = Entry.first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00003180 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003181 PatternToMatch(Instr,
3182 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003183 SrcPattern,
3184 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00003185 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003186 Instr->getValueAsInt("AddedComplexity"),
3187 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003188 }
3189}
3190
Chris Lattnera7722b62010-02-23 06:55:24 +00003191
3192typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3193
Jim Grosbach65586fe2010-12-21 16:16:00 +00003194static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003195 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003196 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003197 if (!P->getName().empty()) {
3198 NameRecord &Rec = Names[P->getName()];
3199 // If this is the first instance of the name, remember the node.
3200 if (Rec.second++ == 0)
3201 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003202 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003203 PatternTop->error("repetition of value: $" + P->getName() +
3204 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003205 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003206
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003207 if (!P->isLeaf()) {
3208 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003209 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003210 }
3211}
3212
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003213void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner0c0baa92010-02-23 06:16:51 +00003214 const PatternToMatch &PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003215 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003216 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003217 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3218 PrintWarning(Pattern->getRecord()->getLoc(),
3219 Twine("Pattern can never match: ") + Reason);
3220 return;
3221 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003222
Chris Lattner1e634e32010-03-01 22:29:19 +00003223 // If the source pattern's root is a complex pattern, that complex pattern
3224 // must specify the nodes it can potentially match.
3225 if (const ComplexPattern *CP =
3226 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3227 if (CP->getRootNodes().empty())
3228 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3229 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003230
3231
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003232 // Find all of the named values in the input and output, ensure they have the
3233 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003234 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003235 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3236 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003237
3238 // Scan all of the named values in the destination pattern, rejecting them if
3239 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003240 for (const auto &Entry : DstNames) {
3241 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003242 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003243 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003244 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003245
Chris Lattnera7722b62010-02-23 06:55:24 +00003246 // Scan all of the named values in the source pattern, rejecting them if the
3247 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003248 for (const auto &Entry : SrcNames)
3249 if (DstNames[Entry.first].first == nullptr &&
3250 SrcNames[Entry.first].second == 1)
3251 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003252
Chris Lattner0c0baa92010-02-23 06:16:51 +00003253 PatternsToMatch.push_back(PTM);
3254}
3255
3256
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003257
3258void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003259 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003260 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003261
3262 // First try to infer flags from the primary instruction pattern, if any.
3263 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003264 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003265 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3266 CodeGenInstruction &InstInfo =
3267 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003268
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003269 // Get the primary instruction pattern.
3270 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3271 if (!Pattern) {
3272 if (InstInfo.hasUndefFlags())
3273 Revisit.push_back(&InstInfo);
3274 continue;
3275 }
3276 InstAnalyzer PatInfo(*this);
3277 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003278 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003279 }
3280
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003281 // Second, look for single-instruction patterns defined outside the
3282 // instruction.
3283 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3284 const PatternToMatch &PTM = *I;
3285
3286 // We can only infer from single-instruction patterns, otherwise we won't
3287 // know which instruction should get the flags.
3288 SmallVector<Record*, 8> PatInstrs;
3289 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3290 if (PatInstrs.size() != 1)
3291 continue;
3292
3293 // Get the single instruction.
3294 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3295
3296 // Only infer properties from the first pattern. We'll verify the others.
3297 if (InstInfo.InferredFrom)
3298 continue;
3299
3300 InstAnalyzer PatInfo(*this);
3301 PatInfo.Analyze(&PTM);
3302 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3303 }
3304
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003305 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003306 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003307
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003308 // Revisit instructions with undefined flags and no pattern.
3309 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003310 for (CodeGenInstruction *InstInfo : Revisit) {
3311 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003312 continue;
3313 // The mayLoad and mayStore flags default to false.
3314 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003315 if (InstInfo->hasSideEffects_Unset)
3316 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003317 }
3318 return;
3319 }
3320
3321 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003322 for (CodeGenInstruction *InstInfo : Revisit) {
3323 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003324 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003325 if (InstInfo->hasSideEffects_Unset)
3326 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003327 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003328 if (InstInfo->mayStore_Unset)
3329 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003330 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003331 if (InstInfo->mayLoad_Unset)
3332 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003333 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003334 }
3335}
3336
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003337
3338/// Verify instruction flags against pattern node properties.
3339void CodeGenDAGPatterns::VerifyInstructionFlags() {
3340 unsigned Errors = 0;
3341 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3342 const PatternToMatch &PTM = *I;
3343 SmallVector<Record*, 8> Instrs;
3344 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3345 if (Instrs.empty())
3346 continue;
3347
3348 // Count the number of instructions with each flag set.
3349 unsigned NumSideEffects = 0;
3350 unsigned NumStores = 0;
3351 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003352 for (const Record *Instr : Instrs) {
3353 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003354 NumSideEffects += InstInfo.hasSideEffects;
3355 NumStores += InstInfo.mayStore;
3356 NumLoads += InstInfo.mayLoad;
3357 }
3358
3359 // Analyze the source pattern.
3360 InstAnalyzer PatInfo(*this);
3361 PatInfo.Analyze(&PTM);
3362
3363 // Collect error messages.
3364 SmallVector<std::string, 4> Msgs;
3365
3366 // Check for missing flags in the output.
3367 // Permit extra flags for now at least.
3368 if (PatInfo.hasSideEffects && !NumSideEffects)
3369 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3370
3371 // Don't verify store flags on instructions with side effects. At least for
3372 // intrinsics, side effects implies mayStore.
3373 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3374 Msgs.push_back("pattern may store, but mayStore isn't set");
3375
3376 // Similarly, mayStore implies mayLoad on intrinsics.
3377 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3378 Msgs.push_back("pattern may load, but mayLoad isn't set");
3379
3380 // Print error messages.
3381 if (Msgs.empty())
3382 continue;
3383 ++Errors;
3384
Craig Topper306cb122015-11-22 20:46:24 +00003385 for (const std::string &Msg : Msgs)
3386 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003387 (Instrs.size() == 1 ?
3388 "instruction" : "output instructions"));
3389 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003390 for (const Record *Instr : Instrs) {
3391 if (Instr != PTM.getSrcRecord())
3392 PrintError(Instr->getLoc(), "defined here");
3393 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003394 if (InstInfo.InferredFrom &&
3395 InstInfo.InferredFrom != InstInfo.TheDef &&
3396 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003397 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003398 }
3399 }
3400 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003401 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003402}
3403
Chris Lattnercabe0372010-03-15 06:00:16 +00003404/// Given a pattern result with an unresolved type, see if we can find one
3405/// instruction with an unresolved result type. Force this result type to an
3406/// arbitrary element if it's possible types to converge results.
3407static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3408 if (N->isLeaf())
3409 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003410
Chris Lattnercabe0372010-03-15 06:00:16 +00003411 // Analyze children.
3412 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3413 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3414 return true;
3415
3416 if (!N->getOperator()->isSubClassOf("Instruction"))
3417 return false;
3418
3419 // If this type is already concrete or completely unknown we can't do
3420 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003421 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3422 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3423 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003424
Chris Lattnerf1447252010-03-19 21:37:09 +00003425 // Otherwise, force its type to the first possibility (an arbitrary choice).
3426 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3427 return true;
3428 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003429
Chris Lattnerf1447252010-03-19 21:37:09 +00003430 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003431}
3432
Chris Lattnerab3242f2008-01-06 01:10:31 +00003433void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003434 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3435
Craig Topper306cb122015-11-22 20:46:24 +00003436 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003437 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003438
3439 // If the pattern references the null_frag, there's nothing to do.
3440 if (hasNullFragReference(Tree))
3441 continue;
3442
Chris Lattner5c2182e2010-03-27 02:53:27 +00003443 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003444
3445 // Inline pattern fragments into it.
3446 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003447
David Greeneaf8ee2c2011-07-29 22:43:06 +00003448 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003449 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003450
Chris Lattner8cab0212008-01-05 22:25:12 +00003451 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003452 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003453
Chris Lattner8cab0212008-01-05 22:25:12 +00003454 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003455 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003456
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003457 if (Result.getNumTrees() != 1)
3458 Result.error("Cannot handle instructions producing instructions "
3459 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003460
Chris Lattner8cab0212008-01-05 22:25:12 +00003461 bool IterateInference;
3462 bool InferredAllPatternTypes, InferredAllResultTypes;
3463 do {
3464 // Infer as many types as possible. If we cannot infer all of them, we
3465 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003466 InferredAllPatternTypes =
3467 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003468
Chris Lattner8cab0212008-01-05 22:25:12 +00003469 // Infer as many types as possible. If we cannot infer all of them, we
3470 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003471 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003472 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003473
Chris Lattnerfdc20712010-03-18 23:15:10 +00003474 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003475
Chris Lattner8cab0212008-01-05 22:25:12 +00003476 // Apply the type of the result to the source pattern. This helps us
3477 // resolve cases where the input type is known to be a pointer type (which
3478 // is considered resolved), but the result knows it needs to be 32- or
3479 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003480 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003481 Pattern->getTree(0)->getNumTypes());
3482 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003483 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3484 i, Result.getTree(0)->getExtType(i), Result);
3485 IterateInference |= Result.getTree(0)->UpdateNodeType(
3486 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003487 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003488
Chris Lattnercabe0372010-03-15 06:00:16 +00003489 // If our iteration has converged and the input pattern's types are fully
3490 // resolved but the result pattern is not fully resolved, we may have a
3491 // situation where we have two instructions in the result pattern and
3492 // the instructions require a common register class, but don't care about
3493 // what actual MVT is used. This is actually a bug in our modelling:
3494 // output patterns should have register classes, not MVTs.
3495 //
3496 // In any case, to handle this, we just go through and disambiguate some
3497 // arbitrary types to the result pattern's nodes.
3498 if (!IterateInference && InferredAllPatternTypes &&
3499 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003500 IterateInference =
3501 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003502 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003503
Chris Lattner8cab0212008-01-05 22:25:12 +00003504 // Verify that we inferred enough types that we can do something with the
3505 // pattern and result. If these fire the user has to add type casts.
3506 if (!InferredAllPatternTypes)
3507 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003508 if (!InferredAllResultTypes) {
3509 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003510 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003511 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003512
Chris Lattner8cab0212008-01-05 22:25:12 +00003513 // Validate that the input pattern is correct.
3514 std::map<std::string, TreePatternNode*> InstInputs;
3515 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003516 std::vector<Record*> InstImpResults;
3517 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3518 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3519 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003520 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003521
3522 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003523 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003524 std::vector<TreePatternNode*> ResultNodeOperands;
3525 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3526 TreePatternNode *OpNode = DstPattern->getChild(ii);
3527 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003528 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003529 std::vector<TreePatternNode*> Children;
3530 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003531 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003532 }
3533 ResultNodeOperands.push_back(OpNode);
3534 }
David Blaikiecf195302014-11-17 22:55:41 +00003535 DstPattern = Result.getOnlyTree();
3536 if (!DstPattern->isLeaf())
3537 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3538 ResultNodeOperands,
3539 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003540
David Blaikiecf195302014-11-17 22:55:41 +00003541 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3542 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3543
3544 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003545 Temp.InferAllTypes();
3546
Jim Grosbach65586fe2010-12-21 16:16:00 +00003547
Chris Lattner0c0baa92010-02-23 06:16:51 +00003548 AddPatternToMatch(Pattern,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003549 PatternToMatch(CurPattern,
3550 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerf1447252010-03-19 21:37:09 +00003551 Pattern->getTree(0),
David Blaikiecf195302014-11-17 22:55:41 +00003552 Temp.getOnlyTree(), InstImpResults,
Chris Lattnerf1447252010-03-19 21:37:09 +00003553 CurPattern->getValueAsInt("AddedComplexity"),
3554 CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003555 }
3556}
3557
3558/// CombineChildVariants - Given a bunch of permutations of each child of the
3559/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003560static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003561 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3562 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003563 CodeGenDAGPatterns &CDP,
3564 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003565 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00003566 for (const auto &Variants : ChildVariants)
3567 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003568 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003569
Chris Lattner8cab0212008-01-05 22:25:12 +00003570 // The end result is an all-pairs construction of the resultant pattern.
3571 std::vector<unsigned> Idxs;
3572 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003573 bool NotDone;
3574 do {
3575#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003576 DEBUG(if (!Idxs.empty()) {
3577 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00003578 for (unsigned Idx : Idxs) {
3579 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003580 }
3581 errs() << "]\n";
3582 });
Scott Michel94420742008-03-05 17:49:05 +00003583#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003584 // Create the variant and add it to the output list.
3585 std::vector<TreePatternNode*> NewChildren;
3586 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3587 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00003588 auto R = llvm::make_unique<TreePatternNode>(
3589 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003590
Chris Lattner8cab0212008-01-05 22:25:12 +00003591 // Copy over properties.
3592 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003593 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003594 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003595 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3596 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003597
Scott Michel94420742008-03-05 17:49:05 +00003598 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003599 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00003600 // Scan to see if this pattern has already been emitted. We can get
3601 // duplication due to things like commuting:
3602 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3603 // which are the same pattern. Ignore the dups.
3604 if (R->canPatternMatch(ErrString, CDP) &&
3605 std::none_of(OutVariants.begin(), OutVariants.end(),
3606 [&](TreePatternNode *Variant) {
3607 return R->isIsomorphicTo(Variant, DepVars);
3608 }))
3609 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003610
Scott Michel94420742008-03-05 17:49:05 +00003611 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003612 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00003613 // [0, 0], [0, 1], [1, 0], [1, 1].
3614 int IdxsIdx;
3615 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3616 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3617 Idxs[IdxsIdx] = 0;
3618 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003619 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003620 }
Scott Michel94420742008-03-05 17:49:05 +00003621 NotDone = (IdxsIdx >= 0);
3622 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003623}
3624
3625/// CombineChildVariants - A helper function for binary operators.
3626///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003627static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003628 const std::vector<TreePatternNode*> &LHS,
3629 const std::vector<TreePatternNode*> &RHS,
3630 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003631 CodeGenDAGPatterns &CDP,
3632 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003633 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3634 ChildVariants.push_back(LHS);
3635 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003636 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003637}
Chris Lattner8cab0212008-01-05 22:25:12 +00003638
3639
3640static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3641 std::vector<TreePatternNode *> &Children) {
3642 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3643 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003644
Chris Lattner8cab0212008-01-05 22:25:12 +00003645 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003646 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003647 N->getTransformFn()) {
3648 Children.push_back(N);
3649 return;
3650 }
3651
3652 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3653 Children.push_back(N->getChild(0));
3654 else
3655 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3656
3657 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3658 Children.push_back(N->getChild(1));
3659 else
3660 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3661}
3662
3663/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3664/// the (potentially recursive) pattern by using algebraic laws.
3665///
3666static void GenerateVariantsOf(TreePatternNode *N,
3667 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003668 CodeGenDAGPatterns &CDP,
3669 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003670 // We cannot permute leaves or ComplexPattern uses.
3671 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003672 OutVariants.push_back(N);
3673 return;
3674 }
3675
3676 // Look up interesting info about the node.
3677 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3678
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003679 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003680 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003681 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003682 std::vector<TreePatternNode*> MaximalChildren;
3683 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3684
3685 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3686 // permutations.
3687 if (MaximalChildren.size() == 3) {
3688 // Find the variants of all of our maximal children.
3689 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003690 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3691 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3692 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003693
Chris Lattner8cab0212008-01-05 22:25:12 +00003694 // There are only two ways we can permute the tree:
3695 // (A op B) op C and A op (B op C)
3696 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003697
Chris Lattner8cab0212008-01-05 22:25:12 +00003698 // Generate legal pair permutations of A/B/C.
3699 std::vector<TreePatternNode*> ABVariants;
3700 std::vector<TreePatternNode*> BAVariants;
3701 std::vector<TreePatternNode*> ACVariants;
3702 std::vector<TreePatternNode*> CAVariants;
3703 std::vector<TreePatternNode*> BCVariants;
3704 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003705 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3706 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3707 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3708 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3709 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3710 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003711
3712 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003713 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3714 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3715 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3716 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3717 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3718 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003719
3720 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003721 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3722 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3723 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3724 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3725 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3726 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003727 return;
3728 }
3729 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003730
Chris Lattner8cab0212008-01-05 22:25:12 +00003731 // Compute permutations of all children.
3732 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3733 ChildVariants.resize(N->getNumChildren());
3734 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003735 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003736
3737 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003738 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003739
3740 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003741 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3742 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3743 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3744 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003745 // Don't count children which are actually register references.
3746 unsigned NC = 0;
3747 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3748 TreePatternNode *Child = N->getChild(i);
3749 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003750 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003751 Record *RR = DI->getDef();
3752 if (RR->isSubClassOf("Register"))
3753 continue;
3754 }
3755 NC++;
3756 }
3757 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003758 if (isCommIntrinsic) {
3759 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3760 // operands are the commutative operands, and there might be more operands
3761 // after those.
3762 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003763 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00003764 std::vector<std::vector<TreePatternNode*> > Variants;
3765 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3766 Variants.push_back(ChildVariants[2]);
3767 Variants.push_back(ChildVariants[1]);
3768 for (unsigned i = 3; i != NC; ++i)
3769 Variants.push_back(ChildVariants[i]);
3770 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3771 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003772 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003773 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003774 }
3775}
3776
3777
3778// GenerateVariants - Generate variants. For example, commutative patterns can
3779// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003780void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003781 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003782
Chris Lattner8cab0212008-01-05 22:25:12 +00003783 // Loop over all of the patterns we've collected, checking to see if we can
3784 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003785 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003786 // the .td file having to contain tons of variants of instructions.
3787 //
3788 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3789 // intentionally do not reconsider these. Any variants of added patterns have
3790 // already been added.
3791 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00003792 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003793 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003794 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003795 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003796 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003797 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003798 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00003799 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003800 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003801
3802 assert(!Variants.empty() && "Must create at least original variant!");
3803 Variants.erase(Variants.begin()); // Remove the original pattern.
3804
3805 if (Variants.empty()) // No variants for this pattern.
3806 continue;
3807
Chris Lattner34822f62009-08-23 04:44:11 +00003808 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00003809 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00003810 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003811
3812 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3813 TreePatternNode *Variant = Variants[v];
3814
Chris Lattner34822f62009-08-23 04:44:11 +00003815 DEBUG(errs() << " VAR#" << v << ": ";
3816 Variant->dump();
3817 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003818
Chris Lattner8cab0212008-01-05 22:25:12 +00003819 // Scan to see if an instruction or explicit pattern already matches this.
3820 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003821 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003822 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003823 if (PatternsToMatch[i].getPredicates() !=
3824 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00003825 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003826 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003827 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3828 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003829 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003830 AlreadyExists = true;
3831 break;
3832 }
3833 }
3834 // If we already have it, ignore the variant.
3835 if (AlreadyExists) continue;
3836
3837 // Otherwise, add it to the list of patterns we have.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003838 PatternsToMatch.emplace_back(
3839 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3840 Variant, PatternsToMatch[i].getDstPattern(),
3841 PatternsToMatch[i].getDstRegs(),
3842 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
Chris Lattner8cab0212008-01-05 22:25:12 +00003843 }
3844
Chris Lattner34822f62009-08-23 04:44:11 +00003845 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003846 }
3847}