blob: 2602bbcf6f61c20be64eb9876f8f9dab1117a90b [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 ||
56 VT == MVT::iPTRAny) && "Not a concrete type!");
57 TypeVec.push_back(VT);
58 }
Chris Lattner8cab0212008-01-05 22:25:12 +000059}
60
Chris Lattnercabe0372010-03-15 06:00:16 +000061
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000062EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) {
Chris Lattnercabe0372010-03-15 06:00:16 +000063 assert(!VTList.empty() && "empty list?");
64 TypeVec.append(VTList.begin(), VTList.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +000065
Chris Lattnercabe0372010-03-15 06:00:16 +000066 if (!VTList.empty())
67 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
68 VTList[0] != MVT::fAny);
Jim Grosbach65586fe2010-12-21 16:16:00 +000069
Chris Lattner4a5f7be2010-03-27 20:32:26 +000070 // Verify no duplicates.
Chris Lattnercabe0372010-03-15 06:00:16 +000071 array_pod_sort(TypeVec.begin(), TypeVec.end());
Chris Lattner4a5f7be2010-03-27 20:32:26 +000072 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
Chris Lattner8cab0212008-01-05 22:25:12 +000073}
74
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000075/// FillWithPossibleTypes - Set to all legal types and return true, only valid
76/// on completely unknown type sets.
Chris Lattner6d765eb2010-03-19 17:41:26 +000077bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
78 bool (*Pred)(MVT::SimpleValueType),
79 const char *PredicateName) {
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000080 assert(isCompletelyUnknown());
Jakob Stoklund Olesen13d4a072013-03-17 17:26:09 +000081 ArrayRef<MVT::SimpleValueType> LegalTypes =
Chris Lattner6d765eb2010-03-19 17:41:26 +000082 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +000083
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000084 if (TP.hasError())
85 return false;
86
Chris Lattner6d765eb2010-03-19 17:41:26 +000087 for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
Craig Topper24064772014-04-15 07:20:03 +000088 if (!Pred || Pred(LegalTypes[i]))
Chris Lattner6d765eb2010-03-19 17:41:26 +000089 TypeVec.push_back(LegalTypes[i]);
90
91 // If we have nothing that matches the predicate, bail out.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000092 if (TypeVec.empty()) {
Chris Lattner6d765eb2010-03-19 17:41:26 +000093 TP.error("Type inference contradiction found, no " +
Jim Grosbach65586fe2010-12-21 16:16:00 +000094 std::string(PredicateName) + " types found");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000095 return false;
96 }
Chris Lattner6d765eb2010-03-19 17:41:26 +000097 // No need to sort with one element.
98 if (TypeVec.size() == 1) return true;
99
100 // Remove duplicates.
101 array_pod_sort(TypeVec.begin(), TypeVec.end());
102 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000103
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000104 return true;
105}
Chris Lattnercabe0372010-03-15 06:00:16 +0000106
107/// hasIntegerTypes - Return true if this TypeSet contains iAny or an
108/// integer value type.
109bool EEVT::TypeSet::hasIntegerTypes() const {
110 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
111 if (isInteger(TypeVec[i]))
112 return true;
113 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000114}
Chris Lattnercabe0372010-03-15 06:00:16 +0000115
116/// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
117/// a floating point value type.
118bool EEVT::TypeSet::hasFloatingPointTypes() const {
119 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
120 if (isFloatingPoint(TypeVec[i]))
121 return true;
122 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000123}
Chris Lattnercabe0372010-03-15 06:00:16 +0000124
Craig Topper74169dc2014-01-28 04:49:01 +0000125/// hasScalarTypes - Return true if this TypeSet contains a scalar value type.
126bool EEVT::TypeSet::hasScalarTypes() const {
127 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
128 if (isScalar(TypeVec[i]))
129 return true;
130 return false;
131}
132
Chris Lattnercabe0372010-03-15 06:00:16 +0000133/// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
134/// value type.
135bool EEVT::TypeSet::hasVectorTypes() const {
136 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
137 if (isVector(TypeVec[i]))
138 return true;
139 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +0000140}
Bob Wilson2cd5da82009-08-11 01:14:02 +0000141
Chris Lattnercabe0372010-03-15 06:00:16 +0000142
143std::string EEVT::TypeSet::getName() const {
Chris Lattnerda5b4ad2010-03-19 01:14:27 +0000144 if (TypeVec.empty()) return "<empty>";
Jim Grosbach65586fe2010-12-21 16:16:00 +0000145
Chris Lattnercabe0372010-03-15 06:00:16 +0000146 std::string Result;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000147
Chris Lattnercabe0372010-03-15 06:00:16 +0000148 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
149 std::string VTName = llvm::getEnumName(TypeVec[i]);
150 // Strip off MVT:: prefix if present.
151 if (VTName.substr(0,5) == "MVT::")
152 VTName = VTName.substr(5);
153 if (i) Result += ':';
154 Result += VTName;
155 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000156
Chris Lattnercabe0372010-03-15 06:00:16 +0000157 if (TypeVec.size() == 1)
158 return Result;
159 return "{" + Result + "}";
Bob Wilson2cd5da82009-08-11 01:14:02 +0000160}
Chris Lattnercabe0372010-03-15 06:00:16 +0000161
162/// MergeInTypeInfo - This merges in type information from the specified
163/// argument. If 'this' changes, it returns true. If the two types are
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000164/// contradictory (e.g. merge f32 into i32) then this flags an error.
Chris Lattnercabe0372010-03-15 06:00:16 +0000165bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000166 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
Chris Lattnercabe0372010-03-15 06:00:16 +0000167 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000168
Chris Lattnercabe0372010-03-15 06:00:16 +0000169 if (isCompletelyUnknown()) {
170 *this = InVT;
171 return true;
172 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000173
Chris Lattnercabe0372010-03-15 06:00:16 +0000174 assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000175
Chris Lattnercabe0372010-03-15 06:00:16 +0000176 // Handle the abstract cases, seeing if we can resolve them better.
177 switch (TypeVec[0]) {
178 default: break;
179 case MVT::iPTR:
180 case MVT::iPTRAny:
181 if (InVT.hasIntegerTypes()) {
182 EEVT::TypeSet InCopy(InVT);
183 InCopy.EnforceInteger(TP);
184 InCopy.EnforceScalar(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000185
Chris Lattnercabe0372010-03-15 06:00:16 +0000186 if (InCopy.isConcrete()) {
187 // If the RHS has one integer type, upgrade iPTR to i32.
188 TypeVec[0] = InVT.TypeVec[0];
189 return true;
190 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000191
Chris Lattnercabe0372010-03-15 06:00:16 +0000192 // If the input has multiple scalar integers, this doesn't add any info.
193 if (!InCopy.isCompletelyUnknown())
194 return false;
195 }
196 break;
197 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000198
Chris Lattnercabe0372010-03-15 06:00:16 +0000199 // If the input constraint is iAny/iPTR and this is an integer type list,
200 // remove non-integer types from the list.
201 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
202 hasIntegerTypes()) {
203 bool MadeChange = EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000204
Chris Lattnercabe0372010-03-15 06:00:16 +0000205 // If we're merging in iPTR/iPTRAny and the node currently has a list of
206 // multiple different integer types, replace them with a single iPTR.
207 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
208 TypeVec.size() != 1) {
209 TypeVec.resize(1);
210 TypeVec[0] = InVT.TypeVec[0];
211 MadeChange = true;
212 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000213
Chris Lattnercabe0372010-03-15 06:00:16 +0000214 return MadeChange;
215 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000216
Chris Lattnercabe0372010-03-15 06:00:16 +0000217 // If this is a type list and the RHS is a typelist as well, eliminate entries
218 // from this list that aren't in the other one.
219 bool MadeChange = false;
220 TypeSet InputSet(*this);
221
222 for (unsigned i = 0; i != TypeVec.size(); ++i) {
223 bool InInVT = false;
224 for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
225 if (TypeVec[i] == InVT.TypeVec[j]) {
226 InInVT = true;
227 break;
228 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000229
Chris Lattnercabe0372010-03-15 06:00:16 +0000230 if (InInVT) continue;
231 TypeVec.erase(TypeVec.begin()+i--);
232 MadeChange = true;
233 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000234
Chris Lattnercabe0372010-03-15 06:00:16 +0000235 // If we removed all of our types, we have a type contradiction.
236 if (!TypeVec.empty())
237 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000238
Chris Lattnercabe0372010-03-15 06:00:16 +0000239 // FIXME: Really want an SMLoc here!
240 TP.error("Type inference contradiction found, merging '" +
241 InVT.getName() + "' into '" + InputSet.getName() + "'");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000242 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000243}
244
245/// EnforceInteger - Remove all non-integer types from this set.
246bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000247 if (TP.hasError())
248 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000249 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000250 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000251 return FillWithPossibleTypes(TP, isInteger, "integer");
Chris Lattnercabe0372010-03-15 06:00:16 +0000252 if (!hasFloatingPointTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000253 return false;
254
255 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000256
Chris Lattnercabe0372010-03-15 06:00:16 +0000257 // Filter out all the fp types.
258 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000259 if (!isInteger(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000260 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000261
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000262 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000263 TP.error("Type inference contradiction found, '" +
264 InputSet.getName() + "' needs to be integer");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000265 return false;
266 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000267 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000268}
269
270/// EnforceFloatingPoint - Remove all integer types from this set.
271bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000272 if (TP.hasError())
273 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000274 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000275 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000276 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
277
Chris Lattnercabe0372010-03-15 06:00:16 +0000278 if (!hasIntegerTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000279 return false;
280
281 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000282
Chris Lattnercabe0372010-03-15 06:00:16 +0000283 // Filter out all the fp types.
284 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000285 if (!isFloatingPoint(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000286 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000287
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000288 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000289 TP.error("Type inference contradiction found, '" +
290 InputSet.getName() + "' needs to be floating point");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000291 return false;
292 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000293 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000294}
295
296/// EnforceScalar - Remove all vector types from this.
297bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000298 if (TP.hasError())
299 return false;
300
Chris Lattnercabe0372010-03-15 06:00:16 +0000301 // If we know nothing, then get the full set.
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000302 if (TypeVec.empty())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000303 return FillWithPossibleTypes(TP, isScalar, "scalar");
304
Chris Lattnercabe0372010-03-15 06:00:16 +0000305 if (!hasVectorTypes())
Chris Lattner6d765eb2010-03-19 17:41:26 +0000306 return false;
307
308 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000309
Chris Lattnercabe0372010-03-15 06:00:16 +0000310 // Filter out all the vector types.
311 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000312 if (!isScalar(TypeVec[i]))
Chris Lattnercabe0372010-03-15 06:00:16 +0000313 TypeVec.erase(TypeVec.begin()+i--);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000314
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000315 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000316 TP.error("Type inference contradiction found, '" +
317 InputSet.getName() + "' needs to be scalar");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000318 return false;
319 }
Chris Lattner6d765eb2010-03-19 17:41:26 +0000320 return true;
Chris Lattnercabe0372010-03-15 06:00:16 +0000321}
322
323/// EnforceVector - Remove all vector types from this.
324bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000325 if (TP.hasError())
326 return false;
327
Chris Lattner6d765eb2010-03-19 17:41:26 +0000328 // If we know nothing, then get the full set.
329 if (TypeVec.empty())
330 return FillWithPossibleTypes(TP, isVector, "vector");
331
Chris Lattnercabe0372010-03-15 06:00:16 +0000332 TypeSet InputSet(*this);
333 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000334
Chris Lattnercabe0372010-03-15 06:00:16 +0000335 // Filter out all the scalar types.
336 for (unsigned i = 0; i != TypeVec.size(); ++i)
Chris Lattner6d765eb2010-03-19 17:41:26 +0000337 if (!isVector(TypeVec[i])) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000338 TypeVec.erase(TypeVec.begin()+i--);
Chris Lattner6d765eb2010-03-19 17:41:26 +0000339 MadeChange = true;
340 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000341
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000342 if (TypeVec.empty()) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000343 TP.error("Type inference contradiction found, '" +
344 InputSet.getName() + "' needs to be a vector");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000345 return false;
346 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000347 return MadeChange;
348}
349
350
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000351
Craig Topper74169dc2014-01-28 04:49:01 +0000352/// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors
353/// this shoud be based on the element type. Update this and other based on
354/// this information.
Chris Lattnercabe0372010-03-15 06:00:16 +0000355bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000356 if (TP.hasError())
357 return false;
358
Chris Lattnercabe0372010-03-15 06:00:16 +0000359 // Both operands must be integer or FP, but we don't care which.
360 bool MadeChange = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000361
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000362 if (isCompletelyUnknown())
363 MadeChange = FillWithPossibleTypes(TP);
364
365 if (Other.isCompletelyUnknown())
366 MadeChange = Other.FillWithPossibleTypes(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000367
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000368 // If one side is known to be integer or known to be FP but the other side has
369 // no information, get at least the type integrality info in there.
370 if (!hasFloatingPointTypes())
371 MadeChange |= Other.EnforceInteger(TP);
372 else if (!hasIntegerTypes())
373 MadeChange |= Other.EnforceFloatingPoint(TP);
374 if (!Other.hasFloatingPointTypes())
375 MadeChange |= EnforceInteger(TP);
376 else if (!Other.hasIntegerTypes())
377 MadeChange |= EnforceFloatingPoint(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000378
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000379 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
380 "Should have a type list now");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000381
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000382 // If one contains vectors but the other doesn't pull vectors out.
383 if (!hasVectorTypes())
384 MadeChange |= Other.EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000385 else if (!hasScalarTypes())
386 MadeChange |= Other.EnforceVector(TP);
Craig Topper6dbcb942014-01-25 05:17:38 +0000387 if (!Other.hasVectorTypes())
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000388 MadeChange |= EnforceScalar(TP);
Craig Topper74169dc2014-01-28 04:49:01 +0000389 else if (!Other.hasScalarTypes())
390 MadeChange |= EnforceVector(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000391
Craig Topper74169dc2014-01-28 04:49:01 +0000392 // For vectors we need to ensure that smaller size doesn't produce larger
393 // vector and vice versa.
394 if (isConcrete() && isVector(getConcrete())) {
395 MVT IVT = getConcrete();
396 unsigned Size = IVT.getSizeInBits();
David Greene433c6182011-02-01 19:12:32 +0000397
Craig Topper74169dc2014-01-28 04:49:01 +0000398 // Only keep types that have at least as many bits.
399 TypeSet InputSet(Other);
David Greene433c6182011-02-01 19:12:32 +0000400
Craig Topper74169dc2014-01-28 04:49:01 +0000401 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
402 assert(isVector(Other.TypeVec[i]) && "EnforceVector didn't work");
403 if (MVT(Other.TypeVec[i]).getSizeInBits() < Size) {
404 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
David Greene433c6182011-02-01 19:12:32 +0000405 MadeChange = true;
David Greene433c6182011-02-01 19:12:32 +0000406 }
407 }
Craig Topper74169dc2014-01-28 04:49:01 +0000408
409 if (Other.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
410 TP.error("Type inference contradiction found, forcing '" +
411 InputSet.getName() + "' to have at least as many bits as " +
412 getName() + "'");
413 return false;
414 }
415 } else if (Other.isConcrete() && isVector(Other.getConcrete())) {
416 MVT IVT = Other.getConcrete();
417 unsigned Size = IVT.getSizeInBits();
418
419 // Only keep types with the same or fewer total bits
420 TypeSet InputSet(*this);
421
422 for (unsigned i = 0; i != TypeVec.size(); ++i) {
423 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
424 if (MVT(TypeVec[i]).getSizeInBits() > Size) {
425 TypeVec.erase(TypeVec.begin()+i--);
426 MadeChange = true;
427 }
428 }
429
430 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
431 TP.error("Type inference contradiction found, forcing '" +
432 InputSet.getName() + "' to have the same or fewer bits than " +
433 Other.getName() + "'");
434 return false;
435 }
David Greene433c6182011-02-01 19:12:32 +0000436 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000437
Craig Topper74169dc2014-01-28 04:49:01 +0000438 // This code does not currently handle nodes which have multiple types,
439 // where some types are integer, and some are fp. Assert that this is not
440 // the case.
441 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
442 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
443 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
444
445 if (TP.hasError())
446 return false;
447
448 // Okay, find the smallest scalar type from the other set and remove
449 // anything the same or smaller from the current set.
450 TypeSet InputSet(Other);
451 MVT::SimpleValueType Smallest = TypeVec[0];
452 for (unsigned i = 0; i != Other.TypeVec.size(); ++i) {
453 if (Other.TypeVec[i] <= Smallest) {
454 Other.TypeVec.erase(Other.TypeVec.begin()+i--);
455 MadeChange = true;
456 }
457 }
458
459 if (Other.TypeVec.empty()) {
460 TP.error("Type inference contradiction found, '" + InputSet.getName() +
461 "' has nothing larger than '" + getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000462 return false;
463 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000464
Craig Topper74169dc2014-01-28 04:49:01 +0000465 // Okay, find the largest scalar type from the other set and remove
466 // anything the same or larger from the current set.
467 InputSet = TypeSet(*this);
468 MVT::SimpleValueType Largest = Other.TypeVec[Other.TypeVec.size()-1];
469 for (unsigned i = 0; i != TypeVec.size(); ++i) {
470 if (TypeVec[i] >= Largest) {
471 TypeVec.erase(TypeVec.begin()+i--);
472 MadeChange = true;
David Greene433c6182011-02-01 19:12:32 +0000473 }
David Greene433c6182011-02-01 19:12:32 +0000474 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000475
Craig Topper74169dc2014-01-28 04:49:01 +0000476 if (TypeVec.empty()) {
477 TP.error("Type inference contradiction found, '" + InputSet.getName() +
478 "' has nothing smaller than '" + Other.getName() +"'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000479 return false;
480 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000481
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000482 return MadeChange;
Chris Lattnercabe0372010-03-15 06:00:16 +0000483}
484
485/// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
Chris Lattner57ebf632010-03-24 00:01:16 +0000486/// whose element is specified by VTOperand.
487bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
Chris Lattnercabe0372010-03-15 06:00:16 +0000488 TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000489 if (TP.hasError())
490 return false;
491
Chris Lattner57ebf632010-03-24 00:01:16 +0000492 // "This" must be a vector and "VTOperand" must be a scalar.
Chris Lattnercabe0372010-03-15 06:00:16 +0000493 bool MadeChange = false;
Chris Lattner57ebf632010-03-24 00:01:16 +0000494 MadeChange |= EnforceVector(TP);
495 MadeChange |= VTOperand.EnforceScalar(TP);
496
497 // If we know the vector type, it forces the scalar to agree.
498 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000499 MVT IVT = getConcrete();
Chris Lattner57ebf632010-03-24 00:01:16 +0000500 IVT = IVT.getVectorElementType();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000501 return MadeChange |
Craig Topper95198f42013-09-25 06:37:18 +0000502 VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP);
Chris Lattner57ebf632010-03-24 00:01:16 +0000503 }
504
505 // If the scalar type is known, filter out vector types whose element types
506 // disagree.
507 if (!VTOperand.isConcrete())
508 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000509
Chris Lattner57ebf632010-03-24 00:01:16 +0000510 MVT::SimpleValueType VT = VTOperand.getConcrete();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000511
Chris Lattner57ebf632010-03-24 00:01:16 +0000512 TypeSet InputSet(*this);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000513
Chris Lattner57ebf632010-03-24 00:01:16 +0000514 // Filter out all the types which don't have the right element type.
515 for (unsigned i = 0; i != TypeVec.size(); ++i) {
516 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
Craig Topper95198f42013-09-25 06:37:18 +0000517 if (MVT(TypeVec[i]).getVectorElementType().SimpleTy != VT) {
Chris Lattnercabe0372010-03-15 06:00:16 +0000518 TypeVec.erase(TypeVec.begin()+i--);
519 MadeChange = true;
520 }
Chris Lattner57ebf632010-03-24 00:01:16 +0000521 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000522
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000523 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
Chris Lattnercabe0372010-03-15 06:00:16 +0000524 TP.error("Type inference contradiction found, forcing '" +
525 InputSet.getName() + "' to have a vector element");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000526 return false;
527 }
Chris Lattnercabe0372010-03-15 06:00:16 +0000528 return MadeChange;
529}
530
David Greene127fd1d2011-01-24 20:53:18 +0000531/// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
532/// vector type specified by VTOperand.
533bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
534 TreePattern &TP) {
Craig Topper6e1faaf2014-01-25 17:40:33 +0000535 if (TP.hasError())
536 return false;
537
David Greene127fd1d2011-01-24 20:53:18 +0000538 // "This" must be a vector and "VTOperand" must be a vector.
539 bool MadeChange = false;
540 MadeChange |= EnforceVector(TP);
541 MadeChange |= VTOperand.EnforceVector(TP);
542
Craig Topper6e1faaf2014-01-25 17:40:33 +0000543 // If one side is known to be integer or known to be FP but the other side has
544 // no information, get at least the type integrality info in there.
545 if (!hasFloatingPointTypes())
546 MadeChange |= VTOperand.EnforceInteger(TP);
547 else if (!hasIntegerTypes())
548 MadeChange |= VTOperand.EnforceFloatingPoint(TP);
549 if (!VTOperand.hasFloatingPointTypes())
550 MadeChange |= EnforceInteger(TP);
551 else if (!VTOperand.hasIntegerTypes())
552 MadeChange |= EnforceFloatingPoint(TP);
553
554 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() &&
555 "Should have a type list now");
David Greene127fd1d2011-01-24 20:53:18 +0000556
557 // If we know the vector type, it forces the scalar types to agree.
Craig Topper6e1faaf2014-01-25 17:40:33 +0000558 // Also force one vector to have more elements than the other.
David Greene127fd1d2011-01-24 20:53:18 +0000559 if (isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000560 MVT IVT = getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000561 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000562 IVT = IVT.getVectorElementType();
563
Craig Topper95198f42013-09-25 06:37:18 +0000564 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000565 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000566
567 // Only keep types that have less elements than VTOperand.
568 TypeSet InputSet(VTOperand);
569
570 for (unsigned i = 0; i != VTOperand.TypeVec.size(); ++i) {
571 assert(isVector(VTOperand.TypeVec[i]) && "EnforceVector didn't work");
572 if (MVT(VTOperand.TypeVec[i]).getVectorNumElements() >= NumElems) {
573 VTOperand.TypeVec.erase(VTOperand.TypeVec.begin()+i--);
574 MadeChange = true;
575 }
576 }
577 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here!
578 TP.error("Type inference contradiction found, forcing '" +
579 InputSet.getName() + "' to have less vector elements than '" +
580 getName() + "'");
581 return false;
582 }
David Greene127fd1d2011-01-24 20:53:18 +0000583 } else if (VTOperand.isConcrete()) {
Craig Topper95198f42013-09-25 06:37:18 +0000584 MVT IVT = VTOperand.getConcrete();
Craig Topper6e1faaf2014-01-25 17:40:33 +0000585 unsigned NumElems = IVT.getVectorNumElements();
David Greene127fd1d2011-01-24 20:53:18 +0000586 IVT = IVT.getVectorElementType();
587
Craig Topper95198f42013-09-25 06:37:18 +0000588 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP);
David Greene127fd1d2011-01-24 20:53:18 +0000589 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
Craig Topper6e1faaf2014-01-25 17:40:33 +0000590
591 // Only keep types that have more elements than 'this'.
592 TypeSet InputSet(*this);
593
594 for (unsigned i = 0; i != TypeVec.size(); ++i) {
595 assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
596 if (MVT(TypeVec[i]).getVectorNumElements() <= NumElems) {
597 TypeVec.erase(TypeVec.begin()+i--);
598 MadeChange = true;
599 }
600 }
601 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
602 TP.error("Type inference contradiction found, forcing '" +
603 InputSet.getName() + "' to have more vector elements than '" +
604 VTOperand.getName() + "'");
605 return false;
606 }
David Greene127fd1d2011-01-24 20:53:18 +0000607 }
608
609 return MadeChange;
610}
611
Chris Lattnercabe0372010-03-15 06:00:16 +0000612//===----------------------------------------------------------------------===//
613// Helpers for working with extended types.
Chris Lattner8cab0212008-01-05 22:25:12 +0000614
Scott Michel94420742008-03-05 17:49:05 +0000615/// Dependent variable map for CodeGenDAGPattern variant generation
616typedef std::map<std::string, int> DepVarMap;
617
618/// Const iterator shorthand for DepVarMap
619typedef DepVarMap::const_iterator DepVarMap_citer;
620
Chris Lattner514e2922011-04-17 21:38:24 +0000621static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
Scott Michel94420742008-03-05 17:49:05 +0000622 if (N->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000623 if (isa<DefInit>(N->getLeafValue()))
Scott Michel94420742008-03-05 17:49:05 +0000624 DepMap[N->getName()]++;
Scott Michel94420742008-03-05 17:49:05 +0000625 } else {
626 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
627 FindDepVarsOf(N->getChild(i), DepMap);
628 }
629}
Chris Lattner514e2922011-04-17 21:38:24 +0000630
631/// Find dependent variables within child patterns
632static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000633 DepVarMap depcounts;
634 FindDepVarsOf(N, depcounts);
635 for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
Chris Lattner514e2922011-04-17 21:38:24 +0000636 if (i->second > 1) // std::pair<std::string, int>
Scott Michel94420742008-03-05 17:49:05 +0000637 DepVars.insert(i->first);
Scott Michel94420742008-03-05 17:49:05 +0000638 }
639}
640
Daniel Dunbarba66a812010-10-08 02:07:22 +0000641#ifndef NDEBUG
Chris Lattner514e2922011-04-17 21:38:24 +0000642/// Dump the dependent variable set:
643static void DumpDepVars(MultipleUseVarSet &DepVars) {
Scott Michel94420742008-03-05 17:49:05 +0000644 if (DepVars.empty()) {
Chris Lattner34822f62009-08-23 04:44:11 +0000645 DEBUG(errs() << "<empty set>");
Scott Michel94420742008-03-05 17:49:05 +0000646 } else {
Chris Lattner34822f62009-08-23 04:44:11 +0000647 DEBUG(errs() << "[ ");
Jim Grosbachb75d0ca2010-10-08 18:13:57 +0000648 for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
649 e = DepVars.end(); i != e; ++i) {
Chris Lattner34822f62009-08-23 04:44:11 +0000650 DEBUG(errs() << (*i) << " ");
Scott Michel94420742008-03-05 17:49:05 +0000651 }
Chris Lattner34822f62009-08-23 04:44:11 +0000652 DEBUG(errs() << "]");
Scott Michel94420742008-03-05 17:49:05 +0000653 }
654}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000655#endif
656
Chris Lattner514e2922011-04-17 21:38:24 +0000657
658//===----------------------------------------------------------------------===//
659// TreePredicateFn Implementation
660//===----------------------------------------------------------------------===//
661
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000662/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
663TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
664 assert((getPredCode().empty() || getImmCode().empty()) &&
665 ".td file corrupt: can't have a node predicate *and* an imm predicate");
666}
667
Chris Lattner514e2922011-04-17 21:38:24 +0000668std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000669 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000670}
671
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000672std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000673 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000674}
675
Chris Lattner514e2922011-04-17 21:38:24 +0000676
677/// isAlwaysTrue - Return true if this is a noop predicate.
678bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000679 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000680}
681
682/// Return the name to use in the generated code to reference this, this is
683/// "Predicate_foo" if from a pattern fragment "foo".
684std::string TreePredicateFn::getFnName() const {
685 return "Predicate_" + PatFragRec->getRecord()->getName();
686}
687
688/// getCodeToRunOnSDNode - Return the code for the function body that
689/// evaluates this predicate. The argument is expected to be in "Node",
690/// not N. This handles casting and conversion to a concrete node type as
691/// appropriate.
692std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000693 // Handle immediate predicates first.
694 std::string ImmCode = getImmCode();
695 if (!ImmCode.empty()) {
696 std::string Result =
697 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000698 return Result + ImmCode;
699 }
700
701 // Handle arbitrary node predicates.
702 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000703 std::string ClassName;
704 if (PatFragRec->getOnlyTree()->isLeaf())
705 ClassName = "SDNode";
706 else {
707 Record *Op = PatFragRec->getOnlyTree()->getOperator();
708 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
709 }
710 std::string Result;
711 if (ClassName == "SDNode")
712 Result = " SDNode *N = Node;\n";
713 else
714 Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
715
716 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000717}
718
Chris Lattner8cab0212008-01-05 22:25:12 +0000719//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000720// PatternToMatch implementation
721//
722
Chris Lattner05925fe2010-03-29 01:40:38 +0000723
724/// getPatternSize - Return the 'size' of this pattern. We want to match large
725/// patterns before small ones. This is used to determine the size of a
726/// pattern.
727static unsigned getPatternSize(const TreePatternNode *P,
728 const CodeGenDAGPatterns &CGP) {
729 unsigned Size = 3; // The node itself.
730 // If the root node is a ConstantSDNode, increases its size.
731 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000732 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000733 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000734
Chris Lattner05925fe2010-03-29 01:40:38 +0000735 // FIXME: This is a hack to statically increase the priority of patterns
736 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
737 // Later we can allow complexity / cost for each pattern to be (optionally)
738 // specified. To get best possible pattern match we'll need to dynamically
739 // calculate the complexity of all patterns a dag can potentially map to.
740 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000741 if (AM) {
Chris Lattner05925fe2010-03-29 01:40:38 +0000742 Size += AM->getNumOperands() * 3;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000743
Tim Northoverc807a172014-05-20 11:52:46 +0000744 // We don't want to count any children twice, so return early.
745 return Size;
746 }
747
Chris Lattner05925fe2010-03-29 01:40:38 +0000748 // If this node has some predicate function that must match, it adds to the
749 // complexity of this node.
750 if (!P->getPredicateFns().empty())
751 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000752
Chris Lattner05925fe2010-03-29 01:40:38 +0000753 // Count children in the count if they are also nodes.
754 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
755 TreePatternNode *Child = P->getChild(i);
756 if (!Child->isLeaf() && Child->getNumTypes() &&
757 Child->getType(0) != MVT::Other)
758 Size += getPatternSize(Child, CGP);
759 else if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000760 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000761 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
762 else if (Child->getComplexPatternInfo(CGP))
763 Size += getPatternSize(Child, CGP);
764 else if (!Child->getPredicateFns().empty())
765 ++Size;
766 }
767 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000768
Chris Lattner05925fe2010-03-29 01:40:38 +0000769 return Size;
770}
771
772/// Compute the complexity metric for the input pattern. This roughly
773/// corresponds to the number of nodes that are covered.
774unsigned PatternToMatch::
775getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
776 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
777}
778
779
Dan Gohman49e19e92008-08-22 00:20:26 +0000780/// getPredicateCheck - Return a single string containing all of this
781/// pattern's predicates concatenated with "&&" operators.
782///
783std::string PatternToMatch::getPredicateCheck() const {
784 std::string PredicateCheck;
785 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +0000786 if (DefInit *Pred = dyn_cast<DefInit>(Predicates->getElement(i))) {
Dan Gohman49e19e92008-08-22 00:20:26 +0000787 Record *Def = Pred->getDef();
788 if (!Def->isSubClassOf("Predicate")) {
789#ifndef NDEBUG
790 Def->dump();
791#endif
Craig Topperc4965bc2012-02-05 07:21:30 +0000792 llvm_unreachable("Unknown predicate type!");
Dan Gohman49e19e92008-08-22 00:20:26 +0000793 }
794 if (!PredicateCheck.empty())
795 PredicateCheck += " && ";
796 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
797 }
798 }
799
800 return PredicateCheck;
801}
802
803//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000804// SDTypeConstraint implementation
805//
806
807SDTypeConstraint::SDTypeConstraint(Record *R) {
808 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000809
Chris Lattner8cab0212008-01-05 22:25:12 +0000810 if (R->isSubClassOf("SDTCisVT")) {
811 ConstraintType = SDTCisVT;
812 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
Chris Lattnerffdac7b2010-03-28 06:04:39 +0000813 if (x.SDTCisVT_Info.VT == MVT::isVoid)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000814 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000815
Chris Lattner8cab0212008-01-05 22:25:12 +0000816 } else if (R->isSubClassOf("SDTCisPtrTy")) {
817 ConstraintType = SDTCisPtrTy;
818 } else if (R->isSubClassOf("SDTCisInt")) {
819 ConstraintType = SDTCisInt;
820 } else if (R->isSubClassOf("SDTCisFP")) {
821 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000822 } else if (R->isSubClassOf("SDTCisVec")) {
823 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +0000824 } else if (R->isSubClassOf("SDTCisSameAs")) {
825 ConstraintType = SDTCisSameAs;
826 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
827 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
828 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000829 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000830 R->getValueAsInt("OtherOperandNum");
831 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
832 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000833 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +0000834 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +0000835 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
836 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +0000837 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +0000838 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
839 ConstraintType = SDTCisSubVecOfVec;
840 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
841 R->getValueAsInt("OtherOpNum");
Chris Lattner8cab0212008-01-05 22:25:12 +0000842 } else {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +0000843 errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
Chris Lattner8cab0212008-01-05 22:25:12 +0000844 exit(1);
845 }
846}
847
848/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +0000849/// N, and the result number in ResNo.
850static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
851 const SDNodeInfo &NodeInfo,
852 unsigned &ResNo) {
853 unsigned NumResults = NodeInfo.getNumResults();
854 if (OpNo < NumResults) {
855 ResNo = OpNo;
856 return N;
857 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000858
Chris Lattner2db7aba2010-03-19 21:56:21 +0000859 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000860
Chris Lattner2db7aba2010-03-19 21:56:21 +0000861 if (OpNo >= N->getNumChildren()) {
Jim Grosbach65586fe2010-12-21 16:16:00 +0000862 errs() << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +0000863 << (OpNo+NumResults) << " ";
Chris Lattner8cab0212008-01-05 22:25:12 +0000864 N->dump();
Daniel Dunbar38a22bf2009-07-03 00:10:29 +0000865 errs() << '\n';
Chris Lattner8cab0212008-01-05 22:25:12 +0000866 exit(1);
867 }
868
Chris Lattner2db7aba2010-03-19 21:56:21 +0000869 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +0000870}
871
872/// ApplyTypeConstraint - Given a node in a pattern, apply this type
873/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000874/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +0000875bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
876 const SDNodeInfo &NodeInfo,
877 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000878 if (TP.hasError())
879 return false;
880
Chris Lattner2db7aba2010-03-19 21:56:21 +0000881 unsigned ResNo = 0; // The result number being referenced.
882 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000883
Chris Lattner8cab0212008-01-05 22:25:12 +0000884 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000885 case SDTCisVT:
886 // Operand must be a particular type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000887 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000888 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +0000889 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +0000890 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000891 case SDTCisInt:
892 // Require it to be one of the legal integer VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000893 return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000894 case SDTCisFP:
895 // Require it to be one of the legal fp VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000896 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
Chris Lattnercabe0372010-03-15 06:00:16 +0000897 case SDTCisVec:
898 // Require it to be one of the legal vector VTs.
Chris Lattnerf1447252010-03-19 21:37:09 +0000899 return NodeToApply->getExtType(ResNo).EnforceVector(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000900 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000901 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000902 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000903 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +0000904 return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
905 OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000906 }
907 case SDTCisVTSmallerThanOp: {
908 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
909 // have an integer type that is smaller than the VT.
910 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +0000911 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +0000912 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000913 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000914 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000915 return false;
916 }
Owen Anderson9f944592009-08-11 20:47:22 +0000917 MVT::SimpleValueType VT =
David Greeneaf8ee2c2011-07-29 22:43:06 +0000918 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
Jim Grosbach65586fe2010-12-21 16:16:00 +0000919
Chris Lattner38c99662010-03-24 00:06:46 +0000920 EEVT::TypeSet TypeListTmp(VT, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000921
Chris Lattner2db7aba2010-03-19 21:56:21 +0000922 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000923 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000924 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
925 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +0000926
Chris Lattner38c99662010-03-24 00:06:46 +0000927 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000928 }
929 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000930 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +0000931 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000932 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
933 BResNo);
Chris Lattnerf1447252010-03-19 21:37:09 +0000934 return NodeToApply->getExtType(ResNo).
935 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +0000936 }
Nate Begeman17bedbc2008-02-09 01:37:05 +0000937 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +0000938 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +0000939 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +0000940 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
941 VResNo);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000942
Chris Lattner57ebf632010-03-24 00:01:16 +0000943 // Filter vector types out of VecOperand that don't have the right element
944 // type.
945 return VecOperand->getExtType(VResNo).
946 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
Nate Begeman17bedbc2008-02-09 01:37:05 +0000947 }
David Greene127fd1d2011-01-24 20:53:18 +0000948 case SDTCisSubVecOfVec: {
949 unsigned VResNo = 0;
950 TreePatternNode *BigVecOperand =
951 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
952 VResNo);
953
954 // Filter vector types out of BigVecOperand that don't have the
955 // right subvector type.
956 return BigVecOperand->getExtType(VResNo).
957 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
958 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000959 }
David Blaikiea5708dc2012-01-17 07:00:13 +0000960 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +0000961}
962
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +0000963// Update the node type to match an instruction operand or result as specified
964// in the ins or outs lists on the instruction definition. Return true if the
965// type was actually changed.
966bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
967 Record *Operand,
968 TreePattern &TP) {
969 // The 'unknown' operand indicates that types should be inferred from the
970 // context.
971 if (Operand->isSubClassOf("unknown_class"))
972 return false;
973
974 // The Operand class specifies a type directly.
975 if (Operand->isSubClassOf("Operand"))
976 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")),
977 TP);
978
979 // PointerLikeRegClass has a type that is determined at runtime.
980 if (Operand->isSubClassOf("PointerLikeRegClass"))
981 return UpdateNodeType(ResNo, MVT::iPTR, TP);
982
983 // Both RegisterClass and RegisterOperand operands derive their types from a
984 // register class def.
Craig Topper24064772014-04-15 07:20:03 +0000985 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +0000986 if (Operand->isSubClassOf("RegisterClass"))
987 RC = Operand;
988 else if (Operand->isSubClassOf("RegisterOperand"))
989 RC = Operand->getValueAsDef("RegClass");
990
991 assert(RC && "Unknown operand type");
992 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
993 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
994}
995
996
Chris Lattner8cab0212008-01-05 22:25:12 +0000997//===----------------------------------------------------------------------===//
998// SDNodeInfo implementation
999//
1000SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
1001 EnumName = R->getValueAsString("Opcode");
1002 SDClassName = R->getValueAsString("SDClass");
1003 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1004 NumResults = TypeProfile->getValueAsInt("NumResults");
1005 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001006
Chris Lattner8cab0212008-01-05 22:25:12 +00001007 // Parse the properties.
1008 Properties = 0;
1009 std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
1010 for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
1011 if (PropList[i]->getName() == "SDNPCommutative") {
1012 Properties |= 1 << SDNPCommutative;
1013 } else if (PropList[i]->getName() == "SDNPAssociative") {
1014 Properties |= 1 << SDNPAssociative;
1015 } else if (PropList[i]->getName() == "SDNPHasChain") {
1016 Properties |= 1 << SDNPHasChain;
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001017 } else if (PropList[i]->getName() == "SDNPOutGlue") {
1018 Properties |= 1 << SDNPOutGlue;
1019 } else if (PropList[i]->getName() == "SDNPInGlue") {
1020 Properties |= 1 << SDNPInGlue;
1021 } else if (PropList[i]->getName() == "SDNPOptInGlue") {
1022 Properties |= 1 << SDNPOptInGlue;
Chris Lattnera348f552008-01-06 06:44:58 +00001023 } else if (PropList[i]->getName() == "SDNPMayStore") {
1024 Properties |= 1 << SDNPMayStore;
Chris Lattner1ca20682008-01-10 04:38:57 +00001025 } else if (PropList[i]->getName() == "SDNPMayLoad") {
1026 Properties |= 1 << SDNPMayLoad;
Chris Lattner42c63ef2008-01-10 05:39:30 +00001027 } else if (PropList[i]->getName() == "SDNPSideEffect") {
1028 Properties |= 1 << SDNPSideEffect;
Mon P Wang6a490372008-06-25 08:15:39 +00001029 } else if (PropList[i]->getName() == "SDNPMemOperand") {
1030 Properties |= 1 << SDNPMemOperand;
Chris Lattner83aeaab2010-03-19 05:07:09 +00001031 } else if (PropList[i]->getName() == "SDNPVariadic") {
1032 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001033 } else {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001034 errs() << "Unknown SD Node property '" << PropList[i]->getName()
1035 << "' on node '" << R->getName() << "'!\n";
Chris Lattner8cab0212008-01-05 22:25:12 +00001036 exit(1);
1037 }
1038 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001039
1040
Chris Lattner8cab0212008-01-05 22:25:12 +00001041 // Parse the type constraints.
1042 std::vector<Record*> ConstraintList =
1043 TypeProfile->getValueAsListOfDefs("Constraints");
1044 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
1045}
1046
Chris Lattner99e53b32010-02-28 00:22:30 +00001047/// getKnownType - If the type constraints on this node imply a fixed type
1048/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001049/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001050MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001051 unsigned NumResults = getNumResults();
1052 assert(NumResults <= 1 &&
1053 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001054 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001055
Chris Lattner99e53b32010-02-28 00:22:30 +00001056 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
1057 // Make sure that this applies to the correct node result.
1058 if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
1059 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001060
Chris Lattner99e53b32010-02-28 00:22:30 +00001061 switch (TypeConstraints[i].ConstraintType) {
1062 default: break;
1063 case SDTypeConstraint::SDTCisVT:
1064 return TypeConstraints[i].x.SDTCisVT_Info.VT;
1065 case SDTypeConstraint::SDTCisPtrTy:
1066 return MVT::iPTR;
1067 }
1068 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001069 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001070}
1071
Chris Lattner8cab0212008-01-05 22:25:12 +00001072//===----------------------------------------------------------------------===//
1073// TreePatternNode implementation
1074//
1075
1076TreePatternNode::~TreePatternNode() {
1077#if 0 // FIXME: implement refcounted tree nodes!
1078 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1079 delete getChild(i);
1080#endif
1081}
1082
Chris Lattnerf1447252010-03-19 21:37:09 +00001083static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1084 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001085 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001086 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001087
Chris Lattner2109cb42010-03-22 20:56:36 +00001088 if (Operator->isSubClassOf("Intrinsic"))
1089 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001090
Chris Lattnerf1447252010-03-19 21:37:09 +00001091 if (Operator->isSubClassOf("SDNode"))
1092 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001093
Chris Lattnerf1447252010-03-19 21:37:09 +00001094 if (Operator->isSubClassOf("PatFrag")) {
1095 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1096 // the forward reference case where one pattern fragment references another
1097 // before it is processed.
1098 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1099 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001100
Chris Lattnerf1447252010-03-19 21:37:09 +00001101 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001102 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001103 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001104 if (Tree)
1105 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1106 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001107 assert(Op && "Invalid Fragment");
1108 return GetNumNodeResults(Op, CDP);
1109 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001110
Chris Lattnerf1447252010-03-19 21:37:09 +00001111 if (Operator->isSubClassOf("Instruction")) {
1112 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001113
1114 // FIXME: Should allow access to all the results here.
Chris Lattnerd8adec72010-11-01 04:03:32 +00001115 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001116
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001117 // Add on one implicit def if it has a resolvable type.
1118 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1119 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001120 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001121 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001122
Chris Lattnerf1447252010-03-19 21:37:09 +00001123 if (Operator->isSubClassOf("SDNodeXForm"))
1124 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001125
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001126 if (Operator->isSubClassOf("ValueType"))
1127 return 1; // A type-cast of one result.
1128
Tim Northoverc807a172014-05-20 11:52:46 +00001129 if (Operator->isSubClassOf("ComplexPattern"))
1130 return 1;
1131
Chris Lattnerf1447252010-03-19 21:37:09 +00001132 Operator->dump();
1133 errs() << "Unhandled node in GetNumNodeResults\n";
1134 exit(1);
1135}
1136
1137void TreePatternNode::print(raw_ostream &OS) const {
1138 if (isLeaf())
1139 OS << *getLeafValue();
1140 else
1141 OS << '(' << getOperator()->getName();
1142
1143 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1144 OS << ':' << getExtType(i).getName();
Chris Lattner8cab0212008-01-05 22:25:12 +00001145
1146 if (!isLeaf()) {
1147 if (getNumChildren() != 0) {
1148 OS << " ";
1149 getChild(0)->print(OS);
1150 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1151 OS << ", ";
1152 getChild(i)->print(OS);
1153 }
1154 }
1155 OS << ")";
1156 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001157
Dan Gohman6e979022008-10-15 06:17:21 +00001158 for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
Chris Lattner514e2922011-04-17 21:38:24 +00001159 OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001160 if (TransformFn)
1161 OS << "<<X:" << TransformFn->getName() << ">>";
1162 if (!getName().empty())
1163 OS << ":$" << getName();
1164
1165}
1166void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001167 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001168}
1169
Scott Michel94420742008-03-05 17:49:05 +00001170/// isIsomorphicTo - Return true if this node is recursively
1171/// isomorphic to the specified node. For this comparison, the node's
1172/// entire state is considered. The assigned name is ignored, since
1173/// nodes with differing names are considered isomorphic. However, if
1174/// the assigned name is present in the dependent variable set, then
1175/// the assigned name is considered significant and the node is
1176/// isomorphic if the names match.
1177bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1178 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001179 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001180 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001181 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001182 getTransformFn() != N->getTransformFn())
1183 return false;
1184
1185 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001186 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1187 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001188 return ((DI->getDef() == NDI->getDef())
1189 && (DepVars.find(getName()) == DepVars.end()
1190 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001191 }
1192 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001193 return getLeafValue() == N->getLeafValue();
1194 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001195
Chris Lattner8cab0212008-01-05 22:25:12 +00001196 if (N->getOperator() != getOperator() ||
1197 N->getNumChildren() != getNumChildren()) return false;
1198 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001199 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001200 return false;
1201 return true;
1202}
1203
1204/// clone - Make a copy of this tree and all of its children.
1205///
1206TreePatternNode *TreePatternNode::clone() const {
1207 TreePatternNode *New;
1208 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001209 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001210 } else {
1211 std::vector<TreePatternNode*> CChildren;
1212 CChildren.reserve(Children.size());
1213 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1214 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001215 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001216 }
1217 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001218 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001219 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001220 New->setTransformFn(getTransformFn());
1221 return New;
1222}
1223
Chris Lattner53c39ba2010-02-14 22:22:58 +00001224/// RemoveAllTypes - Recursively strip all the types of this tree.
1225void TreePatternNode::RemoveAllTypes() {
Chris Lattnerf1447252010-03-19 21:37:09 +00001226 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1227 Types[i] = EEVT::TypeSet(); // Reset to unknown type.
Chris Lattner53c39ba2010-02-14 22:22:58 +00001228 if (isLeaf()) return;
1229 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1230 getChild(i)->RemoveAllTypes();
1231}
1232
1233
Chris Lattner8cab0212008-01-05 22:25:12 +00001234/// SubstituteFormalArguments - Replace the formal arguments in this tree
1235/// with actual values specified by ArgMap.
1236void TreePatternNode::
1237SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1238 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001239
Chris Lattner8cab0212008-01-05 22:25:12 +00001240 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1241 TreePatternNode *Child = getChild(i);
1242 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001243 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001244 // Note that, when substituting into an output pattern, Val might be an
1245 // UnsetInit.
1246 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1247 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001248 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001249 TreePatternNode *NewChild = ArgMap[Child->getName()];
1250 assert(NewChild && "Couldn't find formal argument!");
1251 assert((Child->getPredicateFns().empty() ||
1252 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1253 "Non-empty child predicate clobbered!");
1254 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001255 }
1256 } else {
1257 getChild(i)->SubstituteFormalArguments(ArgMap);
1258 }
1259 }
1260}
1261
1262
1263/// InlinePatternFragments - If this pattern refers to any pattern
1264/// fragments, inline them into place, giving us a pattern without any
1265/// PatFrag references.
1266TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001267 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001268 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001269
1270 if (isLeaf())
1271 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001272 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001273
Chris Lattner8cab0212008-01-05 22:25:12 +00001274 if (!Op->isSubClassOf("PatFrag")) {
1275 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001276 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1277 TreePatternNode *Child = getChild(i);
1278 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1279
1280 assert((Child->getPredicateFns().empty() ||
1281 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1282 "Non-empty child predicate clobbered!");
1283
1284 setChild(i, NewChild);
1285 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001286 return this;
1287 }
1288
1289 // Otherwise, we found a reference to a fragment. First, look up its
1290 // TreePattern record.
1291 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001292
Chris Lattner8cab0212008-01-05 22:25:12 +00001293 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001294 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001295 TP.error("'" + Op->getName() + "' fragment requires " +
1296 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001297 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001298 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001299
1300 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1301
Chris Lattner514e2922011-04-17 21:38:24 +00001302 TreePredicateFn PredFn(Frag);
1303 if (!PredFn.isAlwaysTrue())
1304 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001305
Chris Lattner8cab0212008-01-05 22:25:12 +00001306 // Resolve formal arguments to their actual value.
1307 if (Frag->getNumArgs()) {
1308 // Compute the map of formal to actual arguments.
1309 std::map<std::string, TreePatternNode*> ArgMap;
1310 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1311 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001312
Chris Lattner8cab0212008-01-05 22:25:12 +00001313 FragTree->SubstituteFormalArguments(ArgMap);
1314 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001315
Chris Lattner8cab0212008-01-05 22:25:12 +00001316 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001317 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1318 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001319
1320 // Transfer in the old predicates.
1321 for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
1322 FragTree->addPredicateFn(getPredicateFns()[i]);
1323
Chris Lattner8cab0212008-01-05 22:25:12 +00001324 // Get a new copy of this fragment to stitch into here.
1325 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001326
Chris Lattner2e253b42008-06-30 03:02:03 +00001327 // The fragment we inlined could have recursive inlining that is needed. See
1328 // if there are any pattern fragments in it and inline them as needed.
1329 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001330}
1331
1332/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001333/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001334/// references from the register file information, for example.
1335///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001336/// When Unnamed is set, return the type of a DAG operand with no name, such as
1337/// the F8RC register class argument in:
1338///
1339/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1340///
1341/// When Unnamed is false, return the type of a named DAG operand such as the
1342/// GPR:$src operand above.
1343///
Chris Lattnerf1447252010-03-19 21:37:09 +00001344static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001345 bool NotRegisters,
1346 bool Unnamed,
1347 TreePattern &TP) {
Owen Andersona84be6c2011-06-27 21:06:21 +00001348 // Check to see if this is a register operand.
1349 if (R->isSubClassOf("RegisterOperand")) {
1350 assert(ResNo == 0 && "Regoperand ref only has one result!");
1351 if (NotRegisters)
1352 return EEVT::TypeSet(); // Unknown.
1353 Record *RegClass = R->getValueAsDef("RegClass");
1354 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1355 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
1356 }
1357
Chris Lattnercabe0372010-03-15 06:00:16 +00001358 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001359 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001360 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001361 // An unnamed register class represents itself as an i32 immediate, for
1362 // example on a COPY_TO_REGCLASS instruction.
1363 if (Unnamed)
1364 return EEVT::TypeSet(MVT::i32, TP);
1365
1366 // In a named operand, the register class provides the possible set of
1367 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001368 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001369 return EEVT::TypeSet(); // Unknown.
1370 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1371 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001372 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001373
Chris Lattner6070ee22010-03-23 23:50:31 +00001374 if (R->isSubClassOf("PatFrag")) {
1375 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001376 // Pattern fragment types will be resolved when they are inlined.
Chris Lattnercabe0372010-03-15 06:00:16 +00001377 return EEVT::TypeSet(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001378 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001379
Chris Lattner6070ee22010-03-23 23:50:31 +00001380 if (R->isSubClassOf("Register")) {
1381 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001382 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001383 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001384 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Chris Lattnercabe0372010-03-15 06:00:16 +00001385 return EEVT::TypeSet(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001386 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001387
1388 if (R->isSubClassOf("SubRegIndex")) {
1389 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
1390 return EEVT::TypeSet();
1391 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001392
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001393 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001394 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001395 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1396 //
1397 // (sext_inreg GPR:$src, i16)
1398 // ~~~
1399 if (Unnamed)
1400 return EEVT::TypeSet(MVT::Other, TP);
1401 // With a name, the ValueType simply provides the type of the named
1402 // variable.
1403 //
1404 // (sext_inreg i32:$src, i16)
1405 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001406 if (NotRegisters)
1407 return EEVT::TypeSet(); // Unknown.
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001408 return EEVT::TypeSet(getValueType(R), TP);
1409 }
1410
1411 if (R->isSubClassOf("CondCode")) {
1412 assert(ResNo == 0 && "This node only has one result!");
1413 // Using a CondCodeSDNode.
Chris Lattnercabe0372010-03-15 06:00:16 +00001414 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001415 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001416
Chris Lattner6070ee22010-03-23 23:50:31 +00001417 if (R->isSubClassOf("ComplexPattern")) {
1418 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001419 if (NotRegisters)
Chris Lattnercabe0372010-03-15 06:00:16 +00001420 return EEVT::TypeSet(); // Unknown.
1421 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
1422 TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001423 }
1424 if (R->isSubClassOf("PointerLikeRegClass")) {
1425 assert(ResNo == 0 && "Regclass can only have one result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00001426 return EEVT::TypeSet(MVT::iPTR, TP);
Chris Lattner6070ee22010-03-23 23:50:31 +00001427 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001428
Chris Lattner6070ee22010-03-23 23:50:31 +00001429 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1430 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001431 // Placeholder.
Chris Lattnercabe0372010-03-15 06:00:16 +00001432 return EEVT::TypeSet(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001433 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001434
Tim Northoverc807a172014-05-20 11:52:46 +00001435 if (R->isSubClassOf("Operand"))
1436 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type")));
1437
Chris Lattner8cab0212008-01-05 22:25:12 +00001438 TP.error("Unknown node flavor used in pattern: " + R->getName());
Chris Lattnercabe0372010-03-15 06:00:16 +00001439 return EEVT::TypeSet(MVT::Other, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001440}
1441
Chris Lattner89c65662008-01-06 05:36:50 +00001442
1443/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1444/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1445const CodeGenIntrinsic *TreePatternNode::
1446getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1447 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1448 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1449 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001450 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001451
Sean Silva88eb8dd2012-10-10 20:24:47 +00001452 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001453 return &CDP.getIntrinsicInfo(IID);
1454}
1455
Chris Lattner53c39ba2010-02-14 22:22:58 +00001456/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1457/// return the ComplexPattern information, otherwise return null.
1458const ComplexPattern *
1459TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001460 Record *Rec;
1461 if (isLeaf()) {
1462 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1463 if (!DI)
1464 return nullptr;
1465 Rec = DI->getDef();
1466 } else
1467 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001468
Tim Northoverc807a172014-05-20 11:52:46 +00001469 if (!Rec->isSubClassOf("ComplexPattern"))
1470 return nullptr;
1471 return &CGP.getComplexPattern(Rec);
1472}
1473
1474unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1475 // A ComplexPattern specifically declares how many results it fills in.
1476 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1477 return CP->getNumOperands();
1478
1479 // If MIOperandInfo is specified, that gives the count.
1480 if (isLeaf()) {
1481 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1482 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1483 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1484 if (MIOps->getNumArgs())
1485 return MIOps->getNumArgs();
1486 }
1487 }
1488
1489 // Otherwise there is just one result.
1490 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001491}
1492
1493/// NodeHasProperty - Return true if this node has the specified property.
1494bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001495 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001496 if (isLeaf()) {
1497 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1498 return CP->hasProperty(Property);
1499 return false;
1500 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001501
Chris Lattner53c39ba2010-02-14 22:22:58 +00001502 Record *Operator = getOperator();
1503 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001504
Chris Lattner53c39ba2010-02-14 22:22:58 +00001505 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1506}
1507
1508
1509
1510
1511/// TreeHasProperty - Return true if any node in this tree has the specified
1512/// property.
1513bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001514 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001515 if (NodeHasProperty(Property, CGP))
1516 return true;
1517 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1518 if (getChild(i)->TreeHasProperty(Property, CGP))
1519 return true;
1520 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001521}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001522
Evan Cheng49bad4c2008-06-16 20:29:38 +00001523/// isCommutativeIntrinsic - Return true if the node corresponds to a
1524/// commutative intrinsic.
1525bool
1526TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1527 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1528 return Int->isCommutative;
1529 return false;
1530}
1531
Chris Lattner89c65662008-01-06 05:36:50 +00001532
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001533/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001534/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001535/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001536bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001537 if (TP.hasError())
1538 return false;
1539
Chris Lattnerab3242f2008-01-06 01:10:31 +00001540 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001541 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001542 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001543 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001544 bool MadeChange = false;
1545 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1546 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001547 NotRegisters,
1548 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001549 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001550 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001551
Sean Silvafb509ed2012-10-10 20:24:43 +00001552 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001553 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001554
Chris Lattnerf1447252010-03-19 21:37:09 +00001555 // Int inits are always integers. :)
1556 bool MadeChange = Types[0].EnforceInteger(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001557
Chris Lattnerf1447252010-03-19 21:37:09 +00001558 if (!Types[0].isConcrete())
Chris Lattnercabe0372010-03-15 06:00:16 +00001559 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001560
Chris Lattnerf1447252010-03-19 21:37:09 +00001561 MVT::SimpleValueType VT = getType(0);
Chris Lattnercabe0372010-03-15 06:00:16 +00001562 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1563 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001564
Craig Topper95198f42013-09-25 06:37:18 +00001565 unsigned Size = MVT(VT).getSizeInBits();
Chris Lattnercabe0372010-03-15 06:00:16 +00001566 // Make sure that the value is representable for this type.
1567 if (Size >= 32) return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001568
Richard Smith228e6d42012-08-24 23:29:28 +00001569 // Check that the value doesn't use more bits than we have. It must either
1570 // be a sign- or zero-extended equivalent of the original.
1571 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1572 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
Chris Lattnercabe0372010-03-15 06:00:16 +00001573 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001574
Richard Smith228e6d42012-08-24 23:29:28 +00001575 TP.error("Integer value '" + itostr(II->getValue()) +
Chris Lattnerf1447252010-03-19 21:37:09 +00001576 "' is out of range for type '" + getEnumName(getType(0)) + "'!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001577 return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001578 }
1579 return false;
1580 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001581
Chris Lattner8cab0212008-01-05 22:25:12 +00001582 // special handling for set, which isn't really an SDNode.
1583 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001584 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1585 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001586 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001587
Chris Lattnerf1447252010-03-19 21:37:09 +00001588 TreePatternNode *SetVal = getChild(NC-1);
1589 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1590
Chris Lattner8cab0212008-01-05 22:25:12 +00001591 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001592 TreePatternNode *Child = getChild(i);
1593 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001594
Chris Lattner8cab0212008-01-05 22:25:12 +00001595 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001596 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1597 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001598 }
1599 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001600 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001601
Chris Lattner5c2182e2010-03-27 02:53:27 +00001602 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001603 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1604
Chris Lattner8cab0212008-01-05 22:25:12 +00001605 bool MadeChange = false;
1606 for (unsigned i = 0; i < getNumChildren(); ++i)
1607 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001608 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001609 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001610
Chris Lattneree820ac2010-02-23 05:51:07 +00001611 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001612 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001613
Chris Lattner8cab0212008-01-05 22:25:12 +00001614 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001615 unsigned NumRetVTs = Int->IS.RetVTs.size();
1616 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001617
Bill Wendling91821472008-11-13 09:08:33 +00001618 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001619 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001620
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001621 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001622 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001623 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001624 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001625 return false;
1626 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001627
1628 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001629 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001630
Chris Lattnerf1447252010-03-19 21:37:09 +00001631 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1632 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001633
Chris Lattnerf1447252010-03-19 21:37:09 +00001634 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1635 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1636 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001637 }
1638 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001639 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001640
Chris Lattneree820ac2010-02-23 05:51:07 +00001641 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001642 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001643
Chris Lattner135091b2010-03-28 08:48:47 +00001644 // Check that the number of operands is sane. Negative operands -> varargs.
1645 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001646 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001647 TP.error(getOperator()->getName() + " node requires exactly " +
1648 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001649 return false;
1650 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001651
Chris Lattner8cab0212008-01-05 22:25:12 +00001652 bool MadeChange = NI.ApplyTypeConstraints(this, TP);
1653 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1654 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnerf1447252010-03-19 21:37:09 +00001655 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001656 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001657
Chris Lattneree820ac2010-02-23 05:51:07 +00001658 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001659 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001660 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001661 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001662
Chris Lattnerd44966f2010-03-27 19:15:02 +00001663 bool MadeChange = false;
1664
1665 // Apply the result types to the node, these come from the things in the
1666 // (outs) list of the instruction.
1667 // FIXME: Cap at one result so far.
Chris Lattnerd8adec72010-11-01 04:03:32 +00001668 unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001669 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1670 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001671
Chris Lattnerd44966f2010-03-27 19:15:02 +00001672 // If the instruction has implicit defs, we apply the first one as a result.
1673 // FIXME: This sucks, it should apply all implicit defs.
1674 if (!InstInfo.ImplicitDefs.empty()) {
1675 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001676
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001677 // FIXME: Generalize to multiple possible types and multiple possible
1678 // ImplicitDefs.
1679 MVT::SimpleValueType VT =
1680 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001681
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001682 if (VT != MVT::Other)
1683 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001684 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001685
Chris Lattnercabe0372010-03-15 06:00:16 +00001686 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1687 // be the same.
1688 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001689 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1690 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
1691 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001692 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001693
1694 unsigned ChildNo = 0;
1695 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
1696 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001697
Chris Lattner8cab0212008-01-05 22:25:12 +00001698 // If the instruction expects a predicate or optional def operand, we
1699 // codegen this by setting the operand to it's default value if it has a
1700 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00001701 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001702 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1703 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001704
Chris Lattner8cab0212008-01-05 22:25:12 +00001705 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001706 if (ChildNo >= getNumChildren()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001707 TP.error("Instruction '" + getOperator()->getName() +
1708 "' expects more operands than were provided.");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001709 return false;
1710 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001711
Chris Lattner8cab0212008-01-05 22:25:12 +00001712 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001713 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00001714
1715 // If the operand has sub-operands, they may be provided by distinct
1716 // child patterns, so attempt to match each sub-operand separately.
1717 if (OperandNode->isSubClassOf("Operand")) {
1718 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
1719 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
1720 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00001721 // a single ComplexPattern-related Operand.
1722
1723 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00001724 // Match first sub-operand against the child we already have.
1725 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
1726 MadeChange |=
1727 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1728
1729 // And the remaining sub-operands against subsequent children.
1730 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
1731 if (ChildNo >= getNumChildren()) {
1732 TP.error("Instruction '" + getOperator()->getName() +
1733 "' expects more operands than were provided.");
1734 return false;
1735 }
1736 Child = getChild(ChildNo++);
1737
1738 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
1739 MadeChange |=
1740 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
1741 }
1742 continue;
1743 }
1744 }
1745 }
1746
1747 // If we didn't match by pieces above, attempt to match the whole
1748 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001749 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001750 }
Christopher Lamba7312392008-03-11 09:33:47 +00001751
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001752 if (ChildNo != getNumChildren()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001753 TP.error("Instruction '" + getOperator()->getName() +
1754 "' was provided too many operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001755 return false;
1756 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001757
Ulrich Weigande618abd2013-03-19 19:51:09 +00001758 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1759 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001760 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001761 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001762
Tim Northoverc807a172014-05-20 11:52:46 +00001763 if (getOperator()->isSubClassOf("ComplexPattern")) {
1764 bool MadeChange = false;
1765
1766 for (unsigned i = 0; i < getNumChildren(); ++i)
1767 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
1768
1769 return MadeChange;
1770 }
1771
Chris Lattneree820ac2010-02-23 05:51:07 +00001772 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001773
Chris Lattneree820ac2010-02-23 05:51:07 +00001774 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001775 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00001776 TP.error("Node transform '" + getOperator()->getName() +
1777 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001778 return false;
1779 }
Chris Lattneree820ac2010-02-23 05:51:07 +00001780
Chris Lattnercabe0372010-03-15 06:00:16 +00001781 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
1782
Jim Grosbach65586fe2010-12-21 16:16:00 +00001783
Chris Lattneree820ac2010-02-23 05:51:07 +00001784 // If either the output or input of the xform does not have exact
1785 // type info. We assume they must be the same. Otherwise, it is perfectly
1786 // legal to transform from one type to a completely different type.
Chris Lattnercabe0372010-03-15 06:00:16 +00001787#if 0
Chris Lattneree820ac2010-02-23 05:51:07 +00001788 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001789 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
1790 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
Chris Lattneree820ac2010-02-23 05:51:07 +00001791 return MadeChange;
1792 }
Chris Lattnercabe0372010-03-15 06:00:16 +00001793#endif
1794 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001795}
1796
1797/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
1798/// RHS of a commutative operation, not the on LHS.
1799static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
1800 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
1801 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001802 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00001803 return true;
1804 return false;
1805}
1806
1807
1808/// canPatternMatch - If it is impossible for this pattern to match on this
1809/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00001810/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00001811/// that can never possibly work), and to prevent the pattern permuter from
1812/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001813bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00001814 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001815 if (isLeaf()) return true;
1816
1817 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1818 if (!getChild(i)->canPatternMatch(Reason, CDP))
1819 return false;
1820
1821 // If this is an intrinsic, handle cases that would make it not match. For
1822 // example, if an operand is required to be an immediate.
1823 if (getOperator()->isSubClassOf("Intrinsic")) {
1824 // TODO:
1825 return true;
1826 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001827
Tim Northoverc807a172014-05-20 11:52:46 +00001828 if (getOperator()->isSubClassOf("ComplexPattern"))
1829 return true;
1830
Chris Lattner8cab0212008-01-05 22:25:12 +00001831 // If this node is a commutative operator, check that the LHS isn't an
1832 // immediate.
1833 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00001834 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
1835 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001836 // Scan all of the operands of the node and make sure that only the last one
1837 // is a constant node, unless the RHS also is.
1838 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Evan Cheng49bad4c2008-06-16 20:29:38 +00001839 bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
1840 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00001841 if (OnlyOnRHSOfCommutative(getChild(i))) {
1842 Reason="Immediate value must be on the RHS of commutative operators!";
1843 return false;
1844 }
1845 }
1846 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001847
Chris Lattner8cab0212008-01-05 22:25:12 +00001848 return true;
1849}
1850
1851//===----------------------------------------------------------------------===//
1852// TreePattern implementation
1853//
1854
David Greeneaf8ee2c2011-07-29 22:43:06 +00001855TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001856 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1857 isInputPattern(isInput), HasError(false) {
Chris Lattnercabe0372010-03-15 06:00:16 +00001858 for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001859 Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001860}
1861
David Greeneaf8ee2c2011-07-29 22:43:06 +00001862TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001863 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1864 isInputPattern(isInput), HasError(false) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001865 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00001866}
1867
1868TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001869 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
1870 isInputPattern(isInput), HasError(false) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001871 Trees.push_back(Pat);
1872}
1873
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001874void TreePattern::error(const std::string &Msg) {
1875 if (HasError)
1876 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00001877 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001878 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
1879 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00001880}
1881
Chris Lattnercabe0372010-03-15 06:00:16 +00001882void TreePattern::ComputeNamedNodes() {
1883 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
1884 ComputeNamedNodes(Trees[i]);
1885}
1886
1887void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
1888 if (!N->getName().empty())
1889 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001890
Chris Lattnercabe0372010-03-15 06:00:16 +00001891 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
1892 ComputeNamedNodes(N->getChild(i));
1893}
1894
Chris Lattnerf1447252010-03-19 21:37:09 +00001895
David Greeneaf8ee2c2011-07-29 22:43:06 +00001896TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00001897 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001898 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001899
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001900 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00001901 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001902 /// (foo GPR, imm) -> (foo GPR, (imm))
1903 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00001904 return ParseTreePattern(
1905 DagInit::get(DI, "",
David Greeneaf8ee2c2011-07-29 22:43:06 +00001906 std::vector<std::pair<Init*, std::string> >()),
David Greenee32ebf22011-07-29 19:07:07 +00001907 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001908
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001909 // Input argument?
1910 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00001911 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001912 if (OpName.empty())
1913 error("'node' argument requires a name to match with operand list");
1914 Args.push_back(OpName);
1915 }
1916
1917 Res->setName(OpName);
1918 return Res;
1919 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001920
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00001921 // ?:$name or just $name.
1922 if (TheInit == UnsetInit::get()) {
1923 if (OpName.empty())
1924 error("'?' argument requires a name to match with operand list");
1925 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
1926 Args.push_back(OpName);
1927 Res->setName(OpName);
1928 return Res;
1929 }
1930
Sean Silvafb509ed2012-10-10 20:24:43 +00001931 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001932 if (!OpName.empty())
1933 error("Constant int argument should not have a name!");
1934 return new TreePatternNode(II, 1);
1935 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001936
Sean Silvafb509ed2012-10-10 20:24:43 +00001937 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001938 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001939 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00001940 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001941 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00001942 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001943 }
1944
Sean Silvafb509ed2012-10-10 20:24:43 +00001945 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001946 if (!Dag) {
1947 TheInit->dump();
1948 error("Pattern has unexpected init kind!");
1949 }
Sean Silvafb509ed2012-10-10 20:24:43 +00001950 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001951 if (!OpDef) error("Pattern has unexpected operator type!");
1952 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001953
Chris Lattner8cab0212008-01-05 22:25:12 +00001954 if (Operator->isSubClassOf("ValueType")) {
1955 // If the operator is a ValueType, then this must be "type cast" of a leaf
1956 // node.
1957 if (Dag->getNumArgs() != 1)
1958 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001959
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001960 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00001961
Chris Lattner8cab0212008-01-05 22:25:12 +00001962 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00001963 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
1964 New->UpdateNodeType(0, getValueType(Operator), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001965
Chris Lattneradf7ecf2010-03-28 06:50:34 +00001966 if (!OpName.empty())
1967 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001968 return New;
1969 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001970
Chris Lattner8cab0212008-01-05 22:25:12 +00001971 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001972 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00001973 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00001974 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001975 !Operator->isSubClassOf("SDNodeXForm") &&
1976 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00001977 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00001978 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00001979 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00001980 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001981
Chris Lattner8cab0212008-01-05 22:25:12 +00001982 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00001983 if (isInputPattern) {
1984 if (Operator->isSubClassOf("Instruction") ||
1985 Operator->isSubClassOf("SDNodeXForm"))
1986 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
1987 } else {
1988 if (Operator->isSubClassOf("Intrinsic"))
1989 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001990
Chris Lattner2e9eae12010-03-28 06:57:56 +00001991 if (Operator->isSubClassOf("SDNode") &&
1992 Operator->getName() != "imm" &&
1993 Operator->getName() != "fpimm" &&
1994 Operator->getName() != "tglobaltlsaddr" &&
1995 Operator->getName() != "tconstpool" &&
1996 Operator->getName() != "tjumptable" &&
1997 Operator->getName() != "tframeindex" &&
1998 Operator->getName() != "texternalsym" &&
1999 Operator->getName() != "tblockaddress" &&
2000 Operator->getName() != "tglobaladdr" &&
2001 Operator->getName() != "bb" &&
2002 Operator->getName() != "vt")
2003 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2004 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002005
Chris Lattner8cab0212008-01-05 22:25:12 +00002006 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002007
2008 // Parse all the operands.
2009 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2010 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002011
Chris Lattner8cab0212008-01-05 22:25:12 +00002012 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002013 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002014 // convert the intrinsic name to a number.
2015 if (Operator->isSubClassOf("Intrinsic")) {
2016 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2017 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2018
2019 // If this intrinsic returns void, it must have side-effects and thus a
2020 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002021 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002022 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002023 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002024 // Has side-effects, requires chain.
2025 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002026 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002027 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002028
David Greenee32ebf22011-07-29 19:07:07 +00002029 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002030 Children.insert(Children.begin(), IIDNode);
2031 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002032
Tim Northoverc807a172014-05-20 11:52:46 +00002033 if (Operator->isSubClassOf("ComplexPattern")) {
2034 for (unsigned i = 0; i < Children.size(); ++i) {
2035 TreePatternNode *Child = Children[i];
2036
2037 if (Child->getName().empty())
2038 error("All arguments to a ComplexPattern must be named");
2039
2040 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2041 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2042 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2043 auto OperandId = std::make_pair(Operator, i);
2044 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2045 if (PrevOp != ComplexPatternOperands.end()) {
2046 if (PrevOp->getValue() != OperandId)
2047 error("All ComplexPattern operands must appear consistently: "
2048 "in the same order in just one ComplexPattern instance.");
2049 } else
2050 ComplexPatternOperands[Child->getName()] = OperandId;
2051 }
2052 }
2053
Chris Lattnerf1447252010-03-19 21:37:09 +00002054 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2055 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002056 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002057
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002058 if (!Dag->getName().empty()) {
2059 assert(Result->getName().empty());
2060 Result->setName(Dag->getName());
2061 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002062 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002063}
2064
Chris Lattnera787c9e2010-03-28 08:38:32 +00002065/// SimplifyTree - See if we can simplify this tree to eliminate something that
2066/// will never match in favor of something obvious that will. This is here
2067/// strictly as a convenience to target authors because it allows them to write
2068/// more type generic things and have useless type casts fold away.
2069///
2070/// This returns true if any change is made.
2071static bool SimplifyTree(TreePatternNode *&N) {
2072 if (N->isLeaf())
2073 return false;
2074
2075 // If we have a bitconvert with a resolved type and if the source and
2076 // destination types are the same, then the bitconvert is useless, remove it.
2077 if (N->getOperator()->getName() == "bitconvert" &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002078 N->getExtType(0).isConcrete() &&
2079 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2080 N->getName().empty()) {
2081 N = N->getChild(0);
2082 SimplifyTree(N);
2083 return true;
2084 }
2085
2086 // Walk all children.
2087 bool MadeChange = false;
2088 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
2089 TreePatternNode *Child = N->getChild(i);
2090 MadeChange |= SimplifyTree(Child);
2091 N->setChild(i, Child);
2092 }
2093 return MadeChange;
2094}
2095
2096
2097
Chris Lattner8cab0212008-01-05 22:25:12 +00002098/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002099/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002100/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002101bool TreePattern::
2102InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2103 if (NamedNodes.empty())
2104 ComputeNamedNodes();
2105
Chris Lattner8cab0212008-01-05 22:25:12 +00002106 bool MadeChange = true;
2107 while (MadeChange) {
2108 MadeChange = false;
Chris Lattnera787c9e2010-03-28 08:38:32 +00002109 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002110 MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002111 MadeChange |= SimplifyTree(Trees[i]);
2112 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002113
2114 // If there are constraints on our named nodes, apply them.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002115 for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
Chris Lattnercabe0372010-03-15 06:00:16 +00002116 I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
2117 SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002118
Chris Lattnercabe0372010-03-15 06:00:16 +00002119 // If we have input named node types, propagate their types to the named
2120 // values here.
2121 if (InNamedTypes) {
Jim Grosbach37b80932014-07-09 18:55:49 +00002122 if (!InNamedTypes->count(I->getKey())) {
2123 error("Node '" + std::string(I->getKey()) +
2124 "' in output pattern but not input pattern");
2125 return true;
2126 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002127
2128 const SmallVectorImpl<TreePatternNode*> &InNodes =
2129 InNamedTypes->find(I->getKey())->second;
2130
2131 // The input types should be fully resolved by now.
2132 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2133 // If this node is a register class, and it is the root of the pattern
2134 // then we're mapping something onto an input register. We allow
2135 // changing the type of the input register in this case. This allows
2136 // us to match things like:
2137 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
2138 if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002139 DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002140 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2141 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002142 continue;
2143 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002144
Daniel Dunbard177edf2010-03-21 01:38:21 +00002145 assert(Nodes[i]->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002146 InNodes[0]->getNumTypes() == 1 &&
2147 "FIXME: cannot name multiple result nodes yet");
2148 MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
2149 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002150 }
2151 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002152
Chris Lattnercabe0372010-03-15 06:00:16 +00002153 // If there are multiple nodes with the same name, they must all have the
2154 // same type.
2155 if (I->second.size() > 1) {
2156 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002157 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002158 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002159 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002160
Chris Lattnerf1447252010-03-19 21:37:09 +00002161 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2162 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002163 }
2164 }
2165 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002166 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002167
Chris Lattner8cab0212008-01-05 22:25:12 +00002168 bool HasUnresolvedTypes = false;
2169 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
2170 HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
2171 return !HasUnresolvedTypes;
2172}
2173
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002174void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002175 OS << getRecord()->getName();
2176 if (!Args.empty()) {
2177 OS << "(" << Args[0];
2178 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2179 OS << ", " << Args[i];
2180 OS << ")";
2181 }
2182 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002183
Chris Lattner8cab0212008-01-05 22:25:12 +00002184 if (Trees.size() > 1)
2185 OS << "[\n";
2186 for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
2187 OS << "\t";
2188 Trees[i]->print(OS);
2189 OS << "\n";
2190 }
2191
2192 if (Trees.size() > 1)
2193 OS << "]\n";
2194}
2195
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002196void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002197
2198//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002199// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002200//
2201
Jim Grosbach65586fe2010-12-21 16:16:00 +00002202CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Chris Lattner77d369c2010-12-13 00:23:57 +00002203 Records(R), Target(R) {
2204
Dale Johannesenb842d522009-02-05 01:49:45 +00002205 Intrinsics = LoadIntrinsics(Records, false);
2206 TgtIntrinsics = LoadIntrinsics(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002207 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002208 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002209 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002210 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002211 ParseDefaultOperands();
2212 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002213 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002214 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002215
Chris Lattner8cab0212008-01-05 22:25:12 +00002216 // Generate variants. For example, commutative patterns can match
2217 // multiple ways. Add them to PatternsToMatch as well.
2218 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002219
2220 // Infer instruction flags. For example, we can detect loads,
2221 // stores, and side effects in many cases by examining an
2222 // instruction's pattern.
2223 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002224
2225 // Verify that instruction flags match the patterns.
2226 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002227}
2228
Chris Lattnerab3242f2008-01-06 01:10:31 +00002229CodeGenDAGPatterns::~CodeGenDAGPatterns() {
Benjamin Kramerc2dbd5d2009-08-23 10:39:21 +00002230 for (pf_iterator I = PatternFragments.begin(),
Chris Lattner8cab0212008-01-05 22:25:12 +00002231 E = PatternFragments.end(); I != E; ++I)
2232 delete I->second;
2233}
2234
2235
Chris Lattnerab3242f2008-01-06 01:10:31 +00002236Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002237 Record *N = Records.getDef(Name);
2238 if (!N || !N->isSubClassOf("SDNode")) {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002239 errs() << "Error getting SDNode '" << Name << "'!\n";
Chris Lattner8cab0212008-01-05 22:25:12 +00002240 exit(1);
2241 }
2242 return N;
2243}
2244
2245// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002246void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002247 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
2248 while (!Nodes.empty()) {
2249 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
2250 Nodes.pop_back();
2251 }
2252
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002253 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002254 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2255 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2256 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2257}
2258
2259/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2260/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002261void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002262 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2263 while (!Xforms.empty()) {
2264 Record *XFormNode = Xforms.back();
2265 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00002266 std::string Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002267 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002268
2269 Xforms.pop_back();
2270 }
2271}
2272
Chris Lattnerab3242f2008-01-06 01:10:31 +00002273void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002274 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2275 while (!AMs.empty()) {
2276 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2277 AMs.pop_back();
2278 }
2279}
2280
2281
2282/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2283/// file, building up the PatternFragments map. After we've collected them all,
2284/// inline fragments together as necessary, so that there are no references left
2285/// inside a pattern fragment to a pattern fragment.
2286///
Hal Finkel2756dc12014-02-28 00:26:56 +00002287void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002288 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002289
Chris Lattnere7170df2008-01-05 22:43:57 +00002290 // First step, parse all of the fragments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002291 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Hal Finkel2756dc12014-02-28 00:26:56 +00002292 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2293 continue;
2294
David Greeneaf8ee2c2011-07-29 22:43:06 +00002295 DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002296 TreePattern *P =
2297 new TreePattern(Fragments[i], Tree,
2298 !Fragments[i]->isSubClassOf("OutPatFrag"), *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002299 PatternFragments[Fragments[i]] = P;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002300
Chris Lattnere7170df2008-01-05 22:43:57 +00002301 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002302 std::vector<std::string> &Args = P->getArgList();
Chris Lattnere7170df2008-01-05 22:43:57 +00002303 std::set<std::string> OperandsSet(Args.begin(), Args.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002304
Chris Lattnere7170df2008-01-05 22:43:57 +00002305 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002306 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002307
Chris Lattner8cab0212008-01-05 22:25:12 +00002308 // Parse the operands list.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002309 DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002310 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002311 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002312 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002313 if (!OpsOp ||
2314 (OpsOp->getDef()->getName() != "ops" &&
2315 OpsOp->getDef()->getName() != "outs" &&
2316 OpsOp->getDef()->getName() != "ins"))
2317 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002318
2319 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002320 Args.clear();
2321 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002322 if (!isa<DefInit>(OpsList->getArg(j)) ||
2323 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002324 P->error("Operands list should all be 'node' values.");
2325 if (OpsList->getArgName(j).empty())
2326 P->error("Operands list should have names for each operand!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002327 if (!OperandsSet.count(OpsList->getArgName(j)))
Chris Lattner8cab0212008-01-05 22:25:12 +00002328 P->error("'" + OpsList->getArgName(j) +
2329 "' does not occur in pattern or was multiply specified!");
Chris Lattnere7170df2008-01-05 22:43:57 +00002330 OperandsSet.erase(OpsList->getArgName(j));
Chris Lattner8cab0212008-01-05 22:25:12 +00002331 Args.push_back(OpsList->getArgName(j));
2332 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002333
Chris Lattnere7170df2008-01-05 22:43:57 +00002334 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002335 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002336 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002337
Chris Lattnere7170df2008-01-05 22:43:57 +00002338 // If there is a code init for this fragment, keep track of the fact that
2339 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002340 TreePredicateFn PredFn(P);
2341 if (!PredFn.isAlwaysTrue())
2342 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002343
Chris Lattner8cab0212008-01-05 22:25:12 +00002344 // If there is a node transformation corresponding to this, keep track of
2345 // it.
2346 Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
2347 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2348 P->getOnlyTree()->setTransformFn(Transform);
2349 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002350
Chris Lattner8cab0212008-01-05 22:25:12 +00002351 // Now that we've parsed all of the tree fragments, do a closure on them so
2352 // that there are not references to PatFrags left inside of them.
Chris Lattner2e253b42008-06-30 03:02:03 +00002353 for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
Hal Finkel2756dc12014-02-28 00:26:56 +00002354 if (OutFrags != Fragments[i]->isSubClassOf("OutPatFrag"))
2355 continue;
2356
Chris Lattner2e253b42008-06-30 03:02:03 +00002357 TreePattern *ThePat = PatternFragments[Fragments[i]];
Chris Lattner8cab0212008-01-05 22:25:12 +00002358 ThePat->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002359
Chris Lattner8cab0212008-01-05 22:25:12 +00002360 // Infer as many types as possible. Don't worry about it if we don't infer
2361 // all of them, some may depend on the inputs of the pattern.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002362 ThePat->InferAllTypes();
2363 ThePat->resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002364
Chris Lattner8cab0212008-01-05 22:25:12 +00002365 // If debugging, print out the pattern fragment result.
2366 DEBUG(ThePat->dump());
2367 }
2368}
2369
Chris Lattnerab3242f2008-01-06 01:10:31 +00002370void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002371 std::vector<Record*> DefaultOps;
2372 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002373
2374 // Find some SDNode.
2375 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002376 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002377
Tom Stellardb7246a72012-09-06 14:15:52 +00002378 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2379 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002380
Tom Stellardb7246a72012-09-06 14:15:52 +00002381 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2382 // SomeSDnode so that we can parse this.
2383 std::vector<std::pair<Init*, std::string> > Ops;
2384 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2385 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2386 DefaultInfo->getArgName(op)));
2387 DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002388
Tom Stellardb7246a72012-09-06 14:15:52 +00002389 // Create a TreePattern to parse this.
2390 TreePattern P(DefaultOps[i], DI, false, *this);
2391 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002392
Tom Stellardb7246a72012-09-06 14:15:52 +00002393 // Copy the operands over into a DAGDefaultOperand.
2394 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002395
Tom Stellardb7246a72012-09-06 14:15:52 +00002396 TreePatternNode *T = P.getTree(0);
2397 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2398 TreePatternNode *TPN = T->getChild(op);
2399 while (TPN->ApplyTypeConstraints(P, false))
2400 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002401
Tom Stellardb7246a72012-09-06 14:15:52 +00002402 if (TPN->ContainsUnresolvedType()) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002403 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2404 DefaultOps[i]->getName() +
2405 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002406 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002407 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002408 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002409
2410 // Insert it into the DefaultOperands map so we can find it later.
2411 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002412 }
2413}
2414
2415/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2416/// instruction input. Return true if this is a real use.
2417static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002418 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002419 // No name -> not interesting.
2420 if (Pat->getName().empty()) {
2421 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002422 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002423 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2424 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002425 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002426 }
2427 return false;
2428 }
2429
2430 Record *Rec;
2431 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002432 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002433 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2434 Rec = DI->getDef();
2435 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002436 Rec = Pat->getOperator();
2437 }
2438
2439 // SRCVALUE nodes are ignored.
2440 if (Rec->getName() == "srcvalue")
2441 return false;
2442
2443 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2444 if (!Slot) {
2445 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002446 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002447 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002448 Record *SlotRec;
2449 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002450 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002451 } else {
2452 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2453 SlotRec = Slot->getOperator();
2454 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002455
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002456 // Ensure that the inputs agree if we've already seen this input.
2457 if (Rec != SlotRec)
2458 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002459 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002460 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002461 return true;
2462}
2463
2464/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2465/// part of "I", the instruction), computing the set of inputs and outputs of
2466/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002467void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002468FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2469 std::map<std::string, TreePatternNode*> &InstInputs,
2470 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002471 std::vector<Record*> &InstImpResults) {
2472 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002473 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002474 if (!isUse && Pat->getTransformFn())
2475 I->error("Cannot specify a transform function for a non-input value!");
2476 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002477 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002478
Chris Lattnerf2d70992010-02-17 06:53:36 +00002479 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002480 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2481 TreePatternNode *Dest = Pat->getChild(i);
2482 if (!Dest->isLeaf())
2483 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002484
Sean Silvafb509ed2012-10-10 20:24:43 +00002485 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002486 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2487 I->error("implicitly defined value should be a register!");
2488 InstImpResults.push_back(Val->getDef());
2489 }
2490 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002491 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002492
Chris Lattnerf2d70992010-02-17 06:53:36 +00002493 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002494 // If this is not a set, verify that the children nodes are not void typed,
2495 // and recurse.
2496 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002497 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002498 I->error("Cannot have void nodes inside of patterns!");
2499 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002500 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002501 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002502
Chris Lattner8cab0212008-01-05 22:25:12 +00002503 // If this is a non-leaf node with no children, treat it basically as if
2504 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002505 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002506
Chris Lattner8cab0212008-01-05 22:25:12 +00002507 if (!isUse && Pat->getTransformFn())
2508 I->error("Cannot specify a transform function for a non-input value!");
2509 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002510 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002511
Chris Lattner8cab0212008-01-05 22:25:12 +00002512 // Otherwise, this is a set, validate and collect instruction results.
2513 if (Pat->getNumChildren() == 0)
2514 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002515
Chris Lattner8cab0212008-01-05 22:25:12 +00002516 if (Pat->getTransformFn())
2517 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002518
Chris Lattner8cab0212008-01-05 22:25:12 +00002519 // Check the set destinations.
2520 unsigned NumDests = Pat->getNumChildren()-1;
2521 for (unsigned i = 0; i != NumDests; ++i) {
2522 TreePatternNode *Dest = Pat->getChild(i);
2523 if (!Dest->isLeaf())
2524 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002525
Sean Silvafb509ed2012-10-10 20:24:43 +00002526 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002527 if (!Val)
2528 I->error("set destination should be a register!");
2529
2530 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002531 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002532 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002533 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002534 if (Dest->getName().empty())
2535 I->error("set destination must have a name!");
2536 if (InstResults.count(Dest->getName()))
2537 I->error("cannot set '" + Dest->getName() +"' multiple times");
2538 InstResults[Dest->getName()] = Dest;
2539 } else if (Val->getDef()->isSubClassOf("Register")) {
2540 InstImpResults.push_back(Val->getDef());
2541 } else {
2542 I->error("set destination should be a register!");
2543 }
2544 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002545
Chris Lattner8cab0212008-01-05 22:25:12 +00002546 // Verify and collect info from the computation.
2547 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002548 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002549}
2550
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002551//===----------------------------------------------------------------------===//
2552// Instruction Analysis
2553//===----------------------------------------------------------------------===//
2554
2555class InstAnalyzer {
2556 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002557public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002558 bool hasSideEffects;
2559 bool mayStore;
2560 bool mayLoad;
2561 bool isBitcast;
2562 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002563
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002564 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2565 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2566 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002567
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002568 void Analyze(const TreePattern *Pat) {
2569 // Assume only the first tree is the pattern. The others are clobber nodes.
2570 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002571 }
2572
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002573 void Analyze(const PatternToMatch *Pat) {
2574 AnalyzeNode(Pat->getSrcPattern());
2575 }
2576
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002577private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002578 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002579 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002580 return false;
2581
2582 if (N->getNumChildren() != 2)
2583 return false;
2584
2585 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002586 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002587 return false;
2588
2589 const TreePatternNode *N1 = N->getChild(1);
2590 if (N1->isLeaf())
2591 return false;
2592 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2593 return false;
2594
2595 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2596 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2597 return false;
2598 return OpInfo.getEnumName() == "ISD::BITCAST";
2599 }
2600
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002601public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002602 void AnalyzeNode(const TreePatternNode *N) {
2603 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002604 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002605 Record *LeafRec = DI->getDef();
2606 // Handle ComplexPattern leaves.
2607 if (LeafRec->isSubClassOf("ComplexPattern")) {
2608 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2609 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2610 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002611 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002612 }
2613 }
2614 return;
2615 }
2616
2617 // Analyze children.
2618 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2619 AnalyzeNode(N->getChild(i));
2620
2621 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002622 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002623 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002624 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002625 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002626
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002627 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002628 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2629 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2630 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2631 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002632
2633 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2634 // If this is an intrinsic, analyze it.
2635 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
2636 mayLoad = true;// These may load memory.
2637
Dan Gohmanddb2d652010-08-05 23:36:21 +00002638 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002639 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2640
Dan Gohmanddb2d652010-08-05 23:36:21 +00002641 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002642 // WriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002643 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002644 }
2645 }
2646
2647};
2648
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002649static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002650 const InstAnalyzer &PatInfo,
2651 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002652 bool Error = false;
2653
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002654 // Remember where InstInfo got its flags.
2655 if (InstInfo.hasUndefFlags())
2656 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002657
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002658 // Check explicitly set flags for consistency.
2659 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2660 !InstInfo.hasSideEffects_Unset) {
2661 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2662 // the pattern has no side effects. That could be useful for div/rem
2663 // instructions that may trap.
2664 if (!InstInfo.hasSideEffects) {
2665 Error = true;
2666 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
2667 Twine(InstInfo.hasSideEffects));
2668 }
2669 }
2670
2671 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
2672 Error = true;
2673 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
2674 Twine(InstInfo.mayStore));
2675 }
2676
2677 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
2678 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
2679 // Some targets translate imediates to loads.
2680 if (!InstInfo.mayLoad) {
2681 Error = true;
2682 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
2683 Twine(InstInfo.mayLoad));
2684 }
2685 }
2686
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002687 // Transfer inferred flags.
2688 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
2689 InstInfo.mayStore |= PatInfo.mayStore;
2690 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002691
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002692 // These flags are silently added without any verification.
2693 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00002694
2695 // Don't infer isVariadic. This flag means something different on SDNodes and
2696 // instructions. For example, a CALL SDNode is variadic because it has the
2697 // call arguments as operands, but a CALL instruction is not variadic - it
2698 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002699
2700 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002701}
2702
Jim Grosbach514410b2012-07-17 00:47:06 +00002703/// hasNullFragReference - Return true if the DAG has any reference to the
2704/// null_frag operator.
2705static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002706 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00002707 if (!OpDef) return false;
2708 Record *Operator = OpDef->getDef();
2709
2710 // If this is the null fragment, return true.
2711 if (Operator->getName() == "null_frag") return true;
2712 // If any of the arguments reference the null fragment, return true.
2713 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002714 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002715 if (Arg && hasNullFragReference(Arg))
2716 return true;
2717 }
2718
2719 return false;
2720}
2721
2722/// hasNullFragReference - Return true if any DAG in the list references
2723/// the null_frag operator.
2724static bool hasNullFragReference(ListInit *LI) {
2725 for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002726 DagInit *DI = dyn_cast<DagInit>(LI->getElement(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00002727 assert(DI && "non-dag in an instruction Pattern list?!");
2728 if (hasNullFragReference(DI))
2729 return true;
2730 }
2731 return false;
2732}
2733
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002734/// Get all the instructions in a tree.
2735static void
2736getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
2737 if (Tree->isLeaf())
2738 return;
2739 if (Tree->getOperator()->isSubClassOf("Instruction"))
2740 Instrs.push_back(Tree->getOperator());
2741 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
2742 getInstructionsInTree(Tree->getChild(i), Instrs);
2743}
2744
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002745/// Check the class of a pattern leaf node against the instruction operand it
2746/// represents.
2747static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
2748 Record *Leaf) {
2749 if (OI.Rec == Leaf)
2750 return true;
2751
2752 // Allow direct value types to be used in instruction set patterns.
2753 // The type will be checked later.
2754 if (Leaf->isSubClassOf("ValueType"))
2755 return true;
2756
2757 // Patterns can also be ComplexPattern instances.
2758 if (Leaf->isSubClassOf("ComplexPattern"))
2759 return true;
2760
2761 return false;
2762}
2763
Ahmed Bougacha14107512013-10-28 18:07:21 +00002764const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
2765 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00002766
Ahmed Bougacha14107512013-10-28 18:07:21 +00002767 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002768
Chris Lattner8cab0212008-01-05 22:25:12 +00002769 // Parse the instruction.
Ahmed Bougacha14107512013-10-28 18:07:21 +00002770 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002771 // Inline pattern fragments into it.
2772 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002773
Chris Lattner8cab0212008-01-05 22:25:12 +00002774 // Infer as many types as possible. If we cannot infer all of them, we can
2775 // never do anything with this instruction pattern: report it to the user.
2776 if (!I->InferAllTypes())
2777 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002778
2779 // InstInputs - Keep track of all of the inputs of the instruction, along
Chris Lattner8cab0212008-01-05 22:25:12 +00002780 // with the record they are declared as.
2781 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002782
Chris Lattner8cab0212008-01-05 22:25:12 +00002783 // InstResults - Keep track of all the virtual registers that are 'set'
2784 // in the instruction, including what reg class they are.
2785 std::map<std::string, TreePatternNode*> InstResults;
2786
Chris Lattner8cab0212008-01-05 22:25:12 +00002787 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002788
Chris Lattner8cab0212008-01-05 22:25:12 +00002789 // Verify that the top-level forms in the instruction are of void type, and
2790 // fill in the InstResults map.
2791 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
2792 TreePatternNode *Pat = I->getTree(j);
Chris Lattnerf1447252010-03-19 21:37:09 +00002793 if (Pat->getNumTypes() != 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002794 I->error("Top-level forms in instruction pattern should have"
2795 " void types");
2796
2797 // Find inputs and outputs, and verify the structure of the uses/defs.
2798 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002799 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002800 }
2801
2802 // Now that we have inputs and outputs of the pattern, inspect the operands
2803 // list for the instruction. This determines the order that operands are
2804 // added to the machine instruction the node corresponds to.
2805 unsigned NumResults = InstResults.size();
2806
2807 // Parse the operands list from the (ops) list, validating it.
2808 assert(I->getArgList().empty() && "Args list should still be empty here!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002809
2810 // Check that all of the results occur first in the list.
2811 std::vector<Record*> Results;
Craig Topper24064772014-04-15 07:20:03 +00002812 TreePatternNode *Res0Node = nullptr;
Chris Lattner8cab0212008-01-05 22:25:12 +00002813 for (unsigned i = 0; i != NumResults; ++i) {
Chris Lattnerd8adec72010-11-01 04:03:32 +00002814 if (i == CGI.Operands.size())
Chris Lattner8cab0212008-01-05 22:25:12 +00002815 I->error("'" + InstResults.begin()->first +
2816 "' set but does not appear in operand list!");
Chris Lattnerd8adec72010-11-01 04:03:32 +00002817 const std::string &OpName = CGI.Operands[i].Name;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002818
Chris Lattner8cab0212008-01-05 22:25:12 +00002819 // Check that it exists in InstResults.
2820 TreePatternNode *RNode = InstResults[OpName];
Craig Topper24064772014-04-15 07:20:03 +00002821 if (!RNode)
Chris Lattner8cab0212008-01-05 22:25:12 +00002822 I->error("Operand $" + OpName + " does not exist in operand list!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002823
Chris Lattner8cab0212008-01-05 22:25:12 +00002824 if (i == 0)
2825 Res0Node = RNode;
Sean Silva88eb8dd2012-10-10 20:24:47 +00002826 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
Craig Topper24064772014-04-15 07:20:03 +00002827 if (!R)
Chris Lattner8cab0212008-01-05 22:25:12 +00002828 I->error("Operand $" + OpName + " should be a set destination: all "
2829 "outputs must occur before inputs in operand list!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002830
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002831 if (!checkOperandClass(CGI.Operands[i], R))
Chris Lattner8cab0212008-01-05 22:25:12 +00002832 I->error("Operand $" + OpName + " class mismatch!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002833
Chris Lattner8cab0212008-01-05 22:25:12 +00002834 // Remember the return type.
Chris Lattnerd8adec72010-11-01 04:03:32 +00002835 Results.push_back(CGI.Operands[i].Rec);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002836
Chris Lattner8cab0212008-01-05 22:25:12 +00002837 // Okay, this one checks out.
2838 InstResults.erase(OpName);
2839 }
2840
2841 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
2842 // the copy while we're checking the inputs.
2843 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
2844
2845 std::vector<TreePatternNode*> ResultNodeOperands;
2846 std::vector<Record*> Operands;
Chris Lattnerd8adec72010-11-01 04:03:32 +00002847 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
2848 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
Chris Lattner8cab0212008-01-05 22:25:12 +00002849 const std::string &OpName = Op.Name;
2850 if (OpName.empty())
2851 I->error("Operand #" + utostr(i) + " in operands list has no name!");
2852
2853 if (!InstInputsCheck.count(OpName)) {
Tom Stellardb7246a72012-09-06 14:15:52 +00002854 // If this is an operand with a DefaultOps set filled in, we can ignore
2855 // this. When we codegen it, we will do so as always executed.
2856 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002857 // Does it have a non-empty DefaultOps field? If so, ignore this
2858 // operand.
2859 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
2860 continue;
2861 }
2862 I->error("Operand $" + OpName +
2863 " does not appear in the instruction pattern");
2864 }
2865 TreePatternNode *InVal = InstInputsCheck[OpName];
2866 InstInputsCheck.erase(OpName); // It occurred, remove from map.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002867
Sean Silva88eb8dd2012-10-10 20:24:47 +00002868 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00002869 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002870 if (!checkOperandClass(Op, InRec))
Chris Lattner8cab0212008-01-05 22:25:12 +00002871 I->error("Operand $" + OpName + "'s register class disagrees"
2872 " between the operand and pattern");
2873 }
2874 Operands.push_back(Op.Rec);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002875
Chris Lattner8cab0212008-01-05 22:25:12 +00002876 // Construct the result for the dest-pattern operand list.
2877 TreePatternNode *OpNode = InVal->clone();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002878
Chris Lattner8cab0212008-01-05 22:25:12 +00002879 // No predicate is useful on the result.
Dan Gohman6e979022008-10-15 06:17:21 +00002880 OpNode->clearPredicateFns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002881
Chris Lattner8cab0212008-01-05 22:25:12 +00002882 // Promote the xform function to be an explicit node if set.
2883 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00002884 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00002885 std::vector<TreePatternNode*> Children;
2886 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00002887 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00002888 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002889
Chris Lattner8cab0212008-01-05 22:25:12 +00002890 ResultNodeOperands.push_back(OpNode);
2891 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002892
Chris Lattner8cab0212008-01-05 22:25:12 +00002893 if (!InstInputsCheck.empty())
2894 I->error("Input operand $" + InstInputsCheck.begin()->first +
2895 " occurs in pattern but not in operands list!");
2896
2897 TreePatternNode *ResultPattern =
Chris Lattnerf1447252010-03-19 21:37:09 +00002898 new TreePatternNode(I->getRecord(), ResultNodeOperands,
2899 GetNumNodeResults(I->getRecord(), *this));
Chris Lattner8cab0212008-01-05 22:25:12 +00002900 // Copy fully inferred output node type to instruction result pattern.
Chris Lattnerf1447252010-03-19 21:37:09 +00002901 for (unsigned i = 0; i != NumResults; ++i)
2902 ResultPattern->setType(i, Res0Node->getExtType(i));
Chris Lattner8cab0212008-01-05 22:25:12 +00002903
2904 // Create and insert the instruction.
Chris Lattner5debc332010-04-20 06:30:25 +00002905 // FIXME: InstImpResults should not be part of DAGInstruction.
Chris Lattner9dc68d32010-04-20 06:28:43 +00002906 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00002907 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
Chris Lattner8cab0212008-01-05 22:25:12 +00002908
2909 // Use a temporary tree pattern to infer all types and make sure that the
2910 // constructed result is correct. This depends on the instruction already
Ahmed Bougacha14107512013-10-28 18:07:21 +00002911 // being inserted into the DAGInsts map.
Chris Lattner8cab0212008-01-05 22:25:12 +00002912 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002913 Temp.InferAllTypes(&I->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00002914
Ahmed Bougacha14107512013-10-28 18:07:21 +00002915 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
Chris Lattner8cab0212008-01-05 22:25:12 +00002916 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002917
Ahmed Bougacha14107512013-10-28 18:07:21 +00002918 return TheInsertedInst;
2919 }
2920
2921/// ParseInstructions - Parse all of the instructions, inlining and resolving
2922/// any fragments involved. This populates the Instructions list with fully
2923/// resolved instructions.
2924void CodeGenDAGPatterns::ParseInstructions() {
2925 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
2926
2927 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
Craig Topper24064772014-04-15 07:20:03 +00002928 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00002929
2930 if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
2931 LI = Instrs[i]->getValueAsListInit("Pattern");
2932
2933 // If there is no pattern, only collect minimal information about the
2934 // instruction for its operand list. We have to assume that there is one
2935 // result, as we have no detailed info. A pattern which references the
2936 // null_frag operator is as-if no pattern were specified. Normally this
2937 // is from a multiclass expansion w/ a SDPatternOperator passed in as
2938 // null_frag.
2939 if (!LI || LI->getSize() == 0 || hasNullFragReference(LI)) {
2940 std::vector<Record*> Results;
2941 std::vector<Record*> Operands;
2942
2943 CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
2944
2945 if (InstInfo.Operands.size() != 0) {
2946 if (InstInfo.Operands.NumDefs == 0) {
2947 // These produce no results
2948 for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
2949 Operands.push_back(InstInfo.Operands[j].Rec);
2950 } else {
2951 // Assume the first operand is the result.
2952 Results.push_back(InstInfo.Operands[0].Rec);
2953
2954 // The rest are inputs.
2955 for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
2956 Operands.push_back(InstInfo.Operands[j].Rec);
2957 }
2958 }
2959
2960 // Create and insert the instruction.
2961 std::vector<Record*> ImpResults;
2962 Instructions.insert(std::make_pair(Instrs[i],
Craig Topper24064772014-04-15 07:20:03 +00002963 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00002964 continue; // no pattern.
2965 }
2966
2967 CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
2968 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
2969
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00002970 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00002971 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002972 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002973
Chris Lattner8cab0212008-01-05 22:25:12 +00002974 // If we can, convert the instructions to be patterns that are matched!
Sean Silvaa4e2c5f2012-09-19 01:47:00 +00002975 for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
Benjamin Kramerc2dbd5d2009-08-23 10:39:21 +00002976 Instructions.begin(),
Chris Lattner8cab0212008-01-05 22:25:12 +00002977 E = Instructions.end(); II != E; ++II) {
2978 DAGInstruction &TheInst = II->second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002979 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00002980 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00002981
2982 // FIXME: Assume only the first tree is the pattern. The others are clobber
2983 // nodes.
2984 TreePatternNode *Pattern = I->getTree(0);
2985 TreePatternNode *SrcPattern;
2986 if (Pattern->getOperator()->getName() == "set") {
2987 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
2988 } else{
2989 // Not a set (store or something?)
2990 SrcPattern = Pattern;
2991 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002992
Chris Lattner8cab0212008-01-05 22:25:12 +00002993 Record *Instr = II->first;
Chris Lattner0c0baa92010-02-23 06:16:51 +00002994 AddPatternToMatch(I,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00002995 PatternToMatch(Instr,
2996 Instr->getValueAsListInit("Predicates"),
Chris Lattner94d3b0a2010-02-23 06:35:45 +00002997 SrcPattern,
2998 TheInst.getResultPattern(),
Chris Lattner0c0baa92010-02-23 06:16:51 +00002999 TheInst.getImpResults(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003000 Instr->getValueAsInt("AddedComplexity"),
3001 Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003002 }
3003}
3004
Chris Lattnera7722b62010-02-23 06:55:24 +00003005
3006typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3007
Jim Grosbach65586fe2010-12-21 16:16:00 +00003008static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003009 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003010 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003011 if (!P->getName().empty()) {
3012 NameRecord &Rec = Names[P->getName()];
3013 // If this is the first instance of the name, remember the node.
3014 if (Rec.second++ == 0)
3015 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003016 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003017 PatternTop->error("repetition of value: $" + P->getName() +
3018 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003019 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003020
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003021 if (!P->isLeaf()) {
3022 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003023 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003024 }
3025}
3026
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003027void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Chris Lattner0c0baa92010-02-23 06:16:51 +00003028 const PatternToMatch &PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003029 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003030 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003031 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3032 PrintWarning(Pattern->getRecord()->getLoc(),
3033 Twine("Pattern can never match: ") + Reason);
3034 return;
3035 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003036
Chris Lattner1e634e32010-03-01 22:29:19 +00003037 // If the source pattern's root is a complex pattern, that complex pattern
3038 // must specify the nodes it can potentially match.
3039 if (const ComplexPattern *CP =
3040 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3041 if (CP->getRootNodes().empty())
3042 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3043 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003044
3045
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003046 // Find all of the named values in the input and output, ensure they have the
3047 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003048 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003049 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3050 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003051
3052 // Scan all of the named values in the destination pattern, rejecting them if
3053 // they don't exist in the input pattern.
Chris Lattnera7722b62010-02-23 06:55:24 +00003054 for (std::map<std::string, NameRecord>::iterator
Chris Lattner4b9225b2010-02-23 07:50:58 +00003055 I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
Craig Topper24064772014-04-15 07:20:03 +00003056 if (SrcNames[I->first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003057 Pattern->error("Pattern has input without matching name in output: $" +
3058 I->first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003059 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003060
Chris Lattnera7722b62010-02-23 06:55:24 +00003061 // Scan all of the named values in the source pattern, rejecting them if the
3062 // name isn't used in the dest, and isn't used to tie two values together.
3063 for (std::map<std::string, NameRecord>::iterator
3064 I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
Craig Topper24064772014-04-15 07:20:03 +00003065 if (DstNames[I->first].first == nullptr && SrcNames[I->first].second == 1)
Chris Lattnera7722b62010-02-23 06:55:24 +00003066 Pattern->error("Pattern has dead named input: $" + I->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003067
Chris Lattner0c0baa92010-02-23 06:16:51 +00003068 PatternsToMatch.push_back(PTM);
3069}
3070
3071
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003072
3073void CodeGenDAGPatterns::InferInstructionFlags() {
Chris Lattner918be522010-03-19 00:34:35 +00003074 const std::vector<const CodeGenInstruction*> &Instructions =
3075 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003076
3077 // First try to infer flags from the primary instruction pattern, if any.
3078 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003079 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003080 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3081 CodeGenInstruction &InstInfo =
3082 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003083
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003084 // Treat neverHasSideEffects = 1 as the equivalent of hasSideEffects = 0.
3085 // This flag is obsolete and will be removed.
3086 if (InstInfo.neverHasSideEffects) {
3087 assert(!InstInfo.hasSideEffects);
3088 InstInfo.hasSideEffects_Unset = false;
3089 }
3090
3091 // Get the primary instruction pattern.
3092 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3093 if (!Pattern) {
3094 if (InstInfo.hasUndefFlags())
3095 Revisit.push_back(&InstInfo);
3096 continue;
3097 }
3098 InstAnalyzer PatInfo(*this);
3099 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003100 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003101 }
3102
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003103 // Second, look for single-instruction patterns defined outside the
3104 // instruction.
3105 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3106 const PatternToMatch &PTM = *I;
3107
3108 // We can only infer from single-instruction patterns, otherwise we won't
3109 // know which instruction should get the flags.
3110 SmallVector<Record*, 8> PatInstrs;
3111 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3112 if (PatInstrs.size() != 1)
3113 continue;
3114
3115 // Get the single instruction.
3116 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3117
3118 // Only infer properties from the first pattern. We'll verify the others.
3119 if (InstInfo.InferredFrom)
3120 continue;
3121
3122 InstAnalyzer PatInfo(*this);
3123 PatInfo.Analyze(&PTM);
3124 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3125 }
3126
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003127 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003128 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003129
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003130 // Revisit instructions with undefined flags and no pattern.
3131 if (Target.guessInstructionProperties()) {
3132 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3133 CodeGenInstruction &InstInfo = *Revisit[i];
3134 if (InstInfo.InferredFrom)
3135 continue;
3136 // The mayLoad and mayStore flags default to false.
3137 // Conservatively assume hasSideEffects if it wasn't explicit.
3138 if (InstInfo.hasSideEffects_Unset)
3139 InstInfo.hasSideEffects = true;
3140 }
3141 return;
3142 }
3143
3144 // Complain about any flags that are still undefined.
3145 for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
3146 CodeGenInstruction &InstInfo = *Revisit[i];
3147 if (InstInfo.InferredFrom)
3148 continue;
3149 if (InstInfo.hasSideEffects_Unset)
3150 PrintError(InstInfo.TheDef->getLoc(),
3151 "Can't infer hasSideEffects from patterns");
3152 if (InstInfo.mayStore_Unset)
3153 PrintError(InstInfo.TheDef->getLoc(),
3154 "Can't infer mayStore from patterns");
3155 if (InstInfo.mayLoad_Unset)
3156 PrintError(InstInfo.TheDef->getLoc(),
3157 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003158 }
3159}
3160
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003161
3162/// Verify instruction flags against pattern node properties.
3163void CodeGenDAGPatterns::VerifyInstructionFlags() {
3164 unsigned Errors = 0;
3165 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3166 const PatternToMatch &PTM = *I;
3167 SmallVector<Record*, 8> Instrs;
3168 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3169 if (Instrs.empty())
3170 continue;
3171
3172 // Count the number of instructions with each flag set.
3173 unsigned NumSideEffects = 0;
3174 unsigned NumStores = 0;
3175 unsigned NumLoads = 0;
3176 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3177 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3178 NumSideEffects += InstInfo.hasSideEffects;
3179 NumStores += InstInfo.mayStore;
3180 NumLoads += InstInfo.mayLoad;
3181 }
3182
3183 // Analyze the source pattern.
3184 InstAnalyzer PatInfo(*this);
3185 PatInfo.Analyze(&PTM);
3186
3187 // Collect error messages.
3188 SmallVector<std::string, 4> Msgs;
3189
3190 // Check for missing flags in the output.
3191 // Permit extra flags for now at least.
3192 if (PatInfo.hasSideEffects && !NumSideEffects)
3193 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3194
3195 // Don't verify store flags on instructions with side effects. At least for
3196 // intrinsics, side effects implies mayStore.
3197 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3198 Msgs.push_back("pattern may store, but mayStore isn't set");
3199
3200 // Similarly, mayStore implies mayLoad on intrinsics.
3201 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3202 Msgs.push_back("pattern may load, but mayLoad isn't set");
3203
3204 // Print error messages.
3205 if (Msgs.empty())
3206 continue;
3207 ++Errors;
3208
3209 for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
3210 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
3211 (Instrs.size() == 1 ?
3212 "instruction" : "output instructions"));
3213 // Provide the location of the relevant instruction definitions.
3214 for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
3215 if (Instrs[i] != PTM.getSrcRecord())
3216 PrintError(Instrs[i]->getLoc(), "defined here");
3217 const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
3218 if (InstInfo.InferredFrom &&
3219 InstInfo.InferredFrom != InstInfo.TheDef &&
3220 InstInfo.InferredFrom != PTM.getSrcRecord())
3221 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from patttern");
3222 }
3223 }
3224 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003225 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003226}
3227
Chris Lattnercabe0372010-03-15 06:00:16 +00003228/// Given a pattern result with an unresolved type, see if we can find one
3229/// instruction with an unresolved result type. Force this result type to an
3230/// arbitrary element if it's possible types to converge results.
3231static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3232 if (N->isLeaf())
3233 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003234
Chris Lattnercabe0372010-03-15 06:00:16 +00003235 // Analyze children.
3236 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3237 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3238 return true;
3239
3240 if (!N->getOperator()->isSubClassOf("Instruction"))
3241 return false;
3242
3243 // If this type is already concrete or completely unknown we can't do
3244 // anything.
Chris Lattnerf1447252010-03-19 21:37:09 +00003245 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3246 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
3247 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003248
Chris Lattnerf1447252010-03-19 21:37:09 +00003249 // Otherwise, force its type to the first possibility (an arbitrary choice).
3250 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
3251 return true;
3252 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003253
Chris Lattnerf1447252010-03-19 21:37:09 +00003254 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003255}
3256
Chris Lattnerab3242f2008-01-06 01:10:31 +00003257void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003258 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3259
3260 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00003261 Record *CurPattern = Patterns[i];
David Greeneaf8ee2c2011-07-29 22:43:06 +00003262 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003263
3264 // If the pattern references the null_frag, there's nothing to do.
3265 if (hasNullFragReference(Tree))
3266 continue;
3267
Chris Lattner5c2182e2010-03-27 02:53:27 +00003268 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003269
3270 // Inline pattern fragments into it.
3271 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003272
David Greeneaf8ee2c2011-07-29 22:43:06 +00003273 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Chris Lattner8cab0212008-01-05 22:25:12 +00003274 if (LI->getSize() == 0) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003275
Chris Lattner8cab0212008-01-05 22:25:12 +00003276 // Parse the instruction.
Chris Lattnerf1447252010-03-19 21:37:09 +00003277 TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003278
Chris Lattner8cab0212008-01-05 22:25:12 +00003279 // Inline pattern fragments into it.
3280 Result->InlinePatternFragments();
3281
3282 if (Result->getNumTrees() != 1)
3283 Result->error("Cannot handle instructions producing instructions "
3284 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003285
Chris Lattner8cab0212008-01-05 22:25:12 +00003286 bool IterateInference;
3287 bool InferredAllPatternTypes, InferredAllResultTypes;
3288 do {
3289 // Infer as many types as possible. If we cannot infer all of them, we
3290 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003291 InferredAllPatternTypes =
3292 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003293
Chris Lattner8cab0212008-01-05 22:25:12 +00003294 // Infer as many types as possible. If we cannot infer all of them, we
3295 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003296 InferredAllResultTypes =
3297 Result->InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003298
Chris Lattnerfdc20712010-03-18 23:15:10 +00003299 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003300
Chris Lattner8cab0212008-01-05 22:25:12 +00003301 // Apply the type of the result to the source pattern. This helps us
3302 // resolve cases where the input type is known to be a pointer type (which
3303 // is considered resolved), but the result knows it needs to be 32- or
3304 // 64-bits. Infer the other way for good measure.
Chris Lattnerf1447252010-03-19 21:37:09 +00003305 for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
3306 Pattern->getTree(0)->getNumTypes());
3307 i != e; ++i) {
Chris Lattnerfdc20712010-03-18 23:15:10 +00003308 IterateInference = Pattern->getTree(0)->
Chris Lattnerf1447252010-03-19 21:37:09 +00003309 UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003310 IterateInference |= Result->getTree(0)->
Chris Lattnerf1447252010-03-19 21:37:09 +00003311 UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003312 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003313
Chris Lattnercabe0372010-03-15 06:00:16 +00003314 // If our iteration has converged and the input pattern's types are fully
3315 // resolved but the result pattern is not fully resolved, we may have a
3316 // situation where we have two instructions in the result pattern and
3317 // the instructions require a common register class, but don't care about
3318 // what actual MVT is used. This is actually a bug in our modelling:
3319 // output patterns should have register classes, not MVTs.
3320 //
3321 // In any case, to handle this, we just go through and disambiguate some
3322 // arbitrary types to the result pattern's nodes.
3323 if (!IterateInference && InferredAllPatternTypes &&
3324 !InferredAllResultTypes)
3325 IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
3326 *Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003327 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003328
Chris Lattner8cab0212008-01-05 22:25:12 +00003329 // Verify that we inferred enough types that we can do something with the
3330 // pattern and result. If these fire the user has to add type casts.
3331 if (!InferredAllPatternTypes)
3332 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003333 if (!InferredAllResultTypes) {
3334 Pattern->dump();
Chris Lattner8cab0212008-01-05 22:25:12 +00003335 Result->error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003336 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003337
Chris Lattner8cab0212008-01-05 22:25:12 +00003338 // Validate that the input pattern is correct.
3339 std::map<std::string, TreePatternNode*> InstInputs;
3340 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003341 std::vector<Record*> InstImpResults;
3342 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3343 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3344 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003345 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003346
3347 // Promote the xform function to be an explicit node if set.
3348 TreePatternNode *DstPattern = Result->getOnlyTree();
3349 std::vector<TreePatternNode*> ResultNodeOperands;
3350 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3351 TreePatternNode *OpNode = DstPattern->getChild(ii);
3352 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003353 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003354 std::vector<TreePatternNode*> Children;
3355 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003356 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003357 }
3358 ResultNodeOperands.push_back(OpNode);
3359 }
3360 DstPattern = Result->getOnlyTree();
3361 if (!DstPattern->isLeaf())
3362 DstPattern = new TreePatternNode(DstPattern->getOperator(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003363 ResultNodeOperands,
3364 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003365
Chris Lattnerf1447252010-03-19 21:37:09 +00003366 for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
3367 DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003368
Chris Lattner8cab0212008-01-05 22:25:12 +00003369 TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
3370 Temp.InferAllTypes();
3371
Jim Grosbach65586fe2010-12-21 16:16:00 +00003372
Chris Lattner0c0baa92010-02-23 06:16:51 +00003373 AddPatternToMatch(Pattern,
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003374 PatternToMatch(CurPattern,
3375 CurPattern->getValueAsListInit("Predicates"),
Chris Lattnerf1447252010-03-19 21:37:09 +00003376 Pattern->getTree(0),
3377 Temp.getOnlyTree(), InstImpResults,
3378 CurPattern->getValueAsInt("AddedComplexity"),
3379 CurPattern->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003380 }
3381}
3382
3383/// CombineChildVariants - Given a bunch of permutations of each child of the
3384/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003385static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003386 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3387 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003388 CodeGenDAGPatterns &CDP,
3389 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003390 // Make sure that each operand has at least one variant to choose from.
3391 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3392 if (ChildVariants[i].empty())
3393 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003394
Chris Lattner8cab0212008-01-05 22:25:12 +00003395 // The end result is an all-pairs construction of the resultant pattern.
3396 std::vector<unsigned> Idxs;
3397 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003398 bool NotDone;
3399 do {
3400#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003401 DEBUG(if (!Idxs.empty()) {
3402 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
3403 for (unsigned i = 0; i < Idxs.size(); ++i) {
3404 errs() << Idxs[i] << " ";
3405 }
3406 errs() << "]\n";
3407 });
Scott Michel94420742008-03-05 17:49:05 +00003408#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003409 // Create the variant and add it to the output list.
3410 std::vector<TreePatternNode*> NewChildren;
3411 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3412 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Chris Lattnerf1447252010-03-19 21:37:09 +00003413 TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
3414 Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003415
Chris Lattner8cab0212008-01-05 22:25:12 +00003416 // Copy over properties.
3417 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003418 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003419 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003420 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3421 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003422
Scott Michel94420742008-03-05 17:49:05 +00003423 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003424 std::string ErrString;
3425 if (!R->canPatternMatch(ErrString, CDP)) {
3426 delete R;
3427 } else {
3428 bool AlreadyExists = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003429
Chris Lattner8cab0212008-01-05 22:25:12 +00003430 // Scan to see if this pattern has already been emitted. We can get
3431 // duplication due to things like commuting:
3432 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3433 // which are the same pattern. Ignore the dups.
3434 for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003435 if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003436 AlreadyExists = true;
3437 break;
3438 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003439
Chris Lattner8cab0212008-01-05 22:25:12 +00003440 if (AlreadyExists)
3441 delete R;
3442 else
3443 OutVariants.push_back(R);
3444 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003445
Scott Michel94420742008-03-05 17:49:05 +00003446 // Increment indices to the next permutation by incrementing the
3447 // indicies from last index backward, e.g., generate the sequence
3448 // [0, 0], [0, 1], [1, 0], [1, 1].
3449 int IdxsIdx;
3450 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3451 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3452 Idxs[IdxsIdx] = 0;
3453 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003454 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003455 }
Scott Michel94420742008-03-05 17:49:05 +00003456 NotDone = (IdxsIdx >= 0);
3457 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003458}
3459
3460/// CombineChildVariants - A helper function for binary operators.
3461///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003462static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003463 const std::vector<TreePatternNode*> &LHS,
3464 const std::vector<TreePatternNode*> &RHS,
3465 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003466 CodeGenDAGPatterns &CDP,
3467 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003468 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3469 ChildVariants.push_back(LHS);
3470 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003471 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003472}
Chris Lattner8cab0212008-01-05 22:25:12 +00003473
3474
3475static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3476 std::vector<TreePatternNode *> &Children) {
3477 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3478 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003479
Chris Lattner8cab0212008-01-05 22:25:12 +00003480 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003481 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003482 N->getTransformFn()) {
3483 Children.push_back(N);
3484 return;
3485 }
3486
3487 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3488 Children.push_back(N->getChild(0));
3489 else
3490 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3491
3492 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3493 Children.push_back(N->getChild(1));
3494 else
3495 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3496}
3497
3498/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3499/// the (potentially recursive) pattern by using algebraic laws.
3500///
3501static void GenerateVariantsOf(TreePatternNode *N,
3502 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003503 CodeGenDAGPatterns &CDP,
3504 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003505 // We cannot permute leaves or ComplexPattern uses.
3506 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003507 OutVariants.push_back(N);
3508 return;
3509 }
3510
3511 // Look up interesting info about the node.
3512 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3513
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003514 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003515 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003516 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003517 std::vector<TreePatternNode*> MaximalChildren;
3518 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3519
3520 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3521 // permutations.
3522 if (MaximalChildren.size() == 3) {
3523 // Find the variants of all of our maximal children.
3524 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003525 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3526 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3527 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003528
Chris Lattner8cab0212008-01-05 22:25:12 +00003529 // There are only two ways we can permute the tree:
3530 // (A op B) op C and A op (B op C)
3531 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003532
Chris Lattner8cab0212008-01-05 22:25:12 +00003533 // Generate legal pair permutations of A/B/C.
3534 std::vector<TreePatternNode*> ABVariants;
3535 std::vector<TreePatternNode*> BAVariants;
3536 std::vector<TreePatternNode*> ACVariants;
3537 std::vector<TreePatternNode*> CAVariants;
3538 std::vector<TreePatternNode*> BCVariants;
3539 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00003540 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
3541 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
3542 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
3543 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
3544 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
3545 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003546
3547 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00003548 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
3549 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
3550 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
3551 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
3552 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
3553 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003554
3555 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00003556 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
3557 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
3558 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
3559 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
3560 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
3561 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003562 return;
3563 }
3564 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003565
Chris Lattner8cab0212008-01-05 22:25:12 +00003566 // Compute permutations of all children.
3567 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3568 ChildVariants.resize(N->getNumChildren());
3569 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00003570 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003571
3572 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00003573 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003574
3575 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003576 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
3577 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
3578 assert((N->getNumChildren()==2 || isCommIntrinsic) &&
3579 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003580 // Don't count children which are actually register references.
3581 unsigned NC = 0;
3582 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3583 TreePatternNode *Child = N->getChild(i);
3584 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00003585 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003586 Record *RR = DI->getDef();
3587 if (RR->isSubClassOf("Register"))
3588 continue;
3589 }
3590 NC++;
3591 }
3592 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00003593 if (isCommIntrinsic) {
3594 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
3595 // operands are the commutative operands, and there might be more operands
3596 // after those.
3597 assert(NC >= 3 &&
3598 "Commutative intrinsic should have at least 3 childrean!");
3599 std::vector<std::vector<TreePatternNode*> > Variants;
3600 Variants.push_back(ChildVariants[0]); // Intrinsic id.
3601 Variants.push_back(ChildVariants[2]);
3602 Variants.push_back(ChildVariants[1]);
3603 for (unsigned i = 3; i != NC; ++i)
3604 Variants.push_back(ChildVariants[i]);
3605 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
3606 } else if (NC == 2)
Chris Lattner8cab0212008-01-05 22:25:12 +00003607 CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
Scott Michel94420742008-03-05 17:49:05 +00003608 OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003609 }
3610}
3611
3612
3613// GenerateVariants - Generate variants. For example, commutative patterns can
3614// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003615void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00003616 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003617
Chris Lattner8cab0212008-01-05 22:25:12 +00003618 // Loop over all of the patterns we've collected, checking to see if we can
3619 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003620 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00003621 // the .td file having to contain tons of variants of instructions.
3622 //
3623 // Note that this loop adds new patterns to the PatternsToMatch list, but we
3624 // intentionally do not reconsider these. Any variants of added patterns have
3625 // already been added.
3626 //
3627 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00003628 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00003629 std::vector<TreePatternNode*> Variants;
Scott Michel94420742008-03-05 17:49:05 +00003630 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00003631 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00003632 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00003633 DEBUG(errs() << "\n");
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003634 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
3635 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00003636
3637 assert(!Variants.empty() && "Must create at least original variant!");
3638 Variants.erase(Variants.begin()); // Remove the original pattern.
3639
3640 if (Variants.empty()) // No variants for this pattern.
3641 continue;
3642
Chris Lattner34822f62009-08-23 04:44:11 +00003643 DEBUG(errs() << "FOUND VARIANTS OF: ";
3644 PatternsToMatch[i].getSrcPattern()->dump();
3645 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003646
3647 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
3648 TreePatternNode *Variant = Variants[v];
3649
Chris Lattner34822f62009-08-23 04:44:11 +00003650 DEBUG(errs() << " VAR#" << v << ": ";
3651 Variant->dump();
3652 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003653
Chris Lattner8cab0212008-01-05 22:25:12 +00003654 // Scan to see if an instruction or explicit pattern already matches this.
3655 bool AlreadyExists = false;
3656 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00003657 // Skip if the top level predicates do not match.
3658 if (PatternsToMatch[i].getPredicates() !=
3659 PatternsToMatch[p].getPredicates())
3660 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00003661 // Check to see if this variant already exists.
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00003662 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
3663 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00003664 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003665 AlreadyExists = true;
3666 break;
3667 }
3668 }
3669 // If we already have it, ignore the variant.
3670 if (AlreadyExists) continue;
3671
3672 // Otherwise, add it to the list of patterns we have.
3673 PatternsToMatch.
Jim Grosbachfb116ae2010-12-07 23:05:49 +00003674 push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
3675 PatternsToMatch[i].getPredicates(),
Chris Lattner8cab0212008-01-05 22:25:12 +00003676 Variant, PatternsToMatch[i].getDstPattern(),
3677 PatternsToMatch[i].getDstRegs(),
Chris Lattnerd39f75b2010-03-01 22:09:11 +00003678 PatternsToMatch[i].getAddedComplexity(),
3679 Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003680 }
3681
Chris Lattner34822f62009-08-23 04:44:11 +00003682 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00003683 }
3684}