blob: c30186008df84ed29c53ee165ad78e3d5ea311e8 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner8cab0212008-01-05 22:25:12 +00006//
7//===----------------------------------------------------------------------===//
8//
Chris Lattnerab3242f2008-01-06 01:10:31 +00009// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner8cab0212008-01-05 22:25:12 +000010// represent the patterns present in a .td file for instructions.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner78ac0742008-01-05 23:37:52 +000014#include "CodeGenDAGPatterns.h"
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +000015#include "llvm/ADT/BitVector.h"
Zachary Turner249dc142017-09-20 18:01:40 +000016#include "llvm/ADT/DenseSet.h"
Craig Topperbd199f82018-12-05 00:47:59 +000017#include "llvm/ADT/MapVector.h"
Chris Lattnercabe0372010-03-15 06:00:16 +000018#include "llvm/ADT/STLExtras.h"
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000019#include "llvm/ADT/SmallSet.h"
Craig Topper3522ab32015-11-28 08:23:02 +000020#include "llvm/ADT/SmallString.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000021#include "llvm/ADT/StringExtras.h"
Craig Topperddfdd942017-09-21 04:55:03 +000022#include "llvm/ADT/StringMap.h"
Jim Grosbach3ae48a62012-04-18 17:46:41 +000023#include "llvm/ADT/Twine.h"
Chris Lattner8cab0212008-01-05 22:25:12 +000024#include "llvm/Support/Debug.h"
David Blaikieb48ed1a2012-01-17 04:43:56 +000025#include "llvm/Support/ErrorHandling.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000026#include "llvm/TableGen/Error.h"
27#include "llvm/TableGen/Record.h"
Chuck Rose IIIfe2714f2008-01-15 21:43:17 +000028#include <algorithm>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000029#include <cstdio>
Craig Topperbd199f82018-12-05 00:47:59 +000030#include <iterator>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000031#include <set>
Chris Lattner8cab0212008-01-05 22:25:12 +000032using namespace llvm;
33
Chandler Carruthe96dd892014-04-21 22:55:11 +000034#define DEBUG_TYPE "dag-patterns"
35
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000036static inline bool isIntegerOrPtr(MVT VT) {
37 return VT.isInteger() || VT == MVT::iPTR;
Duncan Sands13237ac2008-06-06 12:08:01 +000038}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000039static inline bool isFloatingPoint(MVT VT) {
40 return VT.isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000041}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000042static inline bool isVector(MVT VT) {
43 return VT.isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000044}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000045static inline bool isScalar(MVT VT) {
46 return !VT.isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000047}
Duncan Sands13237ac2008-06-06 12:08:01 +000048
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000049template <typename Predicate>
50static bool berase_if(MachineValueTypeSet &S, Predicate P) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000051 bool Erased = false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000052 // It is ok to iterate over MachineValueTypeSet and remove elements from it
53 // at the same time.
54 for (MVT T : S) {
55 if (!P(T))
56 continue;
57 Erased = true;
58 S.erase(T);
Chris Lattnercabe0372010-03-15 06:00:16 +000059 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000060 return Erased;
Chris Lattner8cab0212008-01-05 22:25:12 +000061}
62
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000063// --- TypeSetByHwMode
Chris Lattnercabe0372010-03-15 06:00:16 +000064
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000065// This is a parameterized type-set class. For each mode there is a list
66// of types that are currently possible for a given tree node. Type
67// inference will apply to each mode separately.
Jim Grosbach65586fe2010-12-21 16:16:00 +000068
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000069TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
Tom Stellard9ad714f2019-02-20 19:43:47 +000070 for (const ValueTypeByHwMode &VVT : VTList) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000071 insert(VVT);
Tom Stellard9ad714f2019-02-20 19:43:47 +000072 AddrSpaces.push_back(VVT.PtrAddrSpace);
73 }
Chris Lattner8cab0212008-01-05 22:25:12 +000074}
75
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000076bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
77 for (const auto &I : *this) {
78 if (I.second.size() > 1)
79 return false;
80 if (!AllowEmpty && I.second.empty())
81 return false;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000082 }
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000083 return true;
84}
Chris Lattnercabe0372010-03-15 06:00:16 +000085
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000086ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
87 assert(isValueTypeByHwMode(true) &&
88 "The type set has multiple types for at least one HW mode");
89 ValueTypeByHwMode VVT;
Tom Stellard9ad714f2019-02-20 19:43:47 +000090 auto ASI = AddrSpaces.begin();
91
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000092 for (const auto &I : *this) {
93 MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
94 VVT.getOrCreateTypeForMode(I.first, T);
Tom Stellard9ad714f2019-02-20 19:43:47 +000095 if (ASI != AddrSpaces.end())
96 VVT.PtrAddrSpace = *ASI++;
Chris Lattnercabe0372010-03-15 06:00:16 +000097 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000098 return VVT;
Bob Wilson2cd5da82009-08-11 01:14:02 +000099}
Chris Lattnercabe0372010-03-15 06:00:16 +0000100
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000101bool TypeSetByHwMode::isPossible() const {
102 for (const auto &I : *this)
103 if (!I.second.empty())
104 return true;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000105 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000106}
107
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000108bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
109 bool Changed = false;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000110 bool ContainsDefault = false;
111 MVT DT = MVT::Other;
112
Zachary Turner249dc142017-09-20 18:01:40 +0000113 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000114 for (const auto &P : VVT) {
115 unsigned M = P.first;
116 Modes.insert(M);
117 // Make sure there exists a set for each specific mode from VVT.
118 Changed |= getOrCreate(M).insert(P.second).second;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000119 // Cache VVT's default mode.
120 if (DefaultMode == M) {
121 ContainsDefault = true;
122 DT = P.second;
123 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000124 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000125
126 // If VVT has a default mode, add the corresponding type to all
127 // modes in "this" that do not exist in VVT.
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000128 if (ContainsDefault)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000129 for (auto &I : *this)
130 if (!Modes.count(I.first))
131 Changed |= I.second.insert(DT).second;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000132
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000133 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000134}
135
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000136// Constrain the type set to be the intersection with VTS.
137bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
138 bool Changed = false;
139 if (hasDefault()) {
140 for (const auto &I : VTS) {
141 unsigned M = I.first;
142 if (M == DefaultMode || hasMode(M))
143 continue;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000144 Map.insert({M, Map.at(DefaultMode)});
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000145 Changed = true;
146 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000147 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000148
149 for (auto &I : *this) {
150 unsigned M = I.first;
151 SetType &S = I.second;
152 if (VTS.hasMode(M) || VTS.hasDefault()) {
153 Changed |= intersect(I.second, VTS.get(M));
154 } else if (!S.empty()) {
155 S.clear();
156 Changed = true;
157 }
158 }
159 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000160}
161
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000162template <typename Predicate>
163bool TypeSetByHwMode::constrain(Predicate P) {
164 bool Changed = false;
165 for (auto &I : *this)
Benjamin Kramere57308e2017-09-17 11:19:53 +0000166 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000167 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000168}
169
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000170template <typename Predicate>
171bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
172 assert(empty());
173 for (const auto &I : VTS) {
174 SetType &S = getOrCreate(I.first);
175 for (auto J : I.second)
176 if (P(J))
177 S.insert(J);
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000178 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000179 return !empty();
Chris Lattnercabe0372010-03-15 06:00:16 +0000180}
181
Zachary Turner249dc142017-09-20 18:01:40 +0000182void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
183 SmallVector<unsigned, 4> Modes;
184 Modes.reserve(Map.size());
Chris Lattnercabe0372010-03-15 06:00:16 +0000185
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000186 for (const auto &I : *this)
187 Modes.push_back(I.first);
Zachary Turner249dc142017-09-20 18:01:40 +0000188 if (Modes.empty()) {
189 OS << "{}";
190 return;
191 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000192 array_pod_sort(Modes.begin(), Modes.end());
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000193
Zachary Turner249dc142017-09-20 18:01:40 +0000194 OS << '{';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000195 for (unsigned M : Modes) {
Zachary Turner249dc142017-09-20 18:01:40 +0000196 OS << ' ' << getModeName(M) << ':';
197 writeToStream(get(M), OS);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000198 }
Zachary Turner249dc142017-09-20 18:01:40 +0000199 OS << " }";
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000200}
201
Zachary Turner249dc142017-09-20 18:01:40 +0000202void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
203 SmallVector<MVT, 4> Types(S.begin(), S.end());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000204 array_pod_sort(Types.begin(), Types.end());
205
Zachary Turner249dc142017-09-20 18:01:40 +0000206 OS << '[';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000207 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
Zachary Turner249dc142017-09-20 18:01:40 +0000208 OS << ValueTypeByHwMode::getMVTName(Types[i]);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000209 if (i != e-1)
Zachary Turner249dc142017-09-20 18:01:40 +0000210 OS << ' ';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000211 }
Zachary Turner249dc142017-09-20 18:01:40 +0000212 OS << ']';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000213}
214
215bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
Simon Pilgrim0e181332018-08-16 16:16:28 +0000216 // The isSimple call is much quicker than hasDefault - check this first.
217 bool IsSimple = isSimple();
218 bool VTSIsSimple = VTS.isSimple();
219 if (IsSimple && VTSIsSimple)
220 return *begin() == *VTS.begin();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000221
Simon Pilgrim0e181332018-08-16 16:16:28 +0000222 // Speedup: We have a default if the set is simple.
223 bool HaveDefault = IsSimple || hasDefault();
224 bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
225 if (HaveDefault != VTSHaveDefault)
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000226 return false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000227
Zachary Turner249dc142017-09-20 18:01:40 +0000228 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000229 for (auto &I : *this)
230 Modes.insert(I.first);
231 for (const auto &I : VTS)
232 Modes.insert(I.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000233
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000234 if (HaveDefault) {
235 // Both sets have default mode.
236 for (unsigned M : Modes) {
237 if (get(M) != VTS.get(M))
David Majnemerc7004902016-08-12 04:32:37 +0000238 return false;
Craig Topper5712d462015-11-24 08:20:47 +0000239 }
Scott Michel94420742008-03-05 17:49:05 +0000240 } else {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000241 // Neither set has default mode.
242 for (unsigned M : Modes) {
243 // If there is no default mode, an empty set is equivalent to not having
244 // the corresponding mode.
245 bool NoModeThis = !hasMode(M) || get(M).empty();
246 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
247 if (NoModeThis != NoModeVTS)
248 return false;
249 if (!NoModeThis)
250 if (get(M) != VTS.get(M))
251 return false;
252 }
Scott Michel94420742008-03-05 17:49:05 +0000253 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000254
255 return true;
Scott Michel94420742008-03-05 17:49:05 +0000256}
257
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000258namespace llvm {
259 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
260 T.writeToStream(OS);
261 return OS;
262 }
263}
264
Krzysztof Parzyszek426bf362017-09-12 15:31:26 +0000265LLVM_DUMP_METHOD
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000266void TypeSetByHwMode::dump() const {
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000267 dbgs() << *this << '\n';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000268}
269
270bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
271 bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
272 auto Int = [&In](MVT T) -> bool { return !In.count(T); };
273
274 if (OutP == InP)
275 return berase_if(Out, Int);
276
277 // Compute the intersection of scalars separately to account for only
278 // one set containing iPTR.
279 // The itersection of iPTR with a set of integer scalar types that does not
280 // include iPTR will result in the most specific scalar type:
281 // - iPTR is more specific than any set with two elements or more
282 // - iPTR is less specific than any single integer scalar type.
283 // For example
284 // { iPTR } * { i32 } -> { i32 }
285 // { iPTR } * { i32 i64 } -> { iPTR }
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000286 // and
287 // { iPTR i32 } * { i32 } -> { i32 }
288 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
289 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000290
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000291 // Compute the difference between the two sets in such a way that the
292 // iPTR is in the set that is being subtracted. This is to see if there
293 // are any extra scalars in the set without iPTR that are not in the
294 // set containing iPTR. Then the iPTR could be considered a "wildcard"
295 // matching these scalars. If there is only one such scalar, it would
296 // replace the iPTR, if there are more, the iPTR would be retained.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000297 SetType Diff;
298 if (InP) {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000299 Diff = Out;
300 berase_if(Diff, [&In](MVT T) { return In.count(T); });
301 // Pre-remove these elements and rely only on InP/OutP to determine
302 // whether a change has been made.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000303 berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
Scott Michel94420742008-03-05 17:49:05 +0000304 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000305 Diff = In;
306 berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000307 Out.erase(MVT::iPTR);
308 }
309
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000310 // The actual intersection.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000311 bool Changed = berase_if(Out, Int);
312 unsigned NumD = Diff.size();
313 if (NumD == 0)
314 return Changed;
315
316 if (NumD == 1) {
317 Out.insert(*Diff.begin());
318 // This is a change only if Out was the one with iPTR (which is now
319 // being replaced).
320 Changed |= OutP;
321 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000322 // Multiple elements from Out are now replaced with iPTR.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000323 Out.insert(MVT::iPTR);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000324 Changed |= !OutP;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000325 }
326 return Changed;
327}
328
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000329bool TypeSetByHwMode::validate() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000330#ifndef NDEBUG
331 if (empty())
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000332 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000333 bool AllEmpty = true;
334 for (const auto &I : *this)
335 AllEmpty &= I.second.empty();
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000336 return !AllEmpty;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000337#endif
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000338 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000339}
340
341// --- TypeInfer
342
343bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
344 const TypeSetByHwMode &In) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000345 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000346 In.validate();
347 if (In.empty() || Out == In || TP.hasError())
348 return false;
349 if (Out.empty()) {
350 Out = In;
351 return true;
352 }
353
354 bool Changed = Out.constrain(In);
355 if (Changed && Out.empty())
356 TP.error("Type contradiction");
357
358 return Changed;
359}
360
361bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000362 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000363 if (TP.hasError())
364 return false;
365 assert(!Out.empty() && "cannot pick from an empty set");
366
367 bool Changed = false;
368 for (auto &I : Out) {
369 TypeSetByHwMode::SetType &S = I.second;
370 if (S.size() <= 1)
371 continue;
372 MVT T = *S.begin(); // Pick the first element.
373 S.clear();
374 S.insert(T);
375 Changed = true;
376 }
377 return Changed;
378}
379
380bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000381 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000382 if (TP.hasError())
383 return false;
384 if (!Out.empty())
385 return Out.constrain(isIntegerOrPtr);
386
387 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
388}
389
390bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000391 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000392 if (TP.hasError())
393 return false;
394 if (!Out.empty())
395 return Out.constrain(isFloatingPoint);
396
397 return Out.assign_if(getLegalTypes(), isFloatingPoint);
398}
399
400bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000401 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000402 if (TP.hasError())
403 return false;
404 if (!Out.empty())
405 return Out.constrain(isScalar);
406
407 return Out.assign_if(getLegalTypes(), isScalar);
408}
409
410bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000411 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000412 if (TP.hasError())
413 return false;
414 if (!Out.empty())
415 return Out.constrain(isVector);
416
417 return Out.assign_if(getLegalTypes(), isVector);
418}
419
420bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000421 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000422 if (TP.hasError() || !Out.empty())
423 return false;
424
425 Out = getLegalTypes();
426 return true;
427}
428
429template <typename Iter, typename Pred, typename Less>
430static Iter min_if(Iter B, Iter E, Pred P, Less L) {
431 if (B == E)
432 return E;
433 Iter Min = E;
434 for (Iter I = B; I != E; ++I) {
435 if (!P(*I))
436 continue;
437 if (Min == E || L(*I, *Min))
438 Min = I;
439 }
440 return Min;
441}
442
443template <typename Iter, typename Pred, typename Less>
444static Iter max_if(Iter B, Iter E, Pred P, Less L) {
445 if (B == E)
446 return E;
447 Iter Max = E;
448 for (Iter I = B; I != E; ++I) {
449 if (!P(*I))
450 continue;
451 if (Max == E || L(*Max, *I))
452 Max = I;
453 }
454 return Max;
455}
456
457/// Make sure that for each type in Small, there exists a larger type in Big.
458bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
459 TypeSetByHwMode &Big) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000460 ValidateOnExit _1(Small, *this), _2(Big, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000461 if (TP.hasError())
462 return false;
463 bool Changed = false;
464
465 if (Small.empty())
466 Changed |= EnforceAny(Small);
467 if (Big.empty())
468 Changed |= EnforceAny(Big);
469
470 assert(Small.hasDefault() && Big.hasDefault());
471
472 std::vector<unsigned> Modes = union_modes(Small, Big);
473
474 // 1. Only allow integer or floating point types and make sure that
475 // both sides are both integer or both floating point.
476 // 2. Make sure that either both sides have vector types, or neither
477 // of them does.
478 for (unsigned M : Modes) {
479 TypeSetByHwMode::SetType &S = Small.get(M);
480 TypeSetByHwMode::SetType &B = Big.get(M);
481
Krasimir Georgiev866e05f2019-05-07 11:39:35 +0000482 if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000483 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000484 Changed |= berase_if(S, NotInt) |
485 berase_if(B, NotInt);
486 } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000487 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000488 Changed |= berase_if(S, NotFP) |
489 berase_if(B, NotFP);
490 } else if (S.empty() || B.empty()) {
491 Changed = !S.empty() || !B.empty();
492 S.clear();
493 B.clear();
494 } else {
495 TP.error("Incompatible types");
496 return Changed;
Scott Michel94420742008-03-05 17:49:05 +0000497 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000498
499 if (none_of(S, isVector) || none_of(B, isVector)) {
500 Changed |= berase_if(S, isVector) |
501 berase_if(B, isVector);
502 }
503 }
504
505 auto LT = [](MVT A, MVT B) -> bool {
506 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
507 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
508 A.getSizeInBits() < B.getSizeInBits());
509 };
Pete Couperus380eaa02019-05-20 18:09:37 +0000510 auto LE = [&LT](MVT A, MVT B) -> bool {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000511 // This function is used when removing elements: when a vector is compared
512 // to a non-vector, it should return false (to avoid removal).
513 if (A.isVector() != B.isVector())
514 return false;
515
Pete Couperus380eaa02019-05-20 18:09:37 +0000516 return LT(A, B) || (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
517 A.getSizeInBits() == B.getSizeInBits());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000518 };
519
520 for (unsigned M : Modes) {
521 TypeSetByHwMode::SetType &S = Small.get(M);
522 TypeSetByHwMode::SetType &B = Big.get(M);
523 // MinS = min scalar in Small, remove all scalars from Big that are
524 // smaller-or-equal than MinS.
525 auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000526 if (MinS != S.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000527 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000528
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000529 // MaxS = max scalar in Big, remove all scalars from Small that are
530 // larger than MaxS.
531 auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000532 if (MaxS != B.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000533 Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000534
535 // MinV = min vector in Small, remove all vectors from Big that are
536 // smaller-or-equal than MinV.
537 auto MinV = min_if(S.begin(), S.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000538 if (MinV != S.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000539 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000540
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000541 // MaxV = max vector in Big, remove all vectors from Small that are
542 // larger than MaxV.
543 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000544 if (MaxV != B.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000545 Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000546 }
547
548 return Changed;
549}
550
551/// 1. Ensure that for each type T in Vec, T is a vector type, and that
552/// for each type U in Elem, U is a scalar type.
553/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
554/// type T in Vec, such that U is the element type of T.
555bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
556 TypeSetByHwMode &Elem) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000557 ValidateOnExit _1(Vec, *this), _2(Elem, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000558 if (TP.hasError())
559 return false;
560 bool Changed = false;
561
562 if (Vec.empty())
563 Changed |= EnforceVector(Vec);
564 if (Elem.empty())
565 Changed |= EnforceScalar(Elem);
566
567 for (unsigned M : union_modes(Vec, Elem)) {
568 TypeSetByHwMode::SetType &V = Vec.get(M);
569 TypeSetByHwMode::SetType &E = Elem.get(M);
570
571 Changed |= berase_if(V, isScalar); // Scalar = !vector
572 Changed |= berase_if(E, isVector); // Vector = !scalar
573 assert(!V.empty() && !E.empty());
574
575 SmallSet<MVT,4> VT, ST;
576 // Collect element types from the "vector" set.
577 for (MVT T : V)
578 VT.insert(T.getVectorElementType());
579 // Collect scalar types from the "element" set.
580 for (MVT T : E)
581 ST.insert(T);
582
583 // Remove from V all (vector) types whose element type is not in S.
584 Changed |= berase_if(V, [&ST](MVT T) -> bool {
585 return !ST.count(T.getVectorElementType());
586 });
587 // Remove from E all (scalar) types, for which there is no corresponding
588 // type in V.
589 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000590 }
591
592 return Changed;
593}
594
595bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
596 const ValueTypeByHwMode &VVT) {
597 TypeSetByHwMode Tmp(VVT);
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000598 ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000599 return EnforceVectorEltTypeIs(Vec, Tmp);
600}
601
602/// Ensure that for each type T in Sub, T is a vector type, and there
603/// exists a type U in Vec such that U is a vector type with the same
604/// element type as T and at least as many elements as T.
605bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
606 TypeSetByHwMode &Sub) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000607 ValidateOnExit _1(Vec, *this), _2(Sub, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000608 if (TP.hasError())
609 return false;
610
611 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
612 auto IsSubVec = [](MVT B, MVT P) -> bool {
613 if (!B.isVector() || !P.isVector())
614 return false;
Florian Hahn603c6452017-11-07 10:43:56 +0000615 // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
616 // but until there are obvious use-cases for this, keep the
617 // types separate.
618 if (B.isScalableVector() != P.isScalableVector())
619 return false;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000620 if (B.getVectorElementType() != P.getVectorElementType())
621 return false;
622 return B.getVectorNumElements() < P.getVectorNumElements();
623 };
624
625 /// Return true if S has no element (vector type) that T is a sub-vector of,
626 /// i.e. has the same element type as T and more elements.
627 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
628 for (const auto &I : S)
629 if (IsSubVec(T, I))
630 return false;
631 return true;
632 };
633
634 /// Return true if S has no element (vector type) that T is a super-vector
635 /// of, i.e. has the same element type as T and fewer elements.
636 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
637 for (const auto &I : S)
638 if (IsSubVec(I, T))
639 return false;
640 return true;
641 };
642
643 bool Changed = false;
644
645 if (Vec.empty())
646 Changed |= EnforceVector(Vec);
647 if (Sub.empty())
648 Changed |= EnforceVector(Sub);
649
650 for (unsigned M : union_modes(Vec, Sub)) {
651 TypeSetByHwMode::SetType &S = Sub.get(M);
652 TypeSetByHwMode::SetType &V = Vec.get(M);
653
654 Changed |= berase_if(S, isScalar);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000655
656 // Erase all types from S that are not sub-vectors of a type in V.
657 Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000658
659 // Erase all types from V that are not super-vectors of a type in S.
660 Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000661 }
662
663 return Changed;
664}
665
666/// 1. Ensure that V has a scalar type iff W has a scalar type.
667/// 2. Ensure that for each vector type T in V, there exists a vector
668/// type U in W, such that T and U have the same number of elements.
669/// 3. Ensure that for each vector type U in W, there exists a vector
670/// type T in V, such that T and U have the same number of elements
671/// (reverse of 2).
672bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000673 ValidateOnExit _1(V, *this), _2(W, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000674 if (TP.hasError())
675 return false;
676
677 bool Changed = false;
678 if (V.empty())
679 Changed |= EnforceAny(V);
680 if (W.empty())
681 Changed |= EnforceAny(W);
682
683 // An actual vector type cannot have 0 elements, so we can treat scalars
684 // as zero-length vectors. This way both vectors and scalars can be
685 // processed identically.
686 auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
687 return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
688 };
689
690 for (unsigned M : union_modes(V, W)) {
691 TypeSetByHwMode::SetType &VS = V.get(M);
692 TypeSetByHwMode::SetType &WS = W.get(M);
693
694 SmallSet<unsigned,2> VN, WN;
695 for (MVT T : VS)
696 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
697 for (MVT T : WS)
698 WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
699
700 Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
701 Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
702 }
703 return Changed;
704}
705
706/// 1. Ensure that for each type T in A, there exists a type U in B,
707/// such that T and U have equal size in bits.
708/// 2. Ensure that for each type U in B, there exists a type T in A
709/// such that T and U have equal size in bits (reverse of 1).
710bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000711 ValidateOnExit _1(A, *this), _2(B, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000712 if (TP.hasError())
713 return false;
714 bool Changed = false;
715 if (A.empty())
716 Changed |= EnforceAny(A);
717 if (B.empty())
718 Changed |= EnforceAny(B);
719
720 auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
721 return !Sizes.count(T.getSizeInBits());
722 };
723
724 for (unsigned M : union_modes(A, B)) {
725 TypeSetByHwMode::SetType &AS = A.get(M);
726 TypeSetByHwMode::SetType &BS = B.get(M);
727 SmallSet<unsigned,2> AN, BN;
728
729 for (MVT T : AS)
730 AN.insert(T.getSizeInBits());
731 for (MVT T : BS)
732 BN.insert(T.getSizeInBits());
733
734 Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
735 Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
736 }
737
738 return Changed;
739}
740
741void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000742 ValidateOnExit _1(VTS, *this);
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000743 const TypeSetByHwMode &Legal = getLegalTypes();
744 assert(Legal.isDefaultOnly() && "Default-mode only expected");
745 const TypeSetByHwMode::SetType &LegalTypes = Legal.get(DefaultMode);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000746
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000747 for (auto &I : VTS)
748 expandOverloads(I.second, LegalTypes);
Scott Michel94420742008-03-05 17:49:05 +0000749}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000750
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000751void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
752 const TypeSetByHwMode::SetType &Legal) {
753 std::set<MVT> Ovs;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000754 for (MVT T : Out) {
755 if (!T.isOverloaded())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000756 continue;
Zachary Turner249dc142017-09-20 18:01:40 +0000757
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000758 Ovs.insert(T);
759 // MachineValueTypeSet allows iteration and erasing.
760 Out.erase(T);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000761 }
762
763 for (MVT Ov : Ovs) {
764 switch (Ov.SimpleTy) {
765 case MVT::iPTRAny:
766 Out.insert(MVT::iPTR);
767 return;
768 case MVT::iAny:
769 for (MVT T : MVT::integer_valuetypes())
770 if (Legal.count(T))
771 Out.insert(T);
772 for (MVT T : MVT::integer_vector_valuetypes())
773 if (Legal.count(T))
774 Out.insert(T);
775 return;
776 case MVT::fAny:
777 for (MVT T : MVT::fp_valuetypes())
778 if (Legal.count(T))
779 Out.insert(T);
780 for (MVT T : MVT::fp_vector_valuetypes())
781 if (Legal.count(T))
782 Out.insert(T);
783 return;
784 case MVT::vAny:
785 for (MVT T : MVT::vector_valuetypes())
786 if (Legal.count(T))
787 Out.insert(T);
788 return;
789 case MVT::Any:
790 for (MVT T : MVT::all_valuetypes())
791 if (Legal.count(T))
792 Out.insert(T);
793 return;
794 default:
795 break;
796 }
797 }
798}
799
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000800const TypeSetByHwMode &TypeInfer::getLegalTypes() {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000801 if (!LegalTypesCached) {
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000802 TypeSetByHwMode::SetType &LegalTypes = LegalCache.getOrCreate(DefaultMode);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000803 // Stuff all types from all modes into the default mode.
804 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
805 for (const auto &I : LTS)
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000806 LegalTypes.insert(I.second);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000807 LegalTypesCached = true;
808 }
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000809 assert(LegalCache.isDefaultOnly() && "Default-mode only expected");
810 return LegalCache;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000811}
Chris Lattner514e2922011-04-17 21:38:24 +0000812
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000813#ifndef NDEBUG
814TypeInfer::ValidateOnExit::~ValidateOnExit() {
Ulrich Weigand22b1af82018-07-13 16:42:15 +0000815 if (Infer.Validate && !VTS.validate()) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000816 dbgs() << "Type set is empty for each HW mode:\n"
817 "possible type contradiction in the pattern below "
818 "(use -print-records with llvm-tblgen to see all "
819 "expanded records).\n";
820 Infer.TP.dump();
821 llvm_unreachable(nullptr);
822 }
823}
824#endif
825
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000826
827//===----------------------------------------------------------------------===//
828// ScopedName Implementation
829//===----------------------------------------------------------------------===//
830
831bool ScopedName::operator==(const ScopedName &o) const {
832 return Scope == o.Scope && Identifier == o.Identifier;
833}
834
835bool ScopedName::operator!=(const ScopedName &o) const {
836 return !(*this == o);
837}
838
839
Chris Lattner514e2922011-04-17 21:38:24 +0000840//===----------------------------------------------------------------------===//
841// TreePredicateFn Implementation
842//===----------------------------------------------------------------------===//
843
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000844/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
845TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000846 assert(
847 (!hasPredCode() || !hasImmCode()) &&
848 ".td file corrupt: can't have a node predicate *and* an imm predicate");
849}
850
851bool TreePredicateFn::hasPredCode() const {
Daniel Sanders87d196c2017-11-13 22:26:13 +0000852 return isLoad() || isStore() || isAtomic() ||
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000853 !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000854}
855
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000856std::string TreePredicateFn::getPredCode() const {
857 std::string Code = "";
858
Daniel Sanders87d196c2017-11-13 22:26:13 +0000859 if (!isLoad() && !isStore() && !isAtomic()) {
860 Record *MemoryVT = getMemoryVT();
861
862 if (MemoryVT)
863 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
864 "MemoryVT requires IsLoad or IsStore");
865 }
866
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000867 if (!isLoad() && !isStore()) {
868 if (isUnindexed())
869 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
870 "IsUnindexed requires IsLoad or IsStore");
871
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000872 Record *ScalarMemoryVT = getScalarMemoryVT();
873
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000874 if (ScalarMemoryVT)
875 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
876 "ScalarMemoryVT requires IsLoad or IsStore");
877 }
878
Daniel Sanders87d196c2017-11-13 22:26:13 +0000879 if (isLoad() + isStore() + isAtomic() > 1)
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000880 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
Daniel Sanders87d196c2017-11-13 22:26:13 +0000881 "IsLoad, IsStore, and IsAtomic are mutually exclusive");
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000882
883 if (isLoad()) {
884 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
885 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
Matt Arsenault52c26242019-07-31 00:14:43 +0000886 getScalarMemoryVT() == nullptr && getAddressSpaces() == nullptr &&
887 getMinAlignment() < 1)
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000888 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
889 "IsLoad cannot be used by itself");
890 } else {
891 if (isNonExtLoad())
892 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
893 "IsNonExtLoad requires IsLoad");
894 if (isAnyExtLoad())
895 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
896 "IsAnyExtLoad requires IsLoad");
897 if (isSignExtLoad())
898 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
899 "IsSignExtLoad requires IsLoad");
900 if (isZeroExtLoad())
901 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
902 "IsZeroExtLoad requires IsLoad");
903 }
904
905 if (isStore()) {
906 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
Matt Arsenault52c26242019-07-31 00:14:43 +0000907 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr &&
908 getAddressSpaces() == nullptr && getMinAlignment() < 1)
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000909 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
910 "IsStore cannot be used by itself");
911 } else {
912 if (isNonTruncStore())
913 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
914 "IsNonTruncStore requires IsStore");
915 if (isTruncStore())
916 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
917 "IsTruncStore requires IsStore");
918 }
919
Daniel Sanders87d196c2017-11-13 22:26:13 +0000920 if (isAtomic()) {
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000921 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
922 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
923 !isAtomicOrderingAcquireRelease() &&
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000924 !isAtomicOrderingSequentiallyConsistent() &&
925 !isAtomicOrderingAcquireOrStronger() &&
926 !isAtomicOrderingReleaseOrStronger() &&
927 !isAtomicOrderingWeakerThanAcquire() &&
928 !isAtomicOrderingWeakerThanRelease())
Daniel Sanders87d196c2017-11-13 22:26:13 +0000929 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
930 "IsAtomic cannot be used by itself");
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000931 } else {
932 if (isAtomicOrderingMonotonic())
933 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
934 "IsAtomicOrderingMonotonic requires IsAtomic");
935 if (isAtomicOrderingAcquire())
936 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
937 "IsAtomicOrderingAcquire requires IsAtomic");
938 if (isAtomicOrderingRelease())
939 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
940 "IsAtomicOrderingRelease requires IsAtomic");
941 if (isAtomicOrderingAcquireRelease())
942 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
943 "IsAtomicOrderingAcquireRelease requires IsAtomic");
944 if (isAtomicOrderingSequentiallyConsistent())
945 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
946 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000947 if (isAtomicOrderingAcquireOrStronger())
948 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
949 "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
950 if (isAtomicOrderingReleaseOrStronger())
951 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
952 "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
953 if (isAtomicOrderingWeakerThanAcquire())
954 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
955 "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
Daniel Sanders87d196c2017-11-13 22:26:13 +0000956 }
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000957
Daniel Sanders87d196c2017-11-13 22:26:13 +0000958 if (isLoad() || isStore() || isAtomic()) {
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000959 if (ListInit *AddressSpaces = getAddressSpaces()) {
960 Code += "unsigned AddrSpace = cast<MemSDNode>(N)->getAddressSpace();\n"
961 " if (";
962
963 bool First = true;
964 for (Init *Val : AddressSpaces->getValues()) {
965 if (First)
966 First = false;
967 else
968 Code += " && ";
969
970 IntInit *IntVal = dyn_cast<IntInit>(Val);
971 if (!IntVal) {
972 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
973 "AddressSpaces element must be integer");
974 }
975
976 Code += "AddrSpace != " + utostr(IntVal->getValue());
977 }
978
979 Code += ")\nreturn false;\n";
980 }
Daniel Sanders87d196c2017-11-13 22:26:13 +0000981
Matt Arsenault52c26242019-07-31 00:14:43 +0000982 int64_t MinAlign = getMinAlignment();
983 if (MinAlign > 0) {
984 Code += "if (cast<MemSDNode>(N)->getAlignment() < ";
985 Code += utostr(MinAlign);
986 Code += ")\nreturn false;\n";
987 }
988
Daniel Sanders87d196c2017-11-13 22:26:13 +0000989 Record *MemoryVT = getMemoryVT();
990
991 if (MemoryVT)
Matt Arsenaultd00d8572019-07-15 20:59:42 +0000992 Code += ("if (cast<MemSDNode>(N)->getMemoryVT() != MVT::" +
Daniel Sanders87d196c2017-11-13 22:26:13 +0000993 MemoryVT->getName() + ") return false;\n")
994 .str();
995 }
996
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000997 if (isAtomic() && isAtomicOrderingMonotonic())
998 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
999 "AtomicOrdering::Monotonic) return false;\n";
1000 if (isAtomic() && isAtomicOrderingAcquire())
1001 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
1002 "AtomicOrdering::Acquire) return false;\n";
1003 if (isAtomic() && isAtomicOrderingRelease())
1004 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
1005 "AtomicOrdering::Release) return false;\n";
1006 if (isAtomic() && isAtomicOrderingAcquireRelease())
1007 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
1008 "AtomicOrdering::AcquireRelease) return false;\n";
1009 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
1010 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
1011 "AtomicOrdering::SequentiallyConsistent) return false;\n";
1012
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001013 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
1014 Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1015 "return false;\n";
1016 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
1017 Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1018 "return false;\n";
1019
1020 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
1021 Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1022 "return false;\n";
1023 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
1024 Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
1025 "return false;\n";
1026
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001027 if (isLoad() || isStore()) {
1028 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
1029
1030 if (isUnindexed())
1031 Code += ("if (cast<" + SDNodeName +
1032 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
1033 "return false;\n")
1034 .str();
1035
1036 if (isLoad()) {
1037 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
1038 isZeroExtLoad()) > 1)
1039 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1040 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
1041 "IsZeroExtLoad are mutually exclusive");
1042 if (isNonExtLoad())
1043 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
1044 "ISD::NON_EXTLOAD) return false;\n";
1045 if (isAnyExtLoad())
1046 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1047 "return false;\n";
1048 if (isSignExtLoad())
1049 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1050 "return false;\n";
1051 if (isZeroExtLoad())
1052 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1053 "return false;\n";
1054 } else {
1055 if ((isNonTruncStore() + isTruncStore()) > 1)
1056 PrintFatalError(
1057 getOrigPatFragRecord()->getRecord()->getLoc(),
1058 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1059 if (isNonTruncStore())
1060 Code +=
1061 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1062 if (isTruncStore())
1063 Code +=
1064 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1065 }
1066
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001067 Record *ScalarMemoryVT = getScalarMemoryVT();
1068
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001069 if (ScalarMemoryVT)
1070 Code += ("if (cast<" + SDNodeName +
1071 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1072 ScalarMemoryVT->getName() + ") return false;\n")
1073 .str();
1074 }
1075
1076 std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
1077
1078 Code += PredicateCode;
1079
1080 if (PredicateCode.empty() && !Code.empty())
1081 Code += "return true;\n";
1082
1083 return Code;
Chris Lattner514e2922011-04-17 21:38:24 +00001084}
1085
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001086bool TreePredicateFn::hasImmCode() const {
1087 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1088}
1089
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001090std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00001091 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001092}
1093
Daniel Sanders649c5852017-10-13 20:42:18 +00001094bool TreePredicateFn::immCodeUsesAPInt() const {
1095 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1096}
1097
1098bool TreePredicateFn::immCodeUsesAPFloat() const {
1099 bool Unset;
1100 // The return value will be false when IsAPFloat is unset.
1101 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1102 Unset);
1103}
1104
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001105bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1106 bool Value) const {
1107 bool Unset;
1108 bool Result =
1109 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1110 if (Unset)
1111 return false;
1112 return Result == Value;
1113}
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001114bool TreePredicateFn::usesOperands() const {
1115 return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
1116}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001117bool TreePredicateFn::isLoad() const {
1118 return isPredefinedPredicateEqualTo("IsLoad", true);
1119}
1120bool TreePredicateFn::isStore() const {
1121 return isPredefinedPredicateEqualTo("IsStore", true);
1122}
Daniel Sanders87d196c2017-11-13 22:26:13 +00001123bool TreePredicateFn::isAtomic() const {
1124 return isPredefinedPredicateEqualTo("IsAtomic", true);
1125}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001126bool TreePredicateFn::isUnindexed() const {
1127 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1128}
1129bool TreePredicateFn::isNonExtLoad() const {
1130 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1131}
1132bool TreePredicateFn::isAnyExtLoad() const {
1133 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1134}
1135bool TreePredicateFn::isSignExtLoad() const {
1136 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1137}
1138bool TreePredicateFn::isZeroExtLoad() const {
1139 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1140}
1141bool TreePredicateFn::isNonTruncStore() const {
1142 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1143}
1144bool TreePredicateFn::isTruncStore() const {
1145 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1146}
Daniel Sanders6d9d30a2017-11-13 23:03:47 +00001147bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1148 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1149}
1150bool TreePredicateFn::isAtomicOrderingAcquire() const {
1151 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1152}
1153bool TreePredicateFn::isAtomicOrderingRelease() const {
1154 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1155}
1156bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1157 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1158}
1159bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1160 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1161 true);
1162}
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001163bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1164 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1165}
1166bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1167 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1168}
1169bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1170 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1171}
1172bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1173 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1174}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001175Record *TreePredicateFn::getMemoryVT() const {
1176 Record *R = getOrigPatFragRecord()->getRecord();
1177 if (R->isValueUnset("MemoryVT"))
1178 return nullptr;
1179 return R->getValueAsDef("MemoryVT");
1180}
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001181
1182ListInit *TreePredicateFn::getAddressSpaces() const {
1183 Record *R = getOrigPatFragRecord()->getRecord();
1184 if (R->isValueUnset("AddressSpaces"))
1185 return nullptr;
1186 return R->getValueAsListInit("AddressSpaces");
1187}
1188
Matt Arsenault52c26242019-07-31 00:14:43 +00001189int64_t TreePredicateFn::getMinAlignment() const {
1190 Record *R = getOrigPatFragRecord()->getRecord();
1191 if (R->isValueUnset("MinAlignment"))
1192 return 0;
1193 return R->getValueAsInt("MinAlignment");
1194}
1195
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001196Record *TreePredicateFn::getScalarMemoryVT() const {
1197 Record *R = getOrigPatFragRecord()->getRecord();
1198 if (R->isValueUnset("ScalarMemoryVT"))
1199 return nullptr;
1200 return R->getValueAsDef("ScalarMemoryVT");
1201}
Daniel Sanders8ead1292018-06-15 23:13:43 +00001202bool TreePredicateFn::hasGISelPredicateCode() const {
1203 return !PatFragRec->getRecord()
1204 ->getValueAsString("GISelPredicateCode")
1205 .empty();
1206}
1207std::string TreePredicateFn::getGISelPredicateCode() const {
1208 return PatFragRec->getRecord()->getValueAsString("GISelPredicateCode");
1209}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001210
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001211StringRef TreePredicateFn::getImmType() const {
Daniel Sanders649c5852017-10-13 20:42:18 +00001212 if (immCodeUsesAPInt())
1213 return "const APInt &";
1214 if (immCodeUsesAPFloat())
1215 return "const APFloat &";
1216 return "int64_t";
1217}
Chris Lattner514e2922011-04-17 21:38:24 +00001218
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001219StringRef TreePredicateFn::getImmTypeIdentifier() const {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001220 if (immCodeUsesAPInt())
1221 return "APInt";
1222 else if (immCodeUsesAPFloat())
1223 return "APFloat";
1224 return "I64";
1225}
1226
Chris Lattner514e2922011-04-17 21:38:24 +00001227/// isAlwaysTrue - Return true if this is a noop predicate.
1228bool TreePredicateFn::isAlwaysTrue() const {
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001229 return !hasPredCode() && !hasImmCode();
Chris Lattner514e2922011-04-17 21:38:24 +00001230}
1231
1232/// Return the name to use in the generated code to reference this, this is
1233/// "Predicate_foo" if from a pattern fragment "foo".
1234std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +00001235 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +00001236}
1237
1238/// getCodeToRunOnSDNode - Return the code for the function body that
1239/// evaluates this predicate. The argument is expected to be in "Node",
1240/// not N. This handles casting and conversion to a concrete node type as
1241/// appropriate.
1242std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001243 // Handle immediate predicates first.
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001244 std::string ImmCode = getImmCode();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001245 if (!ImmCode.empty()) {
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001246 if (isLoad())
1247 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1248 "IsLoad cannot be used with ImmLeaf or its subclasses");
1249 if (isStore())
1250 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1251 "IsStore cannot be used with ImmLeaf or its subclasses");
1252 if (isUnindexed())
1253 PrintFatalError(
1254 getOrigPatFragRecord()->getRecord()->getLoc(),
1255 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1256 if (isNonExtLoad())
1257 PrintFatalError(
1258 getOrigPatFragRecord()->getRecord()->getLoc(),
1259 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1260 if (isAnyExtLoad())
1261 PrintFatalError(
1262 getOrigPatFragRecord()->getRecord()->getLoc(),
1263 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1264 if (isSignExtLoad())
1265 PrintFatalError(
1266 getOrigPatFragRecord()->getRecord()->getLoc(),
1267 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1268 if (isZeroExtLoad())
1269 PrintFatalError(
1270 getOrigPatFragRecord()->getRecord()->getLoc(),
1271 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1272 if (isNonTruncStore())
1273 PrintFatalError(
1274 getOrigPatFragRecord()->getRecord()->getLoc(),
1275 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1276 if (isTruncStore())
1277 PrintFatalError(
1278 getOrigPatFragRecord()->getRecord()->getLoc(),
1279 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1280 if (getMemoryVT())
1281 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1282 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1283 if (getScalarMemoryVT())
1284 PrintFatalError(
1285 getOrigPatFragRecord()->getRecord()->getLoc(),
1286 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1287
1288 std::string Result = (" " + getImmType() + " Imm = ").str();
Daniel Sanders649c5852017-10-13 20:42:18 +00001289 if (immCodeUsesAPFloat())
1290 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1291 else if (immCodeUsesAPInt())
1292 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1293 else
1294 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001295 return Result + ImmCode;
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001296 }
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001297
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001298 // Handle arbitrary node predicates.
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001299 assert(hasPredCode() && "Don't have any predicate code!");
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001300 StringRef ClassName;
Chris Lattner514e2922011-04-17 21:38:24 +00001301 if (PatFragRec->getOnlyTree()->isLeaf())
1302 ClassName = "SDNode";
1303 else {
1304 Record *Op = PatFragRec->getOnlyTree()->getOperator();
1305 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1306 }
1307 std::string Result;
1308 if (ClassName == "SDNode")
1309 Result = " SDNode *N = Node;\n";
1310 else
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001311 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001312
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001313 return (Twine(Result) + " (void)N;\n" + getPredCode()).str();
Scott Michel94420742008-03-05 17:49:05 +00001314}
1315
Chris Lattner8cab0212008-01-05 22:25:12 +00001316//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +00001317// PatternToMatch implementation
1318//
1319
Craig Topper1a872f22019-03-10 05:21:52 +00001320static bool isImmAllOnesAllZerosMatch(const TreePatternNode *P) {
1321 if (!P->isLeaf())
1322 return false;
1323 DefInit *DI = dyn_cast<DefInit>(P->getLeafValue());
1324 if (!DI)
1325 return false;
1326
1327 Record *R = DI->getDef();
1328 return R->getName() == "immAllOnesV" || R->getName() == "immAllZerosV";
1329}
1330
Chris Lattner05925fe2010-03-29 01:40:38 +00001331/// getPatternSize - Return the 'size' of this pattern. We want to match large
1332/// patterns before small ones. This is used to determine the size of a
1333/// pattern.
Florian Hahn6b1db822018-06-14 20:32:58 +00001334static unsigned getPatternSize(const TreePatternNode *P,
Chris Lattner05925fe2010-03-29 01:40:38 +00001335 const CodeGenDAGPatterns &CGP) {
1336 unsigned Size = 3; // The node itself.
1337 // If the root node is a ConstantSDNode, increases its size.
1338 // e.g. (set R32:$dst, 0).
Florian Hahn6b1db822018-06-14 20:32:58 +00001339 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001340 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001341
Florian Hahn6b1db822018-06-14 20:32:58 +00001342 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001343 Size += AM->getComplexity();
Tim Northoverc807a172014-05-20 11:52:46 +00001344 // We don't want to count any children twice, so return early.
1345 return Size;
1346 }
1347
Chris Lattner05925fe2010-03-29 01:40:38 +00001348 // If this node has some predicate function that must match, it adds to the
1349 // complexity of this node.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001350 if (!P->getPredicateCalls().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001351 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001352
Chris Lattner05925fe2010-03-29 01:40:38 +00001353 // Count children in the count if they are also nodes.
Florian Hahn6b1db822018-06-14 20:32:58 +00001354 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1355 const TreePatternNode *Child = P->getChild(i);
1356 if (!Child->isLeaf() && Child->getNumTypes()) {
Simon Pilgrimc3c14412018-08-15 20:41:19 +00001357 const TypeSetByHwMode &T0 = Child->getExtType(0);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001358 // At this point, all variable type sets should be simple, i.e. only
1359 // have a default mode.
1360 if (T0.getMachineValueType() != MVT::Other) {
1361 Size += getPatternSize(Child, CGP);
1362 continue;
1363 }
1364 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001365 if (Child->isLeaf()) {
1366 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001367 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Florian Hahn6b1db822018-06-14 20:32:58 +00001368 else if (Child->getComplexPatternInfo(CGP))
Chris Lattner05925fe2010-03-29 01:40:38 +00001369 Size += getPatternSize(Child, CGP);
Craig Topper1a872f22019-03-10 05:21:52 +00001370 else if (isImmAllOnesAllZerosMatch(Child))
1371 Size += 4; // Matches a build_vector(+3) and a predicate (+1).
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001372 else if (!Child->getPredicateCalls().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001373 ++Size;
1374 }
1375 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001376
Chris Lattner05925fe2010-03-29 01:40:38 +00001377 return Size;
1378}
1379
1380/// Compute the complexity metric for the input pattern. This roughly
1381/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +00001382int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +00001383getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001384 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
Chris Lattner05925fe2010-03-29 01:40:38 +00001385}
1386
Dan Gohman49e19e92008-08-22 00:20:26 +00001387/// getPredicateCheck - Return a single string containing all of this
1388/// pattern's predicates concatenated with "&&" operators.
1389///
1390std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001391 SmallVector<const Predicate*,4> PredList;
Matt Arsenault57ef94f2019-07-30 15:56:43 +00001392 for (const Predicate &P : Predicates) {
1393 if (!P.getCondString().empty())
1394 PredList.push_back(&P);
1395 }
Benjamin Kramerd5aecb92019-08-22 17:31:59 +00001396 llvm::sort(PredList, deref<std::less<>>());
Craig Topper8985efe2015-11-27 05:44:04 +00001397
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001398 std::string Check;
1399 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1400 if (i != 0)
1401 Check += " && ";
1402 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +00001403 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001404 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +00001405}
1406
1407//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00001408// SDTypeConstraint implementation
1409//
1410
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001411SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001412 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001413
Chris Lattner8cab0212008-01-05 22:25:12 +00001414 if (R->isSubClassOf("SDTCisVT")) {
1415 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001416 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1417 for (const auto &P : VVT)
1418 if (P.second == MVT::isVoid)
1419 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +00001420 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1421 ConstraintType = SDTCisPtrTy;
1422 } else if (R->isSubClassOf("SDTCisInt")) {
1423 ConstraintType = SDTCisInt;
1424 } else if (R->isSubClassOf("SDTCisFP")) {
1425 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +00001426 } else if (R->isSubClassOf("SDTCisVec")) {
1427 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001428 } else if (R->isSubClassOf("SDTCisSameAs")) {
1429 ConstraintType = SDTCisSameAs;
1430 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1431 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1432 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001433 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001434 R->getValueAsInt("OtherOperandNum");
1435 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1436 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001437 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001438 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001439 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1440 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001441 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001442 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1443 ConstraintType = SDTCisSubVecOfVec;
1444 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1445 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001446 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1447 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001448 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1449 for (const auto &P : VVT) {
1450 MVT T = P.second;
1451 if (T.isVector())
1452 PrintFatalError(R->getLoc(),
1453 "Cannot use vector type as SDTCVecEltisVT");
1454 if (!T.isInteger() && !T.isFloatingPoint())
1455 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1456 "as SDTCVecEltisVT");
1457 }
Craig Topper0be34582015-03-05 07:11:34 +00001458 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1459 ConstraintType = SDTCisSameNumEltsAs;
1460 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1461 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001462 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1463 ConstraintType = SDTCisSameSizeAs;
1464 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1465 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001466 } else {
Daniel Sandersdff673b2019-02-12 17:36:57 +00001467 PrintFatalError(R->getLoc(),
1468 "Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001469 }
1470}
1471
1472/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001473/// N, and the result number in ResNo.
Florian Hahn6b1db822018-06-14 20:32:58 +00001474static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
Chris Lattner2db7aba2010-03-19 21:56:21 +00001475 const SDNodeInfo &NodeInfo,
1476 unsigned &ResNo) {
1477 unsigned NumResults = NodeInfo.getNumResults();
1478 if (OpNo < NumResults) {
1479 ResNo = OpNo;
1480 return N;
1481 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001482
Chris Lattner2db7aba2010-03-19 21:56:21 +00001483 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001484
Florian Hahn6b1db822018-06-14 20:32:58 +00001485 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001486 std::string S;
1487 raw_string_ostream OS(S);
1488 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001489 << (OpNo+NumResults) << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001490 N->print(OS);
James Y Knighte452e272015-05-11 22:17:13 +00001491 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001492 }
1493
Florian Hahn6b1db822018-06-14 20:32:58 +00001494 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001495}
1496
1497/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1498/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001499/// change, false otherwise. If a type contradiction is found, flag an error.
Florian Hahn6b1db822018-06-14 20:32:58 +00001500bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
Chris Lattner8cab0212008-01-05 22:25:12 +00001501 const SDNodeInfo &NodeInfo,
1502 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001503 if (TP.hasError())
1504 return false;
1505
Chris Lattner2db7aba2010-03-19 21:56:21 +00001506 unsigned ResNo = 0; // The result number being referenced.
Florian Hahn6b1db822018-06-14 20:32:58 +00001507 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001508 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001509
Chris Lattner8cab0212008-01-05 22:25:12 +00001510 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001511 case SDTCisVT:
1512 // Operand must be a particular type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001513 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001514 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001515 // Operand must be same as target pointer type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001516 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001517 case SDTCisInt:
1518 // Require it to be one of the legal integer VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001519 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001520 case SDTCisFP:
1521 // Require it to be one of the legal fp VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001522 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001523 case SDTCisVec:
1524 // Require it to be one of the legal vector VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001525 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001526 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001527 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001528 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001529 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001530 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1531 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001532 }
1533 case SDTCisVTSmallerThanOp: {
1534 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1535 // have an integer type that is smaller than the VT.
Florian Hahn6b1db822018-06-14 20:32:58 +00001536 if (!NodeToApply->isLeaf() ||
1537 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1538 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001539 ->isSubClassOf("ValueType")) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001540 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001541 return false;
1542 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001543 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001544 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1545 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1546 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001547
Chris Lattner2db7aba2010-03-19 21:56:21 +00001548 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001549 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001550 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1551 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001552
Florian Hahn6b1db822018-06-14 20:32:58 +00001553 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001554 }
1555 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001556 unsigned BResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001557 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001558 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1559 BResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001560 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1561 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001562 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001563 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001564 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001565 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001566 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1567 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001568 // Filter vector types out of VecOperand that don't have the right element
1569 // type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001570 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1571 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001572 }
David Greene127fd1d2011-01-24 20:53:18 +00001573 case SDTCisSubVecOfVec: {
1574 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001575 TreePatternNode *BigVecOperand =
David Greene127fd1d2011-01-24 20:53:18 +00001576 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1577 VResNo);
1578
1579 // Filter vector types out of BigVecOperand that don't have the
1580 // right subvector type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001581 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1582 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001583 }
Craig Topper0be34582015-03-05 07:11:34 +00001584 case SDTCVecEltisVT: {
Florian Hahn6b1db822018-06-14 20:32:58 +00001585 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001586 }
1587 case SDTCisSameNumEltsAs: {
1588 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001589 TreePatternNode *OtherNode =
Craig Topper0be34582015-03-05 07:11:34 +00001590 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1591 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001592 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1593 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001594 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001595 case SDTCisSameSizeAs: {
1596 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001597 TreePatternNode *OtherNode =
Craig Topper9a44b3f2015-11-26 07:02:18 +00001598 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1599 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001600 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1601 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001602 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001603 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001604 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001605}
1606
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001607// Update the node type to match an instruction operand or result as specified
1608// in the ins or outs lists on the instruction definition. Return true if the
1609// type was actually changed.
1610bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1611 Record *Operand,
1612 TreePattern &TP) {
1613 // The 'unknown' operand indicates that types should be inferred from the
1614 // context.
1615 if (Operand->isSubClassOf("unknown_class"))
1616 return false;
1617
1618 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001619 if (Operand->isSubClassOf("Operand")) {
1620 Record *R = Operand->getValueAsDef("Type");
1621 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1622 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1623 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001624
1625 // PointerLikeRegClass has a type that is determined at runtime.
1626 if (Operand->isSubClassOf("PointerLikeRegClass"))
1627 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1628
1629 // Both RegisterClass and RegisterOperand operands derive their types from a
1630 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001631 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001632 if (Operand->isSubClassOf("RegisterClass"))
1633 RC = Operand;
1634 else if (Operand->isSubClassOf("RegisterOperand"))
1635 RC = Operand->getValueAsDef("RegClass");
1636
1637 assert(RC && "Unknown operand type");
1638 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1639 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1640}
1641
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001642bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1643 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1644 if (!TP.getInfer().isConcrete(Types[i], true))
1645 return true;
1646 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001647 if (getChild(i)->ContainsUnresolvedType(TP))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001648 return true;
1649 return false;
1650}
1651
1652bool TreePatternNode::hasProperTypeByHwMode() const {
1653 for (const TypeSetByHwMode &S : Types)
1654 if (!S.isDefaultOnly())
1655 return true;
Florian Hahn75e87c32018-05-30 21:00:18 +00001656 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001657 if (C->hasProperTypeByHwMode())
1658 return true;
1659 return false;
1660}
1661
1662bool TreePatternNode::hasPossibleType() const {
1663 for (const TypeSetByHwMode &S : Types)
1664 if (!S.isPossible())
1665 return false;
Florian Hahn75e87c32018-05-30 21:00:18 +00001666 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001667 if (!C->hasPossibleType())
1668 return false;
1669 return true;
1670}
1671
1672bool TreePatternNode::setDefaultMode(unsigned Mode) {
1673 for (TypeSetByHwMode &S : Types) {
1674 S.makeSimple(Mode);
1675 // Check if the selected mode had a type conflict.
1676 if (S.get(DefaultMode).empty())
1677 return false;
1678 }
Florian Hahn75e87c32018-05-30 21:00:18 +00001679 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001680 if (!C->setDefaultMode(Mode))
1681 return false;
1682 return true;
1683}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001684
Chris Lattner8cab0212008-01-05 22:25:12 +00001685//===----------------------------------------------------------------------===//
1686// SDNodeInfo implementation
1687//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001688SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001689 EnumName = R->getValueAsString("Opcode");
1690 SDClassName = R->getValueAsString("SDClass");
1691 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1692 NumResults = TypeProfile->getValueAsInt("NumResults");
1693 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001694
Chris Lattner8cab0212008-01-05 22:25:12 +00001695 // Parse the properties.
Matt Arsenault303327d2017-12-20 19:36:28 +00001696 Properties = parseSDPatternOperatorProperties(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001697
Chris Lattner8cab0212008-01-05 22:25:12 +00001698 // Parse the type constraints.
1699 std::vector<Record*> ConstraintList =
1700 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001701 for (Record *R : ConstraintList)
1702 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001703}
1704
Chris Lattner99e53b32010-02-28 00:22:30 +00001705/// getKnownType - If the type constraints on this node imply a fixed type
1706/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001707/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001708MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001709 unsigned NumResults = getNumResults();
1710 assert(NumResults <= 1 &&
1711 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001712 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001713
Craig Topper306cb122015-11-22 20:46:24 +00001714 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001715 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001716 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001717 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001718
Craig Topper306cb122015-11-22 20:46:24 +00001719 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001720 default: break;
1721 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001722 if (Constraint.VVT.isSimple())
1723 return Constraint.VVT.getSimple().SimpleTy;
1724 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001725 case SDTypeConstraint::SDTCisPtrTy:
1726 return MVT::iPTR;
1727 }
1728 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001729 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001730}
1731
Chris Lattner8cab0212008-01-05 22:25:12 +00001732//===----------------------------------------------------------------------===//
1733// TreePatternNode implementation
1734//
1735
Chris Lattnerf1447252010-03-19 21:37:09 +00001736static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1737 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001738 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001739 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001740
Chris Lattner2109cb42010-03-22 20:56:36 +00001741 if (Operator->isSubClassOf("Intrinsic"))
1742 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001743
Chris Lattnerf1447252010-03-19 21:37:09 +00001744 if (Operator->isSubClassOf("SDNode"))
1745 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001746
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001747 if (Operator->isSubClassOf("PatFrags")) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001748 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1749 // the forward reference case where one pattern fragment references another
1750 // before it is processed.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001751 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
1752 // The number of results of a fragment with alternative records is the
1753 // maximum number of results across all alternatives.
1754 unsigned NumResults = 0;
1755 for (auto T : PFRec->getTrees())
1756 NumResults = std::max(NumResults, T->getNumTypes());
1757 return NumResults;
1758 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001759
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001760 ListInit *LI = Operator->getValueAsListInit("Fragments");
1761 assert(LI && "Invalid Fragment");
1762 unsigned NumResults = 0;
1763 for (Init *I : LI->getValues()) {
1764 Record *Op = nullptr;
1765 if (DagInit *Dag = dyn_cast<DagInit>(I))
1766 if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
1767 Op = DI->getDef();
1768 assert(Op && "Invalid Fragment");
1769 NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
1770 }
1771 return NumResults;
Chris Lattnerf1447252010-03-19 21:37:09 +00001772 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001773
Chris Lattnerf1447252010-03-19 21:37:09 +00001774 if (Operator->isSubClassOf("Instruction")) {
1775 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001776
Craig Topper3a8eb892015-03-20 05:09:06 +00001777 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1778
1779 // Subtract any defaulted outputs.
1780 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1781 Record *OperandNode = InstInfo.Operands[i].Rec;
1782
1783 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1784 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1785 --NumDefsToAdd;
1786 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001787
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001788 // Add on one implicit def if it has a resolvable type.
1789 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1790 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001791 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001792 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001793
Chris Lattnerf1447252010-03-19 21:37:09 +00001794 if (Operator->isSubClassOf("SDNodeXForm"))
1795 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001796
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001797 if (Operator->isSubClassOf("ValueType"))
1798 return 1; // A type-cast of one result.
1799
Tim Northoverc807a172014-05-20 11:52:46 +00001800 if (Operator->isSubClassOf("ComplexPattern"))
1801 return 1;
1802
Matthias Braun8c209aa2017-01-28 02:02:38 +00001803 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001804 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001805}
1806
1807void TreePatternNode::print(raw_ostream &OS) const {
1808 if (isLeaf())
1809 OS << *getLeafValue();
1810 else
1811 OS << '(' << getOperator()->getName();
1812
Zachary Turner249dc142017-09-20 18:01:40 +00001813 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1814 OS << ':';
1815 getExtType(i).writeToStream(OS);
1816 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001817
1818 if (!isLeaf()) {
1819 if (getNumChildren() != 0) {
1820 OS << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001821 getChild(0)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001822 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1823 OS << ", ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001824 getChild(i)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001825 }
1826 }
1827 OS << ")";
1828 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001829
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001830 for (const TreePredicateCall &Pred : PredicateCalls) {
1831 OS << "<<P:";
1832 if (Pred.Scope)
1833 OS << Pred.Scope << ":";
1834 OS << Pred.Fn.getFnName() << ">>";
1835 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001836 if (TransformFn)
1837 OS << "<<X:" << TransformFn->getName() << ">>";
1838 if (!getName().empty())
1839 OS << ":$" << getName();
1840
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001841 for (const ScopedName &Name : NamesAsPredicateArg)
1842 OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();
Chris Lattner8cab0212008-01-05 22:25:12 +00001843}
1844void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001845 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001846}
1847
Scott Michel94420742008-03-05 17:49:05 +00001848/// isIsomorphicTo - Return true if this node is recursively
1849/// isomorphic to the specified node. For this comparison, the node's
1850/// entire state is considered. The assigned name is ignored, since
1851/// nodes with differing names are considered isomorphic. However, if
1852/// the assigned name is present in the dependent variable set, then
1853/// the assigned name is considered significant and the node is
1854/// isomorphic if the names match.
Florian Hahn6b1db822018-06-14 20:32:58 +00001855bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
Scott Michel94420742008-03-05 17:49:05 +00001856 const MultipleUseVarSet &DepVars) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001857 if (N == this) return true;
1858 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001859 getPredicateCalls() != N->getPredicateCalls() ||
Florian Hahn6b1db822018-06-14 20:32:58 +00001860 getTransformFn() != N->getTransformFn())
Chris Lattner8cab0212008-01-05 22:25:12 +00001861 return false;
1862
1863 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001864 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001865 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001866 return ((DI->getDef() == NDI->getDef())
1867 && (DepVars.find(getName()) == DepVars.end()
Florian Hahn6b1db822018-06-14 20:32:58 +00001868 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001869 }
1870 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001871 return getLeafValue() == N->getLeafValue();
Chris Lattner8cab0212008-01-05 22:25:12 +00001872 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001873
Florian Hahn6b1db822018-06-14 20:32:58 +00001874 if (N->getOperator() != getOperator() ||
1875 N->getNumChildren() != getNumChildren()) return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001876 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001877 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001878 return false;
1879 return true;
1880}
1881
1882/// clone - Make a copy of this tree and all of its children.
1883///
Florian Hahn75e87c32018-05-30 21:00:18 +00001884TreePatternNodePtr TreePatternNode::clone() const {
1885 TreePatternNodePtr New;
Chris Lattner8cab0212008-01-05 22:25:12 +00001886 if (isLeaf()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001887 New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001888 } else {
Florian Hahn75e87c32018-05-30 21:00:18 +00001889 std::vector<TreePatternNodePtr> CChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00001890 CChildren.reserve(Children.size());
1891 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001892 CChildren.push_back(getChild(i)->clone());
Craig Topper26fc06352018-07-15 06:52:49 +00001893 New = std::make_shared<TreePatternNode>(getOperator(), std::move(CChildren),
Florian Hahn75e87c32018-05-30 21:00:18 +00001894 getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001895 }
1896 New->setName(getName());
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001897 New->setNamesAsPredicateArg(getNamesAsPredicateArg());
Chris Lattnerf1447252010-03-19 21:37:09 +00001898 New->Types = Types;
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001899 New->setPredicateCalls(getPredicateCalls());
Chris Lattner8cab0212008-01-05 22:25:12 +00001900 New->setTransformFn(getTransformFn());
1901 return New;
1902}
1903
Chris Lattner53c39ba2010-02-14 22:22:58 +00001904/// RemoveAllTypes - Recursively strip all the types of this tree.
1905void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001906 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001907 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001908 if (isLeaf()) return;
1909 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001910 getChild(i)->RemoveAllTypes();
Chris Lattner53c39ba2010-02-14 22:22:58 +00001911}
1912
1913
Chris Lattner8cab0212008-01-05 22:25:12 +00001914/// SubstituteFormalArguments - Replace the formal arguments in this tree
1915/// with actual values specified by ArgMap.
Florian Hahn75e87c32018-05-30 21:00:18 +00001916void TreePatternNode::SubstituteFormalArguments(
1917 std::map<std::string, TreePatternNodePtr> &ArgMap) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001918 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001919
Chris Lattner8cab0212008-01-05 22:25:12 +00001920 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001921 TreePatternNode *Child = getChild(i);
1922 if (Child->isLeaf()) {
1923 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001924 // Note that, when substituting into an output pattern, Val might be an
1925 // UnsetInit.
1926 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1927 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001928 // We found a use of a formal argument, replace it with its value.
Florian Hahn6b1db822018-06-14 20:32:58 +00001929 TreePatternNodePtr NewChild = ArgMap[Child->getName()];
Dan Gohman6e979022008-10-15 06:17:21 +00001930 assert(NewChild && "Couldn't find formal argument!");
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001931 assert((Child->getPredicateCalls().empty() ||
1932 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
Dan Gohman6e979022008-10-15 06:17:21 +00001933 "Non-empty child predicate clobbered!");
Florian Hahn0a2e0b62018-06-14 11:56:19 +00001934 setChild(i, std::move(NewChild));
Chris Lattner8cab0212008-01-05 22:25:12 +00001935 }
1936 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00001937 getChild(i)->SubstituteFormalArguments(ArgMap);
Chris Lattner8cab0212008-01-05 22:25:12 +00001938 }
1939 }
1940}
1941
1942
1943/// InlinePatternFragments - If this pattern refers to any pattern
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001944/// fragments, return the set of inlined versions (this can be more than
1945/// one if a PatFrags record has multiple alternatives).
1946void TreePatternNode::InlinePatternFragments(
1947 TreePatternNodePtr T, TreePattern &TP,
1948 std::vector<TreePatternNodePtr> &OutAlternatives) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001949
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001950 if (TP.hasError())
1951 return;
1952
1953 if (isLeaf()) {
1954 OutAlternatives.push_back(T); // nothing to do.
1955 return;
1956 }
1957
Chris Lattner8cab0212008-01-05 22:25:12 +00001958 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001959
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001960 if (!Op->isSubClassOf("PatFrags")) {
1961 if (getNumChildren() == 0) {
1962 OutAlternatives.push_back(T);
1963 return;
1964 }
1965
1966 // Recursively inline children nodes.
1967 std::vector<std::vector<TreePatternNodePtr> > ChildAlternatives;
1968 ChildAlternatives.resize(getNumChildren());
Dan Gohman6e979022008-10-15 06:17:21 +00001969 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001970 TreePatternNodePtr Child = getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001971 Child->InlinePatternFragments(Child, TP, ChildAlternatives[i]);
1972 // If there are no alternatives for any child, there are no
1973 // alternatives for this expression as whole.
1974 if (ChildAlternatives[i].empty())
1975 return;
Dan Gohman6e979022008-10-15 06:17:21 +00001976
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001977 for (auto NewChild : ChildAlternatives[i])
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001978 assert((Child->getPredicateCalls().empty() ||
1979 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001980 "Non-empty child predicate clobbered!");
Dan Gohman6e979022008-10-15 06:17:21 +00001981 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001982
1983 // The end result is an all-pairs construction of the resultant pattern.
1984 std::vector<unsigned> Idxs;
1985 Idxs.resize(ChildAlternatives.size());
1986 bool NotDone;
1987 do {
1988 // Create the variant and add it to the output list.
1989 std::vector<TreePatternNodePtr> NewChildren;
1990 for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
1991 NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
1992 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00001993 getOperator(), std::move(NewChildren), getNumTypes());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001994
1995 // Copy over properties.
1996 R->setName(getName());
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001997 R->setNamesAsPredicateArg(getNamesAsPredicateArg());
1998 R->setPredicateCalls(getPredicateCalls());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001999 R->setTransformFn(getTransformFn());
2000 for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
2001 R->setType(i, getExtType(i));
Craig Topperbd199f82018-12-05 00:47:59 +00002002 for (unsigned i = 0, e = getNumResults(); i != e; ++i)
2003 R->setResultIndex(i, getResultIndex(i));
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002004
2005 // Register alternative.
2006 OutAlternatives.push_back(R);
2007
2008 // Increment indices to the next permutation by incrementing the
2009 // indices from last index backward, e.g., generate the sequence
2010 // [0, 0], [0, 1], [1, 0], [1, 1].
2011 int IdxsIdx;
2012 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2013 if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
2014 Idxs[IdxsIdx] = 0;
2015 else
2016 break;
2017 }
2018 NotDone = (IdxsIdx >= 0);
2019 } while (NotDone);
2020
2021 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002022 }
2023
2024 // Otherwise, we found a reference to a fragment. First, look up its
2025 // TreePattern record.
2026 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002027
Chris Lattner8cab0212008-01-05 22:25:12 +00002028 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002029 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002030 TP.error("'" + Op->getName() + "' fragment requires " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002031 Twine(Frag->getNumArgs()) + " operands!");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002032 return;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002033 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002034
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002035 TreePredicateFn PredFn(Frag);
2036 unsigned Scope = 0;
2037 if (TreePredicateFn(Frag).usesOperands())
2038 Scope = TP.getDAGPatterns().allocateScope();
2039
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002040 // Compute the map of formal to actual arguments.
2041 std::map<std::string, TreePatternNodePtr> ArgMap;
2042 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002043 TreePatternNodePtr Child = getChildShared(i);
2044 if (Scope != 0) {
2045 Child = Child->clone();
2046 Child->addNameAsPredicateArg(ScopedName(Scope, Frag->getArgName(i)));
2047 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002048 ArgMap[Frag->getArgName(i)] = Child;
Chris Lattner8cab0212008-01-05 22:25:12 +00002049 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002050
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002051 // Loop over all fragment alternatives.
2052 for (auto Alternative : Frag->getTrees()) {
2053 TreePatternNodePtr FragTree = Alternative->clone();
Dan Gohman6e979022008-10-15 06:17:21 +00002054
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002055 if (!PredFn.isAlwaysTrue())
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002056 FragTree->addPredicateCall(PredFn, Scope);
Dan Gohman6e979022008-10-15 06:17:21 +00002057
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002058 // Resolve formal arguments to their actual value.
2059 if (Frag->getNumArgs())
2060 FragTree->SubstituteFormalArguments(ArgMap);
2061
2062 // Transfer types. Note that the resolved alternative may have fewer
2063 // (but not more) results than the PatFrags node.
2064 FragTree->setName(getName());
2065 for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
2066 FragTree->UpdateNodeType(i, getExtType(i), TP);
2067
2068 // Transfer in the old predicates.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002069 for (const TreePredicateCall &Pred : getPredicateCalls())
2070 FragTree->addPredicateCall(Pred);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002071
2072 // The fragment we inlined could have recursive inlining that is needed. See
2073 // if there are any pattern fragments in it and inline them as needed.
2074 FragTree->InlinePatternFragments(FragTree, TP, OutAlternatives);
2075 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002076}
2077
2078/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00002079/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00002080/// references from the register file information, for example.
2081///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002082/// When Unnamed is set, return the type of a DAG operand with no name, such as
2083/// the F8RC register class argument in:
2084///
2085/// (COPY_TO_REGCLASS GPR:$src, F8RC)
2086///
2087/// When Unnamed is false, return the type of a named DAG operand such as the
2088/// GPR:$src operand above.
2089///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002090static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
2091 bool NotRegisters,
2092 bool Unnamed,
2093 TreePattern &TP) {
2094 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2095
Owen Andersona84be6c2011-06-27 21:06:21 +00002096 // Check to see if this is a register operand.
2097 if (R->isSubClassOf("RegisterOperand")) {
2098 assert(ResNo == 0 && "Regoperand ref only has one result!");
2099 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002100 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00002101 Record *RegClass = R->getValueAsDef("RegClass");
2102 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002103 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00002104 }
2105
Chris Lattnercabe0372010-03-15 06:00:16 +00002106 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00002107 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002108 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002109 // An unnamed register class represents itself as an i32 immediate, for
2110 // example on a COPY_TO_REGCLASS instruction.
2111 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002112 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002113
2114 // In a named operand, the register class provides the possible set of
2115 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002116 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002117 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00002118 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002119 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00002120 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002121
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002122 if (R->isSubClassOf("PatFrags")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002123 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00002124 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002125 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00002126 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002127
Chris Lattner6070ee22010-03-23 23:50:31 +00002128 if (R->isSubClassOf("Register")) {
2129 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002130 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002131 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002132 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002133 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00002134 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002135
2136 if (R->isSubClassOf("SubRegIndex")) {
2137 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002138 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002139 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002140
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002141 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002142 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002143 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2144 //
2145 // (sext_inreg GPR:$src, i16)
2146 // ~~~
2147 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002148 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002149 // With a name, the ValueType simply provides the type of the named
2150 // variable.
2151 //
2152 // (sext_inreg i32:$src, i16)
2153 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002154 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002155 return TypeSetByHwMode(); // Unknown.
2156 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2157 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002158 }
2159
2160 if (R->isSubClassOf("CondCode")) {
2161 assert(ResNo == 0 && "This node only has one result!");
2162 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002163 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00002164 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002165
Chris Lattner6070ee22010-03-23 23:50:31 +00002166 if (R->isSubClassOf("ComplexPattern")) {
2167 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002168 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002169 return TypeSetByHwMode(); // Unknown.
2170 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00002171 }
2172 if (R->isSubClassOf("PointerLikeRegClass")) {
2173 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002174 TypeSetByHwMode VTS(MVT::iPTR);
2175 TP.getInfer().expandOverloads(VTS);
2176 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00002177 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002178
Chris Lattner6070ee22010-03-23 23:50:31 +00002179 if (R->getName() == "node" || R->getName() == "srcvalue" ||
Craig Topper1a872f22019-03-10 05:21:52 +00002180 R->getName() == "zero_reg" || R->getName() == "immAllOnesV" ||
Sjoerd Meijerde234842019-05-30 07:30:37 +00002181 R->getName() == "immAllZerosV" || R->getName() == "undef_tied_input") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002182 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002183 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002184 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002185
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002186 if (R->isSubClassOf("Operand")) {
2187 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2188 Record *T = R->getValueAsDef("Type");
2189 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2190 }
Tim Northoverc807a172014-05-20 11:52:46 +00002191
Chris Lattner8cab0212008-01-05 22:25:12 +00002192 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002193 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00002194}
2195
Chris Lattner89c65662008-01-06 05:36:50 +00002196
2197/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2198/// CodeGenIntrinsic information for it, otherwise return a null pointer.
2199const CodeGenIntrinsic *TreePatternNode::
2200getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2201 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2202 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2203 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00002204 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002205
Florian Hahn6b1db822018-06-14 20:32:58 +00002206 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00002207 return &CDP.getIntrinsicInfo(IID);
2208}
2209
Chris Lattner53c39ba2010-02-14 22:22:58 +00002210/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2211/// return the ComplexPattern information, otherwise return null.
2212const ComplexPattern *
2213TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00002214 Record *Rec;
2215 if (isLeaf()) {
2216 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2217 if (!DI)
2218 return nullptr;
2219 Rec = DI->getDef();
2220 } else
2221 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002222
Tim Northoverc807a172014-05-20 11:52:46 +00002223 if (!Rec->isSubClassOf("ComplexPattern"))
2224 return nullptr;
2225 return &CGP.getComplexPattern(Rec);
2226}
2227
2228unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2229 // A ComplexPattern specifically declares how many results it fills in.
2230 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2231 return CP->getNumOperands();
2232
2233 // If MIOperandInfo is specified, that gives the count.
2234 if (isLeaf()) {
2235 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2236 if (DI && DI->getDef()->isSubClassOf("Operand")) {
2237 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2238 if (MIOps->getNumArgs())
2239 return MIOps->getNumArgs();
2240 }
2241 }
2242
2243 // Otherwise there is just one result.
2244 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00002245}
2246
2247/// NodeHasProperty - Return true if this node has the specified property.
2248bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002249 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002250 if (isLeaf()) {
2251 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2252 return CP->hasProperty(Property);
Matt Arsenault303327d2017-12-20 19:36:28 +00002253
Chris Lattner53c39ba2010-02-14 22:22:58 +00002254 return false;
2255 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002256
Matt Arsenault303327d2017-12-20 19:36:28 +00002257 if (Property != SDNPHasChain) {
2258 // The chain proprety is already present on the different intrinsic node
2259 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2260 // on the intrinsic. Anything else is specific to the individual intrinsic.
2261 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2262 return Int->hasProperty(Property);
2263 }
2264
2265 if (!Operator->isSubClassOf("SDPatternOperator"))
2266 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002267
Chris Lattner53c39ba2010-02-14 22:22:58 +00002268 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2269}
2270
2271
2272
2273
2274/// TreeHasProperty - Return true if any node in this tree has the specified
2275/// property.
2276bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002277 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002278 if (NodeHasProperty(Property, CGP))
2279 return true;
2280 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002281 if (getChild(i)->TreeHasProperty(Property, CGP))
Chris Lattner53c39ba2010-02-14 22:22:58 +00002282 return true;
2283 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002284}
Chris Lattner53c39ba2010-02-14 22:22:58 +00002285
Evan Cheng49bad4c2008-06-16 20:29:38 +00002286/// isCommutativeIntrinsic - Return true if the node corresponds to a
2287/// commutative intrinsic.
2288bool
2289TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2290 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2291 return Int->isCommutative;
2292 return false;
2293}
2294
Florian Hahn6b1db822018-06-14 20:32:58 +00002295static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2296 if (!N->isLeaf())
2297 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00002298
Florian Hahn6b1db822018-06-14 20:32:58 +00002299 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
Matt Arsenaulteb492162014-11-02 23:46:51 +00002300 if (DI && DI->getDef()->isSubClassOf(Class))
2301 return true;
2302
2303 return false;
2304}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002305
2306static void emitTooManyOperandsError(TreePattern &TP,
2307 StringRef InstName,
2308 unsigned Expected,
2309 unsigned Actual) {
2310 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2311 " operands but expected only " + Twine(Expected) + "!");
2312}
2313
2314static void emitTooFewOperandsError(TreePattern &TP,
2315 StringRef InstName,
2316 unsigned Actual) {
2317 TP.error("Instruction '" + InstName +
2318 "' expects more than the provided " + Twine(Actual) + " operands!");
2319}
2320
Bob Wilson1b97f3f2009-01-05 17:23:09 +00002321/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00002322/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002323/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00002324bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002325 if (TP.hasError())
2326 return false;
2327
Chris Lattnerab3242f2008-01-06 01:10:31 +00002328 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00002329 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002330 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002331 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00002332 bool MadeChange = false;
2333 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2334 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002335 NotRegisters,
2336 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002337 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00002338 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002339
Sean Silvafb509ed2012-10-10 20:24:43 +00002340 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002341 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002342
Chris Lattnerf1447252010-03-19 21:37:09 +00002343 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002344 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002345
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002346 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00002347 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002348
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002349 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2350 for (auto &P : VVT) {
2351 MVT::SimpleValueType VT = P.second.SimpleTy;
2352 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2353 continue;
2354 unsigned Size = MVT(VT).getSizeInBits();
2355 // Make sure that the value is representable for this type.
2356 if (Size >= 32)
2357 continue;
2358 // Check that the value doesn't use more bits than we have. It must
2359 // either be a sign- or zero-extended equivalent of the original.
2360 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2361 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2362 SignBitAndAbove == 1)
2363 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002364
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002365 TP.error("Integer value '" + Twine(II->getValue()) +
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002366 "' is out of range for type '" + getEnumName(VT) + "'!");
2367 break;
2368 }
2369 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002370 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002371
Chris Lattner8cab0212008-01-05 22:25:12 +00002372 return false;
2373 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002374
Chris Lattneree820ac2010-02-23 05:51:07 +00002375 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002376 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00002377
Chris Lattner8cab0212008-01-05 22:25:12 +00002378 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00002379 unsigned NumRetVTs = Int->IS.RetVTs.size();
2380 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002381
Bill Wendling91821472008-11-13 09:08:33 +00002382 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00002383 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00002384
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002385 if (getNumChildren() != NumParamVTs + 1) {
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002386 TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2387 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002388 return false;
2389 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002390
2391 // Apply type info to the intrinsic ID.
Florian Hahn6b1db822018-06-14 20:32:58 +00002392 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002393
Chris Lattnerf1447252010-03-19 21:37:09 +00002394 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002395 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002396
Chris Lattnerf1447252010-03-19 21:37:09 +00002397 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
Florian Hahn6b1db822018-06-14 20:32:58 +00002398 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2399 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002400 }
2401 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002402 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002403
Chris Lattneree820ac2010-02-23 05:51:07 +00002404 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002405 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002406
Chris Lattner135091b2010-03-28 08:48:47 +00002407 // Check that the number of operands is sane. Negative operands -> varargs.
2408 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002409 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00002410 TP.error(getOperator()->getName() + " node requires exactly " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002411 Twine(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002412 return false;
2413 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002414
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002415 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00002416 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002417 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2418 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002419 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002420 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002421
Chris Lattneree820ac2010-02-23 05:51:07 +00002422 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002423 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002424 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00002425 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002426
Chris Lattnerd44966f2010-03-27 19:15:02 +00002427 bool MadeChange = false;
2428
2429 // Apply the result types to the node, these come from the things in the
2430 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00002431 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2432 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002433 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2434 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002435
Chris Lattnerd44966f2010-03-27 19:15:02 +00002436 // If the instruction has implicit defs, we apply the first one as a result.
2437 // FIXME: This sucks, it should apply all implicit defs.
2438 if (!InstInfo.ImplicitDefs.empty()) {
2439 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002440
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002441 // FIXME: Generalize to multiple possible types and multiple possible
2442 // ImplicitDefs.
2443 MVT::SimpleValueType VT =
2444 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002445
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002446 if (VT != MVT::Other)
2447 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002448 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002449
Chris Lattnercabe0372010-03-15 06:00:16 +00002450 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2451 // be the same.
2452 if (getOperator()->getName() == "INSERT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00002453 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2454 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2455 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002456 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2457 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2458 // variadic.
2459
2460 unsigned NChild = getNumChildren();
2461 if (NChild < 3) {
2462 TP.error("REG_SEQUENCE requires at least 3 operands!");
2463 return false;
2464 }
2465
2466 if (NChild % 2 == 0) {
2467 TP.error("REG_SEQUENCE requires an odd number of operands!");
2468 return false;
2469 }
2470
2471 if (!isOperandClass(getChild(0), "RegisterClass")) {
2472 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2473 return false;
2474 }
2475
2476 for (unsigned I = 1; I < NChild; I += 2) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002477 TreePatternNode *SubIdxChild = getChild(I + 1);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002478 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2479 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002480 Twine(I + 1) + "!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00002481 return false;
2482 }
2483 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002484 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002485
Simon Tathamc74322a2019-07-04 08:43:20 +00002486 // If one or more operands with a default value appear at the end of the
2487 // formal operand list for an instruction, we allow them to be overridden
2488 // by optional operands provided in the pattern.
2489 //
2490 // But if an operand B without a default appears at any point after an
2491 // operand A with a default, then we don't allow A to be overridden,
2492 // because there would be no way to specify whether the next operand in
2493 // the pattern was intended to override A or skip it.
2494 unsigned NonOverridableOperands = Inst.getNumOperands();
2495 while (NonOverridableOperands > 0 &&
2496 CDP.operandHasDefault(Inst.getOperand(NonOverridableOperands-1)))
2497 --NonOverridableOperands;
2498
Chris Lattner8cab0212008-01-05 22:25:12 +00002499 unsigned ChildNo = 0;
2500 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2501 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002502
Simon Tathamc74322a2019-07-04 08:43:20 +00002503 // If the operand has a default value, do we use it? We must use the
2504 // default if we've run out of children of the pattern DAG to consume,
2505 // or if the operand is followed by a non-defaulted one.
2506 if (CDP.operandHasDefault(OperandNode) &&
2507 (i < NonOverridableOperands || ChildNo >= getNumChildren()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002508 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002509
Simon Tathamc74322a2019-07-04 08:43:20 +00002510 // If we have run out of child nodes and there _isn't_ a default
2511 // value we can use for the next operand, give an error.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002512 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002513 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002514 return false;
2515 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002516
Florian Hahn6b1db822018-06-14 20:32:58 +00002517 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002518 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002519
2520 // If the operand has sub-operands, they may be provided by distinct
2521 // child patterns, so attempt to match each sub-operand separately.
2522 if (OperandNode->isSubClassOf("Operand")) {
2523 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2524 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2525 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002526 // a single ComplexPattern-related Operand.
2527
2528 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002529 // Match first sub-operand against the child we already have.
2530 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2531 MadeChange |=
2532 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2533
2534 // And the remaining sub-operands against subsequent children.
2535 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2536 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002537 emitTooFewOperandsError(TP, getOperator()->getName(),
2538 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002539 return false;
2540 }
Florian Hahn6b1db822018-06-14 20:32:58 +00002541 Child = getChild(ChildNo++);
Ulrich Weigande618abd2013-03-19 19:51:09 +00002542
2543 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2544 MadeChange |=
2545 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2546 }
2547 continue;
2548 }
2549 }
2550 }
2551
2552 // If we didn't match by pieces above, attempt to match the whole
2553 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002554 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002555 }
Christopher Lamba7312392008-03-11 09:33:47 +00002556
Matt Arsenaulteb492162014-11-02 23:46:51 +00002557 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002558 emitTooManyOperandsError(TP, getOperator()->getName(),
2559 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002560 return false;
2561 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002562
Ulrich Weigande618abd2013-03-19 19:51:09 +00002563 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002564 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002565 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002566 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002567
Tim Northoverc807a172014-05-20 11:52:46 +00002568 if (getOperator()->isSubClassOf("ComplexPattern")) {
2569 bool MadeChange = false;
2570
2571 for (unsigned i = 0; i < getNumChildren(); ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002572 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Tim Northoverc807a172014-05-20 11:52:46 +00002573
2574 return MadeChange;
2575 }
2576
Chris Lattneree820ac2010-02-23 05:51:07 +00002577 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002578
Chris Lattneree820ac2010-02-23 05:51:07 +00002579 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002580 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002581 TP.error("Node transform '" + getOperator()->getName() +
2582 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002583 return false;
2584 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002585
Florian Hahn6b1db822018-06-14 20:32:58 +00002586 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002587 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002588}
2589
2590/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2591/// RHS of a commutative operation, not the on LHS.
Florian Hahn6b1db822018-06-14 20:32:58 +00002592static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2593 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
Chris Lattner8cab0212008-01-05 22:25:12 +00002594 return true;
Florian Hahn6b1db822018-06-14 20:32:58 +00002595 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002596 return true;
2597 return false;
2598}
2599
2600
2601/// canPatternMatch - If it is impossible for this pattern to match on this
2602/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002603/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002604/// that can never possibly work), and to prevent the pattern permuter from
2605/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002606bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002607 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002608 if (isLeaf()) return true;
2609
2610 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002611 if (!getChild(i)->canPatternMatch(Reason, CDP))
Chris Lattner8cab0212008-01-05 22:25:12 +00002612 return false;
2613
2614 // If this is an intrinsic, handle cases that would make it not match. For
2615 // example, if an operand is required to be an immediate.
2616 if (getOperator()->isSubClassOf("Intrinsic")) {
2617 // TODO:
2618 return true;
2619 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002620
Tim Northoverc807a172014-05-20 11:52:46 +00002621 if (getOperator()->isSubClassOf("ComplexPattern"))
2622 return true;
2623
Chris Lattner8cab0212008-01-05 22:25:12 +00002624 // If this node is a commutative operator, check that the LHS isn't an
2625 // immediate.
2626 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002627 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2628 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002629 // Scan all of the operands of the node and make sure that only the last one
2630 // is a constant node, unless the RHS also is.
2631 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002632 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002633 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002634 if (OnlyOnRHSOfCommutative(getChild(i))) {
2635 Reason="Immediate value must be on the RHS of commutative operators!";
2636 return false;
2637 }
2638 }
2639 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002640
Chris Lattner8cab0212008-01-05 22:25:12 +00002641 return true;
2642}
2643
2644//===----------------------------------------------------------------------===//
2645// TreePattern implementation
2646//
2647
David Greeneaf8ee2c2011-07-29 22:43:06 +00002648TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002649 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002650 isInputPattern(isInput), HasError(false),
2651 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002652 for (Init *I : RawPat->getValues())
2653 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002654}
2655
David Greeneaf8ee2c2011-07-29 22:43:06 +00002656TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002657 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002658 isInputPattern(isInput), HasError(false),
2659 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002660 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002661}
2662
Florian Hahn75e87c32018-05-30 21:00:18 +00002663TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
2664 CodeGenDAGPatterns &cdp)
2665 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2666 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002667 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002668}
2669
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002670void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002671 if (HasError)
2672 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002673 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002674 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2675 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002676}
2677
Chris Lattnercabe0372010-03-15 06:00:16 +00002678void TreePattern::ComputeNamedNodes() {
Florian Hahn6b1db822018-06-14 20:32:58 +00002679 for (TreePatternNodePtr &Tree : Trees)
2680 ComputeNamedNodes(Tree.get());
Chris Lattnercabe0372010-03-15 06:00:16 +00002681}
2682
Florian Hahn6b1db822018-06-14 20:32:58 +00002683void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002684 if (!N->getName().empty())
Florian Hahn6b1db822018-06-14 20:32:58 +00002685 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002686
Chris Lattnercabe0372010-03-15 06:00:16 +00002687 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002688 ComputeNamedNodes(N->getChild(i));
Chris Lattnercabe0372010-03-15 06:00:16 +00002689}
2690
Florian Hahn75e87c32018-05-30 21:00:18 +00002691TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
2692 StringRef OpName) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002693 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002694 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002695
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002696 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002697 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002698 /// (foo GPR, imm) -> (foo GPR, (imm))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002699 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
David Greenee32ebf22011-07-29 19:07:07 +00002700 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002701 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002702 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002703 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002704
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002705 // Input argument?
Florian Hahn75e87c32018-05-30 21:00:18 +00002706 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002707 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002708 if (OpName.empty())
2709 error("'node' argument requires a name to match with operand list");
2710 Args.push_back(OpName);
2711 }
2712
2713 Res->setName(OpName);
2714 return Res;
2715 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002716
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002717 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002718 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002719 if (OpName.empty())
2720 error("'?' argument requires a name to match with operand list");
Florian Hahn75e87c32018-05-30 21:00:18 +00002721 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002722 Args.push_back(OpName);
2723 Res->setName(OpName);
2724 return Res;
2725 }
2726
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002727 if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002728 if (!OpName.empty())
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002729 error("Constant int or bit argument should not have a name!");
2730 if (isa<BitInit>(TheInit))
2731 TheInit = TheInit->convertInitializerTo(IntRecTy::get());
2732 return std::make_shared<TreePatternNode>(TheInit, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002733 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002734
Sean Silvafb509ed2012-10-10 20:24:43 +00002735 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002736 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002737 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002738 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002739 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002740 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002741 }
2742
Sean Silvafb509ed2012-10-10 20:24:43 +00002743 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002744 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002745 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002746 error("Pattern has unexpected init kind!");
2747 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002748 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002749 if (!OpDef) error("Pattern has unexpected operator type!");
2750 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002751
Chris Lattner8cab0212008-01-05 22:25:12 +00002752 if (Operator->isSubClassOf("ValueType")) {
2753 // If the operator is a ValueType, then this must be "type cast" of a leaf
2754 // node.
2755 if (Dag->getNumArgs() != 1)
2756 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002757
Florian Hahn75e87c32018-05-30 21:00:18 +00002758 TreePatternNodePtr New =
2759 ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002760
Chris Lattner8cab0212008-01-05 22:25:12 +00002761 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002762 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002763 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2764 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002765
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002766 if (!OpName.empty())
2767 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002768 return New;
2769 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002770
Chris Lattner8cab0212008-01-05 22:25:12 +00002771 // Verify that this is something that makes sense for an operator.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002772 if (!Operator->isSubClassOf("PatFrags") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002773 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002774 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002775 !Operator->isSubClassOf("SDNodeXForm") &&
2776 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002777 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002778 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002779 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002780 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002781
Chris Lattner8cab0212008-01-05 22:25:12 +00002782 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002783 if (isInputPattern) {
2784 if (Operator->isSubClassOf("Instruction") ||
2785 Operator->isSubClassOf("SDNodeXForm"))
2786 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2787 } else {
2788 if (Operator->isSubClassOf("Intrinsic"))
2789 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002790
Chris Lattner2e9eae12010-03-28 06:57:56 +00002791 if (Operator->isSubClassOf("SDNode") &&
2792 Operator->getName() != "imm" &&
2793 Operator->getName() != "fpimm" &&
2794 Operator->getName() != "tglobaltlsaddr" &&
2795 Operator->getName() != "tconstpool" &&
2796 Operator->getName() != "tjumptable" &&
2797 Operator->getName() != "tframeindex" &&
2798 Operator->getName() != "texternalsym" &&
2799 Operator->getName() != "tblockaddress" &&
2800 Operator->getName() != "tglobaladdr" &&
2801 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002802 Operator->getName() != "vt" &&
2803 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002804 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2805 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002806
Florian Hahn75e87c32018-05-30 21:00:18 +00002807 std::vector<TreePatternNodePtr> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002808
2809 // Parse all the operands.
2810 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002811 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002812
Hal Finkel8b4bdfdb2018-01-03 11:35:09 +00002813 // Get the actual number of results before Operator is converted to an intrinsic
2814 // node (which is hard-coded to have either zero or one result).
2815 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2816
Fangrui Song956ee792018-03-30 22:22:31 +00002817 // If the operator is an intrinsic, then this is just syntactic sugar for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002818 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002819 // convert the intrinsic name to a number.
2820 if (Operator->isSubClassOf("Intrinsic")) {
2821 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2822 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2823
2824 // If this intrinsic returns void, it must have side-effects and thus a
2825 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002826 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002827 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Momchil Velikov52c39392019-07-17 10:53:13 +00002828 else if (Int.ModRef != CodeGenIntrinsic::NoMem || Int.hasSideEffects)
Chris Lattner8cab0212008-01-05 22:25:12 +00002829 // Has side-effects, requires chain.
2830 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002831 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002832 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002833
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002834 Children.insert(Children.begin(),
2835 std::make_shared<TreePatternNode>(IntInit::get(IID), 1));
Chris Lattner8cab0212008-01-05 22:25:12 +00002836 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002837
Tim Northoverc807a172014-05-20 11:52:46 +00002838 if (Operator->isSubClassOf("ComplexPattern")) {
2839 for (unsigned i = 0; i < Children.size(); ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002840 TreePatternNodePtr Child = Children[i];
Tim Northoverc807a172014-05-20 11:52:46 +00002841
2842 if (Child->getName().empty())
2843 error("All arguments to a ComplexPattern must be named");
2844
2845 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2846 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2847 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2848 auto OperandId = std::make_pair(Operator, i);
2849 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2850 if (PrevOp != ComplexPatternOperands.end()) {
2851 if (PrevOp->getValue() != OperandId)
2852 error("All ComplexPattern operands must appear consistently: "
2853 "in the same order in just one ComplexPattern instance.");
2854 } else
2855 ComplexPatternOperands[Child->getName()] = OperandId;
2856 }
2857 }
2858
Florian Hahn6b1db822018-06-14 20:32:58 +00002859 TreePatternNodePtr Result =
Craig Topper26fc06352018-07-15 06:52:49 +00002860 std::make_shared<TreePatternNode>(Operator, std::move(Children),
2861 NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002862 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002863
Matthias Braun7cf3b112016-12-05 06:00:41 +00002864 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002865 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002866 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002867 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002868 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002869}
2870
Chris Lattnera787c9e2010-03-28 08:38:32 +00002871/// SimplifyTree - See if we can simplify this tree to eliminate something that
2872/// will never match in favor of something obvious that will. This is here
2873/// strictly as a convenience to target authors because it allows them to write
2874/// more type generic things and have useless type casts fold away.
2875///
2876/// This returns true if any change is made.
Florian Hahn75e87c32018-05-30 21:00:18 +00002877static bool SimplifyTree(TreePatternNodePtr &N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002878 if (N->isLeaf())
2879 return false;
2880
2881 // If we have a bitconvert with a resolved type and if the source and
2882 // destination types are the same, then the bitconvert is useless, remove it.
2883 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002884 N->getExtType(0).isValueTypeByHwMode(false) &&
Florian Hahn6b1db822018-06-14 20:32:58 +00002885 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002886 N->getName().empty()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002887 N = N->getChildShared(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002888 SimplifyTree(N);
2889 return true;
2890 }
2891
2892 // Walk all children.
2893 bool MadeChange = false;
2894 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002895 TreePatternNodePtr Child = N->getChildShared(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002896 MadeChange |= SimplifyTree(Child);
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002897 N->setChild(i, std::move(Child));
Chris Lattnera787c9e2010-03-28 08:38:32 +00002898 }
2899 return MadeChange;
2900}
2901
2902
2903
Chris Lattner8cab0212008-01-05 22:25:12 +00002904/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002905/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002906/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002907bool TreePattern::
2908InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2909 if (NamedNodes.empty())
2910 ComputeNamedNodes();
2911
Chris Lattner8cab0212008-01-05 22:25:12 +00002912 bool MadeChange = true;
2913 while (MadeChange) {
2914 MadeChange = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002915 for (TreePatternNodePtr &Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002916 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2917 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002918 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002919
2920 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002921 for (auto &Entry : NamedNodes) {
2922 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002923
Chris Lattnercabe0372010-03-15 06:00:16 +00002924 // If we have input named node types, propagate their types to the named
2925 // values here.
2926 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002927 if (!InNamedTypes->count(Entry.getKey())) {
2928 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002929 "' in output pattern but not input pattern");
2930 return true;
2931 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002932
2933 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002934 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002935
2936 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002937 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002938 // If this node is a register class, and it is the root of the pattern
2939 // then we're mapping something onto an input register. We allow
2940 // changing the type of the input register in this case. This allows
2941 // us to match things like:
2942 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Florian Hahn75e87c32018-05-30 21:00:18 +00002943 if (Node == Trees[0].get() && Node->isLeaf()) {
Craig Topper306cb122015-11-22 20:46:24 +00002944 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002945 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2946 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002947 continue;
2948 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002949
Craig Topper306cb122015-11-22 20:46:24 +00002950 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002951 InNodes[0]->getNumTypes() == 1 &&
2952 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002953 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2954 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002955 }
2956 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002957
Chris Lattnercabe0372010-03-15 06:00:16 +00002958 // If there are multiple nodes with the same name, they must all have the
2959 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002960 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002961 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002962 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002963 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002964 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002965
Chris Lattnerf1447252010-03-19 21:37:09 +00002966 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2967 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002968 }
2969 }
2970 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002971 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002972
Chris Lattner8cab0212008-01-05 22:25:12 +00002973 bool HasUnresolvedTypes = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002974 for (const TreePatternNodePtr &Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002975 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002976 return !HasUnresolvedTypes;
2977}
2978
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002979void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002980 OS << getRecord()->getName();
2981 if (!Args.empty()) {
2982 OS << "(" << Args[0];
2983 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2984 OS << ", " << Args[i];
2985 OS << ")";
2986 }
2987 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002988
Chris Lattner8cab0212008-01-05 22:25:12 +00002989 if (Trees.size() > 1)
2990 OS << "[\n";
Florian Hahn75e87c32018-05-30 21:00:18 +00002991 for (const TreePatternNodePtr &Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002992 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002993 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002994 OS << "\n";
2995 }
2996
2997 if (Trees.size() > 1)
2998 OS << "]\n";
2999}
3000
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00003001void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00003002
3003//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00003004// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00003005//
3006
Daniel Sanders7e523672017-11-11 03:23:44 +00003007CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
3008 PatternRewriterFn PatternRewriter)
3009 : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
3010 PatternRewriter(PatternRewriter) {
Chris Lattner77d369c2010-12-13 00:23:57 +00003011
Justin Bogner92a8c612016-07-15 16:31:37 +00003012 Intrinsics = CodeGenIntrinsicTable(Records, false);
3013 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00003014 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00003015 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00003016 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00003017 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003018 ParseDefaultOperands();
3019 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00003020 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00003021 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003022
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003023 // Break patterns with parameterized types into a series of patterns,
3024 // where each one has a fixed type and is predicated on the conditions
3025 // of the associated HW mode.
3026 ExpandHwModeBasedTypes();
3027
Chris Lattner8cab0212008-01-05 22:25:12 +00003028 // Generate variants. For example, commutative patterns can match
3029 // multiple ways. Add them to PatternsToMatch as well.
3030 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003031
3032 // Infer instruction flags. For example, we can detect loads,
3033 // stores, and side effects in many cases by examining an
3034 // instruction's pattern.
3035 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003036
3037 // Verify that instruction flags match the patterns.
3038 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00003039}
3040
Daniel Sanders9e0ae7b2017-10-13 19:00:01 +00003041Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00003042 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00003043 if (!N || !N->isSubClassOf("SDNode"))
3044 PrintFatalError("Error getting SDNode '" + Name + "'!");
3045
Chris Lattner8cab0212008-01-05 22:25:12 +00003046 return N;
3047}
3048
3049// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003050void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003051 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003052 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3053
Chris Lattner8cab0212008-01-05 22:25:12 +00003054 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003055 Record *R = Nodes.back();
3056 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00003057 Nodes.pop_back();
3058 }
3059
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003060 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00003061 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
3062 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
3063 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
3064}
3065
3066/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
3067/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003068void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003069 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
3070 while (!Xforms.empty()) {
3071 Record *XFormNode = Xforms.back();
3072 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00003073 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00003074 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00003075
3076 Xforms.pop_back();
3077 }
3078}
3079
Chris Lattnerab3242f2008-01-06 01:10:31 +00003080void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003081 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
3082 while (!AMs.empty()) {
3083 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
3084 AMs.pop_back();
3085 }
3086}
3087
3088
3089/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3090/// file, building up the PatternFragments map. After we've collected them all,
3091/// inline fragments together as necessary, so that there are no references left
3092/// inside a pattern fragment to a pattern fragment.
3093///
Hal Finkel2756dc12014-02-28 00:26:56 +00003094void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003095 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrags");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003096
Chris Lattnere7170df2008-01-05 22:43:57 +00003097 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00003098 for (Record *Frag : Fragments) {
3099 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00003100 continue;
3101
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003102 ListInit *LI = Frag->getValueAsListInit("Fragments");
Hal Finkel2756dc12014-02-28 00:26:56 +00003103 TreePattern *P =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003104 (PatternFragments[Frag] = std::make_unique<TreePattern>(
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003105 Frag, LI, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00003106 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003107
Chris Lattnere7170df2008-01-05 22:43:57 +00003108 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00003109 std::vector<std::string> &Args = P->getArgList();
Zachary Turner249dc142017-09-20 18:01:40 +00003110 // Copy the args so we can take StringRefs to them.
3111 auto ArgsCopy = Args;
3112 SmallDenseSet<StringRef, 4> OperandsSet;
3113 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003114
Chris Lattnere7170df2008-01-05 22:43:57 +00003115 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00003116 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003117
Chris Lattner8cab0212008-01-05 22:25:12 +00003118 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00003119 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00003120 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00003121 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003122 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00003123 if (!OpsOp ||
3124 (OpsOp->getDef()->getName() != "ops" &&
3125 OpsOp->getDef()->getName() != "outs" &&
3126 OpsOp->getDef()->getName() != "ins"))
3127 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003128
3129 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00003130 Args.clear();
3131 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003132 if (!isa<DefInit>(OpsList->getArg(j)) ||
3133 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00003134 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00003135 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00003136 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00003137 StringRef ArgNameStr = OpsList->getArgNameStr(j);
3138 if (!OperandsSet.count(ArgNameStr))
3139 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00003140 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00003141 OperandsSet.erase(ArgNameStr);
3142 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003143 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003144
Chris Lattnere7170df2008-01-05 22:43:57 +00003145 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003146 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00003147 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003148
Chris Lattner8cab0212008-01-05 22:25:12 +00003149 // If there is a node transformation corresponding to this, keep track of
3150 // it.
Craig Topper306cb122015-11-22 20:46:24 +00003151 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00003152 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003153 for (auto T : P->getTrees())
3154 T->setTransformFn(Transform);
Chris Lattner8cab0212008-01-05 22:25:12 +00003155 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003156
Chris Lattner8cab0212008-01-05 22:25:12 +00003157 // Now that we've parsed all of the tree fragments, do a closure on them so
3158 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00003159 for (Record *Frag : Fragments) {
3160 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00003161 continue;
3162
Craig Topper306cb122015-11-22 20:46:24 +00003163 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00003164 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003165
Chris Lattner8cab0212008-01-05 22:25:12 +00003166 // Infer as many types as possible. Don't worry about it if we don't infer
Ulrich Weigand22b1af82018-07-13 16:42:15 +00003167 // all of them, some may depend on the inputs of the pattern. Also, don't
3168 // validate type sets; validation may cause spurious failures e.g. if a
3169 // fragment needs floating-point types but the current target does not have
3170 // any (this is only an error if that fragment is ever used!).
3171 {
3172 TypeInfer::SuppressValidation SV(ThePat.getInfer());
3173 ThePat.InferAllTypes();
3174 ThePat.resetError();
3175 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003176
Chris Lattner8cab0212008-01-05 22:25:12 +00003177 // If debugging, print out the pattern fragment result.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003178 LLVM_DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003179 }
3180}
3181
Chris Lattnerab3242f2008-01-06 01:10:31 +00003182void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00003183 std::vector<Record*> DefaultOps;
3184 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00003185
3186 // Find some SDNode.
3187 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00003188 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003189
Tom Stellardb7246a72012-09-06 14:15:52 +00003190 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3191 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003192
Tom Stellardb7246a72012-09-06 14:15:52 +00003193 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3194 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00003195 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00003196 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3197 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3198 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00003199 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003200
Tom Stellardb7246a72012-09-06 14:15:52 +00003201 // Create a TreePattern to parse this.
3202 TreePattern P(DefaultOps[i], DI, false, *this);
3203 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003204
Tom Stellardb7246a72012-09-06 14:15:52 +00003205 // Copy the operands over into a DAGDefaultOperand.
3206 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003207
Florian Hahn75e87c32018-05-30 21:00:18 +00003208 const TreePatternNodePtr &T = P.getTree(0);
Tom Stellardb7246a72012-09-06 14:15:52 +00003209 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
Florian Hahn75e87c32018-05-30 21:00:18 +00003210 TreePatternNodePtr TPN = T->getChildShared(op);
Tom Stellardb7246a72012-09-06 14:15:52 +00003211 while (TPN->ApplyTypeConstraints(P, false))
3212 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003213
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003214 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00003215 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3216 DefaultOps[i]->getName() +
3217 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003218 }
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003219 DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
Chris Lattner8cab0212008-01-05 22:25:12 +00003220 }
Tom Stellardb7246a72012-09-06 14:15:52 +00003221
3222 // Insert it into the DefaultOperands map so we can find it later.
3223 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00003224 }
3225}
3226
3227/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3228/// instruction input. Return true if this is a real use.
David Blaikie19b22d42018-06-11 22:14:43 +00003229static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003230 std::map<std::string, TreePatternNodePtr> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003231 // No name -> not interesting.
3232 if (Pat->getName().empty()) {
3233 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003234 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00003235 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3236 DI->getDef()->isSubClassOf("RegisterOperand")))
David Blaikie19b22d42018-06-11 22:14:43 +00003237 I.error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003238 }
3239 return false;
3240 }
3241
3242 Record *Rec;
3243 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003244 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
David Blaikie19b22d42018-06-11 22:14:43 +00003245 if (!DI)
3246 I.error("Input $" + Pat->getName() + " must be an identifier!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003247 Rec = DI->getDef();
3248 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00003249 Rec = Pat->getOperator();
3250 }
3251
3252 // SRCVALUE nodes are ignored.
3253 if (Rec->getName() == "srcvalue")
3254 return false;
3255
Florian Hahn75e87c32018-05-30 21:00:18 +00003256 TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
Chris Lattner8cab0212008-01-05 22:25:12 +00003257 if (!Slot) {
3258 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003259 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00003260 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003261 Record *SlotRec;
3262 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003263 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003264 } else {
3265 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3266 SlotRec = Slot->getOperator();
3267 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003268
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003269 // Ensure that the inputs agree if we've already seen this input.
3270 if (Rec != SlotRec)
David Blaikie19b22d42018-06-11 22:14:43 +00003271 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003272 // Ensure that the types can agree as well.
3273 Slot->UpdateNodeType(0, Pat->getExtType(0), I);
3274 Pat->UpdateNodeType(0, Slot->getExtType(0), I);
Chris Lattnerf1447252010-03-19 21:37:09 +00003275 if (Slot->getExtTypes() != Pat->getExtTypes())
David Blaikie19b22d42018-06-11 22:14:43 +00003276 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00003277 return true;
3278}
3279
3280/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3281/// part of "I", the instruction), computing the set of inputs and outputs of
3282/// the pattern. Report errors if we see anything naughty.
Florian Hahn75e87c32018-05-30 21:00:18 +00003283void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
Florian Hahn6b1db822018-06-14 20:32:58 +00003284 TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003285 std::map<std::string, TreePatternNodePtr> &InstInputs,
Craig Topperbd199f82018-12-05 00:47:59 +00003286 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3287 &InstResults,
Florian Hahn75e87c32018-05-30 21:00:18 +00003288 std::vector<Record *> &InstImpResults) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003289
3290 // The instruction pattern still has unresolved fragments. For *named*
3291 // nodes we must resolve those here. This may not result in multiple
3292 // alternatives.
3293 if (!Pat->getName().empty()) {
3294 TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3295 SrcPattern.InlinePatternFragments();
3296 SrcPattern.InferAllTypes();
3297 Pat = SrcPattern.getOnlyTree();
3298 }
3299
Chris Lattner8cab0212008-01-05 22:25:12 +00003300 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00003301 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00003302 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003303 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003304 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003305 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003306
Chris Lattnerf2d70992010-02-17 06:53:36 +00003307 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003308 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003309 TreePatternNode *Dest = Pat->getChild(i);
3310 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003311 I.error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003312
Florian Hahn6b1db822018-06-14 20:32:58 +00003313 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00003314 if (!Val || !Val->getDef()->isSubClassOf("Register"))
David Blaikie19b22d42018-06-11 22:14:43 +00003315 I.error("implicitly defined value should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003316 InstImpResults.push_back(Val->getDef());
3317 }
3318 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003319 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003320
Chris Lattnerf2d70992010-02-17 06:53:36 +00003321 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003322 // If this is not a set, verify that the children nodes are not void typed,
3323 // and recurse.
3324 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003325 if (Pat->getChild(i)->getNumTypes() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003326 I.error("Cannot have void nodes inside of patterns!");
Florian Hahn75e87c32018-05-30 21:00:18 +00003327 FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3328 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003329 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003330
Chris Lattner8cab0212008-01-05 22:25:12 +00003331 // If this is a non-leaf node with no children, treat it basically as if
3332 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00003333 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003334
Chris Lattner8cab0212008-01-05 22:25:12 +00003335 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003336 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003337 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003338 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003339
Chris Lattner8cab0212008-01-05 22:25:12 +00003340 // Otherwise, this is a set, validate and collect instruction results.
3341 if (Pat->getNumChildren() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003342 I.error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003343
Chris Lattner8cab0212008-01-05 22:25:12 +00003344 if (Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003345 I.error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003346
Chris Lattner8cab0212008-01-05 22:25:12 +00003347 // Check the set destinations.
3348 unsigned NumDests = Pat->getNumChildren()-1;
3349 for (unsigned i = 0; i != NumDests; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003350 TreePatternNodePtr Dest = Pat->getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003351 // For set destinations we also must resolve fragments here.
3352 TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3353 DestPattern.InlinePatternFragments();
3354 DestPattern.InferAllTypes();
3355 Dest = DestPattern.getOnlyTree();
3356
Chris Lattner8cab0212008-01-05 22:25:12 +00003357 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003358 I.error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003359
Sean Silvafb509ed2012-10-10 20:24:43 +00003360 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00003361 if (!Val) {
David Blaikie19b22d42018-06-11 22:14:43 +00003362 I.error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00003363 continue;
3364 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003365
3366 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003367 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00003368 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00003369 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003370 if (Dest->getName().empty())
David Blaikie19b22d42018-06-11 22:14:43 +00003371 I.error("set destination must have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003372 if (InstResults.count(Dest->getName()))
David Blaikie19b22d42018-06-11 22:14:43 +00003373 I.error("cannot set '" + Dest->getName() + "' multiple times");
Chris Lattner8cab0212008-01-05 22:25:12 +00003374 InstResults[Dest->getName()] = Dest;
3375 } else if (Val->getDef()->isSubClassOf("Register")) {
3376 InstImpResults.push_back(Val->getDef());
3377 } else {
David Blaikie19b22d42018-06-11 22:14:43 +00003378 I.error("set destination should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003379 }
3380 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003381
Chris Lattner8cab0212008-01-05 22:25:12 +00003382 // Verify and collect info from the computation.
Florian Hahn75e87c32018-05-30 21:00:18 +00003383 FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3384 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003385}
3386
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003387//===----------------------------------------------------------------------===//
3388// Instruction Analysis
3389//===----------------------------------------------------------------------===//
3390
3391class InstAnalyzer {
3392 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003393public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003394 bool hasSideEffects;
3395 bool mayStore;
3396 bool mayLoad;
3397 bool isBitcast;
3398 bool isVariadic;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003399 bool hasChain;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003400
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003401 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3402 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003403 isBitcast(false), isVariadic(false), hasChain(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003404
Craig Topper2a053a92017-06-20 16:34:37 +00003405 void Analyze(const PatternToMatch &Pat) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003406 const TreePatternNode *N = Pat.getSrcPattern();
3407 AnalyzeNode(N);
3408 // These properties are detected only on the root node.
3409 isBitcast = IsNodeBitcast(N);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003410 }
3411
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003412private:
Florian Hahn6b1db822018-06-14 20:32:58 +00003413 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003414 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00003415 return false;
3416
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003417 if (N->isLeaf())
3418 return false;
3419 if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
Evan Cheng880e299d2011-03-15 05:09:26 +00003420 return false;
3421
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003422 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
Evan Cheng880e299d2011-03-15 05:09:26 +00003423 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3424 return false;
3425 return OpInfo.getEnumName() == "ISD::BITCAST";
3426 }
3427
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003428public:
Florian Hahn6b1db822018-06-14 20:32:58 +00003429 void AnalyzeNode(const TreePatternNode *N) {
3430 if (N->isLeaf()) {
3431 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003432 Record *LeafRec = DI->getDef();
3433 // Handle ComplexPattern leaves.
3434 if (LeafRec->isSubClassOf("ComplexPattern")) {
3435 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3436 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3437 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003438 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003439 }
3440 }
3441 return;
3442 }
3443
3444 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00003445 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3446 AnalyzeNode(N->getChild(i));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003447
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003448 // Notice properties of the node.
Florian Hahn6b1db822018-06-14 20:32:58 +00003449 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3450 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3451 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3452 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003453 if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003454
Florian Hahn6b1db822018-06-14 20:32:58 +00003455 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003456 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003457 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003458 mayLoad = true;// These may load memory.
3459
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003460 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003461 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3462
Matt Arsenault868af922017-04-28 21:01:46 +00003463 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3464 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003465 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003466 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003467 }
3468 }
3469
3470};
3471
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003472static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003473 const InstAnalyzer &PatInfo,
3474 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003475 bool Error = false;
3476
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003477 // Remember where InstInfo got its flags.
3478 if (InstInfo.hasUndefFlags())
3479 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003480
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003481 // Check explicitly set flags for consistency.
3482 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3483 !InstInfo.hasSideEffects_Unset) {
3484 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3485 // the pattern has no side effects. That could be useful for div/rem
3486 // instructions that may trap.
3487 if (!InstInfo.hasSideEffects) {
3488 Error = true;
3489 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3490 Twine(InstInfo.hasSideEffects));
3491 }
3492 }
3493
3494 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3495 Error = true;
3496 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3497 Twine(InstInfo.mayStore));
3498 }
3499
3500 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3501 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003502 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003503 if (!InstInfo.mayLoad) {
3504 Error = true;
3505 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3506 Twine(InstInfo.mayLoad));
3507 }
3508 }
3509
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003510 // Transfer inferred flags.
3511 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3512 InstInfo.mayStore |= PatInfo.mayStore;
3513 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003514
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003515 // These flags are silently added without any verification.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003516 // FIXME: To match historical behavior of TableGen, for now add those flags
3517 // only when we're inferring from the primary instruction pattern.
3518 if (PatDef->isSubClassOf("Instruction")) {
3519 InstInfo.isBitcast |= PatInfo.isBitcast;
3520 InstInfo.hasChain |= PatInfo.hasChain;
3521 InstInfo.hasChain_Inferred = true;
3522 }
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003523
3524 // Don't infer isVariadic. This flag means something different on SDNodes and
3525 // instructions. For example, a CALL SDNode is variadic because it has the
3526 // call arguments as operands, but a CALL instruction is not variadic - it
3527 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003528
3529 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003530}
3531
Jim Grosbach514410b2012-07-17 00:47:06 +00003532/// hasNullFragReference - Return true if the DAG has any reference to the
3533/// null_frag operator.
3534static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003535 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003536 if (!OpDef) return false;
3537 Record *Operator = OpDef->getDef();
3538
3539 // If this is the null fragment, return true.
3540 if (Operator->getName() == "null_frag") return true;
3541 // If any of the arguments reference the null fragment, return true.
3542 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003543 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003544 if (Arg && hasNullFragReference(Arg))
3545 return true;
3546 }
3547
3548 return false;
3549}
3550
3551/// hasNullFragReference - Return true if any DAG in the list references
3552/// the null_frag operator.
3553static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003554 for (Init *I : LI->getValues()) {
3555 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003556 assert(DI && "non-dag in an instruction Pattern list?!");
3557 if (hasNullFragReference(DI))
3558 return true;
3559 }
3560 return false;
3561}
3562
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003563/// Get all the instructions in a tree.
3564static void
Florian Hahn6b1db822018-06-14 20:32:58 +00003565getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3566 if (Tree->isLeaf())
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003567 return;
Florian Hahn6b1db822018-06-14 20:32:58 +00003568 if (Tree->getOperator()->isSubClassOf("Instruction"))
3569 Instrs.push_back(Tree->getOperator());
3570 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3571 getInstructionsInTree(Tree->getChild(i), Instrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003572}
3573
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003574/// Check the class of a pattern leaf node against the instruction operand it
3575/// represents.
3576static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3577 Record *Leaf) {
3578 if (OI.Rec == Leaf)
3579 return true;
3580
3581 // Allow direct value types to be used in instruction set patterns.
3582 // The type will be checked later.
3583 if (Leaf->isSubClassOf("ValueType"))
3584 return true;
3585
3586 // Patterns can also be ComplexPattern instances.
3587 if (Leaf->isSubClassOf("ComplexPattern"))
3588 return true;
3589
3590 return false;
3591}
3592
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003593void CodeGenDAGPatterns::parseInstructionPattern(
Ahmed Bougacha14107512013-10-28 18:07:21 +00003594 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003595
Craig Topper0d1fb902015-03-10 03:25:04 +00003596 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003597
Craig Topper0d1fb902015-03-10 03:25:04 +00003598 // Parse the instruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003599 TreePattern I(CGI.TheDef, Pat, true, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003600
Craig Topper0d1fb902015-03-10 03:25:04 +00003601 // InstInputs - Keep track of all of the inputs of the instruction, along
3602 // with the record they are declared as.
Florian Hahn75e87c32018-05-30 21:00:18 +00003603 std::map<std::string, TreePatternNodePtr> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003604
Craig Topper0d1fb902015-03-10 03:25:04 +00003605 // InstResults - Keep track of all the virtual registers that are 'set'
3606 // in the instruction, including what reg class they are.
Craig Topperbd199f82018-12-05 00:47:59 +00003607 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3608 InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003609
Craig Topper0d1fb902015-03-10 03:25:04 +00003610 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003611
Craig Topper0d1fb902015-03-10 03:25:04 +00003612 // Verify that the top-level forms in the instruction are of void type, and
3613 // fill in the InstResults map.
Zachary Turner249dc142017-09-20 18:01:40 +00003614 SmallString<32> TypesString;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003615 for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
Zachary Turner249dc142017-09-20 18:01:40 +00003616 TypesString.clear();
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003617 TreePatternNodePtr Pat = I.getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003618 if (Pat->getNumTypes() != 0) {
Zachary Turner249dc142017-09-20 18:01:40 +00003619 raw_svector_ostream OS(TypesString);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003620 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3621 if (k > 0)
Zachary Turner249dc142017-09-20 18:01:40 +00003622 OS << ", ";
3623 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003624 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003625 I.error("Top-level forms in instruction pattern should have"
Zachary Turner249dc142017-09-20 18:01:40 +00003626 " void types, has types " +
3627 OS.str());
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003628 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003629
Craig Topper0d1fb902015-03-10 03:25:04 +00003630 // Find inputs and outputs, and verify the structure of the uses/defs.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003631 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Craig Topper0d1fb902015-03-10 03:25:04 +00003632 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003633 }
3634
Craig Topper0d1fb902015-03-10 03:25:04 +00003635 // Now that we have inputs and outputs of the pattern, inspect the operands
3636 // list for the instruction. This determines the order that operands are
3637 // added to the machine instruction the node corresponds to.
3638 unsigned NumResults = InstResults.size();
3639
3640 // Parse the operands list from the (ops) list, validating it.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003641 assert(I.getArgList().empty() && "Args list should still be empty here!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003642
3643 // Check that all of the results occur first in the list.
3644 std::vector<Record*> Results;
Craig Topperbd199f82018-12-05 00:47:59 +00003645 std::vector<unsigned> ResultIndices;
Florian Hahn75e87c32018-05-30 21:00:18 +00003646 SmallVector<TreePatternNodePtr, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003647 for (unsigned i = 0; i != NumResults; ++i) {
Craig Topperbd199f82018-12-05 00:47:59 +00003648 if (i == CGI.Operands.size()) {
3649 const std::string &OpName =
3650 std::find_if(InstResults.begin(), InstResults.end(),
3651 [](const std::pair<std::string, TreePatternNodePtr> &P) {
3652 return P.second;
3653 })
3654 ->first;
3655
3656 I.error("'" + OpName + "' set but does not appear in operand list!");
3657 }
3658
Craig Topper0d1fb902015-03-10 03:25:04 +00003659 const std::string &OpName = CGI.Operands[i].Name;
3660
3661 // Check that it exists in InstResults.
Craig Topperbd199f82018-12-05 00:47:59 +00003662 auto InstResultIter = InstResults.find(OpName);
3663 if (InstResultIter == InstResults.end() || !InstResultIter->second)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003664 I.error("Operand $" + OpName + " does not exist in operand list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003665
Craig Topperbd199f82018-12-05 00:47:59 +00003666 TreePatternNodePtr RNode = InstResultIter->second;
Craig Topper0d1fb902015-03-10 03:25:04 +00003667 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003668 ResNodes.push_back(std::move(RNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003669 if (!R)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003670 I.error("Operand $" + OpName + " should be a set destination: all "
Craig Topper0d1fb902015-03-10 03:25:04 +00003671 "outputs must occur before inputs in operand list!");
3672
3673 if (!checkOperandClass(CGI.Operands[i], R))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003674 I.error("Operand $" + OpName + " class mismatch!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003675
3676 // Remember the return type.
3677 Results.push_back(CGI.Operands[i].Rec);
3678
Craig Topperbd199f82018-12-05 00:47:59 +00003679 // Remember the result index.
3680 ResultIndices.push_back(std::distance(InstResults.begin(), InstResultIter));
3681
Craig Topper0d1fb902015-03-10 03:25:04 +00003682 // Okay, this one checks out.
Craig Topperbd199f82018-12-05 00:47:59 +00003683 InstResultIter->second = nullptr;
Craig Topper0d1fb902015-03-10 03:25:04 +00003684 }
3685
Craig Topper765b9202018-07-15 06:52:48 +00003686 // Loop over the inputs next.
Florian Hahn75e87c32018-05-30 21:00:18 +00003687 std::vector<TreePatternNodePtr> ResultNodeOperands;
Craig Topper0d1fb902015-03-10 03:25:04 +00003688 std::vector<Record*> Operands;
3689 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3690 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3691 const std::string &OpName = Op.Name;
3692 if (OpName.empty())
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003693 I.error("Operand #" + Twine(i) + " in operands list has no name!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003694
Craig Topper765b9202018-07-15 06:52:48 +00003695 if (!InstInputs.count(OpName)) {
Craig Topper0d1fb902015-03-10 03:25:04 +00003696 // If this is an operand with a DefaultOps set filled in, we can ignore
3697 // this. When we codegen it, we will do so as always executed.
3698 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3699 // Does it have a non-empty DefaultOps field? If so, ignore this
3700 // operand.
3701 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3702 continue;
3703 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003704 I.error("Operand $" + OpName +
Craig Topper0d1fb902015-03-10 03:25:04 +00003705 " does not appear in the instruction pattern");
3706 }
Craig Topper765b9202018-07-15 06:52:48 +00003707 TreePatternNodePtr InVal = InstInputs[OpName];
3708 InstInputs.erase(OpName); // It occurred, remove from map.
Craig Topper0d1fb902015-03-10 03:25:04 +00003709
3710 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3711 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3712 if (!checkOperandClass(Op, InRec))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003713 I.error("Operand $" + OpName + "'s register class disagrees"
Craig Topper0d1fb902015-03-10 03:25:04 +00003714 " between the operand and pattern");
3715 }
3716 Operands.push_back(Op.Rec);
3717
3718 // Construct the result for the dest-pattern operand list.
Florian Hahn75e87c32018-05-30 21:00:18 +00003719 TreePatternNodePtr OpNode = InVal->clone();
Craig Topper0d1fb902015-03-10 03:25:04 +00003720
3721 // No predicate is useful on the result.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003722 OpNode->clearPredicateCalls();
Craig Topper0d1fb902015-03-10 03:25:04 +00003723
3724 // Promote the xform function to be an explicit node if set.
3725 if (Record *Xform = OpNode->getTransformFn()) {
3726 OpNode->setTransformFn(nullptr);
Florian Hahn75e87c32018-05-30 21:00:18 +00003727 std::vector<TreePatternNodePtr> Children;
Craig Topper0d1fb902015-03-10 03:25:04 +00003728 Children.push_back(OpNode);
Craig Topper26fc06352018-07-15 06:52:49 +00003729 OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
Florian Hahn6b1db822018-06-14 20:32:58 +00003730 OpNode->getNumTypes());
Craig Topper0d1fb902015-03-10 03:25:04 +00003731 }
3732
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003733 ResultNodeOperands.push_back(std::move(OpNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003734 }
3735
Craig Topper765b9202018-07-15 06:52:48 +00003736 if (!InstInputs.empty())
3737 I.error("Input operand $" + InstInputs.begin()->first +
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003738 " occurs in pattern but not in operands list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003739
Florian Hahn6b1db822018-06-14 20:32:58 +00003740 TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00003741 I.getRecord(), std::move(ResultNodeOperands),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003742 GetNumNodeResults(I.getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003743 // Copy fully inferred output node types to instruction result pattern.
3744 for (unsigned i = 0; i != NumResults; ++i) {
3745 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3746 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
Craig Topperbd199f82018-12-05 00:47:59 +00003747 ResultPattern->setResultIndex(i, ResultIndices[i]);
Craig Topper3a8eb892015-03-20 05:09:06 +00003748 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003749
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003750 // FIXME: Assume only the first tree is the pattern. The others are clobber
3751 // nodes.
3752 TreePatternNodePtr Pattern = I.getTree(0);
3753 TreePatternNodePtr SrcPattern;
3754 if (Pattern->getOperator()->getName() == "set") {
3755 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3756 } else{
3757 // Not a set (store or something?)
3758 SrcPattern = Pattern;
3759 }
3760
Craig Topper0d1fb902015-03-10 03:25:04 +00003761 // Create and insert the instruction.
3762 // FIXME: InstImpResults should not be part of DAGInstruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003763 Record *R = I.getRecord();
3764 DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
3765 std::forward_as_tuple(Results, Operands, InstImpResults,
3766 SrcPattern, ResultPattern));
Craig Topper0d1fb902015-03-10 03:25:04 +00003767
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003768 LLVM_DEBUG(I.dump());
Craig Topper0d1fb902015-03-10 03:25:04 +00003769}
3770
Ahmed Bougacha14107512013-10-28 18:07:21 +00003771/// ParseInstructions - Parse all of the instructions, inlining and resolving
3772/// any fragments involved. This populates the Instructions list with fully
3773/// resolved instructions.
3774void CodeGenDAGPatterns::ParseInstructions() {
3775 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3776
Craig Topper306cb122015-11-22 20:46:24 +00003777 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003778 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003779
Craig Topper306cb122015-11-22 20:46:24 +00003780 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3781 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003782
3783 // If there is no pattern, only collect minimal information about the
3784 // instruction for its operand list. We have to assume that there is one
3785 // result, as we have no detailed info. A pattern which references the
3786 // null_frag operator is as-if no pattern were specified. Normally this
3787 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3788 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003789 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003790 std::vector<Record*> Results;
3791 std::vector<Record*> Operands;
3792
Craig Topper306cb122015-11-22 20:46:24 +00003793 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003794
3795 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003796 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3797 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003798
Craig Topper3a8eb892015-03-20 05:09:06 +00003799 // The rest are inputs.
3800 for (unsigned j = InstInfo.Operands.NumDefs,
3801 e = InstInfo.Operands.size(); j < e; ++j)
3802 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003803 }
3804
3805 // Create and insert the instruction.
3806 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003807 Instructions.insert(std::make_pair(Instr,
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003808 DAGInstruction(Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003809 continue; // no pattern.
3810 }
3811
Craig Topper306cb122015-11-22 20:46:24 +00003812 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003813 parseInstructionPattern(CGI, LI, Instructions);
Chris Lattner8cab0212008-01-05 22:25:12 +00003814 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003815
Chris Lattner8cab0212008-01-05 22:25:12 +00003816 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003817 for (auto &Entry : Instructions) {
Craig Topper306cb122015-11-22 20:46:24 +00003818 Record *Instr = Entry.first;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003819 DAGInstruction &TheInst = Entry.second;
3820 TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
3821 TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
3822
3823 if (SrcPattern && ResultPattern) {
3824 TreePattern Pattern(Instr, SrcPattern, true, *this);
3825 TreePattern Result(Instr, ResultPattern, false, *this);
3826 ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
3827 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003828 }
3829}
3830
Florian Hahn6b1db822018-06-14 20:32:58 +00003831typedef std::pair<TreePatternNode *, unsigned> NameRecord;
Chris Lattnera7722b62010-02-23 06:55:24 +00003832
Florian Hahn6b1db822018-06-14 20:32:58 +00003833static void FindNames(TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003834 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003835 TreePattern *PatternTop) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003836 if (!P->getName().empty()) {
3837 NameRecord &Rec = Names[P->getName()];
Chris Lattnera7722b62010-02-23 06:55:24 +00003838 // If this is the first instance of the name, remember the node.
3839 if (Rec.second++ == 0)
Florian Hahn6b1db822018-06-14 20:32:58 +00003840 Rec.first = P;
3841 else if (Rec.first->getExtTypes() != P->getExtTypes())
3842 PatternTop->error("repetition of value: $" + P->getName() +
Chris Lattner5b0e2492010-02-23 07:22:28 +00003843 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003844 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003845
Florian Hahn6b1db822018-06-14 20:32:58 +00003846 if (!P->isLeaf()) {
3847 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3848 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003849 }
3850}
3851
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003852std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3853 std::vector<Predicate> Preds;
3854 for (Init *I : L->getValues()) {
3855 if (DefInit *Pred = dyn_cast<DefInit>(I))
3856 Preds.push_back(Pred->getDef());
3857 else
3858 llvm_unreachable("Non-def on the list");
3859 }
3860
3861 // Sort so that different orders get canonicalized to the same string.
Fangrui Song0cac7262018-09-27 02:13:45 +00003862 llvm::sort(Preds);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003863 return Preds;
3864}
3865
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003866void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003867 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003868 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003869 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003870 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3871 PrintWarning(Pattern->getRecord()->getLoc(),
3872 Twine("Pattern can never match: ") + Reason);
3873 return;
3874 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003875
Chris Lattner1e634e32010-03-01 22:29:19 +00003876 // If the source pattern's root is a complex pattern, that complex pattern
3877 // must specify the nodes it can potentially match.
3878 if (const ComplexPattern *CP =
3879 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3880 if (CP->getRootNodes().empty())
3881 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3882 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003883
3884
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003885 // Find all of the named values in the input and output, ensure they have the
3886 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003887 std::map<std::string, NameRecord> SrcNames, DstNames;
Florian Hahn6b1db822018-06-14 20:32:58 +00003888 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3889 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003890
3891 // Scan all of the named values in the destination pattern, rejecting them if
3892 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003893 for (const auto &Entry : DstNames) {
3894 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003895 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003896 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003897 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003898
Chris Lattnera7722b62010-02-23 06:55:24 +00003899 // Scan all of the named values in the source pattern, rejecting them if the
3900 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003901 for (const auto &Entry : SrcNames)
3902 if (DstNames[Entry.first].first == nullptr &&
3903 SrcNames[Entry.first].second == 1)
3904 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003905
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003906 PatternsToMatch.push_back(PTM);
Chris Lattner0c0baa92010-02-23 06:16:51 +00003907}
3908
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003909void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003910 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003911 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003912
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003913 unsigned Errors = 0;
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003914
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003915 // Try to infer flags from all patterns in PatternToMatch. These include
3916 // both the primary instruction patterns (which always come first) and
3917 // patterns defined outside the instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003918 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003919 // We can only infer from single-instruction patterns, otherwise we won't
3920 // know which instruction should get the flags.
3921 SmallVector<Record*, 8> PatInstrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003922 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003923 if (PatInstrs.size() != 1)
3924 continue;
3925
3926 // Get the single instruction.
3927 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3928
3929 // Only infer properties from the first pattern. We'll verify the others.
3930 if (InstInfo.InferredFrom)
3931 continue;
3932
3933 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003934 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003935 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3936 }
3937
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003938 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003939 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003940
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003941 // If requested by the target, guess any undefined properties.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003942 if (Target.guessInstructionProperties()) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003943 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3944 CodeGenInstruction *InstInfo =
3945 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003946 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003947 continue;
3948 // The mayLoad and mayStore flags default to false.
3949 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003950 if (InstInfo->hasSideEffects_Unset)
3951 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003952 }
3953 return;
3954 }
3955
3956 // Complain about any flags that are still undefined.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003957 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3958 CodeGenInstruction *InstInfo =
3959 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003960 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003961 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003962 if (InstInfo->hasSideEffects_Unset)
3963 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003964 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003965 if (InstInfo->mayStore_Unset)
3966 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003967 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003968 if (InstInfo->mayLoad_Unset)
3969 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003970 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003971 }
3972}
3973
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003974
3975/// Verify instruction flags against pattern node properties.
3976void CodeGenDAGPatterns::VerifyInstructionFlags() {
3977 unsigned Errors = 0;
3978 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3979 const PatternToMatch &PTM = *I;
3980 SmallVector<Record*, 8> Instrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003981 getInstructionsInTree(PTM.getDstPattern(), Instrs);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003982 if (Instrs.empty())
3983 continue;
3984
3985 // Count the number of instructions with each flag set.
3986 unsigned NumSideEffects = 0;
3987 unsigned NumStores = 0;
3988 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003989 for (const Record *Instr : Instrs) {
3990 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003991 NumSideEffects += InstInfo.hasSideEffects;
3992 NumStores += InstInfo.mayStore;
3993 NumLoads += InstInfo.mayLoad;
3994 }
3995
3996 // Analyze the source pattern.
3997 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003998 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003999
4000 // Collect error messages.
4001 SmallVector<std::string, 4> Msgs;
4002
4003 // Check for missing flags in the output.
4004 // Permit extra flags for now at least.
4005 if (PatInfo.hasSideEffects && !NumSideEffects)
4006 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
4007
4008 // Don't verify store flags on instructions with side effects. At least for
4009 // intrinsics, side effects implies mayStore.
4010 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
4011 Msgs.push_back("pattern may store, but mayStore isn't set");
4012
4013 // Similarly, mayStore implies mayLoad on intrinsics.
4014 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
4015 Msgs.push_back("pattern may load, but mayLoad isn't set");
4016
4017 // Print error messages.
4018 if (Msgs.empty())
4019 continue;
4020 ++Errors;
4021
Craig Topper306cb122015-11-22 20:46:24 +00004022 for (const std::string &Msg : Msgs)
4023 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004024 (Instrs.size() == 1 ?
4025 "instruction" : "output instructions"));
4026 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00004027 for (const Record *Instr : Instrs) {
4028 if (Instr != PTM.getSrcRecord())
4029 PrintError(Instr->getLoc(), "defined here");
4030 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004031 if (InstInfo.InferredFrom &&
4032 InstInfo.InferredFrom != InstInfo.TheDef &&
4033 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004034 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004035 }
4036 }
4037 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00004038 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004039}
4040
Chris Lattnercabe0372010-03-15 06:00:16 +00004041/// Given a pattern result with an unresolved type, see if we can find one
4042/// instruction with an unresolved result type. Force this result type to an
4043/// arbitrary element if it's possible types to converge results.
Florian Hahn6b1db822018-06-14 20:32:58 +00004044static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
4045 if (N->isLeaf())
Chris Lattnercabe0372010-03-15 06:00:16 +00004046 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004047
Chris Lattnercabe0372010-03-15 06:00:16 +00004048 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00004049 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4050 if (ForceArbitraryInstResultType(N->getChild(i), TP))
Chris Lattnercabe0372010-03-15 06:00:16 +00004051 return true;
4052
Florian Hahn6b1db822018-06-14 20:32:58 +00004053 if (!N->getOperator()->isSubClassOf("Instruction"))
Chris Lattnercabe0372010-03-15 06:00:16 +00004054 return false;
4055
4056 // If this type is already concrete or completely unknown we can't do
4057 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004058 TypeInfer &TI = TP.getInfer();
Florian Hahn6b1db822018-06-14 20:32:58 +00004059 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
4060 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00004061 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004062
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004063 // Otherwise, force its type to an arbitrary choice.
Florian Hahn6b1db822018-06-14 20:32:58 +00004064 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00004065 return true;
4066 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004067
Chris Lattnerf1447252010-03-19 21:37:09 +00004068 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00004069}
4070
Ulrich Weigand58a97862018-08-01 11:57:58 +00004071// Promote xform function to be an explicit node wherever set.
4072static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
4073 if (Record *Xform = N->getTransformFn()) {
4074 N->setTransformFn(nullptr);
4075 std::vector<TreePatternNodePtr> Children;
4076 Children.push_back(PromoteXForms(N));
4077 return std::make_shared<TreePatternNode>(Xform, std::move(Children),
4078 N->getNumTypes());
4079 }
4080
4081 if (!N->isLeaf())
4082 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4083 TreePatternNodePtr Child = N->getChildShared(i);
Ulrich Weigandf989cd72018-08-01 12:07:32 +00004084 N->setChild(i, PromoteXForms(Child));
Ulrich Weigand58a97862018-08-01 11:57:58 +00004085 }
4086 return N;
4087}
4088
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004089void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
4090 TreePattern &Pattern, TreePattern &Result,
4091 const std::vector<Record *> &InstImpResults) {
4092
4093 // Inline pattern fragments and expand multiple alternatives.
4094 Pattern.InlinePatternFragments();
4095 Result.InlinePatternFragments();
4096
4097 if (Result.getNumTrees() != 1)
4098 Result.error("Cannot use multi-alternative fragments in result pattern!");
4099
4100 // Infer types.
4101 bool IterateInference;
4102 bool InferredAllPatternTypes, InferredAllResultTypes;
4103 do {
4104 // Infer as many types as possible. If we cannot infer all of them, we
4105 // can never do anything with this pattern: report it to the user.
4106 InferredAllPatternTypes =
4107 Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
4108
4109 // Infer as many types as possible. If we cannot infer all of them, we
4110 // can never do anything with this pattern: report it to the user.
4111 InferredAllResultTypes =
4112 Result.InferAllTypes(&Pattern.getNamedNodesMap());
4113
4114 IterateInference = false;
4115
4116 // Apply the type of the result to the source pattern. This helps us
4117 // resolve cases where the input type is known to be a pointer type (which
4118 // is considered resolved), but the result knows it needs to be 32- or
4119 // 64-bits. Infer the other way for good measure.
4120 for (auto T : Pattern.getTrees())
4121 for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
4122 T->getNumTypes());
4123 i != e; ++i) {
4124 IterateInference |= T->UpdateNodeType(
4125 i, Result.getOnlyTree()->getExtType(i), Result);
4126 IterateInference |= Result.getOnlyTree()->UpdateNodeType(
4127 i, T->getExtType(i), Result);
4128 }
4129
4130 // If our iteration has converged and the input pattern's types are fully
4131 // resolved but the result pattern is not fully resolved, we may have a
4132 // situation where we have two instructions in the result pattern and
4133 // the instructions require a common register class, but don't care about
4134 // what actual MVT is used. This is actually a bug in our modelling:
4135 // output patterns should have register classes, not MVTs.
4136 //
4137 // In any case, to handle this, we just go through and disambiguate some
4138 // arbitrary types to the result pattern's nodes.
4139 if (!IterateInference && InferredAllPatternTypes &&
4140 !InferredAllResultTypes)
4141 IterateInference =
4142 ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
4143 } while (IterateInference);
4144
4145 // Verify that we inferred enough types that we can do something with the
4146 // pattern and result. If these fire the user has to add type casts.
4147 if (!InferredAllPatternTypes)
4148 Pattern.error("Could not infer all types in pattern!");
4149 if (!InferredAllResultTypes) {
4150 Pattern.dump();
4151 Result.error("Could not infer all types in pattern result!");
4152 }
4153
Ulrich Weigand58a97862018-08-01 11:57:58 +00004154 // Promote xform function to be an explicit node wherever set.
4155 TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004156
4157 TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4158 Temp.InferAllTypes();
4159
4160 ListInit *Preds = TheDef->getValueAsListInit("Predicates");
4161 int Complexity = TheDef->getValueAsInt("AddedComplexity");
4162
4163 if (PatternRewriter)
4164 PatternRewriter(&Pattern);
4165
4166 // A pattern may end up with an "impossible" type, i.e. a situation
4167 // where all types have been eliminated for some node in this pattern.
4168 // This could occur for intrinsics that only make sense for a specific
4169 // value type, and use a specific register class. If, for some mode,
4170 // that register class does not accept that type, the type inference
4171 // will lead to a contradiction, which is not an error however, but
4172 // a sign that this pattern will simply never match.
4173 if (Temp.getOnlyTree()->hasPossibleType())
4174 for (auto T : Pattern.getTrees())
4175 if (T->hasPossibleType())
4176 AddPatternToMatch(&Pattern,
4177 PatternToMatch(TheDef, makePredList(Preds),
4178 T, Temp.getOnlyTree(),
4179 InstImpResults, Complexity,
4180 TheDef->getID()));
4181}
4182
Chris Lattnerab3242f2008-01-06 01:10:31 +00004183void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00004184 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
4185
Craig Topper306cb122015-11-22 20:46:24 +00004186 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00004187 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00004188
4189 // If the pattern references the null_frag, there's nothing to do.
4190 if (hasNullFragReference(Tree))
4191 continue;
4192
Florian Hahn75e87c32018-05-30 21:00:18 +00004193 TreePattern Pattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00004194
David Greeneaf8ee2c2011-07-29 22:43:06 +00004195 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00004196 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004197
Chris Lattner8cab0212008-01-05 22:25:12 +00004198 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004199 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004200
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004201 if (Result.getNumTrees() != 1)
4202 Result.error("Cannot handle instructions producing instructions "
4203 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004204
Chris Lattner8cab0212008-01-05 22:25:12 +00004205 // Validate that the input pattern is correct.
Florian Hahn75e87c32018-05-30 21:00:18 +00004206 std::map<std::string, TreePatternNodePtr> InstInputs;
Craig Topperbd199f82018-12-05 00:47:59 +00004207 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
4208 InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00004209 std::vector<Record*> InstImpResults;
Florian Hahn75e87c32018-05-30 21:00:18 +00004210 for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
David Blaikie19b22d42018-06-11 22:14:43 +00004211 FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
Florian Hahn75e87c32018-05-30 21:00:18 +00004212 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004213
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004214 ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004215 }
4216}
4217
Florian Hahn6b1db822018-06-14 20:32:58 +00004218static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004219 for (const TypeSetByHwMode &VTS : N->getExtTypes())
4220 for (const auto &I : VTS)
4221 Modes.insert(I.first);
4222
4223 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00004224 collectModes(Modes, N->getChild(i));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004225}
4226
4227void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4228 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4229 std::map<unsigned,std::vector<Predicate>> ModeChecks;
4230 std::vector<PatternToMatch> Copy = PatternsToMatch;
4231 PatternsToMatch.clear();
4232
Florian Hahn75e87c32018-05-30 21:00:18 +00004233 auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) {
4234 TreePatternNodePtr NewSrc = P.SrcPattern->clone();
4235 TreePatternNodePtr NewDst = P.DstPattern->clone();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004236 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004237 return;
4238 }
4239
4240 std::vector<Predicate> Preds = P.Predicates;
4241 const std::vector<Predicate> &MC = ModeChecks[Mode];
4242 Preds.insert(Preds.end(), MC.begin(), MC.end());
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004243 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, std::move(NewSrc),
4244 std::move(NewDst), P.getDstRegs(),
4245 P.getAddedComplexity(), Record::getNewUID(),
4246 Mode);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004247 };
4248
4249 for (PatternToMatch &P : Copy) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004250 TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
Florian Hahn6b1db822018-06-14 20:32:58 +00004251 if (P.SrcPattern->hasProperTypeByHwMode())
4252 SrcP = P.SrcPattern;
4253 if (P.DstPattern->hasProperTypeByHwMode())
4254 DstP = P.DstPattern;
4255 if (!SrcP && !DstP) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004256 PatternsToMatch.push_back(P);
4257 continue;
4258 }
4259
4260 std::set<unsigned> Modes;
Florian Hahn6b1db822018-06-14 20:32:58 +00004261 if (SrcP)
4262 collectModes(Modes, SrcP.get());
4263 if (DstP)
4264 collectModes(Modes, DstP.get());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004265
4266 // The predicate for the default mode needs to be constructed for each
4267 // pattern separately.
4268 // Since not all modes must be present in each pattern, if a mode m is
4269 // absent, then there is no point in constructing a check for m. If such
4270 // a check was created, it would be equivalent to checking the default
4271 // mode, except not all modes' predicates would be a part of the checking
4272 // code. The subsequently generated check for the default mode would then
4273 // have the exact same patterns, but a different predicate code. To avoid
4274 // duplicated patterns with different predicate checks, construct the
4275 // default check as a negation of all predicates that are actually present
4276 // in the source/destination patterns.
4277 std::vector<Predicate> DefaultPred;
4278
4279 for (unsigned M : Modes) {
4280 if (M == DefaultMode)
4281 continue;
4282 if (ModeChecks.find(M) != ModeChecks.end())
4283 continue;
4284
4285 // Fill the map entry for this mode.
4286 const HwMode &HM = CGH.getMode(M);
4287 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4288
4289 // Add negations of the HM's predicates to the default predicate.
4290 DefaultPred.emplace_back(Predicate(HM.Features, false));
4291 }
4292
4293 for (unsigned M : Modes) {
4294 if (M == DefaultMode)
4295 continue;
4296 AppendPattern(P, M);
4297 }
4298
4299 bool HasDefault = Modes.count(DefaultMode);
4300 if (HasDefault)
4301 AppendPattern(P, DefaultMode);
4302 }
4303}
4304
4305/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turner249dc142017-09-20 18:01:40 +00004306typedef StringMap<int> DepVarMap;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004307
Florian Hahn6b1db822018-06-14 20:32:58 +00004308static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4309 if (N->isLeaf()) {
4310 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
4311 DepMap[N->getName()]++;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004312 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00004313 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4314 FindDepVarsOf(N->getChild(i), DepMap);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004315 }
4316}
4317
4318/// Find dependent variables within child patterns
Florian Hahn6b1db822018-06-14 20:32:58 +00004319static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004320 DepVarMap depcounts;
4321 FindDepVarsOf(N, depcounts);
Zachary Turner249dc142017-09-20 18:01:40 +00004322 for (const auto &Pair : depcounts) {
4323 if (Pair.getValue() > 1)
4324 DepVars.insert(Pair.getKey());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004325 }
4326}
4327
4328#ifndef NDEBUG
4329/// Dump the dependent variable set:
4330static void DumpDepVars(MultipleUseVarSet &DepVars) {
4331 if (DepVars.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004332 LLVM_DEBUG(errs() << "<empty set>");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004333 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004334 LLVM_DEBUG(errs() << "[ ");
Zachary Turner249dc142017-09-20 18:01:40 +00004335 for (const auto &DepVar : DepVars) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004336 LLVM_DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004337 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004338 LLVM_DEBUG(errs() << "]");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004339 }
4340}
4341#endif
4342
4343
Chris Lattner8cab0212008-01-05 22:25:12 +00004344/// CombineChildVariants - Given a bunch of permutations of each child of the
4345/// 'operator' node, put them together in all possible ways.
Florian Hahn75e87c32018-05-30 21:00:18 +00004346static void CombineChildVariants(
Florian Hahn6b1db822018-06-14 20:32:58 +00004347 TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004348 const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4349 std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4350 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004351 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00004352 for (const auto &Variants : ChildVariants)
4353 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00004354 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004355
Chris Lattner8cab0212008-01-05 22:25:12 +00004356 // The end result is an all-pairs construction of the resultant pattern.
4357 std::vector<unsigned> Idxs;
4358 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00004359 bool NotDone;
4360 do {
4361#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004362 LLVM_DEBUG(if (!Idxs.empty()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004363 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004364 for (unsigned Idx : Idxs) {
4365 errs() << Idx << " ";
4366 }
4367 errs() << "]\n";
4368 });
Scott Michel94420742008-03-05 17:49:05 +00004369#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00004370 // Create the variant and add it to the output list.
Florian Hahn75e87c32018-05-30 21:00:18 +00004371 std::vector<TreePatternNodePtr> NewChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004372 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4373 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Florian Hahn75e87c32018-05-30 21:00:18 +00004374 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00004375 Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004376
Chris Lattner8cab0212008-01-05 22:25:12 +00004377 // Copy over properties.
Florian Hahn6b1db822018-06-14 20:32:58 +00004378 R->setName(Orig->getName());
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00004379 R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
4380 R->setPredicateCalls(Orig->getPredicateCalls());
Florian Hahn6b1db822018-06-14 20:32:58 +00004381 R->setTransformFn(Orig->getTransformFn());
4382 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4383 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00004384
Scott Michel94420742008-03-05 17:49:05 +00004385 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00004386 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00004387 // Scan to see if this pattern has already been emitted. We can get
4388 // duplication due to things like commuting:
4389 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4390 // which are the same pattern. Ignore the dups.
4391 if (R->canPatternMatch(ErrString, CDP) &&
Florian Hahn75e87c32018-05-30 21:00:18 +00004392 none_of(OutVariants, [&](TreePatternNodePtr Variant) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004393 return R->isIsomorphicTo(Variant.get(), DepVars);
David Majnemer0a16c222016-08-11 21:15:00 +00004394 }))
Florian Hahn75e87c32018-05-30 21:00:18 +00004395 OutVariants.push_back(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004396
Scott Michel94420742008-03-05 17:49:05 +00004397 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004398 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00004399 // [0, 0], [0, 1], [1, 0], [1, 1].
4400 int IdxsIdx;
4401 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4402 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4403 Idxs[IdxsIdx] = 0;
4404 else
Chris Lattner8cab0212008-01-05 22:25:12 +00004405 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00004406 }
Scott Michel94420742008-03-05 17:49:05 +00004407 NotDone = (IdxsIdx >= 0);
4408 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00004409}
4410
4411/// CombineChildVariants - A helper function for binary operators.
4412///
Florian Hahn6b1db822018-06-14 20:32:58 +00004413static void CombineChildVariants(TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004414 const std::vector<TreePatternNodePtr> &LHS,
4415 const std::vector<TreePatternNodePtr> &RHS,
4416 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004417 CodeGenDAGPatterns &CDP,
4418 const MultipleUseVarSet &DepVars) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004419 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004420 ChildVariants.push_back(LHS);
4421 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00004422 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004423}
Chris Lattner8cab0212008-01-05 22:25:12 +00004424
Florian Hahn75e87c32018-05-30 21:00:18 +00004425static void
Florian Hahn6b1db822018-06-14 20:32:58 +00004426GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004427 std::vector<TreePatternNodePtr> &Children) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004428 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4429 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00004430
Chris Lattner8cab0212008-01-05 22:25:12 +00004431 // Only permit raw nodes.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00004432 if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00004433 N->getTransformFn()) {
4434 Children.push_back(N);
4435 return;
4436 }
4437
Florian Hahn6b1db822018-06-14 20:32:58 +00004438 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004439 Children.push_back(N->getChildShared(0));
Chris Lattner8cab0212008-01-05 22:25:12 +00004440 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004441 GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004442
Florian Hahn6b1db822018-06-14 20:32:58 +00004443 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004444 Children.push_back(N->getChildShared(1));
Chris Lattner8cab0212008-01-05 22:25:12 +00004445 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004446 GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004447}
4448
4449/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4450/// the (potentially recursive) pattern by using algebraic laws.
4451///
Florian Hahn6b1db822018-06-14 20:32:58 +00004452static void GenerateVariantsOf(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004453 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004454 CodeGenDAGPatterns &CDP,
4455 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00004456 // We cannot permute leaves or ComplexPattern uses.
4457 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004458 OutVariants.push_back(N);
4459 return;
4460 }
4461
4462 // Look up interesting info about the node.
4463 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4464
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004465 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00004466 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00004467 // Re-associate by pulling together all of the linked operators
Florian Hahn75e87c32018-05-30 21:00:18 +00004468 std::vector<TreePatternNodePtr> MaximalChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004469 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4470
4471 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4472 // permutations.
4473 if (MaximalChildren.size() == 3) {
4474 // Find the variants of all of our maximal children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004475 std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00004476 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4477 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4478 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004479
Chris Lattner8cab0212008-01-05 22:25:12 +00004480 // There are only two ways we can permute the tree:
4481 // (A op B) op C and A op (B op C)
4482 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004483
Chris Lattner8cab0212008-01-05 22:25:12 +00004484 // Generate legal pair permutations of A/B/C.
Florian Hahn75e87c32018-05-30 21:00:18 +00004485 std::vector<TreePatternNodePtr> ABVariants;
4486 std::vector<TreePatternNodePtr> BAVariants;
4487 std::vector<TreePatternNodePtr> ACVariants;
4488 std::vector<TreePatternNodePtr> CAVariants;
4489 std::vector<TreePatternNodePtr> BCVariants;
4490 std::vector<TreePatternNodePtr> CBVariants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004491 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4492 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4493 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4494 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4495 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4496 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004497
4498 // Combine those into the result: (x op x) op x
Florian Hahn6b1db822018-06-14 20:32:58 +00004499 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4500 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4501 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4502 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4503 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4504 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004505
4506 // Combine those into the result: x op (x op x)
Florian Hahn6b1db822018-06-14 20:32:58 +00004507 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4508 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4509 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4510 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4511 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4512 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004513 return;
4514 }
4515 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004516
Chris Lattner8cab0212008-01-05 22:25:12 +00004517 // Compute permutations of all children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004518 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004519 ChildVariants.resize(N->getNumChildren());
4520 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn75e87c32018-05-30 21:00:18 +00004521 GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004522
4523 // Build all permutations based on how the children were formed.
Florian Hahn6b1db822018-06-14 20:32:58 +00004524 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004525
4526 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004527 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4528 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004529 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004530 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004531 // Don't count children which are actually register references.
4532 unsigned NC = 0;
4533 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004534 TreePatternNode *Child = N->getChild(i);
4535 if (Child->isLeaf())
4536 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004537 Record *RR = DI->getDef();
4538 if (RR->isSubClassOf("Register"))
4539 continue;
4540 }
4541 NC++;
4542 }
4543 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004544 if (isCommIntrinsic) {
4545 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4546 // operands are the commutative operands, and there might be more operands
4547 // after those.
4548 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004549 "Commutative intrinsic should have at least 3 children!");
Florian Hahn75e87c32018-05-30 21:00:18 +00004550 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004551 Variants.push_back(std::move(ChildVariants[0])); // Intrinsic id.
4552 Variants.push_back(std::move(ChildVariants[2]));
4553 Variants.push_back(std::move(ChildVariants[1]));
Evan Cheng49bad4c2008-06-16 20:29:38 +00004554 for (unsigned i = 3; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004555 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004556 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004557 } else if (NC == N->getNumChildren()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004558 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004559 Variants.push_back(std::move(ChildVariants[1]));
4560 Variants.push_back(std::move(ChildVariants[0]));
Craig Topper98a96282017-09-04 03:44:33 +00004561 for (unsigned i = 2; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004562 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004563 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004564 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004565 }
4566}
4567
4568
4569// GenerateVariants - Generate variants. For example, commutative patterns can
4570// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004571void CodeGenDAGPatterns::GenerateVariants() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004572 LLVM_DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004573
Chris Lattner8cab0212008-01-05 22:25:12 +00004574 // Loop over all of the patterns we've collected, checking to see if we can
4575 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004576 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004577 // the .td file having to contain tons of variants of instructions.
4578 //
4579 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4580 // intentionally do not reconsider these. Any variants of added patterns have
4581 // already been added.
4582 //
Simon Pilgrim0621f562018-09-18 11:30:30 +00004583 const unsigned NumOriginalPatterns = PatternsToMatch.size();
4584 BitVector MatchedPatterns(NumOriginalPatterns);
4585 std::vector<BitVector> MatchedPredicates(NumOriginalPatterns,
4586 BitVector(NumOriginalPatterns));
4587
4588 typedef std::pair<MultipleUseVarSet, std::vector<TreePatternNodePtr>>
4589 DepsAndVariants;
4590 std::map<unsigned, DepsAndVariants> PatternsWithVariants;
4591
4592 // Collect patterns with more than one variant.
4593 for (unsigned i = 0; i != NumOriginalPatterns; ++i) {
4594 MultipleUseVarSet DepVars;
Florian Hahn75e87c32018-05-30 21:00:18 +00004595 std::vector<TreePatternNodePtr> Variants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004596 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004597 LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4598 LLVM_DEBUG(DumpDepVars(DepVars));
4599 LLVM_DEBUG(errs() << "\n");
Florian Hahn75e87c32018-05-30 21:00:18 +00004600 GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4601 *this, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004602
4603 assert(!Variants.empty() && "Must create at least original variant!");
Simon Pilgrim0621f562018-09-18 11:30:30 +00004604 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004605 continue;
4606
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004607 LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4608 PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004609
Simon Pilgrim0621f562018-09-18 11:30:30 +00004610 PatternsWithVariants[i] = std::make_pair(DepVars, Variants);
4611
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +00004612 // Cache matching predicates.
Simon Pilgrim0621f562018-09-18 11:30:30 +00004613 if (MatchedPatterns[i])
4614 continue;
4615
4616 const std::vector<Predicate> &Predicates =
4617 PatternsToMatch[i].getPredicates();
4618
4619 BitVector &Matches = MatchedPredicates[i];
Simon Pilgrim6d706772018-09-19 12:23:50 +00004620 MatchedPatterns.set(i);
4621 Matches.set(i);
Simon Pilgrim0621f562018-09-18 11:30:30 +00004622
4623 // Don't test patterns that have already been cached - it won't match.
4624 for (unsigned p = 0; p != NumOriginalPatterns; ++p)
4625 if (!MatchedPatterns[p])
4626 Matches[p] = (Predicates == PatternsToMatch[p].getPredicates());
4627
4628 // Copy this to all the matching patterns.
4629 for (int p = Matches.find_first(); p != -1; p = Matches.find_next(p))
Simon Pilgrime3c6f8d2018-09-18 12:01:25 +00004630 if (p != (int)i) {
Simon Pilgrim6d706772018-09-19 12:23:50 +00004631 MatchedPatterns.set(p);
Simon Pilgrim0621f562018-09-18 11:30:30 +00004632 MatchedPredicates[p] = Matches;
4633 }
4634 }
4635
4636 for (auto it : PatternsWithVariants) {
4637 unsigned i = it.first;
4638 const MultipleUseVarSet &DepVars = it.second.first;
4639 const std::vector<TreePatternNodePtr> &Variants = it.second.second;
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +00004640
Chris Lattner8cab0212008-01-05 22:25:12 +00004641 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004642 TreePatternNodePtr Variant = Variants[v];
Simon Pilgrim0621f562018-09-18 11:30:30 +00004643 BitVector &Matches = MatchedPredicates[i];
Chris Lattner8cab0212008-01-05 22:25:12 +00004644
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004645 LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump();
4646 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004647
Chris Lattner8cab0212008-01-05 22:25:12 +00004648 // Scan to see if an instruction or explicit pattern already matches this.
4649 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004650 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004651 // Skip if the top level predicates do not match.
Simon Pilgrim0621f562018-09-18 11:30:30 +00004652 if (!Matches[p])
Evan Cheng34c8c742009-06-26 05:59:16 +00004653 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004654 // Check to see if this variant already exists.
Florian Hahn6b1db822018-06-14 20:32:58 +00004655 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004656 DepVars)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004657 LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004658 AlreadyExists = true;
4659 break;
4660 }
4661 }
4662 // If we already have it, ignore the variant.
4663 if (AlreadyExists) continue;
4664
4665 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004666 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004667 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
Florian Hahn75e87c32018-05-30 21:00:18 +00004668 Variant, PatternsToMatch[i].getDstPatternShared(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004669 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004670 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Simon Pilgrim0621f562018-09-18 11:30:30 +00004671 MatchedPredicates.push_back(Matches);
4672
Simon Pilgrimb2444352018-09-18 14:05:07 +00004673 // Add a new match the same as this pattern.
Simon Pilgrimb2444352018-09-18 14:05:07 +00004674 for (auto &P : MatchedPredicates)
Simon Pilgrim429df292018-09-19 11:18:49 +00004675 P.push_back(P[i]);
Chris Lattner8cab0212008-01-05 22:25:12 +00004676 }
4677
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004678 LLVM_DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004679 }
4680}