blob: aac84705562e56d3f543cafbc43addb1ecb1c32d [file] [log] [blame]
Chris Lattnerab3242f2008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerab3242f2008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner8cab0212008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner78ac0742008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Chris Lattnercabe0372010-03-15 06:00:16 +000016#include "llvm/ADT/STLExtras.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000017#include "llvm/ADT/StringExtras.h"
Jim Grosbach3ae48a62012-04-18 17:46:41 +000018#include "llvm/ADT/Twine.h"
Chris Lattner8cab0212008-01-05 22:25:12 +000019#include "llvm/Support/Debug.h"
David Blaikieb48ed1a2012-01-17 04:43:56 +000020#include "llvm/Support/ErrorHandling.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000021#include "llvm/TableGen/Error.h"
22#include "llvm/TableGen/Record.h"
Chuck Rose IIIfe2714f2008-01-15 21:43:17 +000023#include <algorithm>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000024#include <cstdio>
25#include <set>
Chris Lattner8cab0212008-01-05 22:25:12 +000026using namespace llvm;
27
Chandler Carruthe96dd892014-04-21 22:55:11 +000028#define DEBUG_TYPE "dag-patterns"
29
Chris Lattner8cab0212008-01-05 22:25:12 +000030//===----------------------------------------------------------------------===//
Chris Lattnercabe0372010-03-15 06:00:16 +000031// EEVT::TypeSet Implementation
32//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +000033
Owen Anderson9f944592009-08-11 20:47:22 +000034static inline bool isInteger(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000035 return MVT(VT).isInteger();
Duncan Sands13237ac2008-06-06 12:08:01 +000036}
Owen Anderson9f944592009-08-11 20:47:22 +000037static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000038 return MVT(VT).isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000039}
Owen Anderson9f944592009-08-11 20:47:22 +000040static inline bool isVector(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000041 return MVT(VT).isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000042}
Chris Lattner6d765eb2010-03-19 17:41:26 +000043static inline bool isScalar(MVT::SimpleValueType VT) {
Craig Topper95198f42013-09-25 06:37:18 +000044 return !MVT(VT).isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000045}
Duncan Sands13237ac2008-06-06 12:08:01 +000046
Chris Lattnercabe0372010-03-15 06:00:16 +000047EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
48 if (VT == MVT::iAny)
49 EnforceInteger(TP);
50 else if (VT == MVT::fAny)
51 EnforceFloatingPoint(TP);
52 else if (VT == MVT::vAny)
53 EnforceVector(TP);
54 else {
55 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
Ramkumar Ramachandra75a4f352015-01-22 20:14:38 +000056 VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!");
Chris Lattnercabe0372010-03-15 06:00:16 +000057 TypeVec.push_back(VT);
58 }
Chris Lattner8cab0212008-01-05 22:25:12 +000059}
60
Chris Lattnercabe0372010-03-15 06:00:16 +000061
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000062EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
Chris Lattnercabe0372010-03-15 06:00:16 +000063 assert(!VTList.empty() && "empty list?");
64 TypeVec.append(VTList.begin(), VTList.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +000065
Chris Lattnercabe0372010-03-15 06:00:16 +000066 if (!VTList.empty())
67 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
68 VTList[0] != MVT::fAny);
Jim Grosbach65586fe2010-12-21 16:16:00 +000069
Chris Lattner4a5f7be2010-03-27 20:32:26 +000070 // Verify no duplicates.
Chris Lattnercabe0372010-03-15 06:00:16 +000071 array_pod_sort(TypeVec.begin(), TypeVec.end());
Chris Lattner4a5f7be2010-03-27 20:32:26 +000072 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
Chris Lattner8cab0212008-01-05 22:25:12 +000073}
74
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000075/// FillWithPossibleTypes - Set to all legal types and return true, only valid
76/// on completely unknown type sets.
Chris Lattner6d765eb2010-03-19 17:41:26 +000077bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
78 bool (*Pred)(MVT::SimpleValueType),
79 const char *PredicateName) {
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000080 assert(isCompletelyUnknown());
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000081 ArrayRef<MVT::SimpleValueType> LegalTypes =
Chris Lattner6d765eb2010-03-19 17:41:26 +000082 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +000083
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000084 if (TP.hasError())
85 return false;
86
Craig Topper306cb122015-11-22 20:46:24 +000087 for (MVT::SimpleValueType VT : LegalTypes)
88 if (!Pred || Pred(VT))
89 TypeVec.push_back(VT);
Chris Lattner6d765eb2010-03-19 17:41:26 +000090
91 // If we have nothing that matches the predicate, bail out.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000092 if (TypeVec.empty()) {
Chris Lattner6d765eb2010-03-19 17:41:26 +000093 TP.error("Type inference contradiction found, no " +
Jim Grosbach65586fe2010-12-21 16:16:00 +000094 std::string(PredicateName) + " types found");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000095 return false;
96 }
Chris Lattner6d765eb2010-03-19 17:41:26 +000097 // No need to sort with one element.
98 if (TypeVec.size() == 1) return true;
99
100 // Remove duplicates.
101 array_pod_sort(TypeVec.begin(), TypeVec.end());
102 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000103
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000104 return true;
105}
Chris Lattnercabe0372010-03-15 06:00:16 +0000106
107/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
108/// integer value type.
109bool EEVT::TypeSet::hasIntegerTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000110 return std::any_of(TypeVec.begin(), TypeVec.end(), isInteger);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000111}
Chris Lattnercabe0372010-03-15 06:00:16 +0000112
113/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
114/// a floating point value type.
115bool EEVT::TypeSet::hasFloatingPointTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000116 return std::any_of(TypeVec.begin(), TypeVec.end(), isFloatingPoint);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000117}
Chris Lattnercabe0372010-03-15 06:00:16 +0000118
Craig Topper74169dc2014-01-28 04:49:01 +0000119/// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
120bool EEVT::TypeSet::hasScalarTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000121 return std::any_of(TypeVec.begin(), TypeVec.end(), isScalar);
Craig Topper74169dc2014-01-28 04:49:01 +0000122}
123
Chris Lattnercabe0372010-03-15 06:00:16 +0000124/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
125/// value type.
126bool EEVT::TypeSet::hasVectorTypes() const {
David Blaikieb8fc0182015-11-22 20:02:58 +0000127 return std::any_of(TypeVec.begin(), TypeVec.end(), isVector);
Chris Lattner8cab0212008-01-05 22:25:12 +0000128}
Bob Wilson2cd5da82009-08-11 01:14:02 +0000129
Chris Lattnercabe0372010-03-15 06:00:16 +0000130
131std::string EEVT::TypeSet::getName() const {
Chris Lattnerda5b4ad2010-03-19 01:14:27 +0000132 if (TypeVec.empty()) return "<empty>";
Jim Grosbach65586fe2010-12-21 16:16:00 +0000133
Chris Lattnercabe0372010-03-15 06:00:16 +0000134 std::string Result;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000135
Chris Lattnercabe0372010-03-15 06:00:16 +0000136 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
137 std::string VTName = llvm::getEnumName(TypeVec[i]);
138 // Strip off MVT:: prefix if present.
139 if (VTName.substr(0,5) == "MVT::")
140 VTName = VTName.substr(5);
141 if (i) Result += ':';
142 Result += VTName;
143 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000144
Chris Lattnercabe0372010-03-15 06:00:16 +0000145 if (TypeVec.size() == 1)
146 return Result;
147 return "{" + Result + "}";
Bob Wilson2cd5da82009-08-11 01:14:02 +0000148}
Chris Lattnercabe0372010-03-15 06:00:16 +0000149
150/// MergeInTypeInfo - This merges in type information from the specified
151/// argument. If 'this' changes, it returns true. If the two types are
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000152/// contradictory (e.g. merge f32 into i32) then this flags an error.
Chris Lattnercabe0372010-03-15 06:00:16 +0000153bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000154 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
Chris Lattnercabe0372010-03-15 06:00:16 +0000155 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000156
Chris Lattnercabe0372010-03-15 06:00:16 +0000157 if (isCompletelyUnknown()) {
158 *this = InVT;
159 return true;
160 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000161
Craig Topperd2177de2015-11-23 07:19:08 +0000162 assert(!TypeVec.empty() && !InVT.TypeVec.empty() && "No unknowns");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000163
Chris Lattnercabe0372010-03-15 06:00:16 +0000164 // Handle the abstract cases, seeing if we can resolve them better.
165 switch (TypeVec[0]) {
166 default: break;
167 case MVT::iPTR:
168 case MVT::iPTRAny:
169 if (InVT.hasIntegerTypes()) {
170 EEVT::TypeSet InCopy(InVT);
171 InCopy.EnforceInteger(TP);
172 InCopy.EnforceScalar(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000173
Chris Lattnercabe0372010-03-15 06:00:16 +0000174 if (InCopy.isConcrete()) {
175 // If the RHS has one integer type, upgrade iPTR to i32.
176 TypeVec[0] = InVT.TypeVec[0];
177 return true;
178 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000179
Chris Lattnercabe0372010-03-15 06:00:16 +0000180 // If the input has multiple scalar integers, this doesn't add any info.
181 if (!InCopy.isCompletelyUnknown())
182 return false;
183 }
184 break;
185 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000186
Chris Lattnercabe0372010-03-15 06:00:16 +0000187 // If the input constraint is iAny/iPTR and this is an integer type list,
188 // remove non-integer types from the list.
189 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
190 hasIntegerTypes()) {
191 bool MadeChange = EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000192
Chris Lattnercabe0372010-03-15 06:00:16 +0000193 // If we're merging in iPTR/iPTRAny and the node currently has a list of
194 // multiple different integer types, replace them with a single iPTR.
195 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
196 TypeVec.size() != 1) {
197 TypeVec.resize(1);
198 TypeVec[0] = InVT.TypeVec[0];
199 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.
207 bool MadeChange = false;
208 TypeSet InputSet(*this);
209
210 for (unsigned i = 0; i != TypeVec.size(); ++i) {
Craig Toppercbdc27e2015-11-22 19:27:02 +0000211 if (std::find(InVT.TypeVec.begin(), InVT.TypeVec.end(), TypeVec[i]) !=
212 InVT.TypeVec.end())
213 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000214
Chris Lattnercabe0372010-03-15 06:00:16 +0000215 TypeVec.erase(TypeVec.begin()+i--);
216 MadeChange = true;
217 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000218
Chris Lattnercabe0372010-03-15 06:00:16 +0000219 // If we removed all of our types, we have a type contradiction.
220 if (!TypeVec.empty())
221 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000222
Chris Lattnercabe0372010-03-15 06:00:16 +0000223 // FIXME: Really want an SMLoc here!
224 TP.error("Type inference contradiction found, merging '" +
225 InVT.getName() + "' into '" + InputSet.getName() + "'");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000226 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000227}
228
229/// EnforceInteger - Remove all non-integer types from this set.
230bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000231 if (TP.hasError())
232 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000233 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000234 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000235 return FillWithPossibleTypes(TP, isInteger, "integer");
Craig Topperd2177de2015-11-23 07:19:08 +0000236
Chris Lattnercabe0372010-03-15 06:00:16 +0000237 if (!hasFloatingPointTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000238 return false;
239
240 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000241
Chris Lattnercabe0372010-03-15 06:00:16 +0000242 // Filter out all the fp types.
Craig Topperde2d7592015-11-23 07:19:10 +0000243 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
244 std::not1(std::ptr_fun(isInteger))),
245 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000246
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000247 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000248 TP.error("Type inference contradiction found, '" +
249 InputSet.getName() + "' needs to be integer");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000250 return false;
251 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000252 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000253}
254
255/// EnforceFloatingPoint - Remove all integer types from this set.
256bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000257 if (TP.hasError())
258 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000259 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000260 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000261 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
262
Chris Lattnercabe0372010-03-15 06:00:16 +0000263 if (!hasIntegerTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000264 return false;
265
266 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000267
Craig Topperde2d7592015-11-23 07:19:10 +0000268 // Filter out all the integer types.
269 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
270 std::not1(std::ptr_fun(isFloatingPoint))),
271 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000272
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000273 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000274 TP.error("Type inference contradiction found, '" +
275 InputSet.getName() + "' needs to be floating point");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000276 return false;
277 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000278 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000279}
280
281/// EnforceScalar - Remove all vector types from this.
282bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000283 if (TP.hasError())
284 return false;
285
Chris Lattnercabe0372010-03-15 06:00:16 +0000286 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000287 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000288 return FillWithPossibleTypes(TP, isScalar, "scalar");
289
Chris Lattnercabe0372010-03-15 06:00:16 +0000290 if (!hasVectorTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000291 return false;
292
293 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000294
Chris Lattnercabe0372010-03-15 06:00:16 +0000295 // Filter out all the vector types.
Craig Topperde2d7592015-11-23 07:19:10 +0000296 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
297 std::not1(std::ptr_fun(isScalar))),
298 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000299
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000300 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000301 TP.error("Type inference contradiction found, '" +
302 InputSet.getName() + "' needs to be scalar");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000303 return false;
304 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000305 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000306}
307
308/// EnforceVector - Remove all vector types from this.
309bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000310 if (TP.hasError())
311 return false;
312
Chris Lattner6d765eb2010-03-19 17:41:26 +0000313 // If we know nothing, then get the full set.
314 if (TypeVec.empty())
315 return FillWithPossibleTypes(TP, isVector, "vector");
316
Chris Lattnercabe0372010-03-15 06:00:16 +0000317 TypeSet InputSet(*this);
318 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000319
Chris Lattnercabe0372010-03-15 06:00:16 +0000320 // Filter out all the scalar types.
Craig Topperde2d7592015-11-23 07:19:10 +0000321 TypeVec.erase(std::remove_if(TypeVec.begin(), TypeVec.end(),
322 std::not1(std::ptr_fun(isVector))),
323 TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000324
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000325 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000326 TP.error("Type inference contradiction found, '" +
327 InputSet.getName() + "' needs to be a vector");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000328 return false;
329 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000330 return MadeChange;
331}
332
333
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000334
Craig Topper74169dc2014-01-28 04:49:01 +0000335/// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000336/// this should be based on the element type. Update this and other based on
Craig Topper74169dc2014-01-28 04:49:01 +0000337/// this information.
Chris Lattnercabe0372010-03-15 06:00:16 +0000338bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000339 if (TP.hasError())
340 return false;
341
Chris Lattnercabe0372010-03-15 06:00:16 +0000342 // Both operands must be integer or FP, but we don't care which.
343 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000344
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000345 if (isCompletelyUnknown())
346 MadeChange = FillWithPossibleTypes(TP);
347
348 if (Other.isCompletelyUnknown())
349 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000350
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000351 // If one side is known to be integer or known to be FP but the other side has
352 // no information, get at least the type integrality info in there.
353 if (!hasFloatingPointTypes())
354 MadeChange |= Other.EnforceInteger(TP);
355 else if (!hasIntegerTypes())
356 MadeChange |= Other.EnforceFloatingPoint(TP);
357 if (!Other.hasFloatingPointTypes())
358 MadeChange |= EnforceInteger(TP);
359 else if (!Other.hasIntegerTypes())
360 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000361
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000362 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
363 "Should have a type list now");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000364
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000365 // If one contains vectors but the other doesn't pull vectors out.
366 if (!hasVectorTypes())
367 MadeChange |= Other.EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000368 else if (!hasScalarTypes())
369 MadeChange |= Other.EnforceVector(TP);
Craig Topper6dbcb942014-01-25 05:17:38 +0000370 if (!Other.hasVectorTypes())
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000371 MadeChange |= EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000372 else if (!Other.hasScalarTypes())
373 MadeChange |= EnforceVector(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000374
Craig Topper74169dc2014-01-28 04:49:01 +0000375 // This code does not currently handle nodes which have multiple types,
376 // where some types are integer, and some are fp. Assert that this is not
377 // the case.
378 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
379 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
380 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
381
382 if (TP.hasError())
383 return false;
384
Craig Topper7bbd37b2015-03-10 03:25:07 +0000385 // Okay, find the smallest type from current set and remove anything the
386 // same or smaller from the other set. We need to ensure that the scalar
387 // type size is smaller than the scalar size of the smallest type. For
388 // vectors, we also need to make sure that the total size is no larger than
389 // the size of the smallest type.
Craig Topper74169dc2014-01-28 04:49:01 +0000390 TypeSet InputSet(Other);
Craig Topper7bbd37b2015-03-10 03:25:07 +0000391 MVT Smallest = TypeVec[0];
Craig Topper74169dc2014-01-28 04:49:01 +0000392 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
Craig Topper7bbd37b2015-03-10 03:25:07 +0000393 MVT OtherVT = Other.TypeVec[i];
394 // Don't compare vector and non-vector types.
395 if (OtherVT.isVector() != Smallest.isVector())
396 continue;
397 // The getSizeInBits() check here is only needed for vectors, but is
398 // a subset of the scalar check for scalars so no need to qualify.
399 if (OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() ||
400 OtherVT.getSizeInBits() < Smallest.getSizeInBits()) {
Craig Topper74169dc2014-01-28 04:49:01 +0000401 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
402 MadeChange = true;
403 }
404 }
405
406 if (Other.TypeVec.empty()) {
407 TP.error("Type inference contradiction found, '" + InputSet.getName() +
408 "' has nothing larger than '" + getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000409 return false;
410 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000411
Craig Topper7bbd37b2015-03-10 03:25:07 +0000412 // Okay, find the largest type from the other set and remove anything the
413 // same or smaller from the current set. We need to ensure that the scalar
414 // type size is larger than the scalar size of the largest type. For
415 // vectors, we also need to make sure that the total size is no smaller than
416 // the size of the largest type.
Craig Topper74169dc2014-01-28 04:49:01 +0000417 InputSet = TypeSet(*this);
Craig Topper7bbd37b2015-03-10 03:25:07 +0000418 MVT Largest = Other.TypeVec[Other.TypeVec.size()-1];
Craig Topper74169dc2014-01-28 04:49:01 +0000419 for (unsigned i = 0; i != TypeVec.size(); ++i) {
Craig Topper7bbd37b2015-03-10 03:25:07 +0000420 MVT OtherVT = TypeVec[i];
421 // Don't compare vector and non-vector types.
422 if (OtherVT.isVector() != Largest.isVector())
423 continue;
424 // The getSizeInBits() check here is only needed for vectors, but is
425 // a subset of the scalar check for scalars so no need to qualify.
426 if (OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() ||
427 OtherVT.getSizeInBits() > Largest.getSizeInBits()) {
Craig Topper74169dc2014-01-28 04:49:01 +0000428 TypeVec.erase(TypeVec.begin()+i--);
429 MadeChange = true;
David Greene433c6182011-02-01 19:12:32 +0000430 }
David Greene433c6182011-02-01 19:12:32 +0000431 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000432
Craig Topper74169dc2014-01-28 04:49:01 +0000433 if (TypeVec.empty()) {
434 TP.error("Type inference contradiction found, '" + InputSet.getName() +
435 "' has nothing smaller than '" + Other.getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000436 return false;
437 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000438
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000439 return MadeChange;
Chris Lattnercabe0372010-03-15 06:00:16 +0000440}
441
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000442/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Chris Lattner57ebf632010-03-24 00:01:16 +0000443/// whose element is specified by VTOperand.
Craig Topper0be34582015-03-05 07:11:34 +0000444bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT,
445 TreePattern &TP) {
446 bool MadeChange = false;
447
448 MadeChange |= EnforceVector(TP);
449
450 TypeSet InputSet(*this);
451
452 // Filter out all the types which don't have the right element type.
453 for (unsigned i = 0; i != TypeVec.size(); ++i) {
454 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
455 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
456 TypeVec.erase(TypeVec.begin()+i--);
457 MadeChange = true;
458 }
459 }
460
461 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
462 TP.error("Type inference contradiction found, forcing '" +
463 InputSet.getName() + "' to have a vector element");
464 return false;
465 }
466
467 return MadeChange;
468}
469
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000470/// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type
Craig Topper0be34582015-03-05 07:11:34 +0000471/// whose element is specified by VTOperand.
Chris Lattner57ebf632010-03-24 00:01:16 +0000472bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattnercabe0372010-03-15 06:00:16 +0000473 TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000474 if (TP.hasError())
475 return false;
476
Chris Lattner57ebf632010-03-24 00:01:16 +0000477 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattnercabe0372010-03-15 06:00:16 +0000478 bool MadeChange = false;
Chris Lattner57ebf632010-03-24 00:01:16 +0000479 MadeChange |= EnforceVector(TP);
480 MadeChange |= VTOperand.EnforceScalar(TP);
481
482 // If we know the vector type, it forces the scalar to agree.
483 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000484 MVT IVT = getConcrete();
Chris Lattner57ebf632010-03-24 00:01:16 +0000485 IVT = IVT.getVectorElementType();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000486 return MadeChange |
Craig Topper95198f42013-09-25 06:37:18 +0000487 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
Chris Lattner57ebf632010-03-24 00:01:16 +0000488 }
489
490 // If the scalar type is known, filter out vector types whose element types
491 // disagree.
492 if (!VTOperand.isConcrete())
493 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000494
Chris Lattner57ebf632010-03-24 00:01:16 +0000495 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000496
Chris Lattner57ebf632010-03-24 00:01:16 +0000497 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000498
Chris Lattner57ebf632010-03-24 00:01:16 +0000499 // Filter out all the types which don't have the right element type.
500 for (unsigned i = 0; i != TypeVec.size(); ++i) {
501 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
Craig Topper95198f42013-09-25 06:37:18 +0000502 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000503 TypeVec.erase(TypeVec.begin()+i--);
504 MadeChange = true;
505 }
Chris Lattner57ebf632010-03-24 00:01:16 +0000506 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000507
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000508 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
Chris Lattnercabe0372010-03-15 06:00:16 +0000509 TP.error("Type inference contradiction found, forcing '" +
510 InputSet.getName() + "' to have a vector element");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000511 return false;
512 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000513 return MadeChange;
514}
515
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000516/// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a
David Greene127fd1d2011-01-24 20:53:18 +0000517/// vector type specified by VTOperand.
518bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
519 TreePattern &TP) {
Craig Topper6e1faaf2014-01-25 17:40:33 +0000520 if (TP.hasError())
521 return false;
522
David Greene127fd1d2011-01-24 20:53:18 +0000523 // "This" must be a vector and "VTOperand" must be a vector.
524 bool MadeChange = false;
525 MadeChange |= EnforceVector(TP);
526 MadeChange |= VTOperand.EnforceVector(TP);
527
Craig Topper6e1faaf2014-01-25 17:40:33 +0000528 // If one side is known to be integer or known to be FP but the other side has
529 // no information, get at least the type integrality info in there.
530 if (!hasFloatingPointTypes())
531 MadeChange |= VTOperand.EnforceInteger(TP);
532 else if (!hasIntegerTypes())
533 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
534 if (!VTOperand.hasFloatingPointTypes())
535 MadeChange |= EnforceInteger(TP);
536 else if (!VTOperand.hasIntegerTypes())
537 MadeChange |= EnforceFloatingPoint(TP);
538
539 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
540 "Should have a type list now");
David Greene127fd1d2011-01-24 20:53:18 +0000541
542 // If we know the vector type, it forces the scalar types to agree.
Craig Topper6e1faaf2014-01-25 17:40:33 +0000543 // Also force one vector to have more elements than the other.
David Greene127fd1d2011-01-24 20:53:18 +0000544 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000545 MVT IVT = getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000546 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000547 IVT = IVT.getVectorElementType();
548
Craig Topper95198f42013-09-25 06:37:18 +0000549 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000550 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000551
552 // Only keep types that have less elements than VTOperand.
553 TypeSet InputSet(VTOperand);
554
555 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
556 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
557 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
558 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
559 MadeChange = true;
560 }
561 }
562 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
563 TP.error("Type inference contradiction found, forcing '" +
564 InputSet.getName() + "' to have less vector elements than '" +
565 getName() + "'");
566 return false;
567 }
David Greene127fd1d2011-01-24 20:53:18 +0000568 } else if (VTOperand.isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000569 MVT IVT = VTOperand.getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000570 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000571 IVT = IVT.getVectorElementType();
572
Craig Topper95198f42013-09-25 06:37:18 +0000573 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000574 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000575
576 // Only keep types that have more elements than 'this'.
577 TypeSet InputSet(*this);
578
579 for (unsigned i = 0; i != TypeVec.size(); ++i) {
580 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
581 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
582 TypeVec.erase(TypeVec.begin()+i--);
583 MadeChange = true;
584 }
585 }
586 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
587 TP.error("Type inference contradiction found, forcing '" +
588 InputSet.getName() + "' to have more vector elements than '" +
589 VTOperand.getName() + "'");
590 return false;
591 }
David Greene127fd1d2011-01-24 20:53:18 +0000592 }
593
594 return MadeChange;
595}
596
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000597/// EnforceVectorSameNumElts - 'this' is now constrained to
Craig Topper0be34582015-03-05 07:11:34 +0000598/// be a vector with same num elements as VTOperand.
599bool EEVT::TypeSet::EnforceVectorSameNumElts(EEVT::TypeSet &VTOperand,
600 TreePattern &TP) {
601 if (TP.hasError())
602 return false;
603
604 // "This" must be a vector and "VTOperand" must be a vector.
605 bool MadeChange = false;
606 MadeChange |= EnforceVector(TP);
607 MadeChange |= VTOperand.EnforceVector(TP);
608
609 // If we know one of the vector types, it forces the other type to agree.
610 if (isConcrete()) {
611 MVT IVT = getConcrete();
612 unsigned NumElems = IVT.getVectorNumElements();
613
614 // Only keep types that have same elements as VTOperand.
615 TypeSet InputSet(VTOperand);
616
617 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
618 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
619 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() != NumElems) {
620 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
621 MadeChange = true;
622 }
623 }
624 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
625 TP.error("Type inference contradiction found, forcing '" +
626 InputSet.getName() + "' to have same number elements as '" +
627 getName() + "'");
628 return false;
629 }
630 } else if (VTOperand.isConcrete()) {
631 MVT IVT = VTOperand.getConcrete();
632 unsigned NumElems = IVT.getVectorNumElements();
633
634 // Only keep types that have same elements as 'this'.
635 TypeSet InputSet(*this);
636
637 for (unsigned i = 0; i != TypeVec.size(); ++i) {
638 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
639 if (MVT(TypeVec[i]).getVectorNumElements() != NumElems) {
640 TypeVec.erase(TypeVec.begin()+i--);
641 MadeChange = true;
642 }
643 }
644 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
645 TP.error("Type inference contradiction found, forcing '" +
646 InputSet.getName() + "' to have same number elements than '" +
647 VTOperand.getName() + "'");
648 return false;
649 }
650 }
651
652 return MadeChange;
653}
654
Chris Lattnercabe0372010-03-15 06:00:16 +0000655//===----------------------------------------------------------------------===//
656// Helpers for working with extended types.
Chris Lattner8cab0212008-01-05 22:25:12 +0000657
Scott Michel94420742008-03-05 17:49:05 +0000658/// Dependent variable map for CodeGenDAGPattern variant generation
659typedef std::map<std::string, int> DepVarMap;
660
Chris Lattner514e2922011-04-17 21:38:24 +0000661static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel94420742008-03-05 17:49:05 +0000662 if (N->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000663 if (isa<DefInit>(N->getLeafValue()))
Scott Michel94420742008-03-05 17:49:05 +0000664 DepMap[N->getName()]++;
Scott Michel94420742008-03-05 17:49:05 +0000665 } else {
666 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
667 FindDepVarsOf(N->getChild(i), DepMap);
668 }
669}
Chris Lattner514e2922011-04-17 21:38:24 +0000670
671/// Find dependent variables within child patterns
672static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000673 DepVarMap depcounts;
674 FindDepVarsOf(N, depcounts);
Craig Topper306cb122015-11-22 20:46:24 +0000675 for (const std::pair<std::string, int> &Pair : depcounts) {
676 if (Pair.second > 1)
677 DepVars.insert(Pair.first);
Scott Michel94420742008-03-05 17:49:05 +0000678 }
679}
680
Daniel Dunbarba66a812010-10-08 02:07:22 +0000681#ifndef NDEBUG
Chris Lattner514e2922011-04-17 21:38:24 +0000682/// Dump the dependent variable set:
683static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000684 if (DepVars.empty()) {
Chris Lattner34822f62009-08-23 04:44:11 +0000685 DEBUG(errs() << "<empty set>");
Scott Michel94420742008-03-05 17:49:05 +0000686 } else {
Chris Lattner34822f62009-08-23 04:44:11 +0000687 DEBUG(errs() << "[ ");
Craig Topper306cb122015-11-22 20:46:24 +0000688 for (const std::string &DepVar : DepVars) {
689 DEBUG(errs() << DepVar << " ");
Scott Michel94420742008-03-05 17:49:05 +0000690 }
Chris Lattner34822f62009-08-23 04:44:11 +0000691 DEBUG(errs() << "]");
Scott Michel94420742008-03-05 17:49:05 +0000692 }
693}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000694#endif
695
Chris Lattner514e2922011-04-17 21:38:24 +0000696
697//===----------------------------------------------------------------------===//
698// TreePredicateFn Implementation
699//===----------------------------------------------------------------------===//
700
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000701/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
702TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
703 assert((getPredCode().empty() || getImmCode().empty()) &&
704 ".td file corrupt: can't have a node predicate *and* an imm predicate");
705}
706
Chris Lattner514e2922011-04-17 21:38:24 +0000707std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000708 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000709}
710
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000711std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000712 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000713}
714
Chris Lattner514e2922011-04-17 21:38:24 +0000715
716/// isAlwaysTrue - Return true if this is a noop predicate.
717bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000718 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000719}
720
721/// Return the name to use in the generated code to reference this, this is
722/// "Predicate_foo" if from a pattern fragment "foo".
723std::string TreePredicateFn::getFnName() const {
724 return "Predicate_" + PatFragRec->getRecord()->getName();
725}
726
727/// getCodeToRunOnSDNode - Return the code for the function body that
728/// evaluates this predicate. The argument is expected to be in "Node",
729/// not N. This handles casting and conversion to a concrete node type as
730/// appropriate.
731std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000732 // Handle immediate predicates first.
733 std::string ImmCode = getImmCode();
734 if (!ImmCode.empty()) {
735 std::string Result =
736 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000737 return Result + ImmCode;
738 }
739
740 // Handle arbitrary node predicates.
741 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000742 std::string ClassName;
743 if (PatFragRec->getOnlyTree()->isLeaf())
744 ClassName = "SDNode";
745 else {
746 Record *Op = PatFragRec->getOnlyTree()->getOperator();
747 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
748 }
749 std::string Result;
750 if (ClassName == "SDNode")
751 Result = " SDNode *N = Node;\n";
752 else
Craig Topper5b0f57d2015-10-11 16:59:29 +0000753 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
Chris Lattner514e2922011-04-17 21:38:24 +0000754
755 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000756}
757
Chris Lattner8cab0212008-01-05 22:25:12 +0000758//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000759// PatternToMatch implementation
760//
761
Chris Lattner05925fe2010-03-29 01:40:38 +0000762
763/// getPatternSize - Return the 'size' of this pattern. We want to match large
764/// patterns before small ones. This is used to determine the size of a
765/// pattern.
766static unsigned getPatternSize(const TreePatternNode *P,
767 const CodeGenDAGPatterns &CGP) {
768 unsigned Size = 3; // The node itself.
769 // If the root node is a ConstantSDNode, increases its size.
770 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000771 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000772 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000773
Chris Lattner05925fe2010-03-29 01:40:38 +0000774 // FIXME: This is a hack to statically increase the priority of patterns
775 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
776 // Later we can allow complexity / cost for each pattern to be (optionally)
777 // specified. To get best possible pattern match we'll need to dynamically
778 // calculate the complexity of all patterns a dag can potentially map to.
779 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000780 if (AM) {
Chris Lattner05925fe2010-03-29 01:40:38 +0000781 Size += AM->getNumOperands() * 3;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000782
Tim Northoverc807a172014-05-20 11:52:46 +0000783 // We don't want to count any children twice, so return early.
784 return Size;
785 }
786
Chris Lattner05925fe2010-03-29 01:40:38 +0000787 // If this node has some predicate function that must match, it adds to the
788 // complexity of this node.
789 if (!P->getPredicateFns().empty())
790 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000791
Chris Lattner05925fe2010-03-29 01:40:38 +0000792 // Count children in the count if they are also nodes.
793 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
794 TreePatternNode *Child = P->getChild(i);
795 if (!Child->isLeaf() && Child->getNumTypes() &&
796 Child->getType(0) != MVT::Other)
797 Size += getPatternSize(Child, CGP);
798 else if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000799 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000800 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
801 else if (Child->getComplexPatternInfo(CGP))
802 Size += getPatternSize(Child, CGP);
803 else if (!Child->getPredicateFns().empty())
804 ++Size;
805 }
806 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000807
Chris Lattner05925fe2010-03-29 01:40:38 +0000808 return Size;
809}
810
811/// Compute the complexity metric for the input pattern. This roughly
812/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000813int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000814getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
815 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
816}
817
818
Dan Gohman49e19e92008-08-22 00:20:26 +0000819/// getPredicateCheck - Return a single string containing all of this
820/// pattern's predicates concatenated with "&&" operators.
821///
822std::string PatternToMatch::getPredicateCheck() const {
823 std::string PredicateCheck;
Craig Topperef0578a2015-06-02 04:15:51 +0000824 for (Init *I : Predicates->getValues()) {
825 if (DefInit *Pred = dyn_cast<DefInit>(I)) {
Dan Gohman49e19e92008-08-22 00:20:26 +0000826 Record *Def = Pred->getDef();
827 if (!Def->isSubClassOf("Predicate")) {
828#ifndef NDEBUG
829 Def->dump();
830#endif
Craig Topperc4965bc2012-02-05 07:21:30 +0000831 llvm_unreachable("Unknown predicate type!");
Dan Gohman49e19e92008-08-22 00:20:26 +0000832 }
833 if (!PredicateCheck.empty())
834 PredicateCheck += " && ";
835 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
836 }
837 }
838
839 return PredicateCheck;
840}
841
842//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000843// SDTypeConstraint implementation
844//
845
846SDTypeConstraint::SDTypeConstraint(Record *R) {
847 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000848
Chris Lattner8cab0212008-01-05 22:25:12 +0000849 if (R->isSubClassOf("SDTCisVT")) {
850 ConstraintType = SDTCisVT;
851 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerffdac7b2010-03-28 06:04:39 +0000852 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000853 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000854
Chris Lattner8cab0212008-01-05 22:25:12 +0000855 } else if (R->isSubClassOf("SDTCisPtrTy")) {
856 ConstraintType = SDTCisPtrTy;
857 } else if (R->isSubClassOf("SDTCisInt")) {
858 ConstraintType = SDTCisInt;
859 } else if (R->isSubClassOf("SDTCisFP")) {
860 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000861 } else if (R->isSubClassOf("SDTCisVec")) {
862 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000863 } else if (R->isSubClassOf("SDTCisSameAs")) {
864 ConstraintType = SDTCisSameAs;
865 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
866 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
867 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000868 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000869 R->getValueAsInt("OtherOperandNum");
870 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
871 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000872 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000873 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000874 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
875 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000876 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000877 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
878 ConstraintType = SDTCisSubVecOfVec;
879 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
880 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +0000881 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
882 ConstraintType = SDTCVecEltisVT;
883 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
884 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector())
885 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT");
886 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() &&
887 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint())
888 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
889 "as SDTCVecEltisVT");
890 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
891 ConstraintType = SDTCisSameNumEltsAs;
892 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
893 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +0000894 } else {
James Y Knighte452e272015-05-11 22:17:13 +0000895 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +0000896 }
897}
898
899/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000900/// N, and the result number in ResNo.
901static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
902 const SDNodeInfo &NodeInfo,
903 unsigned &ResNo) {
904 unsigned NumResults = NodeInfo.getNumResults();
905 if (OpNo < NumResults) {
906 ResNo = OpNo;
907 return N;
908 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000909
Chris Lattner2db7aba2010-03-19 21:56:21 +0000910 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000911
Chris Lattner2db7aba2010-03-19 21:56:21 +0000912 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +0000913 std::string S;
914 raw_string_ostream OS(S);
915 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000916 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +0000917 N->print(OS);
918 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +0000919 }
920
Chris Lattner2db7aba2010-03-19 21:56:21 +0000921 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +0000922}
923
924/// ApplyTypeConstraint - Given a node in a pattern, apply this type
925/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000926/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +0000927bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
928 const SDNodeInfo &NodeInfo,
929 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000930 if (TP.hasError())
931 return false;
932
Chris Lattner2db7aba2010-03-19 21:56:21 +0000933 unsigned ResNo = 0; // The result number being referenced.
934 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000935
Chris Lattner8cab0212008-01-05 22:25:12 +0000936 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000937 case SDTCisVT:
938 // Operand must be a particular type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000939 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000940 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +0000941 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000942 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000943 case SDTCisInt:
944 // Require it to be one of the legal integer VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000945 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000946 case SDTCisFP:
947 // Require it to be one of the legal fp VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000948 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000949 case SDTCisVec:
950 // Require it to be one of the legal vector VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000951 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000952 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000953 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000954 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000955 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +0000956 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
957 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000958 }
959 case SDTCisVTSmallerThanOp: {
960 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
961 // have an integer type that is smaller than the VT.
962 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +0000963 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +0000964 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000965 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000966 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000967 return false;
968 }
Owen Anderson9f944592009-08-11 20:47:22 +0000969 MVT::SimpleValueType VT =
David Greeneaf8ee2c2011-07-29 22:43:06 +0000970 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000971
Chris Lattner38c99662010-03-24 00:06:46 +0000972 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000973
Chris Lattner2db7aba2010-03-19 21:56:21 +0000974 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000975 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000976 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
977 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +0000978
Chris Lattner38c99662010-03-24 00:06:46 +0000979 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000980 }
981 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000982 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000983 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000984 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
985 BResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +0000986 return NodeToApply->getExtType(ResNo).
987 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000988 }
Nate Begeman17bedbc2008-02-09 01:37:05 +0000989 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000990 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +0000991 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000992 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
993 VResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000994
Chris Lattner57ebf632010-03-24 00:01:16 +0000995 // Filter vector types out of VecOperand that don't have the right element
996 // type.
997 return VecOperand->getExtType(VResNo).
998 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begeman17bedbc2008-02-09 01:37:05 +0000999 }
David Greene127fd1d2011-01-24 20:53:18 +00001000 case SDTCisSubVecOfVec: {
1001 unsigned VResNo = 0;
1002 TreePatternNode *BigVecOperand =
1003 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1004 VResNo);
1005
1006 // Filter vector types out of BigVecOperand that don't have the
1007 // right subvector type.
1008 return BigVecOperand->getExtType(VResNo).
1009 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
1010 }
Craig Topper0be34582015-03-05 07:11:34 +00001011 case SDTCVecEltisVT: {
1012 return NodeToApply->getExtType(ResNo).
1013 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP);
1014 }
1015 case SDTCisSameNumEltsAs: {
1016 unsigned OResNo = 0;
1017 TreePatternNode *OtherNode =
1018 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1019 N, NodeInfo, OResNo);
1020 return OtherNode->getExtType(OResNo).
1021 EnforceVectorSameNumElts(NodeToApply->getExtType(ResNo), TP);
1022 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001023 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001024 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001025}
1026
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001027// Update the node type to match an instruction operand or result as specified
1028// in the ins or outs lists on the instruction definition. Return true if the
1029// type was actually changed.
1030bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1031 Record *Operand,
1032 TreePattern &TP) {
1033 // The 'unknown' operand indicates that types should be inferred from the
1034 // context.
1035 if (Operand->isSubClassOf("unknown_class"))
1036 return false;
1037
1038 // The Operand class specifies a type directly.
1039 if (Operand->isSubClassOf("Operand"))
1040 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
1041 TP);
1042
1043 // PointerLikeRegClass has a type that is determined at runtime.
1044 if (Operand->isSubClassOf("PointerLikeRegClass"))
1045 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1046
1047 // Both RegisterClass and RegisterOperand operands derive their types from a
1048 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001049 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001050 if (Operand->isSubClassOf("RegisterClass"))
1051 RC = Operand;
1052 else if (Operand->isSubClassOf("RegisterOperand"))
1053 RC = Operand->getValueAsDef("RegClass");
1054
1055 assert(RC && "Unknown operand type");
1056 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1057 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1058}
1059
1060
Chris Lattner8cab0212008-01-05 22:25:12 +00001061//===----------------------------------------------------------------------===//
1062// SDNodeInfo implementation
1063//
1064SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1065 EnumName = R->getValueAsString("Opcode");
1066 SDClassName = R->getValueAsString("SDClass");
1067 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1068 NumResults = TypeProfile->getValueAsInt("NumResults");
1069 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001070
Chris Lattner8cab0212008-01-05 22:25:12 +00001071 // Parse the properties.
1072 Properties = 0;
Craig Topper306cb122015-11-22 20:46:24 +00001073 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1074 if (Property->getName() == "SDNPCommutative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001075 Properties |= 1 << SDNPCommutative;
Craig Topper306cb122015-11-22 20:46:24 +00001076 } else if (Property->getName() == "SDNPAssociative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001077 Properties |= 1 << SDNPAssociative;
Craig Topper306cb122015-11-22 20:46:24 +00001078 } else if (Property->getName() == "SDNPHasChain") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001079 Properties |= 1 << SDNPHasChain;
Craig Topper306cb122015-11-22 20:46:24 +00001080 } else if (Property->getName() == "SDNPOutGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001081 Properties |= 1 << SDNPOutGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001082 } else if (Property->getName() == "SDNPInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001083 Properties |= 1 << SDNPInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001084 } else if (Property->getName() == "SDNPOptInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001085 Properties |= 1 << SDNPOptInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001086 } else if (Property->getName() == "SDNPMayStore") {
Chris Lattnera348f552008-01-06 06:44:58 +00001087 Properties |= 1 << SDNPMayStore;
Craig Topper306cb122015-11-22 20:46:24 +00001088 } else if (Property->getName() == "SDNPMayLoad") {
Chris Lattner1ca20682008-01-10 04:38:57 +00001089 Properties |= 1 << SDNPMayLoad;
Craig Topper306cb122015-11-22 20:46:24 +00001090 } else if (Property->getName() == "SDNPSideEffect") {
Chris Lattner42c63ef2008-01-10 05:39:30 +00001091 Properties |= 1 << SDNPSideEffect;
Craig Topper306cb122015-11-22 20:46:24 +00001092 } else if (Property->getName() == "SDNPMemOperand") {
Mon P Wang6a490372008-06-25 08:15:39 +00001093 Properties |= 1 << SDNPMemOperand;
Craig Topper306cb122015-11-22 20:46:24 +00001094 } else if (Property->getName() == "SDNPVariadic") {
Chris Lattner83aeaab2010-03-19 05:07:09 +00001095 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001096 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001097 PrintFatalError("Unknown SD Node property '" +
Craig Topper306cb122015-11-22 20:46:24 +00001098 Property->getName() + "' on node '" +
James Y Knighte452e272015-05-11 22:17:13 +00001099 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001100 }
1101 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001102
1103
Chris Lattner8cab0212008-01-05 22:25:12 +00001104 // Parse the type constraints.
1105 std::vector<Record*> ConstraintList =
1106 TypeProfile->getValueAsListOfDefs("Constraints");
1107 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1108}
1109
Chris Lattner99e53b32010-02-28 00:22:30 +00001110/// getKnownType - If the type constraints on this node imply a fixed type
1111/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001112/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001113MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001114 unsigned NumResults = getNumResults();
1115 assert(NumResults <= 1 &&
1116 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001117 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001118
Craig Topper306cb122015-11-22 20:46:24 +00001119 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001120 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001121 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001122 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001123
Craig Topper306cb122015-11-22 20:46:24 +00001124 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001125 default: break;
1126 case SDTypeConstraint::SDTCisVT:
Craig Topper306cb122015-11-22 20:46:24 +00001127 return Constraint.x.SDTCisVT_Info.VT;
Chris Lattner99e53b32010-02-28 00:22:30 +00001128 case SDTypeConstraint::SDTCisPtrTy:
1129 return MVT::iPTR;
1130 }
1131 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001132 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001133}
1134
Chris Lattner8cab0212008-01-05 22:25:12 +00001135//===----------------------------------------------------------------------===//
1136// TreePatternNode implementation
1137//
1138
1139TreePatternNode::~TreePatternNode() {
1140#if 0 // FIXME: implement refcounted tree nodes!
1141 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1142 delete getChild(i);
1143#endif
1144}
1145
Chris Lattnerf1447252010-03-19 21:37:09 +00001146static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1147 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001148 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001149 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001150
Chris Lattner2109cb42010-03-22 20:56:36 +00001151 if (Operator->isSubClassOf("Intrinsic"))
1152 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001153
Chris Lattnerf1447252010-03-19 21:37:09 +00001154 if (Operator->isSubClassOf("SDNode"))
1155 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001156
Chris Lattnerf1447252010-03-19 21:37:09 +00001157 if (Operator->isSubClassOf("PatFrag")) {
1158 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1159 // the forward reference case where one pattern fragment references another
1160 // before it is processed.
1161 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1162 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001163
Chris Lattnerf1447252010-03-19 21:37:09 +00001164 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001165 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001166 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001167 if (Tree)
1168 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1169 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001170 assert(Op && "Invalid Fragment");
1171 return GetNumNodeResults(Op, CDP);
1172 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001173
Chris Lattnerf1447252010-03-19 21:37:09 +00001174 if (Operator->isSubClassOf("Instruction")) {
1175 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001176
Craig Topper3a8eb892015-03-20 05:09:06 +00001177 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1178
1179 // Subtract any defaulted outputs.
1180 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1181 Record *OperandNode = InstInfo.Operands[i].Rec;
1182
1183 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1184 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1185 --NumDefsToAdd;
1186 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001187
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001188 // Add on one implicit def if it has a resolvable type.
1189 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1190 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001191 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001192 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001193
Chris Lattnerf1447252010-03-19 21:37:09 +00001194 if (Operator->isSubClassOf("SDNodeXForm"))
1195 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001196
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001197 if (Operator->isSubClassOf("ValueType"))
1198 return 1; // A type-cast of one result.
1199
Tim Northoverc807a172014-05-20 11:52:46 +00001200 if (Operator->isSubClassOf("ComplexPattern"))
1201 return 1;
1202
Chris Lattnerf1447252010-03-19 21:37:09 +00001203 Operator->dump();
James Y Knighte452e272015-05-11 22:17:13 +00001204 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001205}
1206
1207void TreePatternNode::print(raw_ostream &OS) const {
1208 if (isLeaf())
1209 OS << *getLeafValue();
1210 else
1211 OS << '(' << getOperator()->getName();
1212
1213 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1214 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001215
1216 if (!isLeaf()) {
1217 if (getNumChildren() != 0) {
1218 OS << " ";
1219 getChild(0)->print(OS);
1220 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1221 OS << ", ";
1222 getChild(i)->print(OS);
1223 }
1224 }
1225 OS << ")";
1226 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001227
Craig Topper306cb122015-11-22 20:46:24 +00001228 for (const TreePredicateFn &Pred : PredicateFns)
1229 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001230 if (TransformFn)
1231 OS << "<<X:" << TransformFn->getName() << ">>";
1232 if (!getName().empty())
1233 OS << ":$" << getName();
1234
1235}
1236void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001237 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001238}
1239
Scott Michel94420742008-03-05 17:49:05 +00001240/// isIsomorphicTo - Return true if this node is recursively
1241/// isomorphic to the specified node. For this comparison, the node's
1242/// entire state is considered. The assigned name is ignored, since
1243/// nodes with differing names are considered isomorphic. However, if
1244/// the assigned name is present in the dependent variable set, then
1245/// the assigned name is considered significant and the node is
1246/// isomorphic if the names match.
1247bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1248 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001249 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001250 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001251 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001252 getTransformFn() != N->getTransformFn())
1253 return false;
1254
1255 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001256 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1257 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001258 return ((DI->getDef() == NDI->getDef())
1259 && (DepVars.find(getName()) == DepVars.end()
1260 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001261 }
1262 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001263 return getLeafValue() == N->getLeafValue();
1264 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001265
Chris Lattner8cab0212008-01-05 22:25:12 +00001266 if (N->getOperator() != getOperator() ||
1267 N->getNumChildren() != getNumChildren()) return false;
1268 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001269 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001270 return false;
1271 return true;
1272}
1273
1274/// clone - Make a copy of this tree and all of its children.
1275///
1276TreePatternNode *TreePatternNode::clone() const {
1277 TreePatternNode *New;
1278 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001279 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001280 } else {
1281 std::vector<TreePatternNode*> CChildren;
1282 CChildren.reserve(Children.size());
1283 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1284 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001285 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001286 }
1287 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001288 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001289 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001290 New->setTransformFn(getTransformFn());
1291 return New;
1292}
1293
Chris Lattner53c39ba2010-02-14 22:22:58 +00001294/// RemoveAllTypes - Recursively strip all the types of this tree.
1295void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001296 // Reset to unknown type.
1297 std::fill(Types.begin(), Types.end(), EEVT::TypeSet());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001298 if (isLeaf()) return;
1299 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1300 getChild(i)->RemoveAllTypes();
1301}
1302
1303
Chris Lattner8cab0212008-01-05 22:25:12 +00001304/// SubstituteFormalArguments - Replace the formal arguments in this tree
1305/// with actual values specified by ArgMap.
1306void TreePatternNode::
1307SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1308 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001309
Chris Lattner8cab0212008-01-05 22:25:12 +00001310 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1311 TreePatternNode *Child = getChild(i);
1312 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001313 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001314 // Note that, when substituting into an output pattern, Val might be an
1315 // UnsetInit.
1316 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1317 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001318 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001319 TreePatternNode *NewChild = ArgMap[Child->getName()];
1320 assert(NewChild && "Couldn't find formal argument!");
1321 assert((Child->getPredicateFns().empty() ||
1322 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1323 "Non-empty child predicate clobbered!");
1324 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001325 }
1326 } else {
1327 getChild(i)->SubstituteFormalArguments(ArgMap);
1328 }
1329 }
1330}
1331
1332
1333/// InlinePatternFragments - If this pattern refers to any pattern
1334/// fragments, inline them into place, giving us a pattern without any
1335/// PatFrag references.
1336TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001337 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001338 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001339
1340 if (isLeaf())
1341 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001342 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001343
Chris Lattner8cab0212008-01-05 22:25:12 +00001344 if (!Op->isSubClassOf("PatFrag")) {
1345 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001346 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1347 TreePatternNode *Child = getChild(i);
1348 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1349
1350 assert((Child->getPredicateFns().empty() ||
1351 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1352 "Non-empty child predicate clobbered!");
1353
1354 setChild(i, NewChild);
1355 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001356 return this;
1357 }
1358
1359 // Otherwise, we found a reference to a fragment. First, look up its
1360 // TreePattern record.
1361 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001362
Chris Lattner8cab0212008-01-05 22:25:12 +00001363 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001364 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001365 TP.error("'" + Op->getName() + "' fragment requires " +
1366 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001367 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001368 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001369
1370 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1371
Chris Lattner514e2922011-04-17 21:38:24 +00001372 TreePredicateFn PredFn(Frag);
1373 if (!PredFn.isAlwaysTrue())
1374 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001375
Chris Lattner8cab0212008-01-05 22:25:12 +00001376 // Resolve formal arguments to their actual value.
1377 if (Frag->getNumArgs()) {
1378 // Compute the map of formal to actual arguments.
1379 std::map<std::string, TreePatternNode*> ArgMap;
1380 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1381 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001382
Chris Lattner8cab0212008-01-05 22:25:12 +00001383 FragTree->SubstituteFormalArguments(ArgMap);
1384 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001385
Chris Lattner8cab0212008-01-05 22:25:12 +00001386 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001387 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1388 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001389
1390 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001391 for (const TreePredicateFn &Pred : getPredicateFns())
1392 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001393
Chris Lattner8cab0212008-01-05 22:25:12 +00001394 // Get a new copy of this fragment to stitch into here.
1395 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001396
Chris Lattner2e253b42008-06-30 03:02:03 +00001397 // The fragment we inlined could have recursive inlining that is needed. See
1398 // if there are any pattern fragments in it and inline them as needed.
1399 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001400}
1401
1402/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001403/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001404/// references from the register file information, for example.
1405///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001406/// When Unnamed is set, return the type of a DAG operand with no name, such as
1407/// the F8RC register class argument in:
1408///
1409/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1410///
1411/// When Unnamed is false, return the type of a named DAG operand such as the
1412/// GPR:$src operand above.
1413///
Chris Lattnerf1447252010-03-19 21:37:09 +00001414static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001415 bool NotRegisters,
1416 bool Unnamed,
1417 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001418 // Check to see if this is a register operand.
1419 if (R->isSubClassOf("RegisterOperand")) {
1420 assert(ResNo == 0 && "Regoperand ref only has one result!");
1421 if (NotRegisters)
1422 return EEVT::TypeSet(); // Unknown.
1423 Record *RegClass = R->getValueAsDef("RegClass");
1424 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1425 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1426 }
1427
Chris Lattnercabe0372010-03-15 06:00:16 +00001428 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001429 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001430 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001431 // An unnamed register class represents itself as an i32 immediate, for
1432 // example on a COPY_TO_REGCLASS instruction.
1433 if (Unnamed)
1434 return EEVT::TypeSet(MVT::i32, TP);
1435
1436 // In a named operand, the register class provides the possible set of
1437 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001438 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001439 return EEVT::TypeSet(); // Unknown.
1440 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1441 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001442 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001443
Chris Lattner6070ee22010-03-23 23:50:31 +00001444 if (R->isSubClassOf("PatFrag")) {
1445 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001446 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001447 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001448 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001449
Chris Lattner6070ee22010-03-23 23:50:31 +00001450 if (R->isSubClassOf("Register")) {
1451 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001452 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001453 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001454 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001455 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001456 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001457
1458 if (R->isSubClassOf("SubRegIndex")) {
1459 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00001460 return EEVT::TypeSet(MVT::i32, TP);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001461 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001462
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001463 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001464 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001465 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1466 //
1467 // (sext_inreg GPR:$src, i16)
1468 // ~~~
1469 if (Unnamed)
1470 return EEVT::TypeSet(MVT::Other, TP);
1471 // With a name, the ValueType simply provides the type of the named
1472 // variable.
1473 //
1474 // (sext_inreg i32:$src, i16)
1475 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001476 if (NotRegisters)
1477 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001478 return EEVT::TypeSet(getValueType(R), TP);
1479 }
1480
1481 if (R->isSubClassOf("CondCode")) {
1482 assert(ResNo == 0 && "This node only has one result!");
1483 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001484 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001485 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001486
Chris Lattner6070ee22010-03-23 23:50:31 +00001487 if (R->isSubClassOf("ComplexPattern")) {
1488 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001489 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001490 return EEVT::TypeSet(); // Unknown.
1491 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1492 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001493 }
1494 if (R->isSubClassOf("PointerLikeRegClass")) {
1495 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001496 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001497 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001498
Chris Lattner6070ee22010-03-23 23:50:31 +00001499 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1500 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001501 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001502 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001503 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001504
Tim Northoverc807a172014-05-20 11:52:46 +00001505 if (R->isSubClassOf("Operand"))
1506 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1507
Chris Lattner8cab0212008-01-05 22:25:12 +00001508 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001509 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001510}
1511
Chris Lattner89c65662008-01-06 05:36:50 +00001512
1513/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1514/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1515const CodeGenIntrinsic *TreePatternNode::
1516getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1517 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1518 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1519 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001520 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001521
Sean Silva88eb8dd2012-10-10 20:24:47 +00001522 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001523 return &CDP.getIntrinsicInfo(IID);
1524}
1525
Chris Lattner53c39ba2010-02-14 22:22:58 +00001526/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1527/// return the ComplexPattern information, otherwise return null.
1528const ComplexPattern *
1529TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001530 Record *Rec;
1531 if (isLeaf()) {
1532 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1533 if (!DI)
1534 return nullptr;
1535 Rec = DI->getDef();
1536 } else
1537 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001538
Tim Northoverc807a172014-05-20 11:52:46 +00001539 if (!Rec->isSubClassOf("ComplexPattern"))
1540 return nullptr;
1541 return &CGP.getComplexPattern(Rec);
1542}
1543
1544unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1545 // A ComplexPattern specifically declares how many results it fills in.
1546 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1547 return CP->getNumOperands();
1548
1549 // If MIOperandInfo is specified, that gives the count.
1550 if (isLeaf()) {
1551 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1552 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1553 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1554 if (MIOps->getNumArgs())
1555 return MIOps->getNumArgs();
1556 }
1557 }
1558
1559 // Otherwise there is just one result.
1560 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001561}
1562
1563/// NodeHasProperty - Return true if this node has the specified property.
1564bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001565 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001566 if (isLeaf()) {
1567 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1568 return CP->hasProperty(Property);
1569 return false;
1570 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001571
Chris Lattner53c39ba2010-02-14 22:22:58 +00001572 Record *Operator = getOperator();
1573 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001574
Chris Lattner53c39ba2010-02-14 22:22:58 +00001575 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1576}
1577
1578
1579
1580
1581/// TreeHasProperty - Return true if any node in this tree has the specified
1582/// property.
1583bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001584 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001585 if (NodeHasProperty(Property, CGP))
1586 return true;
1587 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1588 if (getChild(i)->TreeHasProperty(Property, CGP))
1589 return true;
1590 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001591}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001592
Evan Cheng49bad4c2008-06-16 20:29:38 +00001593/// isCommutativeIntrinsic - Return true if the node corresponds to a
1594/// commutative intrinsic.
1595bool
1596TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1597 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1598 return Int->isCommutative;
1599 return false;
1600}
1601
Matt Arsenaulteb492162014-11-02 23:46:51 +00001602static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1603 if (!N->isLeaf())
1604 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001605
Matt Arsenaulteb492162014-11-02 23:46:51 +00001606 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1607 if (DI && DI->getDef()->isSubClassOf(Class))
1608 return true;
1609
1610 return false;
1611}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001612
1613static void emitTooManyOperandsError(TreePattern &TP,
1614 StringRef InstName,
1615 unsigned Expected,
1616 unsigned Actual) {
1617 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1618 " operands but expected only " + Twine(Expected) + "!");
1619}
1620
1621static void emitTooFewOperandsError(TreePattern &TP,
1622 StringRef InstName,
1623 unsigned Actual) {
1624 TP.error("Instruction '" + InstName +
1625 "' expects more than the provided " + Twine(Actual) + " operands!");
1626}
1627
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001628/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001629/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001630/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001631bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001632 if (TP.hasError())
1633 return false;
1634
Chris Lattnerab3242f2008-01-06 01:10:31 +00001635 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001636 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001637 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001638 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001639 bool MadeChange = false;
1640 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1641 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001642 NotRegisters,
1643 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001644 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001645 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001646
Sean Silvafb509ed2012-10-10 20:24:43 +00001647 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001648 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001649
Chris Lattnerf1447252010-03-19 21:37:09 +00001650 // Int inits are always integers. :)
1651 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001652
Chris Lattnerf1447252010-03-19 21:37:09 +00001653 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001654 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001655
Chris Lattnerf1447252010-03-19 21:37:09 +00001656 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001657 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1658 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001659
Craig Topper95198f42013-09-25 06:37:18 +00001660 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001661 // Make sure that the value is representable for this type.
1662 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001663
Richard Smith228e6d42012-08-24 23:29:28 +00001664 // Check that the value doesn't use more bits than we have. It must either
1665 // be a sign- or zero-extended equivalent of the original.
1666 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1667 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001668 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001669
Richard Smith228e6d42012-08-24 23:29:28 +00001670 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001671 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001672 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001673 }
1674 return false;
1675 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001676
Chris Lattner8cab0212008-01-05 22:25:12 +00001677 // special handling for set, which isn't really an SDNode.
1678 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001679 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1680 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001681 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001682
Chris Lattnerf1447252010-03-19 21:37:09 +00001683 TreePatternNode *SetVal = getChild(NC-1);
1684 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1685
Elena Demikhovsky09954792015-03-01 08:23:41 +00001686 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001687 TreePatternNode *Child = getChild(i);
1688 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001689
Chris Lattner8cab0212008-01-05 22:25:12 +00001690 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001691 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1692 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001693 }
1694 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001695 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001696
Chris Lattner5c2182e2010-03-27 02:53:27 +00001697 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001698 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1699
Chris Lattner8cab0212008-01-05 22:25:12 +00001700 bool MadeChange = false;
1701 for (unsigned i = 0; i < getNumChildren(); ++i)
1702 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001703 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001704 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001705
Chris Lattneree820ac2010-02-23 05:51:07 +00001706 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001707 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001708
Chris Lattner8cab0212008-01-05 22:25:12 +00001709 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001710 unsigned NumRetVTs = Int->IS.RetVTs.size();
1711 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001712
Bill Wendling91821472008-11-13 09:08:33 +00001713 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001714 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001715
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001716 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001717 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001718 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001719 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001720 return false;
1721 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001722
1723 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001724 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001725
Chris Lattnerf1447252010-03-19 21:37:09 +00001726 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1727 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001728
Chris Lattnerf1447252010-03-19 21:37:09 +00001729 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1730 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1731 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001732 }
1733 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001734 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001735
Chris Lattneree820ac2010-02-23 05:51:07 +00001736 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001737 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001738
Chris Lattner135091b2010-03-28 08:48:47 +00001739 // Check that the number of operands is sane. Negative operands -> varargs.
1740 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001741 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001742 TP.error(getOperator()->getName() + " node requires exactly " +
1743 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001744 return false;
1745 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001746
Chris Lattner8cab0212008-01-05 22:25:12 +00001747 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1748 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1749 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001750 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001751 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001752
Chris Lattneree820ac2010-02-23 05:51:07 +00001753 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001754 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001755 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001756 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001757
Chris Lattnerd44966f2010-03-27 19:15:02 +00001758 bool MadeChange = false;
1759
1760 // Apply the result types to the node, these come from the things in the
1761 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00001762 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1763 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001764 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1765 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001766
Chris Lattnerd44966f2010-03-27 19:15:02 +00001767 // If the instruction has implicit defs, we apply the first one as a result.
1768 // FIXME: This sucks, it should apply all implicit defs.
1769 if (!InstInfo.ImplicitDefs.empty()) {
1770 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001771
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001772 // FIXME: Generalize to multiple possible types and multiple possible
1773 // ImplicitDefs.
1774 MVT::SimpleValueType VT =
1775 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001776
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001777 if (VT != MVT::Other)
1778 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001779 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001780
Chris Lattnercabe0372010-03-15 06:00:16 +00001781 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1782 // be the same.
1783 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001784 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1785 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1786 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00001787 } else if (getOperator()->getName() == "REG_SEQUENCE") {
1788 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
1789 // variadic.
1790
1791 unsigned NChild = getNumChildren();
1792 if (NChild < 3) {
1793 TP.error("REG_SEQUENCE requires at least 3 operands!");
1794 return false;
1795 }
1796
1797 if (NChild % 2 == 0) {
1798 TP.error("REG_SEQUENCE requires an odd number of operands!");
1799 return false;
1800 }
1801
1802 if (!isOperandClass(getChild(0), "RegisterClass")) {
1803 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
1804 return false;
1805 }
1806
1807 for (unsigned I = 1; I < NChild; I += 2) {
1808 TreePatternNode *SubIdxChild = getChild(I + 1);
1809 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
1810 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
1811 itostr(I + 1) + "!");
1812 return false;
1813 }
1814 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001815 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001816
1817 unsigned ChildNo = 0;
1818 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1819 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001820
Chris Lattner8cab0212008-01-05 22:25:12 +00001821 // If the instruction expects a predicate or optional def operand, we
1822 // codegen this by setting the operand to it's default value if it has a
1823 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001824 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001825 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1826 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001827
Chris Lattner8cab0212008-01-05 22:25:12 +00001828 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001829 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001830 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001831 return false;
1832 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001833
Chris Lattner8cab0212008-01-05 22:25:12 +00001834 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001835 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001836
1837 // If the operand has sub-operands, they may be provided by distinct
1838 // child patterns, so attempt to match each sub-operand separately.
1839 if (OperandNode->isSubClassOf("Operand")) {
1840 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1841 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1842 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00001843 // a single ComplexPattern-related Operand.
1844
1845 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00001846 // Match first sub-operand against the child we already have.
1847 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1848 MadeChange |=
1849 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1850
1851 // And the remaining sub-operands against subsequent children.
1852 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1853 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001854 emitTooFewOperandsError(TP, getOperator()->getName(),
1855 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00001856 return false;
1857 }
1858 Child = getChild(ChildNo++);
1859
1860 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1861 MadeChange |=
1862 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1863 }
1864 continue;
1865 }
1866 }
1867 }
1868
1869 // If we didn't match by pieces above, attempt to match the whole
1870 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001871 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001872 }
Christopher Lamba7312392008-03-11 09:33:47 +00001873
Matt Arsenaulteb492162014-11-02 23:46:51 +00001874 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001875 emitTooManyOperandsError(TP, getOperator()->getName(),
1876 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001877 return false;
1878 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001879
Ulrich Weigande618abd2013-03-19 19:51:09 +00001880 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1881 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001882 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001883 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001884
Tim Northoverc807a172014-05-20 11:52:46 +00001885 if (getOperator()->isSubClassOf("ComplexPattern")) {
1886 bool MadeChange = false;
1887
1888 for (unsigned i = 0; i < getNumChildren(); ++i)
1889 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1890
1891 return MadeChange;
1892 }
1893
Chris Lattneree820ac2010-02-23 05:51:07 +00001894 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001895
Chris Lattneree820ac2010-02-23 05:51:07 +00001896 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001897 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001898 TP.error("Node transform '" + getOperator()->getName() +
1899 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001900 return false;
1901 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001902
Chris Lattnercabe0372010-03-15 06:00:16 +00001903 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1904
Jim Grosbach65586fe2010-12-21 16:16:00 +00001905
Chris Lattneree820ac2010-02-23 05:51:07 +00001906 // If either the output or input of the xform does not have exact
1907 // type info. We assume they must be the same. Otherwise, it is perfectly
1908 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001909#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001910 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001911 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1912 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001913 return MadeChange;
1914 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001915#endif
1916 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001917}
1918
1919/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1920/// RHS of a commutative operation, not the on LHS.
1921static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1922 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1923 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001924 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001925 return true;
1926 return false;
1927}
1928
1929
1930/// canPatternMatch - If it is impossible for this pattern to match on this
1931/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00001932/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00001933/// that can never possibly work), and to prevent the pattern permuter from
1934/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001935bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00001936 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001937 if (isLeaf()) return true;
1938
1939 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1940 if (!getChild(i)->canPatternMatch(Reason, CDP))
1941 return false;
1942
1943 // If this is an intrinsic, handle cases that would make it not match. For
1944 // example, if an operand is required to be an immediate.
1945 if (getOperator()->isSubClassOf("Intrinsic")) {
1946 // TODO:
1947 return true;
1948 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001949
Tim Northoverc807a172014-05-20 11:52:46 +00001950 if (getOperator()->isSubClassOf("ComplexPattern"))
1951 return true;
1952
Chris Lattner8cab0212008-01-05 22:25:12 +00001953 // If this node is a commutative operator, check that the LHS isn't an
1954 // immediate.
1955 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00001956 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1957 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001958 // Scan all of the operands of the node and make sure that only the last one
1959 // is a constant node, unless the RHS also is.
1960 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng49bad4c2008-06-16 20:29:38 +00001961 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1962 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00001963 if (OnlyOnRHSOfCommutative(getChild(i))) {
1964 Reason="Immediate value must be on the RHS of commutative operators!";
1965 return false;
1966 }
1967 }
1968 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001969
Chris Lattner8cab0212008-01-05 22:25:12 +00001970 return true;
1971}
1972
1973//===----------------------------------------------------------------------===//
1974// TreePattern implementation
1975//
1976
David Greeneaf8ee2c2011-07-29 22:43:06 +00001977TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001978 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1979 isInputPattern(isInput), HasError(false) {
Craig Topperef0578a2015-06-02 04:15:51 +00001980 for (Init *I : RawPat->getValues())
1981 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001982}
1983
David Greeneaf8ee2c2011-07-29 22:43:06 +00001984TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001985 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1986 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001987 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001988}
1989
David Blaikiecf195302014-11-17 22:55:41 +00001990TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001991 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1992 isInputPattern(isInput), HasError(false) {
David Blaikiecf195302014-11-17 22:55:41 +00001993 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00001994}
1995
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00001996void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001997 if (HasError)
1998 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00001999 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002000 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2001 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002002}
2003
Chris Lattnercabe0372010-03-15 06:00:16 +00002004void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00002005 for (TreePatternNode *Tree : Trees)
2006 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00002007}
2008
2009void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2010 if (!N->getName().empty())
2011 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002012
Chris Lattnercabe0372010-03-15 06:00:16 +00002013 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2014 ComputeNamedNodes(N->getChild(i));
2015}
2016
David Blaikiecf195302014-11-17 22:55:41 +00002017
2018TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002019 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002020 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002021
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002022 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002023 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002024 /// (foo GPR, imm) -> (foo GPR, (imm))
2025 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002026 return ParseTreePattern(
2027 DagInit::get(DI, "",
David Greeneaf8ee2c2011-07-29 22:43:06 +00002028 std::vector<std::pair<Init*, std::string> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002029 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002030
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002031 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002032 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002033 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002034 if (OpName.empty())
2035 error("'node' argument requires a name to match with operand list");
2036 Args.push_back(OpName);
2037 }
2038
2039 Res->setName(OpName);
2040 return Res;
2041 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002042
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002043 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002044 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002045 if (OpName.empty())
2046 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002047 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002048 Args.push_back(OpName);
2049 Res->setName(OpName);
2050 return Res;
2051 }
2052
Sean Silvafb509ed2012-10-10 20:24:43 +00002053 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002054 if (!OpName.empty())
2055 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002056 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002057 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002058
Sean Silvafb509ed2012-10-10 20:24:43 +00002059 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002060 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002061 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002062 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002063 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002064 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002065 }
2066
Sean Silvafb509ed2012-10-10 20:24:43 +00002067 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002068 if (!Dag) {
2069 TheInit->dump();
2070 error("Pattern has unexpected init kind!");
2071 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002072 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002073 if (!OpDef) error("Pattern has unexpected operator type!");
2074 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002075
Chris Lattner8cab0212008-01-05 22:25:12 +00002076 if (Operator->isSubClassOf("ValueType")) {
2077 // If the operator is a ValueType, then this must be "type cast" of a leaf
2078 // node.
2079 if (Dag->getNumArgs() != 1)
2080 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002081
David Blaikiecf195302014-11-17 22:55:41 +00002082 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002083
Chris Lattner8cab0212008-01-05 22:25:12 +00002084 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002085 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
2086 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002087
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002088 if (!OpName.empty())
2089 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002090 return New;
2091 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002092
Chris Lattner8cab0212008-01-05 22:25:12 +00002093 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002094 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002095 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002096 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002097 !Operator->isSubClassOf("SDNodeXForm") &&
2098 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002099 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002100 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002101 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002102 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002103
Chris Lattner8cab0212008-01-05 22:25:12 +00002104 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002105 if (isInputPattern) {
2106 if (Operator->isSubClassOf("Instruction") ||
2107 Operator->isSubClassOf("SDNodeXForm"))
2108 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2109 } else {
2110 if (Operator->isSubClassOf("Intrinsic"))
2111 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002112
Chris Lattner2e9eae12010-03-28 06:57:56 +00002113 if (Operator->isSubClassOf("SDNode") &&
2114 Operator->getName() != "imm" &&
2115 Operator->getName() != "fpimm" &&
2116 Operator->getName() != "tglobaltlsaddr" &&
2117 Operator->getName() != "tconstpool" &&
2118 Operator->getName() != "tjumptable" &&
2119 Operator->getName() != "tframeindex" &&
2120 Operator->getName() != "texternalsym" &&
2121 Operator->getName() != "tblockaddress" &&
2122 Operator->getName() != "tglobaladdr" &&
2123 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002124 Operator->getName() != "vt" &&
2125 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002126 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2127 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002128
Chris Lattner8cab0212008-01-05 22:25:12 +00002129 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002130
2131 // Parse all the operands.
2132 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
David Blaikiecf195302014-11-17 22:55:41 +00002133 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002134
Chris Lattner8cab0212008-01-05 22:25:12 +00002135 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002136 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002137 // convert the intrinsic name to a number.
2138 if (Operator->isSubClassOf("Intrinsic")) {
2139 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2140 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2141
2142 // If this intrinsic returns void, it must have side-effects and thus a
2143 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002144 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002145 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002146 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002147 // Has side-effects, requires chain.
2148 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002149 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002150 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002151
David Greenee32ebf22011-07-29 19:07:07 +00002152 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002153 Children.insert(Children.begin(), IIDNode);
2154 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002155
Tim Northoverc807a172014-05-20 11:52:46 +00002156 if (Operator->isSubClassOf("ComplexPattern")) {
2157 for (unsigned i = 0; i < Children.size(); ++i) {
2158 TreePatternNode *Child = Children[i];
2159
2160 if (Child->getName().empty())
2161 error("All arguments to a ComplexPattern must be named");
2162
2163 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2164 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2165 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2166 auto OperandId = std::make_pair(Operator, i);
2167 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2168 if (PrevOp != ComplexPatternOperands.end()) {
2169 if (PrevOp->getValue() != OperandId)
2170 error("All ComplexPattern operands must appear consistently: "
2171 "in the same order in just one ComplexPattern instance.");
2172 } else
2173 ComplexPatternOperands[Child->getName()] = OperandId;
2174 }
2175 }
2176
Chris Lattnerf1447252010-03-19 21:37:09 +00002177 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002178 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002179 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002180
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002181 if (!Dag->getName().empty()) {
2182 assert(Result->getName().empty());
2183 Result->setName(Dag->getName());
2184 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002185 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002186}
2187
Chris Lattnera787c9e2010-03-28 08:38:32 +00002188/// SimplifyTree - See if we can simplify this tree to eliminate something that
2189/// will never match in favor of something obvious that will. This is here
2190/// strictly as a convenience to target authors because it allows them to write
2191/// more type generic things and have useless type casts fold away.
2192///
2193/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002194static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002195 if (N->isLeaf())
2196 return false;
2197
2198 // If we have a bitconvert with a resolved type and if the source and
2199 // destination types are the same, then the bitconvert is useless, remove it.
2200 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002201 N->getExtType(0).isConcrete() &&
2202 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2203 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002204 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002205 SimplifyTree(N);
2206 return true;
2207 }
2208
2209 // Walk all children.
2210 bool MadeChange = false;
2211 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002212 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002213 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002214 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002215 }
2216 return MadeChange;
2217}
2218
2219
2220
Chris Lattner8cab0212008-01-05 22:25:12 +00002221/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002222/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002223/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002224bool TreePattern::
2225InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2226 if (NamedNodes.empty())
2227 ComputeNamedNodes();
2228
Chris Lattner8cab0212008-01-05 22:25:12 +00002229 bool MadeChange = true;
2230 while (MadeChange) {
2231 MadeChange = false;
Craig Topper306cb122015-11-22 20:46:24 +00002232 for (TreePatternNode *Tree : Trees) {
2233 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2234 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002235 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002236
2237 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002238 for (auto &Entry : NamedNodes) {
2239 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002240
Chris Lattnercabe0372010-03-15 06:00:16 +00002241 // If we have input named node types, propagate their types to the named
2242 // values here.
2243 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002244 if (!InNamedTypes->count(Entry.getKey())) {
2245 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002246 "' in output pattern but not input pattern");
2247 return true;
2248 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002249
2250 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002251 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002252
2253 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002254 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002255 // If this node is a register class, and it is the root of the pattern
2256 // then we're mapping something onto an input register. We allow
2257 // changing the type of the input register in this case. This allows
2258 // us to match things like:
2259 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002260 if (Node == Trees[0] && Node->isLeaf()) {
2261 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002262 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2263 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002264 continue;
2265 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002266
Craig Topper306cb122015-11-22 20:46:24 +00002267 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002268 InNodes[0]->getNumTypes() == 1 &&
2269 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002270 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2271 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002272 }
2273 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002274
Chris Lattnercabe0372010-03-15 06:00:16 +00002275 // If there are multiple nodes with the same name, they must all have the
2276 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002277 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002278 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002279 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002280 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002281 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002282
Chris Lattnerf1447252010-03-19 21:37:09 +00002283 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2284 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002285 }
2286 }
2287 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002288 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002289
Chris Lattner8cab0212008-01-05 22:25:12 +00002290 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002291 for (const TreePatternNode *Tree : Trees)
2292 HasUnresolvedTypes |= Tree->ContainsUnresolvedType();
Chris Lattner8cab0212008-01-05 22:25:12 +00002293 return !HasUnresolvedTypes;
2294}
2295
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002296void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002297 OS << getRecord()->getName();
2298 if (!Args.empty()) {
2299 OS << "(" << Args[0];
2300 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2301 OS << ", " << Args[i];
2302 OS << ")";
2303 }
2304 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002305
Chris Lattner8cab0212008-01-05 22:25:12 +00002306 if (Trees.size() > 1)
2307 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002308 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002309 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002310 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002311 OS << "\n";
2312 }
2313
2314 if (Trees.size() > 1)
2315 OS << "]\n";
2316}
2317
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002318void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002319
2320//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002321// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002322//
2323
Jim Grosbach65586fe2010-12-21 16:16:00 +00002324CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002325 Records(R), Target(R) {
2326
Dale Johannesenb842d522009-02-05 01:49:45 +00002327 Intrinsics = LoadIntrinsics(Records, false);
2328 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002329 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002330 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002331 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002332 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002333 ParseDefaultOperands();
2334 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002335 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002336 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002337
Chris Lattner8cab0212008-01-05 22:25:12 +00002338 // Generate variants. For example, commutative patterns can match
2339 // multiple ways. Add them to PatternsToMatch as well.
2340 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002341
2342 // Infer instruction flags. For example, we can detect loads,
2343 // stores, and side effects in many cases by examining an
2344 // instruction's pattern.
2345 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002346
2347 // Verify that instruction flags match the patterns.
2348 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002349}
2350
Chris Lattnerab3242f2008-01-06 01:10:31 +00002351Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002352 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002353 if (!N || !N->isSubClassOf("SDNode"))
2354 PrintFatalError("Error getting SDNode '" + Name + "'!");
2355
Chris Lattner8cab0212008-01-05 22:25:12 +00002356 return N;
2357}
2358
2359// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002360void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002361 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2362 while (!Nodes.empty()) {
2363 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2364 Nodes.pop_back();
2365 }
2366
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002367 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002368 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2369 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2370 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2371}
2372
2373/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2374/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002375void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002376 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2377 while (!Xforms.empty()) {
2378 Record *XFormNode = Xforms.back();
2379 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00002380 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002381 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002382
2383 Xforms.pop_back();
2384 }
2385}
2386
Chris Lattnerab3242f2008-01-06 01:10:31 +00002387void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002388 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2389 while (!AMs.empty()) {
2390 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2391 AMs.pop_back();
2392 }
2393}
2394
2395
2396/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2397/// file, building up the PatternFragments map. After we've collected them all,
2398/// inline fragments together as necessary, so that there are no references left
2399/// inside a pattern fragment to a pattern fragment.
2400///
Hal Finkel2756dc12014-02-28 00:26:56 +00002401void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002402 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002403
Chris Lattnere7170df2008-01-05 22:43:57 +00002404 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002405 for (Record *Frag : Fragments) {
2406 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002407 continue;
2408
Craig Topper306cb122015-11-22 20:46:24 +00002409 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002410 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002411 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2412 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002413 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002414
Chris Lattnere7170df2008-01-05 22:43:57 +00002415 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002416 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002417 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002418
Chris Lattnere7170df2008-01-05 22:43:57 +00002419 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002420 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002421
Chris Lattner8cab0212008-01-05 22:25:12 +00002422 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002423 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002424 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002425 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002426 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002427 if (!OpsOp ||
2428 (OpsOp->getDef()->getName() != "ops" &&
2429 OpsOp->getDef()->getName() != "outs" &&
2430 OpsOp->getDef()->getName() != "ins"))
2431 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002432
2433 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002434 Args.clear();
2435 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002436 if (!isa<DefInit>(OpsList->getArg(j)) ||
2437 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002438 P->error("Operands list should all be 'node' values.");
2439 if (OpsList->getArgName(j).empty())
2440 P->error("Operands list should have names for each operand!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002441 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner8cab0212008-01-05 22:25:12 +00002442 P->error("'" + OpsList->getArgName(j) +
2443 "' does not occur in pattern or was multiply specified!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002444 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner8cab0212008-01-05 22:25:12 +00002445 Args.push_back(OpsList->getArgName(j));
2446 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002447
Chris Lattnere7170df2008-01-05 22:43:57 +00002448 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002449 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002450 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002451
Chris Lattnere7170df2008-01-05 22:43:57 +00002452 // If there is a code init for this fragment, keep track of the fact that
2453 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002454 TreePredicateFn PredFn(P);
2455 if (!PredFn.isAlwaysTrue())
2456 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002457
Chris Lattner8cab0212008-01-05 22:25:12 +00002458 // If there is a node transformation corresponding to this, keep track of
2459 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002460 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002461 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2462 P->getOnlyTree()->setTransformFn(Transform);
2463 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002464
Chris Lattner8cab0212008-01-05 22:25:12 +00002465 // Now that we've parsed all of the tree fragments, do a closure on them so
2466 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002467 for (Record *Frag : Fragments) {
2468 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002469 continue;
2470
Craig Topper306cb122015-11-22 20:46:24 +00002471 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002472 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002473
Chris Lattner8cab0212008-01-05 22:25:12 +00002474 // Infer as many types as possible. Don't worry about it if we don't infer
2475 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002476 ThePat.InferAllTypes();
2477 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002478
Chris Lattner8cab0212008-01-05 22:25:12 +00002479 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002480 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002481 }
2482}
2483
Chris Lattnerab3242f2008-01-06 01:10:31 +00002484void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002485 std::vector<Record*> DefaultOps;
2486 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002487
2488 // Find some SDNode.
2489 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002490 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002491
Tom Stellardb7246a72012-09-06 14:15:52 +00002492 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2493 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002494
Tom Stellardb7246a72012-09-06 14:15:52 +00002495 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2496 // SomeSDnode so that we can parse this.
2497 std::vector<std::pair<Init*, std::string> > Ops;
2498 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2499 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2500 DefaultInfo->getArgName(op)));
2501 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002502
Tom Stellardb7246a72012-09-06 14:15:52 +00002503 // Create a TreePattern to parse this.
2504 TreePattern P(DefaultOps[i], DI, false, *this);
2505 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002506
Tom Stellardb7246a72012-09-06 14:15:52 +00002507 // Copy the operands over into a DAGDefaultOperand.
2508 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002509
Tom Stellardb7246a72012-09-06 14:15:52 +00002510 TreePatternNode *T = P.getTree(0);
2511 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2512 TreePatternNode *TPN = T->getChild(op);
2513 while (TPN->ApplyTypeConstraints(P, false))
2514 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002515
Tom Stellardb7246a72012-09-06 14:15:52 +00002516 if (TPN->ContainsUnresolvedType()) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002517 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2518 DefaultOps[i]->getName() +
2519 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002520 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002521 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002522 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002523
2524 // Insert it into the DefaultOperands map so we can find it later.
2525 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002526 }
2527}
2528
2529/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2530/// instruction input. Return true if this is a real use.
2531static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002532 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002533 // No name -> not interesting.
2534 if (Pat->getName().empty()) {
2535 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002536 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002537 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2538 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002539 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002540 }
2541 return false;
2542 }
2543
2544 Record *Rec;
2545 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002546 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002547 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2548 Rec = DI->getDef();
2549 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002550 Rec = Pat->getOperator();
2551 }
2552
2553 // SRCVALUE nodes are ignored.
2554 if (Rec->getName() == "srcvalue")
2555 return false;
2556
2557 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2558 if (!Slot) {
2559 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002560 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002561 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002562 Record *SlotRec;
2563 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002564 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002565 } else {
2566 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2567 SlotRec = Slot->getOperator();
2568 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002569
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002570 // Ensure that the inputs agree if we've already seen this input.
2571 if (Rec != SlotRec)
2572 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002573 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002574 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002575 return true;
2576}
2577
2578/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2579/// part of "I", the instruction), computing the set of inputs and outputs of
2580/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002581void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002582FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2583 std::map<std::string, TreePatternNode*> &InstInputs,
2584 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002585 std::vector<Record*> &InstImpResults) {
2586 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002587 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002588 if (!isUse && Pat->getTransformFn())
2589 I->error("Cannot specify a transform function for a non-input value!");
2590 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002591 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002592
Chris Lattnerf2d70992010-02-17 06:53:36 +00002593 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002594 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2595 TreePatternNode *Dest = Pat->getChild(i);
2596 if (!Dest->isLeaf())
2597 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002598
Sean Silvafb509ed2012-10-10 20:24:43 +00002599 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002600 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2601 I->error("implicitly defined value should be a register!");
2602 InstImpResults.push_back(Val->getDef());
2603 }
2604 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002605 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002606
Chris Lattnerf2d70992010-02-17 06:53:36 +00002607 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002608 // If this is not a set, verify that the children nodes are not void typed,
2609 // and recurse.
2610 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002611 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002612 I->error("Cannot have void nodes inside of patterns!");
2613 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002614 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002615 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002616
Chris Lattner8cab0212008-01-05 22:25:12 +00002617 // If this is a non-leaf node with no children, treat it basically as if
2618 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002619 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002620
Chris Lattner8cab0212008-01-05 22:25:12 +00002621 if (!isUse && Pat->getTransformFn())
2622 I->error("Cannot specify a transform function for a non-input value!");
2623 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002624 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002625
Chris Lattner8cab0212008-01-05 22:25:12 +00002626 // Otherwise, this is a set, validate and collect instruction results.
2627 if (Pat->getNumChildren() == 0)
2628 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002629
Chris Lattner8cab0212008-01-05 22:25:12 +00002630 if (Pat->getTransformFn())
2631 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002632
Chris Lattner8cab0212008-01-05 22:25:12 +00002633 // Check the set destinations.
2634 unsigned NumDests = Pat->getNumChildren()-1;
2635 for (unsigned i = 0; i != NumDests; ++i) {
2636 TreePatternNode *Dest = Pat->getChild(i);
2637 if (!Dest->isLeaf())
2638 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002639
Sean Silvafb509ed2012-10-10 20:24:43 +00002640 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002641 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002642 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002643 continue;
2644 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002645
2646 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002647 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002648 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002649 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002650 if (Dest->getName().empty())
2651 I->error("set destination must have a name!");
2652 if (InstResults.count(Dest->getName()))
2653 I->error("cannot set '" + Dest->getName() +"' multiple times");
2654 InstResults[Dest->getName()] = Dest;
2655 } else if (Val->getDef()->isSubClassOf("Register")) {
2656 InstImpResults.push_back(Val->getDef());
2657 } else {
2658 I->error("set destination should be a register!");
2659 }
2660 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002661
Chris Lattner8cab0212008-01-05 22:25:12 +00002662 // Verify and collect info from the computation.
2663 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002664 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002665}
2666
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002667//===----------------------------------------------------------------------===//
2668// Instruction Analysis
2669//===----------------------------------------------------------------------===//
2670
2671class InstAnalyzer {
2672 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002673public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002674 bool hasSideEffects;
2675 bool mayStore;
2676 bool mayLoad;
2677 bool isBitcast;
2678 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002679
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002680 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2681 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2682 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002683
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002684 void Analyze(const TreePattern *Pat) {
2685 // Assume only the first tree is the pattern. The others are clobber nodes.
2686 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002687 }
2688
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002689 void Analyze(const PatternToMatch *Pat) {
2690 AnalyzeNode(Pat->getSrcPattern());
2691 }
2692
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002693private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002694 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002695 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002696 return false;
2697
2698 if (N->getNumChildren() != 2)
2699 return false;
2700
2701 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002702 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002703 return false;
2704
2705 const TreePatternNode *N1 = N->getChild(1);
2706 if (N1->isLeaf())
2707 return false;
2708 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2709 return false;
2710
2711 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2712 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2713 return false;
2714 return OpInfo.getEnumName() == "ISD::BITCAST";
2715 }
2716
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002717public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002718 void AnalyzeNode(const TreePatternNode *N) {
2719 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002720 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002721 Record *LeafRec = DI->getDef();
2722 // Handle ComplexPattern leaves.
2723 if (LeafRec->isSubClassOf("ComplexPattern")) {
2724 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2725 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2726 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002727 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002728 }
2729 }
2730 return;
2731 }
2732
2733 // Analyze children.
2734 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2735 AnalyzeNode(N->getChild(i));
2736
2737 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002738 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002739 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002740 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002741 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002742
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002743 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002744 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2745 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2746 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2747 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002748
2749 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2750 // If this is an intrinsic, analyze it.
2751 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2752 mayLoad = true;// These may load memory.
2753
Dan Gohmanddb2d652010-08-05 23:36:21 +00002754 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002755 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2756
Dan Gohmanddb2d652010-08-05 23:36:21 +00002757 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002758 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002759 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002760 }
2761 }
2762
2763};
2764
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002765static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002766 const InstAnalyzer &PatInfo,
2767 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002768 bool Error = false;
2769
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002770 // Remember where InstInfo got its flags.
2771 if (InstInfo.hasUndefFlags())
2772 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002773
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002774 // Check explicitly set flags for consistency.
2775 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2776 !InstInfo.hasSideEffects_Unset) {
2777 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2778 // the pattern has no side effects. That could be useful for div/rem
2779 // instructions that may trap.
2780 if (!InstInfo.hasSideEffects) {
2781 Error = true;
2782 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2783 Twine(InstInfo.hasSideEffects));
2784 }
2785 }
2786
2787 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2788 Error = true;
2789 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2790 Twine(InstInfo.mayStore));
2791 }
2792
2793 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2794 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00002795 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002796 if (!InstInfo.mayLoad) {
2797 Error = true;
2798 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2799 Twine(InstInfo.mayLoad));
2800 }
2801 }
2802
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002803 // Transfer inferred flags.
2804 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2805 InstInfo.mayStore |= PatInfo.mayStore;
2806 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002807
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002808 // These flags are silently added without any verification.
2809 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002810
2811 // Don't infer isVariadic. This flag means something different on SDNodes and
2812 // instructions. For example, a CALL SDNode is variadic because it has the
2813 // call arguments as operands, but a CALL instruction is not variadic - it
2814 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002815
2816 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002817}
2818
Jim Grosbach514410b2012-07-17 00:47:06 +00002819/// hasNullFragReference - Return true if the DAG has any reference to the
2820/// null_frag operator.
2821static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002822 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002823 if (!OpDef) return false;
2824 Record *Operator = OpDef->getDef();
2825
2826 // If this is the null fragment, return true.
2827 if (Operator->getName() == "null_frag") return true;
2828 // If any of the arguments reference the null fragment, return true.
2829 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002830 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002831 if (Arg && hasNullFragReference(Arg))
2832 return true;
2833 }
2834
2835 return false;
2836}
2837
2838/// hasNullFragReference - Return true if any DAG in the list references
2839/// the null_frag operator.
2840static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00002841 for (Init *I : LI->getValues()) {
2842 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00002843 assert(DI && "non-dag in an instruction Pattern list?!");
2844 if (hasNullFragReference(DI))
2845 return true;
2846 }
2847 return false;
2848}
2849
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002850/// Get all the instructions in a tree.
2851static void
2852getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2853 if (Tree->isLeaf())
2854 return;
2855 if (Tree->getOperator()->isSubClassOf("Instruction"))
2856 Instrs.push_back(Tree->getOperator());
2857 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2858 getInstructionsInTree(Tree->getChild(i), Instrs);
2859}
2860
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002861/// Check the class of a pattern leaf node against the instruction operand it
2862/// represents.
2863static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2864 Record *Leaf) {
2865 if (OI.Rec == Leaf)
2866 return true;
2867
2868 // Allow direct value types to be used in instruction set patterns.
2869 // The type will be checked later.
2870 if (Leaf->isSubClassOf("ValueType"))
2871 return true;
2872
2873 // Patterns can also be ComplexPattern instances.
2874 if (Leaf->isSubClassOf("ComplexPattern"))
2875 return true;
2876
2877 return false;
2878}
2879
Ahmed Bougacha14107512013-10-28 18:07:21 +00002880const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2881 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002882
Craig Topper0d1fb902015-03-10 03:25:04 +00002883 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002884
Craig Topper0d1fb902015-03-10 03:25:04 +00002885 // Parse the instruction.
2886 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
2887 // Inline pattern fragments into it.
2888 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002889
Craig Topper0d1fb902015-03-10 03:25:04 +00002890 // Infer as many types as possible. If we cannot infer all of them, we can
2891 // never do anything with this instruction pattern: report it to the user.
2892 if (!I->InferAllTypes())
2893 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002894
Craig Topper0d1fb902015-03-10 03:25:04 +00002895 // InstInputs - Keep track of all of the inputs of the instruction, along
2896 // with the record they are declared as.
2897 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002898
Craig Topper0d1fb902015-03-10 03:25:04 +00002899 // InstResults - Keep track of all the virtual registers that are 'set'
2900 // in the instruction, including what reg class they are.
2901 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00002902
Craig Topper0d1fb902015-03-10 03:25:04 +00002903 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002904
Craig Topper0d1fb902015-03-10 03:25:04 +00002905 // Verify that the top-level forms in the instruction are of void type, and
2906 // fill in the InstResults map.
2907 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2908 TreePatternNode *Pat = I->getTree(j);
2909 if (Pat->getNumTypes() != 0)
2910 I->error("Top-level forms in instruction pattern should have"
2911 " void types");
Chris Lattner8cab0212008-01-05 22:25:12 +00002912
Craig Topper0d1fb902015-03-10 03:25:04 +00002913 // Find inputs and outputs, and verify the structure of the uses/defs.
2914 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
2915 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00002916 }
2917
Craig Topper0d1fb902015-03-10 03:25:04 +00002918 // Now that we have inputs and outputs of the pattern, inspect the operands
2919 // list for the instruction. This determines the order that operands are
2920 // added to the machine instruction the node corresponds to.
2921 unsigned NumResults = InstResults.size();
2922
2923 // Parse the operands list from the (ops) list, validating it.
2924 assert(I->getArgList().empty() && "Args list should still be empty here!");
2925
2926 // Check that all of the results occur first in the list.
2927 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00002928 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00002929 for (unsigned i = 0; i != NumResults; ++i) {
2930 if (i == CGI.Operands.size())
2931 I->error("'" + InstResults.begin()->first +
2932 "' set but does not appear in operand list!");
2933 const std::string &OpName = CGI.Operands[i].Name;
2934
2935 // Check that it exists in InstResults.
2936 TreePatternNode *RNode = InstResults[OpName];
2937 if (!RNode)
2938 I->error("Operand $" + OpName + " does not exist in operand list!");
2939
Craig Topper3a8eb892015-03-20 05:09:06 +00002940 ResNodes.push_back(RNode);
2941
Craig Topper0d1fb902015-03-10 03:25:04 +00002942 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
2943 if (!R)
2944 I->error("Operand $" + OpName + " should be a set destination: all "
2945 "outputs must occur before inputs in operand list!");
2946
2947 if (!checkOperandClass(CGI.Operands[i], R))
2948 I->error("Operand $" + OpName + " class mismatch!");
2949
2950 // Remember the return type.
2951 Results.push_back(CGI.Operands[i].Rec);
2952
2953 // Okay, this one checks out.
2954 InstResults.erase(OpName);
2955 }
2956
2957 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2958 // the copy while we're checking the inputs.
2959 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2960
2961 std::vector<TreePatternNode*> ResultNodeOperands;
2962 std::vector<Record*> Operands;
2963 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2964 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
2965 const std::string &OpName = Op.Name;
2966 if (OpName.empty())
2967 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2968
2969 if (!InstInputsCheck.count(OpName)) {
2970 // If this is an operand with a DefaultOps set filled in, we can ignore
2971 // this. When we codegen it, we will do so as always executed.
2972 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
2973 // Does it have a non-empty DefaultOps field? If so, ignore this
2974 // operand.
2975 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2976 continue;
2977 }
2978 I->error("Operand $" + OpName +
2979 " does not appear in the instruction pattern");
2980 }
2981 TreePatternNode *InVal = InstInputsCheck[OpName];
2982 InstInputsCheck.erase(OpName); // It occurred, remove from map.
2983
2984 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
2985 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
2986 if (!checkOperandClass(Op, InRec))
2987 I->error("Operand $" + OpName + "'s register class disagrees"
2988 " between the operand and pattern");
2989 }
2990 Operands.push_back(Op.Rec);
2991
2992 // Construct the result for the dest-pattern operand list.
2993 TreePatternNode *OpNode = InVal->clone();
2994
2995 // No predicate is useful on the result.
2996 OpNode->clearPredicateFns();
2997
2998 // Promote the xform function to be an explicit node if set.
2999 if (Record *Xform = OpNode->getTransformFn()) {
3000 OpNode->setTransformFn(nullptr);
3001 std::vector<TreePatternNode*> Children;
3002 Children.push_back(OpNode);
3003 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3004 }
3005
3006 ResultNodeOperands.push_back(OpNode);
3007 }
3008
3009 if (!InstInputsCheck.empty())
3010 I->error("Input operand $" + InstInputsCheck.begin()->first +
3011 " occurs in pattern but not in operands list!");
3012
3013 TreePatternNode *ResultPattern =
3014 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3015 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003016 // Copy fully inferred output node types to instruction result pattern.
3017 for (unsigned i = 0; i != NumResults; ++i) {
3018 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3019 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3020 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003021
3022 // Create and insert the instruction.
3023 // FIXME: InstImpResults should not be part of DAGInstruction.
3024 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3025 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3026
3027 // Use a temporary tree pattern to infer all types and make sure that the
3028 // constructed result is correct. This depends on the instruction already
3029 // being inserted into the DAGInsts map.
3030 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3031 Temp.InferAllTypes(&I->getNamedNodesMap());
3032
3033 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3034 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3035
3036 return TheInsertedInst;
3037}
3038
Ahmed Bougacha14107512013-10-28 18:07:21 +00003039/// ParseInstructions - Parse all of the instructions, inlining and resolving
3040/// any fragments involved. This populates the Instructions list with fully
3041/// resolved instructions.
3042void CodeGenDAGPatterns::ParseInstructions() {
3043 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3044
Craig Topper306cb122015-11-22 20:46:24 +00003045 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003046 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003047
Craig Topper306cb122015-11-22 20:46:24 +00003048 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3049 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003050
3051 // If there is no pattern, only collect minimal information about the
3052 // instruction for its operand list. We have to assume that there is one
3053 // result, as we have no detailed info. A pattern which references the
3054 // null_frag operator is as-if no pattern were specified. Normally this
3055 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3056 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003057 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003058 std::vector<Record*> Results;
3059 std::vector<Record*> Operands;
3060
Craig Topper306cb122015-11-22 20:46:24 +00003061 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003062
3063 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003064 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3065 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003066
Craig Topper3a8eb892015-03-20 05:09:06 +00003067 // The rest are inputs.
3068 for (unsigned j = InstInfo.Operands.NumDefs,
3069 e = InstInfo.Operands.size(); j < e; ++j)
3070 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003071 }
3072
3073 // Create and insert the instruction.
3074 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003075 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003076 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003077 continue; // no pattern.
3078 }
3079
Craig Topper306cb122015-11-22 20:46:24 +00003080 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003081 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3082
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003083 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003084 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003085 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003086
Chris Lattner8cab0212008-01-05 22:25:12 +00003087 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003088 for (auto &Entry : Instructions) {
3089 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003090 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003091 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003092
3093 // FIXME: Assume only the first tree is the pattern. The others are clobber
3094 // nodes.
3095 TreePatternNode *Pattern = I->getTree(0);
3096 TreePatternNode *SrcPattern;
3097 if (Pattern->getOperator()->getName() == "set") {
3098 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3099 } else{
3100 // Not a set (store or something?)
3101 SrcPattern = Pattern;
3102 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003103
Craig Topper306cb122015-11-22 20:46:24 +00003104 Record *Instr = Entry.first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00003105 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003106 PatternToMatch(Instr,
3107 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003108 SrcPattern,
3109 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00003110 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003111 Instr->getValueAsInt("AddedComplexity"),
3112 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003113 }
3114}
3115
Chris Lattnera7722b62010-02-23 06:55:24 +00003116
3117typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3118
Jim Grosbach65586fe2010-12-21 16:16:00 +00003119static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003120 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003121 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003122 if (!P->getName().empty()) {
3123 NameRecord &Rec = Names[P->getName()];
3124 // If this is the first instance of the name, remember the node.
3125 if (Rec.second++ == 0)
3126 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003127 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003128 PatternTop->error("repetition of value: $" + P->getName() +
3129 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003130 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003131
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003132 if (!P->isLeaf()) {
3133 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003134 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003135 }
3136}
3137
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003138void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner0c0baa92010-02-23 06:16:51 +00003139 const PatternToMatch &PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003140 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003141 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003142 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3143 PrintWarning(Pattern->getRecord()->getLoc(),
3144 Twine("Pattern can never match: ") + Reason);
3145 return;
3146 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003147
Chris Lattner1e634e32010-03-01 22:29:19 +00003148 // If the source pattern's root is a complex pattern, that complex pattern
3149 // must specify the nodes it can potentially match.
3150 if (const ComplexPattern *CP =
3151 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3152 if (CP->getRootNodes().empty())
3153 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3154 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003155
3156
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003157 // Find all of the named values in the input and output, ensure they have the
3158 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003159 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003160 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3161 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003162
3163 // Scan all of the named values in the destination pattern, rejecting them if
3164 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003165 for (const auto &Entry : DstNames) {
3166 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003167 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003168 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003169 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003170
Chris Lattnera7722b62010-02-23 06:55:24 +00003171 // Scan all of the named values in the source pattern, rejecting them if the
3172 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003173 for (const auto &Entry : SrcNames)
3174 if (DstNames[Entry.first].first == nullptr &&
3175 SrcNames[Entry.first].second == 1)
3176 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003177
Chris Lattner0c0baa92010-02-23 06:16:51 +00003178 PatternsToMatch.push_back(PTM);
3179}
3180
3181
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003182
3183void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattner918be522010-03-19 00:34:35 +00003184 const std::vector<const CodeGenInstruction*> &Instructions =
3185 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003186
3187 // First try to infer flags from the primary instruction pattern, if any.
3188 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003189 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003190 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3191 CodeGenInstruction &InstInfo =
3192 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003193
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003194 // Get the primary instruction pattern.
3195 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3196 if (!Pattern) {
3197 if (InstInfo.hasUndefFlags())
3198 Revisit.push_back(&InstInfo);
3199 continue;
3200 }
3201 InstAnalyzer PatInfo(*this);
3202 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003203 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003204 }
3205
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003206 // Second, look for single-instruction patterns defined outside the
3207 // instruction.
3208 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3209 const PatternToMatch &PTM = *I;
3210
3211 // We can only infer from single-instruction patterns, otherwise we won't
3212 // know which instruction should get the flags.
3213 SmallVector<Record*, 8> PatInstrs;
3214 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3215 if (PatInstrs.size() != 1)
3216 continue;
3217
3218 // Get the single instruction.
3219 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3220
3221 // Only infer properties from the first pattern. We'll verify the others.
3222 if (InstInfo.InferredFrom)
3223 continue;
3224
3225 InstAnalyzer PatInfo(*this);
3226 PatInfo.Analyze(&PTM);
3227 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3228 }
3229
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003230 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003231 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003232
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003233 // Revisit instructions with undefined flags and no pattern.
3234 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003235 for (CodeGenInstruction *InstInfo : Revisit) {
3236 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003237 continue;
3238 // The mayLoad and mayStore flags default to false.
3239 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003240 if (InstInfo->hasSideEffects_Unset)
3241 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003242 }
3243 return;
3244 }
3245
3246 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003247 for (CodeGenInstruction *InstInfo : Revisit) {
3248 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003249 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003250 if (InstInfo->hasSideEffects_Unset)
3251 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003252 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003253 if (InstInfo->mayStore_Unset)
3254 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003255 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003256 if (InstInfo->mayLoad_Unset)
3257 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003258 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003259 }
3260}
3261
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003262
3263/// Verify instruction flags against pattern node properties.
3264void CodeGenDAGPatterns::VerifyInstructionFlags() {
3265 unsigned Errors = 0;
3266 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3267 const PatternToMatch &PTM = *I;
3268 SmallVector<Record*, 8> Instrs;
3269 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3270 if (Instrs.empty())
3271 continue;
3272
3273 // Count the number of instructions with each flag set.
3274 unsigned NumSideEffects = 0;
3275 unsigned NumStores = 0;
3276 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003277 for (const Record *Instr : Instrs) {
3278 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003279 NumSideEffects += InstInfo.hasSideEffects;
3280 NumStores += InstInfo.mayStore;
3281 NumLoads += InstInfo.mayLoad;
3282 }
3283
3284 // Analyze the source pattern.
3285 InstAnalyzer PatInfo(*this);
3286 PatInfo.Analyze(&PTM);
3287
3288 // Collect error messages.
3289 SmallVector<std::string, 4> Msgs;
3290
3291 // Check for missing flags in the output.
3292 // Permit extra flags for now at least.
3293 if (PatInfo.hasSideEffects && !NumSideEffects)
3294 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3295
3296 // Don't verify store flags on instructions with side effects. At least for
3297 // intrinsics, side effects implies mayStore.
3298 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3299 Msgs.push_back("pattern may store, but mayStore isn't set");
3300
3301 // Similarly, mayStore implies mayLoad on intrinsics.
3302 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3303 Msgs.push_back("pattern may load, but mayLoad isn't set");
3304
3305 // Print error messages.
3306 if (Msgs.empty())
3307 continue;
3308 ++Errors;
3309
Craig Topper306cb122015-11-22 20:46:24 +00003310 for (const std::string &Msg : Msgs)
3311 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003312 (Instrs.size() == 1 ?
3313 "instruction" : "output instructions"));
3314 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003315 for (const Record *Instr : Instrs) {
3316 if (Instr != PTM.getSrcRecord())
3317 PrintError(Instr->getLoc(), "defined here");
3318 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003319 if (InstInfo.InferredFrom &&
3320 InstInfo.InferredFrom != InstInfo.TheDef &&
3321 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003322 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003323 }
3324 }
3325 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003326 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003327}
3328
Chris Lattnercabe0372010-03-15 06:00:16 +00003329/// Given a pattern result with an unresolved type, see if we can find one
3330/// instruction with an unresolved result type. Force this result type to an
3331/// arbitrary element if it's possible types to converge results.
3332static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3333 if (N->isLeaf())
3334 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003335
Chris Lattnercabe0372010-03-15 06:00:16 +00003336 // Analyze children.
3337 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3338 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3339 return true;
3340
3341 if (!N->getOperator()->isSubClassOf("Instruction"))
3342 return false;
3343
3344 // If this type is already concrete or completely unknown we can't do
3345 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003346 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3347 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3348 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003349
Chris Lattnerf1447252010-03-19 21:37:09 +00003350 // Otherwise, force its type to the first possibility (an arbitrary choice).
3351 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3352 return true;
3353 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003354
Chris Lattnerf1447252010-03-19 21:37:09 +00003355 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003356}
3357
Chris Lattnerab3242f2008-01-06 01:10:31 +00003358void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003359 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3360
Craig Topper306cb122015-11-22 20:46:24 +00003361 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003362 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003363
3364 // If the pattern references the null_frag, there's nothing to do.
3365 if (hasNullFragReference(Tree))
3366 continue;
3367
Chris Lattner5c2182e2010-03-27 02:53:27 +00003368 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003369
3370 // Inline pattern fragments into it.
3371 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003372
David Greeneaf8ee2c2011-07-29 22:43:06 +00003373 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003374 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003375
Chris Lattner8cab0212008-01-05 22:25:12 +00003376 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003377 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003378
Chris Lattner8cab0212008-01-05 22:25:12 +00003379 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003380 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003381
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003382 if (Result.getNumTrees() != 1)
3383 Result.error("Cannot handle instructions producing instructions "
3384 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003385
Chris Lattner8cab0212008-01-05 22:25:12 +00003386 bool IterateInference;
3387 bool InferredAllPatternTypes, InferredAllResultTypes;
3388 do {
3389 // Infer as many types as possible. If we cannot infer all of them, we
3390 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003391 InferredAllPatternTypes =
3392 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003393
Chris Lattner8cab0212008-01-05 22:25:12 +00003394 // Infer as many types as possible. If we cannot infer all of them, we
3395 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003396 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003397 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003398
Chris Lattnerfdc20712010-03-18 23:15:10 +00003399 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003400
Chris Lattner8cab0212008-01-05 22:25:12 +00003401 // Apply the type of the result to the source pattern. This helps us
3402 // resolve cases where the input type is known to be a pointer type (which
3403 // is considered resolved), but the result knows it needs to be 32- or
3404 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003405 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003406 Pattern->getTree(0)->getNumTypes());
3407 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003408 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3409 i, Result.getTree(0)->getExtType(i), Result);
3410 IterateInference |= Result.getTree(0)->UpdateNodeType(
3411 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003412 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003413
Chris Lattnercabe0372010-03-15 06:00:16 +00003414 // If our iteration has converged and the input pattern's types are fully
3415 // resolved but the result pattern is not fully resolved, we may have a
3416 // situation where we have two instructions in the result pattern and
3417 // the instructions require a common register class, but don't care about
3418 // what actual MVT is used. This is actually a bug in our modelling:
3419 // output patterns should have register classes, not MVTs.
3420 //
3421 // In any case, to handle this, we just go through and disambiguate some
3422 // arbitrary types to the result pattern's nodes.
3423 if (!IterateInference && InferredAllPatternTypes &&
3424 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003425 IterateInference =
3426 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003427 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003428
Chris Lattner8cab0212008-01-05 22:25:12 +00003429 // Verify that we inferred enough types that we can do something with the
3430 // pattern and result. If these fire the user has to add type casts.
3431 if (!InferredAllPatternTypes)
3432 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003433 if (!InferredAllResultTypes) {
3434 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003435 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003436 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003437
Chris Lattner8cab0212008-01-05 22:25:12 +00003438 // Validate that the input pattern is correct.
3439 std::map<std::string, TreePatternNode*> InstInputs;
3440 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003441 std::vector<Record*> InstImpResults;
3442 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3443 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3444 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003445 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003446
3447 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003448 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003449 std::vector<TreePatternNode*> ResultNodeOperands;
3450 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3451 TreePatternNode *OpNode = DstPattern->getChild(ii);
3452 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003453 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003454 std::vector<TreePatternNode*> Children;
3455 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003456 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003457 }
3458 ResultNodeOperands.push_back(OpNode);
3459 }
David Blaikiecf195302014-11-17 22:55:41 +00003460 DstPattern = Result.getOnlyTree();
3461 if (!DstPattern->isLeaf())
3462 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3463 ResultNodeOperands,
3464 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003465
David Blaikiecf195302014-11-17 22:55:41 +00003466 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3467 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3468
3469 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003470 Temp.InferAllTypes();
3471
Jim Grosbach65586fe2010-12-21 16:16:00 +00003472
Chris Lattner0c0baa92010-02-23 06:16:51 +00003473 AddPatternToMatch(Pattern,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003474 PatternToMatch(CurPattern,
3475 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerf1447252010-03-19 21:37:09 +00003476 Pattern->getTree(0),
David Blaikiecf195302014-11-17 22:55:41 +00003477 Temp.getOnlyTree(), InstImpResults,
Chris Lattnerf1447252010-03-19 21:37:09 +00003478 CurPattern->getValueAsInt("AddedComplexity"),
3479 CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003480 }
3481}
3482
3483/// CombineChildVariants - Given a bunch of permutations of each child of the
3484/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003485static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003486 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3487 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003488 CodeGenDAGPatterns &CDP,
3489 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003490 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00003491 for (const auto &Variants : ChildVariants)
3492 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003493 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003494
Chris Lattner8cab0212008-01-05 22:25:12 +00003495 // The end result is an all-pairs construction of the resultant pattern.
3496 std::vector<unsigned> Idxs;
3497 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003498 bool NotDone;
3499 do {
3500#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003501 DEBUG(if (!Idxs.empty()) {
3502 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00003503 for (unsigned Idx : Idxs) {
3504 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003505 }
3506 errs() << "]\n";
3507 });
Scott Michel94420742008-03-05 17:49:05 +00003508#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003509 // Create the variant and add it to the output list.
3510 std::vector<TreePatternNode*> NewChildren;
3511 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3512 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00003513 auto R = llvm::make_unique<TreePatternNode>(
3514 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003515
Chris Lattner8cab0212008-01-05 22:25:12 +00003516 // Copy over properties.
3517 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003518 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003519 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003520 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3521 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003522
Scott Michel94420742008-03-05 17:49:05 +00003523 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003524 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00003525 // Scan to see if this pattern has already been emitted. We can get
3526 // duplication due to things like commuting:
3527 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3528 // which are the same pattern. Ignore the dups.
3529 if (R->canPatternMatch(ErrString, CDP) &&
3530 std::none_of(OutVariants.begin(), OutVariants.end(),
3531 [&](TreePatternNode *Variant) {
3532 return R->isIsomorphicTo(Variant, DepVars);
3533 }))
3534 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003535
Scott Michel94420742008-03-05 17:49:05 +00003536 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003537 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00003538 // [0, 0], [0, 1], [1, 0], [1, 1].
3539 int IdxsIdx;
3540 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3541 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3542 Idxs[IdxsIdx] = 0;
3543 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003544 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003545 }
Scott Michel94420742008-03-05 17:49:05 +00003546 NotDone = (IdxsIdx >= 0);
3547 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003548}
3549
3550/// CombineChildVariants - A helper function for binary operators.
3551///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003552static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003553 const std::vector<TreePatternNode*> &LHS,
3554 const std::vector<TreePatternNode*> &RHS,
3555 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003556 CodeGenDAGPatterns &CDP,
3557 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003558 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3559 ChildVariants.push_back(LHS);
3560 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003561 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003562}
Chris Lattner8cab0212008-01-05 22:25:12 +00003563
3564
3565static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3566 std::vector<TreePatternNode *> &Children) {
3567 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3568 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003569
Chris Lattner8cab0212008-01-05 22:25:12 +00003570 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003571 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003572 N->getTransformFn()) {
3573 Children.push_back(N);
3574 return;
3575 }
3576
3577 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3578 Children.push_back(N->getChild(0));
3579 else
3580 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3581
3582 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3583 Children.push_back(N->getChild(1));
3584 else
3585 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3586}
3587
3588/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3589/// the (potentially recursive) pattern by using algebraic laws.
3590///
3591static void GenerateVariantsOf(TreePatternNode *N,
3592 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003593 CodeGenDAGPatterns &CDP,
3594 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003595 // We cannot permute leaves or ComplexPattern uses.
3596 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003597 OutVariants.push_back(N);
3598 return;
3599 }
3600
3601 // Look up interesting info about the node.
3602 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3603
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003604 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003605 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003606 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003607 std::vector<TreePatternNode*> MaximalChildren;
3608 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3609
3610 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3611 // permutations.
3612 if (MaximalChildren.size() == 3) {
3613 // Find the variants of all of our maximal children.
3614 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003615 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3616 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3617 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003618
Chris Lattner8cab0212008-01-05 22:25:12 +00003619 // There are only two ways we can permute the tree:
3620 // (A op B) op C and A op (B op C)
3621 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003622
Chris Lattner8cab0212008-01-05 22:25:12 +00003623 // Generate legal pair permutations of A/B/C.
3624 std::vector<TreePatternNode*> ABVariants;
3625 std::vector<TreePatternNode*> BAVariants;
3626 std::vector<TreePatternNode*> ACVariants;
3627 std::vector<TreePatternNode*> CAVariants;
3628 std::vector<TreePatternNode*> BCVariants;
3629 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003630 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3631 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3632 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3633 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3634 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3635 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003636
3637 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003638 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3639 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3640 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3641 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3642 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3643 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003644
3645 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003646 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3647 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3648 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3649 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3650 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3651 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003652 return;
3653 }
3654 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003655
Chris Lattner8cab0212008-01-05 22:25:12 +00003656 // Compute permutations of all children.
3657 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3658 ChildVariants.resize(N->getNumChildren());
3659 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003660 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003661
3662 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003663 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003664
3665 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003666 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3667 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3668 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3669 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003670 // Don't count children which are actually register references.
3671 unsigned NC = 0;
3672 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3673 TreePatternNode *Child = N->getChild(i);
3674 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003675 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003676 Record *RR = DI->getDef();
3677 if (RR->isSubClassOf("Register"))
3678 continue;
3679 }
3680 NC++;
3681 }
3682 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003683 if (isCommIntrinsic) {
3684 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3685 // operands are the commutative operands, and there might be more operands
3686 // after those.
3687 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003688 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00003689 std::vector<std::vector<TreePatternNode*> > Variants;
3690 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3691 Variants.push_back(ChildVariants[2]);
3692 Variants.push_back(ChildVariants[1]);
3693 for (unsigned i = 3; i != NC; ++i)
3694 Variants.push_back(ChildVariants[i]);
3695 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3696 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003697 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003698 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003699 }
3700}
3701
3702
3703// GenerateVariants - Generate variants. For example, commutative patterns can
3704// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003705void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003706 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003707
Chris Lattner8cab0212008-01-05 22:25:12 +00003708 // Loop over all of the patterns we've collected, checking to see if we can
3709 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003710 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003711 // the .td file having to contain tons of variants of instructions.
3712 //
3713 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3714 // intentionally do not reconsider these. Any variants of added patterns have
3715 // already been added.
3716 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00003717 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003718 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003719 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003720 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003721 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003722 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003723 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00003724 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003725 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003726
3727 assert(!Variants.empty() && "Must create at least original variant!");
3728 Variants.erase(Variants.begin()); // Remove the original pattern.
3729
3730 if (Variants.empty()) // No variants for this pattern.
3731 continue;
3732
Chris Lattner34822f62009-08-23 04:44:11 +00003733 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00003734 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00003735 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003736
3737 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3738 TreePatternNode *Variant = Variants[v];
3739
Chris Lattner34822f62009-08-23 04:44:11 +00003740 DEBUG(errs() << " VAR#" << v << ": ";
3741 Variant->dump();
3742 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003743
Chris Lattner8cab0212008-01-05 22:25:12 +00003744 // Scan to see if an instruction or explicit pattern already matches this.
3745 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00003746 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003747 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003748 if (PatternsToMatch[i].getPredicates() !=
3749 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00003750 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003751 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003752 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3753 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003754 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003755 AlreadyExists = true;
3756 break;
3757 }
3758 }
3759 // If we already have it, ignore the variant.
3760 if (AlreadyExists) continue;
3761
3762 // Otherwise, add it to the list of patterns we have.
Craig Topper2f70a7e2015-11-22 22:43:40 +00003763 PatternsToMatch.emplace_back(
3764 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
3765 Variant, PatternsToMatch[i].getDstPattern(),
3766 PatternsToMatch[i].getDstRegs(),
3767 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID());
Chris Lattner8cab0212008-01-05 22:25:12 +00003768 }
3769
Chris Lattner34822f62009-08-23 04:44:11 +00003770 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003771 }
3772}