blob: dc88da220e8cb3e0df67028e3a1d28459ada7712 [file] [log] [blame]
Chris Lattnerab3242f2008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerab3242f2008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner8cab0212008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner78ac0742008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Zachary Turner249dc142017-09-20 18:01:40 +000016#include "llvm/ADT/DenseSet.h"
Chris Lattnercabe0372010-03-15 06:00:16 +000017#include "llvm/ADT/STLExtras.h"
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000018#include "llvm/ADT/SmallSet.h"
Craig Topper3522ab32015-11-28 08:23:02 +000019#include "llvm/ADT/SmallString.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000020#include "llvm/ADT/StringExtras.h"
Craig Topperddfdd942017-09-21 04:55:03 +000021#include "llvm/ADT/StringMap.h"
Jim Grosbach3ae48a62012-04-18 17:46:41 +000022#include "llvm/ADT/Twine.h"
Chris Lattner8cab0212008-01-05 22:25:12 +000023#include "llvm/Support/Debug.h"
David Blaikieb48ed1a2012-01-17 04:43:56 +000024#include "llvm/Support/ErrorHandling.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000025#include "llvm/TableGen/Error.h"
26#include "llvm/TableGen/Record.h"
Chuck Rose IIIfe2714f2008-01-15 21:43:17 +000027#include <algorithm>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000028#include <cstdio>
29#include <set>
Chris Lattner8cab0212008-01-05 22:25:12 +000030using namespace llvm;
31
Chandler Carruthe96dd892014-04-21 22:55:11 +000032#define DEBUG_TYPE "dag-patterns"
33
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000034static inline bool isIntegerOrPtr(MVT VT) {
35 return VT.isInteger() || VT == MVT::iPTR;
Duncan Sands13237ac2008-06-06 12:08:01 +000036}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000037static inline bool isFloatingPoint(MVT VT) {
38 return VT.isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000039}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000040static inline bool isVector(MVT VT) {
41 return VT.isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000042}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000043static inline bool isScalar(MVT VT) {
44 return !VT.isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000045}
Duncan Sands13237ac2008-06-06 12:08:01 +000046
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000047template <typename Predicate>
48static bool berase_if(MachineValueTypeSet &S, Predicate P) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000049 bool Erased = false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000050 // It is ok to iterate over MachineValueTypeSet and remove elements from it
51 // at the same time.
52 for (MVT T : S) {
53 if (!P(T))
54 continue;
55 Erased = true;
56 S.erase(T);
Chris Lattnercabe0372010-03-15 06:00:16 +000057 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000058 return Erased;
Chris Lattner8cab0212008-01-05 22:25:12 +000059}
60
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000061// --- TypeSetByHwMode
Chris Lattnercabe0372010-03-15 06:00:16 +000062
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000063// This is a parameterized type-set class. For each mode there is a list
64// of types that are currently possible for a given tree node. Type
65// inference will apply to each mode separately.
Jim Grosbach65586fe2010-12-21 16:16:00 +000066
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000067TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
68 for (const ValueTypeByHwMode &VVT : VTList)
69 insert(VVT);
Chris Lattner8cab0212008-01-05 22:25:12 +000070}
71
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000072bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
73 for (const auto &I : *this) {
74 if (I.second.size() > 1)
75 return false;
76 if (!AllowEmpty && I.second.empty())
77 return false;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000078 }
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000079 return true;
80}
Chris Lattnercabe0372010-03-15 06:00:16 +000081
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000082ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
83 assert(isValueTypeByHwMode(true) &&
84 "The type set has multiple types for at least one HW mode");
85 ValueTypeByHwMode VVT;
86 for (const auto &I : *this) {
87 MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
88 VVT.getOrCreateTypeForMode(I.first, T);
Chris Lattnercabe0372010-03-15 06:00:16 +000089 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000090 return VVT;
Bob Wilson2cd5da82009-08-11 01:14:02 +000091}
Chris Lattnercabe0372010-03-15 06:00:16 +000092
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000093bool TypeSetByHwMode::isPossible() const {
94 for (const auto &I : *this)
95 if (!I.second.empty())
96 return true;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000097 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +000098}
99
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000100bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
101 bool Changed = false;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000102 bool ContainsDefault = false;
103 MVT DT = MVT::Other;
104
Zachary Turner249dc142017-09-20 18:01:40 +0000105 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000106 for (const auto &P : VVT) {
107 unsigned M = P.first;
108 Modes.insert(M);
109 // Make sure there exists a set for each specific mode from VVT.
110 Changed |= getOrCreate(M).insert(P.second).second;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000111 // Cache VVT's default mode.
112 if (DefaultMode == M) {
113 ContainsDefault = true;
114 DT = P.second;
115 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000116 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000117
118 // If VVT has a default mode, add the corresponding type to all
119 // modes in "this" that do not exist in VVT.
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000120 if (ContainsDefault)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000121 for (auto &I : *this)
122 if (!Modes.count(I.first))
123 Changed |= I.second.insert(DT).second;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000124
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000125 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000126}
127
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000128// Constrain the type set to be the intersection with VTS.
129bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
130 bool Changed = false;
131 if (hasDefault()) {
132 for (const auto &I : VTS) {
133 unsigned M = I.first;
134 if (M == DefaultMode || hasMode(M))
135 continue;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000136 Map.insert({M, Map.at(DefaultMode)});
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000137 Changed = true;
138 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000139 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000140
141 for (auto &I : *this) {
142 unsigned M = I.first;
143 SetType &S = I.second;
144 if (VTS.hasMode(M) || VTS.hasDefault()) {
145 Changed |= intersect(I.second, VTS.get(M));
146 } else if (!S.empty()) {
147 S.clear();
148 Changed = true;
149 }
150 }
151 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000152}
153
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000154template <typename Predicate>
155bool TypeSetByHwMode::constrain(Predicate P) {
156 bool Changed = false;
157 for (auto &I : *this)
Benjamin Kramere57308e2017-09-17 11:19:53 +0000158 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000159 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000160}
161
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000162template <typename Predicate>
163bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
164 assert(empty());
165 for (const auto &I : VTS) {
166 SetType &S = getOrCreate(I.first);
167 for (auto J : I.second)
168 if (P(J))
169 S.insert(J);
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000170 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000171 return !empty();
Chris Lattnercabe0372010-03-15 06:00:16 +0000172}
173
Zachary Turner249dc142017-09-20 18:01:40 +0000174void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
175 SmallVector<unsigned, 4> Modes;
176 Modes.reserve(Map.size());
Chris Lattnercabe0372010-03-15 06:00:16 +0000177
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000178 for (const auto &I : *this)
179 Modes.push_back(I.first);
Zachary Turner249dc142017-09-20 18:01:40 +0000180 if (Modes.empty()) {
181 OS << "{}";
182 return;
183 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000184 array_pod_sort(Modes.begin(), Modes.end());
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000185
Zachary Turner249dc142017-09-20 18:01:40 +0000186 OS << '{';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000187 for (unsigned M : Modes) {
Zachary Turner249dc142017-09-20 18:01:40 +0000188 OS << ' ' << getModeName(M) << ':';
189 writeToStream(get(M), OS);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000190 }
Zachary Turner249dc142017-09-20 18:01:40 +0000191 OS << " }";
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000192}
193
Zachary Turner249dc142017-09-20 18:01:40 +0000194void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
195 SmallVector<MVT, 4> Types(S.begin(), S.end());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000196 array_pod_sort(Types.begin(), Types.end());
197
Zachary Turner249dc142017-09-20 18:01:40 +0000198 OS << '[';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000199 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
Zachary Turner249dc142017-09-20 18:01:40 +0000200 OS << ValueTypeByHwMode::getMVTName(Types[i]);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000201 if (i != e-1)
Zachary Turner249dc142017-09-20 18:01:40 +0000202 OS << ' ';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000203 }
Zachary Turner249dc142017-09-20 18:01:40 +0000204 OS << ']';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000205}
206
207bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
Simon Pilgrim0e181332018-08-16 16:16:28 +0000208 // The isSimple call is much quicker than hasDefault - check this first.
209 bool IsSimple = isSimple();
210 bool VTSIsSimple = VTS.isSimple();
211 if (IsSimple && VTSIsSimple)
212 return *begin() == *VTS.begin();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000213
Simon Pilgrim0e181332018-08-16 16:16:28 +0000214 // Speedup: We have a default if the set is simple.
215 bool HaveDefault = IsSimple || hasDefault();
216 bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
217 if (HaveDefault != VTSHaveDefault)
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000218 return false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000219
Zachary Turner249dc142017-09-20 18:01:40 +0000220 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000221 for (auto &I : *this)
222 Modes.insert(I.first);
223 for (const auto &I : VTS)
224 Modes.insert(I.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000225
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000226 if (HaveDefault) {
227 // Both sets have default mode.
228 for (unsigned M : Modes) {
229 if (get(M) != VTS.get(M))
David Majnemerc7004902016-08-12 04:32:37 +0000230 return false;
Craig Topper5712d462015-11-24 08:20:47 +0000231 }
Scott Michel94420742008-03-05 17:49:05 +0000232 } else {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000233 // Neither set has default mode.
234 for (unsigned M : Modes) {
235 // If there is no default mode, an empty set is equivalent to not having
236 // the corresponding mode.
237 bool NoModeThis = !hasMode(M) || get(M).empty();
238 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
239 if (NoModeThis != NoModeVTS)
240 return false;
241 if (!NoModeThis)
242 if (get(M) != VTS.get(M))
243 return false;
244 }
Scott Michel94420742008-03-05 17:49:05 +0000245 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000246
247 return true;
Scott Michel94420742008-03-05 17:49:05 +0000248}
249
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000250namespace llvm {
251 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
252 T.writeToStream(OS);
253 return OS;
254 }
255}
256
Krzysztof Parzyszek426bf362017-09-12 15:31:26 +0000257LLVM_DUMP_METHOD
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000258void TypeSetByHwMode::dump() const {
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000259 dbgs() << *this << '\n';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000260}
261
262bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
263 bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
264 auto Int = [&In](MVT T) -> bool { return !In.count(T); };
265
266 if (OutP == InP)
267 return berase_if(Out, Int);
268
269 // Compute the intersection of scalars separately to account for only
270 // one set containing iPTR.
271 // The itersection of iPTR with a set of integer scalar types that does not
272 // include iPTR will result in the most specific scalar type:
273 // - iPTR is more specific than any set with two elements or more
274 // - iPTR is less specific than any single integer scalar type.
275 // For example
276 // { iPTR } * { i32 } -> { i32 }
277 // { iPTR } * { i32 i64 } -> { iPTR }
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000278 // and
279 // { iPTR i32 } * { i32 } -> { i32 }
280 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
281 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000282
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000283 // Compute the difference between the two sets in such a way that the
284 // iPTR is in the set that is being subtracted. This is to see if there
285 // are any extra scalars in the set without iPTR that are not in the
286 // set containing iPTR. Then the iPTR could be considered a "wildcard"
287 // matching these scalars. If there is only one such scalar, it would
288 // replace the iPTR, if there are more, the iPTR would be retained.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000289 SetType Diff;
290 if (InP) {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000291 Diff = Out;
292 berase_if(Diff, [&In](MVT T) { return In.count(T); });
293 // Pre-remove these elements and rely only on InP/OutP to determine
294 // whether a change has been made.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000295 berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
Scott Michel94420742008-03-05 17:49:05 +0000296 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000297 Diff = In;
298 berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000299 Out.erase(MVT::iPTR);
300 }
301
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000302 // The actual intersection.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000303 bool Changed = berase_if(Out, Int);
304 unsigned NumD = Diff.size();
305 if (NumD == 0)
306 return Changed;
307
308 if (NumD == 1) {
309 Out.insert(*Diff.begin());
310 // This is a change only if Out was the one with iPTR (which is now
311 // being replaced).
312 Changed |= OutP;
313 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000314 // Multiple elements from Out are now replaced with iPTR.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000315 Out.insert(MVT::iPTR);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000316 Changed |= !OutP;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000317 }
318 return Changed;
319}
320
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000321bool TypeSetByHwMode::validate() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000322#ifndef NDEBUG
323 if (empty())
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000324 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000325 bool AllEmpty = true;
326 for (const auto &I : *this)
327 AllEmpty &= I.second.empty();
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000328 return !AllEmpty;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000329#endif
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000330 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000331}
332
333// --- TypeInfer
334
335bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
336 const TypeSetByHwMode &In) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000337 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000338 In.validate();
339 if (In.empty() || Out == In || TP.hasError())
340 return false;
341 if (Out.empty()) {
342 Out = In;
343 return true;
344 }
345
346 bool Changed = Out.constrain(In);
347 if (Changed && Out.empty())
348 TP.error("Type contradiction");
349
350 return Changed;
351}
352
353bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000354 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000355 if (TP.hasError())
356 return false;
357 assert(!Out.empty() && "cannot pick from an empty set");
358
359 bool Changed = false;
360 for (auto &I : Out) {
361 TypeSetByHwMode::SetType &S = I.second;
362 if (S.size() <= 1)
363 continue;
364 MVT T = *S.begin(); // Pick the first element.
365 S.clear();
366 S.insert(T);
367 Changed = true;
368 }
369 return Changed;
370}
371
372bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000373 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000374 if (TP.hasError())
375 return false;
376 if (!Out.empty())
377 return Out.constrain(isIntegerOrPtr);
378
379 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
380}
381
382bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000383 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000384 if (TP.hasError())
385 return false;
386 if (!Out.empty())
387 return Out.constrain(isFloatingPoint);
388
389 return Out.assign_if(getLegalTypes(), isFloatingPoint);
390}
391
392bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000393 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000394 if (TP.hasError())
395 return false;
396 if (!Out.empty())
397 return Out.constrain(isScalar);
398
399 return Out.assign_if(getLegalTypes(), isScalar);
400}
401
402bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000403 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000404 if (TP.hasError())
405 return false;
406 if (!Out.empty())
407 return Out.constrain(isVector);
408
409 return Out.assign_if(getLegalTypes(), isVector);
410}
411
412bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000413 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000414 if (TP.hasError() || !Out.empty())
415 return false;
416
417 Out = getLegalTypes();
418 return true;
419}
420
421template <typename Iter, typename Pred, typename Less>
422static Iter min_if(Iter B, Iter E, Pred P, Less L) {
423 if (B == E)
424 return E;
425 Iter Min = E;
426 for (Iter I = B; I != E; ++I) {
427 if (!P(*I))
428 continue;
429 if (Min == E || L(*I, *Min))
430 Min = I;
431 }
432 return Min;
433}
434
435template <typename Iter, typename Pred, typename Less>
436static Iter max_if(Iter B, Iter E, Pred P, Less L) {
437 if (B == E)
438 return E;
439 Iter Max = E;
440 for (Iter I = B; I != E; ++I) {
441 if (!P(*I))
442 continue;
443 if (Max == E || L(*Max, *I))
444 Max = I;
445 }
446 return Max;
447}
448
449/// Make sure that for each type in Small, there exists a larger type in Big.
450bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
451 TypeSetByHwMode &Big) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000452 ValidateOnExit _1(Small, *this), _2(Big, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000453 if (TP.hasError())
454 return false;
455 bool Changed = false;
456
457 if (Small.empty())
458 Changed |= EnforceAny(Small);
459 if (Big.empty())
460 Changed |= EnforceAny(Big);
461
462 assert(Small.hasDefault() && Big.hasDefault());
463
464 std::vector<unsigned> Modes = union_modes(Small, Big);
465
466 // 1. Only allow integer or floating point types and make sure that
467 // both sides are both integer or both floating point.
468 // 2. Make sure that either both sides have vector types, or neither
469 // of them does.
470 for (unsigned M : Modes) {
471 TypeSetByHwMode::SetType &S = Small.get(M);
472 TypeSetByHwMode::SetType &B = Big.get(M);
473
474 if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000475 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000476 Changed |= berase_if(S, NotInt) |
477 berase_if(B, NotInt);
478 } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000479 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000480 Changed |= berase_if(S, NotFP) |
481 berase_if(B, NotFP);
482 } else if (S.empty() || B.empty()) {
483 Changed = !S.empty() || !B.empty();
484 S.clear();
485 B.clear();
486 } else {
487 TP.error("Incompatible types");
488 return Changed;
Scott Michel94420742008-03-05 17:49:05 +0000489 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000490
491 if (none_of(S, isVector) || none_of(B, isVector)) {
492 Changed |= berase_if(S, isVector) |
493 berase_if(B, isVector);
494 }
495 }
496
497 auto LT = [](MVT A, MVT B) -> bool {
498 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
499 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
500 A.getSizeInBits() < B.getSizeInBits());
501 };
502 auto LE = [](MVT A, MVT B) -> bool {
503 // This function is used when removing elements: when a vector is compared
504 // to a non-vector, it should return false (to avoid removal).
505 if (A.isVector() != B.isVector())
506 return false;
507
508 // Note on the < comparison below:
509 // X86 has patterns like
510 // (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))),
511 // where the truncated vector is given a type v16i8, while the source
512 // vector has type v4i32. They both have the same size in bits.
513 // The minimal type in the result is obviously v16i8, and when we remove
514 // all types from the source that are smaller-or-equal than v8i16, the
515 // only source type would also be removed (since it's equal in size).
516 return A.getScalarSizeInBits() <= B.getScalarSizeInBits() ||
517 A.getSizeInBits() < B.getSizeInBits();
518 };
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
Chris Lattner514e2922011-04-17 21:38:24 +0000826//===----------------------------------------------------------------------===//
827// TreePredicateFn Implementation
828//===----------------------------------------------------------------------===//
829
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000830/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
831TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000832 assert(
833 (!hasPredCode() || !hasImmCode()) &&
834 ".td file corrupt: can't have a node predicate *and* an imm predicate");
835}
836
837bool TreePredicateFn::hasPredCode() const {
Daniel Sanders87d196c2017-11-13 22:26:13 +0000838 return isLoad() || isStore() || isAtomic() ||
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000839 !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000840}
841
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000842std::string TreePredicateFn::getPredCode() const {
843 std::string Code = "";
844
Daniel Sanders87d196c2017-11-13 22:26:13 +0000845 if (!isLoad() && !isStore() && !isAtomic()) {
846 Record *MemoryVT = getMemoryVT();
847
848 if (MemoryVT)
849 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
850 "MemoryVT requires IsLoad or IsStore");
851 }
852
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000853 if (!isLoad() && !isStore()) {
854 if (isUnindexed())
855 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
856 "IsUnindexed requires IsLoad or IsStore");
857
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000858 Record *ScalarMemoryVT = getScalarMemoryVT();
859
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000860 if (ScalarMemoryVT)
861 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
862 "ScalarMemoryVT requires IsLoad or IsStore");
863 }
864
Daniel Sanders87d196c2017-11-13 22:26:13 +0000865 if (isLoad() + isStore() + isAtomic() > 1)
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000866 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
Daniel Sanders87d196c2017-11-13 22:26:13 +0000867 "IsLoad, IsStore, and IsAtomic are mutually exclusive");
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000868
869 if (isLoad()) {
870 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
871 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
872 getScalarMemoryVT() == nullptr)
873 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
874 "IsLoad cannot be used by itself");
875 } else {
876 if (isNonExtLoad())
877 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
878 "IsNonExtLoad requires IsLoad");
879 if (isAnyExtLoad())
880 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
881 "IsAnyExtLoad requires IsLoad");
882 if (isSignExtLoad())
883 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
884 "IsSignExtLoad requires IsLoad");
885 if (isZeroExtLoad())
886 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
887 "IsZeroExtLoad requires IsLoad");
888 }
889
890 if (isStore()) {
891 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
892 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr)
893 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
894 "IsStore cannot be used by itself");
895 } else {
896 if (isNonTruncStore())
897 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
898 "IsNonTruncStore requires IsStore");
899 if (isTruncStore())
900 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
901 "IsTruncStore requires IsStore");
902 }
903
Daniel Sanders87d196c2017-11-13 22:26:13 +0000904 if (isAtomic()) {
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000905 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
906 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
907 !isAtomicOrderingAcquireRelease() &&
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000908 !isAtomicOrderingSequentiallyConsistent() &&
909 !isAtomicOrderingAcquireOrStronger() &&
910 !isAtomicOrderingReleaseOrStronger() &&
911 !isAtomicOrderingWeakerThanAcquire() &&
912 !isAtomicOrderingWeakerThanRelease())
Daniel Sanders87d196c2017-11-13 22:26:13 +0000913 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
914 "IsAtomic cannot be used by itself");
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000915 } else {
916 if (isAtomicOrderingMonotonic())
917 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
918 "IsAtomicOrderingMonotonic requires IsAtomic");
919 if (isAtomicOrderingAcquire())
920 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
921 "IsAtomicOrderingAcquire requires IsAtomic");
922 if (isAtomicOrderingRelease())
923 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
924 "IsAtomicOrderingRelease requires IsAtomic");
925 if (isAtomicOrderingAcquireRelease())
926 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
927 "IsAtomicOrderingAcquireRelease requires IsAtomic");
928 if (isAtomicOrderingSequentiallyConsistent())
929 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
930 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000931 if (isAtomicOrderingAcquireOrStronger())
932 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
933 "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
934 if (isAtomicOrderingReleaseOrStronger())
935 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
936 "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
937 if (isAtomicOrderingWeakerThanAcquire())
938 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
939 "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
Daniel Sanders87d196c2017-11-13 22:26:13 +0000940 }
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000941
Daniel Sanders87d196c2017-11-13 22:26:13 +0000942 if (isLoad() || isStore() || isAtomic()) {
943 StringRef SDNodeName =
944 isLoad() ? "LoadSDNode" : isStore() ? "StoreSDNode" : "AtomicSDNode";
945
946 Record *MemoryVT = getMemoryVT();
947
948 if (MemoryVT)
949 Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT() != MVT::" +
950 MemoryVT->getName() + ") return false;\n")
951 .str();
952 }
953
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000954 if (isAtomic() && isAtomicOrderingMonotonic())
955 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
956 "AtomicOrdering::Monotonic) return false;\n";
957 if (isAtomic() && isAtomicOrderingAcquire())
958 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
959 "AtomicOrdering::Acquire) return false;\n";
960 if (isAtomic() && isAtomicOrderingRelease())
961 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
962 "AtomicOrdering::Release) return false;\n";
963 if (isAtomic() && isAtomicOrderingAcquireRelease())
964 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
965 "AtomicOrdering::AcquireRelease) return false;\n";
966 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
967 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
968 "AtomicOrdering::SequentiallyConsistent) return false;\n";
969
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000970 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
971 Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
972 "return false;\n";
973 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
974 Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
975 "return false;\n";
976
977 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
978 Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
979 "return false;\n";
980 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
981 Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
982 "return false;\n";
983
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000984 if (isLoad() || isStore()) {
985 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
986
987 if (isUnindexed())
988 Code += ("if (cast<" + SDNodeName +
989 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
990 "return false;\n")
991 .str();
992
993 if (isLoad()) {
994 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
995 isZeroExtLoad()) > 1)
996 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
997 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
998 "IsZeroExtLoad are mutually exclusive");
999 if (isNonExtLoad())
1000 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
1001 "ISD::NON_EXTLOAD) return false;\n";
1002 if (isAnyExtLoad())
1003 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1004 "return false;\n";
1005 if (isSignExtLoad())
1006 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1007 "return false;\n";
1008 if (isZeroExtLoad())
1009 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1010 "return false;\n";
1011 } else {
1012 if ((isNonTruncStore() + isTruncStore()) > 1)
1013 PrintFatalError(
1014 getOrigPatFragRecord()->getRecord()->getLoc(),
1015 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1016 if (isNonTruncStore())
1017 Code +=
1018 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1019 if (isTruncStore())
1020 Code +=
1021 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1022 }
1023
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001024 Record *ScalarMemoryVT = getScalarMemoryVT();
1025
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001026 if (ScalarMemoryVT)
1027 Code += ("if (cast<" + SDNodeName +
1028 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1029 ScalarMemoryVT->getName() + ") return false;\n")
1030 .str();
1031 }
1032
1033 std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
1034
1035 Code += PredicateCode;
1036
1037 if (PredicateCode.empty() && !Code.empty())
1038 Code += "return true;\n";
1039
1040 return Code;
Chris Lattner514e2922011-04-17 21:38:24 +00001041}
1042
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001043bool TreePredicateFn::hasImmCode() const {
1044 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1045}
1046
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001047std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00001048 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001049}
1050
Daniel Sanders649c5852017-10-13 20:42:18 +00001051bool TreePredicateFn::immCodeUsesAPInt() const {
1052 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1053}
1054
1055bool TreePredicateFn::immCodeUsesAPFloat() const {
1056 bool Unset;
1057 // The return value will be false when IsAPFloat is unset.
1058 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1059 Unset);
1060}
1061
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001062bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1063 bool Value) const {
1064 bool Unset;
1065 bool Result =
1066 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1067 if (Unset)
1068 return false;
1069 return Result == Value;
1070}
1071bool TreePredicateFn::isLoad() const {
1072 return isPredefinedPredicateEqualTo("IsLoad", true);
1073}
1074bool TreePredicateFn::isStore() const {
1075 return isPredefinedPredicateEqualTo("IsStore", true);
1076}
Daniel Sanders87d196c2017-11-13 22:26:13 +00001077bool TreePredicateFn::isAtomic() const {
1078 return isPredefinedPredicateEqualTo("IsAtomic", true);
1079}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001080bool TreePredicateFn::isUnindexed() const {
1081 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1082}
1083bool TreePredicateFn::isNonExtLoad() const {
1084 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1085}
1086bool TreePredicateFn::isAnyExtLoad() const {
1087 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1088}
1089bool TreePredicateFn::isSignExtLoad() const {
1090 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1091}
1092bool TreePredicateFn::isZeroExtLoad() const {
1093 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1094}
1095bool TreePredicateFn::isNonTruncStore() const {
1096 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1097}
1098bool TreePredicateFn::isTruncStore() const {
1099 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1100}
Daniel Sanders6d9d30a2017-11-13 23:03:47 +00001101bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1102 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1103}
1104bool TreePredicateFn::isAtomicOrderingAcquire() const {
1105 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1106}
1107bool TreePredicateFn::isAtomicOrderingRelease() const {
1108 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1109}
1110bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1111 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1112}
1113bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1114 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1115 true);
1116}
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001117bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1118 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1119}
1120bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1121 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1122}
1123bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1124 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1125}
1126bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1127 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1128}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001129Record *TreePredicateFn::getMemoryVT() const {
1130 Record *R = getOrigPatFragRecord()->getRecord();
1131 if (R->isValueUnset("MemoryVT"))
1132 return nullptr;
1133 return R->getValueAsDef("MemoryVT");
1134}
1135Record *TreePredicateFn::getScalarMemoryVT() const {
1136 Record *R = getOrigPatFragRecord()->getRecord();
1137 if (R->isValueUnset("ScalarMemoryVT"))
1138 return nullptr;
1139 return R->getValueAsDef("ScalarMemoryVT");
1140}
Daniel Sanders8ead1292018-06-15 23:13:43 +00001141bool TreePredicateFn::hasGISelPredicateCode() const {
1142 return !PatFragRec->getRecord()
1143 ->getValueAsString("GISelPredicateCode")
1144 .empty();
1145}
1146std::string TreePredicateFn::getGISelPredicateCode() const {
1147 return PatFragRec->getRecord()->getValueAsString("GISelPredicateCode");
1148}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001149
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001150StringRef TreePredicateFn::getImmType() const {
Daniel Sanders649c5852017-10-13 20:42:18 +00001151 if (immCodeUsesAPInt())
1152 return "const APInt &";
1153 if (immCodeUsesAPFloat())
1154 return "const APFloat &";
1155 return "int64_t";
1156}
Chris Lattner514e2922011-04-17 21:38:24 +00001157
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001158StringRef TreePredicateFn::getImmTypeIdentifier() const {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001159 if (immCodeUsesAPInt())
1160 return "APInt";
1161 else if (immCodeUsesAPFloat())
1162 return "APFloat";
1163 return "I64";
1164}
1165
Chris Lattner514e2922011-04-17 21:38:24 +00001166/// isAlwaysTrue - Return true if this is a noop predicate.
1167bool TreePredicateFn::isAlwaysTrue() const {
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001168 return !hasPredCode() && !hasImmCode();
Chris Lattner514e2922011-04-17 21:38:24 +00001169}
1170
1171/// Return the name to use in the generated code to reference this, this is
1172/// "Predicate_foo" if from a pattern fragment "foo".
1173std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +00001174 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +00001175}
1176
1177/// getCodeToRunOnSDNode - Return the code for the function body that
1178/// evaluates this predicate. The argument is expected to be in "Node",
1179/// not N. This handles casting and conversion to a concrete node type as
1180/// appropriate.
1181std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001182 // Handle immediate predicates first.
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001183 std::string ImmCode = getImmCode();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001184 if (!ImmCode.empty()) {
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001185 if (isLoad())
1186 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1187 "IsLoad cannot be used with ImmLeaf or its subclasses");
1188 if (isStore())
1189 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1190 "IsStore cannot be used with ImmLeaf or its subclasses");
1191 if (isUnindexed())
1192 PrintFatalError(
1193 getOrigPatFragRecord()->getRecord()->getLoc(),
1194 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1195 if (isNonExtLoad())
1196 PrintFatalError(
1197 getOrigPatFragRecord()->getRecord()->getLoc(),
1198 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1199 if (isAnyExtLoad())
1200 PrintFatalError(
1201 getOrigPatFragRecord()->getRecord()->getLoc(),
1202 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1203 if (isSignExtLoad())
1204 PrintFatalError(
1205 getOrigPatFragRecord()->getRecord()->getLoc(),
1206 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1207 if (isZeroExtLoad())
1208 PrintFatalError(
1209 getOrigPatFragRecord()->getRecord()->getLoc(),
1210 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1211 if (isNonTruncStore())
1212 PrintFatalError(
1213 getOrigPatFragRecord()->getRecord()->getLoc(),
1214 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1215 if (isTruncStore())
1216 PrintFatalError(
1217 getOrigPatFragRecord()->getRecord()->getLoc(),
1218 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1219 if (getMemoryVT())
1220 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1221 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1222 if (getScalarMemoryVT())
1223 PrintFatalError(
1224 getOrigPatFragRecord()->getRecord()->getLoc(),
1225 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1226
1227 std::string Result = (" " + getImmType() + " Imm = ").str();
Daniel Sanders649c5852017-10-13 20:42:18 +00001228 if (immCodeUsesAPFloat())
1229 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1230 else if (immCodeUsesAPInt())
1231 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1232 else
1233 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001234 return Result + ImmCode;
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001235 }
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001236
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001237 // Handle arbitrary node predicates.
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001238 assert(hasPredCode() && "Don't have any predicate code!");
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001239 StringRef ClassName;
Chris Lattner514e2922011-04-17 21:38:24 +00001240 if (PatFragRec->getOnlyTree()->isLeaf())
1241 ClassName = "SDNode";
1242 else {
1243 Record *Op = PatFragRec->getOnlyTree()->getOperator();
1244 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1245 }
1246 std::string Result;
1247 if (ClassName == "SDNode")
1248 Result = " SDNode *N = Node;\n";
1249 else
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001250 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001251
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001252 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +00001253}
1254
Chris Lattner8cab0212008-01-05 22:25:12 +00001255//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +00001256// PatternToMatch implementation
1257//
1258
Chris Lattner05925fe2010-03-29 01:40:38 +00001259/// getPatternSize - Return the 'size' of this pattern. We want to match large
1260/// patterns before small ones. This is used to determine the size of a
1261/// pattern.
Florian Hahn6b1db822018-06-14 20:32:58 +00001262static unsigned getPatternSize(const TreePatternNode *P,
Chris Lattner05925fe2010-03-29 01:40:38 +00001263 const CodeGenDAGPatterns &CGP) {
1264 unsigned Size = 3; // The node itself.
1265 // If the root node is a ConstantSDNode, increases its size.
1266 // e.g. (set R32:$dst, 0).
Florian Hahn6b1db822018-06-14 20:32:58 +00001267 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001268 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001269
Florian Hahn6b1db822018-06-14 20:32:58 +00001270 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001271 Size += AM->getComplexity();
Tim Northoverc807a172014-05-20 11:52:46 +00001272 // We don't want to count any children twice, so return early.
1273 return Size;
1274 }
1275
Chris Lattner05925fe2010-03-29 01:40:38 +00001276 // If this node has some predicate function that must match, it adds to the
1277 // complexity of this node.
Florian Hahn6b1db822018-06-14 20:32:58 +00001278 if (!P->getPredicateFns().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001279 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001280
Chris Lattner05925fe2010-03-29 01:40:38 +00001281 // Count children in the count if they are also nodes.
Florian Hahn6b1db822018-06-14 20:32:58 +00001282 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1283 const TreePatternNode *Child = P->getChild(i);
1284 if (!Child->isLeaf() && Child->getNumTypes()) {
Simon Pilgrimc3c14412018-08-15 20:41:19 +00001285 const TypeSetByHwMode &T0 = Child->getExtType(0);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001286 // At this point, all variable type sets should be simple, i.e. only
1287 // have a default mode.
1288 if (T0.getMachineValueType() != MVT::Other) {
1289 Size += getPatternSize(Child, CGP);
1290 continue;
1291 }
1292 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001293 if (Child->isLeaf()) {
1294 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001295 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Florian Hahn6b1db822018-06-14 20:32:58 +00001296 else if (Child->getComplexPatternInfo(CGP))
Chris Lattner05925fe2010-03-29 01:40:38 +00001297 Size += getPatternSize(Child, CGP);
Florian Hahn6b1db822018-06-14 20:32:58 +00001298 else if (!Child->getPredicateFns().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001299 ++Size;
1300 }
1301 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001302
Chris Lattner05925fe2010-03-29 01:40:38 +00001303 return Size;
1304}
1305
1306/// Compute the complexity metric for the input pattern. This roughly
1307/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +00001308int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +00001309getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001310 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
Chris Lattner05925fe2010-03-29 01:40:38 +00001311}
1312
Dan Gohman49e19e92008-08-22 00:20:26 +00001313/// getPredicateCheck - Return a single string containing all of this
1314/// pattern's predicates concatenated with "&&" operators.
1315///
1316std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001317 SmallVector<const Predicate*,4> PredList;
1318 for (const Predicate &P : Predicates)
1319 PredList.push_back(&P);
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00001320 llvm::sort(PredList.begin(), PredList.end(), deref<llvm::less>());
Craig Topper8985efe2015-11-27 05:44:04 +00001321
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001322 std::string Check;
1323 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1324 if (i != 0)
1325 Check += " && ";
1326 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +00001327 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001328 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +00001329}
1330
1331//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00001332// SDTypeConstraint implementation
1333//
1334
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001335SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001336 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001337
Chris Lattner8cab0212008-01-05 22:25:12 +00001338 if (R->isSubClassOf("SDTCisVT")) {
1339 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001340 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1341 for (const auto &P : VVT)
1342 if (P.second == MVT::isVoid)
1343 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +00001344 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1345 ConstraintType = SDTCisPtrTy;
1346 } else if (R->isSubClassOf("SDTCisInt")) {
1347 ConstraintType = SDTCisInt;
1348 } else if (R->isSubClassOf("SDTCisFP")) {
1349 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +00001350 } else if (R->isSubClassOf("SDTCisVec")) {
1351 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001352 } else if (R->isSubClassOf("SDTCisSameAs")) {
1353 ConstraintType = SDTCisSameAs;
1354 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1355 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1356 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001357 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001358 R->getValueAsInt("OtherOperandNum");
1359 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1360 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001361 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001362 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001363 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1364 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001365 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001366 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1367 ConstraintType = SDTCisSubVecOfVec;
1368 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1369 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001370 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1371 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001372 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1373 for (const auto &P : VVT) {
1374 MVT T = P.second;
1375 if (T.isVector())
1376 PrintFatalError(R->getLoc(),
1377 "Cannot use vector type as SDTCVecEltisVT");
1378 if (!T.isInteger() && !T.isFloatingPoint())
1379 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1380 "as SDTCVecEltisVT");
1381 }
Craig Topper0be34582015-03-05 07:11:34 +00001382 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1383 ConstraintType = SDTCisSameNumEltsAs;
1384 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1385 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001386 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1387 ConstraintType = SDTCisSameSizeAs;
1388 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1389 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001390 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001391 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001392 }
1393}
1394
1395/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001396/// N, and the result number in ResNo.
Florian Hahn6b1db822018-06-14 20:32:58 +00001397static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
Chris Lattner2db7aba2010-03-19 21:56:21 +00001398 const SDNodeInfo &NodeInfo,
1399 unsigned &ResNo) {
1400 unsigned NumResults = NodeInfo.getNumResults();
1401 if (OpNo < NumResults) {
1402 ResNo = OpNo;
1403 return N;
1404 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001405
Chris Lattner2db7aba2010-03-19 21:56:21 +00001406 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001407
Florian Hahn6b1db822018-06-14 20:32:58 +00001408 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001409 std::string S;
1410 raw_string_ostream OS(S);
1411 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001412 << (OpNo+NumResults) << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001413 N->print(OS);
James Y Knighte452e272015-05-11 22:17:13 +00001414 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001415 }
1416
Florian Hahn6b1db822018-06-14 20:32:58 +00001417 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001418}
1419
1420/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1421/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001422/// change, false otherwise. If a type contradiction is found, flag an error.
Florian Hahn6b1db822018-06-14 20:32:58 +00001423bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
Chris Lattner8cab0212008-01-05 22:25:12 +00001424 const SDNodeInfo &NodeInfo,
1425 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001426 if (TP.hasError())
1427 return false;
1428
Chris Lattner2db7aba2010-03-19 21:56:21 +00001429 unsigned ResNo = 0; // The result number being referenced.
Florian Hahn6b1db822018-06-14 20:32:58 +00001430 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001431 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001432
Chris Lattner8cab0212008-01-05 22:25:12 +00001433 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001434 case SDTCisVT:
1435 // Operand must be a particular type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001436 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001437 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001438 // Operand must be same as target pointer type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001439 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001440 case SDTCisInt:
1441 // Require it to be one of the legal integer VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001442 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001443 case SDTCisFP:
1444 // Require it to be one of the legal fp VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001445 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001446 case SDTCisVec:
1447 // Require it to be one of the legal vector VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001448 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001449 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001450 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001451 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001452 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001453 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1454 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001455 }
1456 case SDTCisVTSmallerThanOp: {
1457 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1458 // have an integer type that is smaller than the VT.
Florian Hahn6b1db822018-06-14 20:32:58 +00001459 if (!NodeToApply->isLeaf() ||
1460 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1461 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001462 ->isSubClassOf("ValueType")) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001463 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001464 return false;
1465 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001466 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001467 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1468 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1469 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001470
Chris Lattner2db7aba2010-03-19 21:56:21 +00001471 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001472 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001473 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1474 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001475
Florian Hahn6b1db822018-06-14 20:32:58 +00001476 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001477 }
1478 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001479 unsigned BResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001480 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001481 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1482 BResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001483 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1484 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001485 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001486 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001487 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001488 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001489 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1490 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001491 // Filter vector types out of VecOperand that don't have the right element
1492 // type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001493 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1494 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001495 }
David Greene127fd1d2011-01-24 20:53:18 +00001496 case SDTCisSubVecOfVec: {
1497 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001498 TreePatternNode *BigVecOperand =
David Greene127fd1d2011-01-24 20:53:18 +00001499 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1500 VResNo);
1501
1502 // Filter vector types out of BigVecOperand that don't have the
1503 // right subvector type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001504 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1505 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001506 }
Craig Topper0be34582015-03-05 07:11:34 +00001507 case SDTCVecEltisVT: {
Florian Hahn6b1db822018-06-14 20:32:58 +00001508 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001509 }
1510 case SDTCisSameNumEltsAs: {
1511 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001512 TreePatternNode *OtherNode =
Craig Topper0be34582015-03-05 07:11:34 +00001513 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1514 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001515 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1516 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001517 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001518 case SDTCisSameSizeAs: {
1519 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001520 TreePatternNode *OtherNode =
Craig Topper9a44b3f2015-11-26 07:02:18 +00001521 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1522 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001523 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1524 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001525 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001526 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001527 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001528}
1529
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001530// Update the node type to match an instruction operand or result as specified
1531// in the ins or outs lists on the instruction definition. Return true if the
1532// type was actually changed.
1533bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1534 Record *Operand,
1535 TreePattern &TP) {
1536 // The 'unknown' operand indicates that types should be inferred from the
1537 // context.
1538 if (Operand->isSubClassOf("unknown_class"))
1539 return false;
1540
1541 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001542 if (Operand->isSubClassOf("Operand")) {
1543 Record *R = Operand->getValueAsDef("Type");
1544 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1545 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1546 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001547
1548 // PointerLikeRegClass has a type that is determined at runtime.
1549 if (Operand->isSubClassOf("PointerLikeRegClass"))
1550 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1551
1552 // Both RegisterClass and RegisterOperand operands derive their types from a
1553 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001554 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001555 if (Operand->isSubClassOf("RegisterClass"))
1556 RC = Operand;
1557 else if (Operand->isSubClassOf("RegisterOperand"))
1558 RC = Operand->getValueAsDef("RegClass");
1559
1560 assert(RC && "Unknown operand type");
1561 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1562 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1563}
1564
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001565bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1566 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1567 if (!TP.getInfer().isConcrete(Types[i], true))
1568 return true;
1569 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001570 if (getChild(i)->ContainsUnresolvedType(TP))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001571 return true;
1572 return false;
1573}
1574
1575bool TreePatternNode::hasProperTypeByHwMode() const {
1576 for (const TypeSetByHwMode &S : Types)
1577 if (!S.isDefaultOnly())
1578 return true;
Florian Hahn75e87c32018-05-30 21:00:18 +00001579 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001580 if (C->hasProperTypeByHwMode())
1581 return true;
1582 return false;
1583}
1584
1585bool TreePatternNode::hasPossibleType() const {
1586 for (const TypeSetByHwMode &S : Types)
1587 if (!S.isPossible())
1588 return false;
Florian Hahn75e87c32018-05-30 21:00:18 +00001589 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001590 if (!C->hasPossibleType())
1591 return false;
1592 return true;
1593}
1594
1595bool TreePatternNode::setDefaultMode(unsigned Mode) {
1596 for (TypeSetByHwMode &S : Types) {
1597 S.makeSimple(Mode);
1598 // Check if the selected mode had a type conflict.
1599 if (S.get(DefaultMode).empty())
1600 return false;
1601 }
Florian Hahn75e87c32018-05-30 21:00:18 +00001602 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001603 if (!C->setDefaultMode(Mode))
1604 return false;
1605 return true;
1606}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001607
Chris Lattner8cab0212008-01-05 22:25:12 +00001608//===----------------------------------------------------------------------===//
1609// SDNodeInfo implementation
1610//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001611SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001612 EnumName = R->getValueAsString("Opcode");
1613 SDClassName = R->getValueAsString("SDClass");
1614 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1615 NumResults = TypeProfile->getValueAsInt("NumResults");
1616 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001617
Chris Lattner8cab0212008-01-05 22:25:12 +00001618 // Parse the properties.
Matt Arsenault303327d2017-12-20 19:36:28 +00001619 Properties = parseSDPatternOperatorProperties(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001620
Chris Lattner8cab0212008-01-05 22:25:12 +00001621 // Parse the type constraints.
1622 std::vector<Record*> ConstraintList =
1623 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001624 for (Record *R : ConstraintList)
1625 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001626}
1627
Chris Lattner99e53b32010-02-28 00:22:30 +00001628/// getKnownType - If the type constraints on this node imply a fixed type
1629/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001630/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001631MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001632 unsigned NumResults = getNumResults();
1633 assert(NumResults <= 1 &&
1634 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001635 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001636
Craig Topper306cb122015-11-22 20:46:24 +00001637 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001638 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001639 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001640 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001641
Craig Topper306cb122015-11-22 20:46:24 +00001642 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001643 default: break;
1644 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001645 if (Constraint.VVT.isSimple())
1646 return Constraint.VVT.getSimple().SimpleTy;
1647 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001648 case SDTypeConstraint::SDTCisPtrTy:
1649 return MVT::iPTR;
1650 }
1651 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001652 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001653}
1654
Chris Lattner8cab0212008-01-05 22:25:12 +00001655//===----------------------------------------------------------------------===//
1656// TreePatternNode implementation
1657//
1658
Chris Lattnerf1447252010-03-19 21:37:09 +00001659static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1660 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001661 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001662 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001663
Chris Lattner2109cb42010-03-22 20:56:36 +00001664 if (Operator->isSubClassOf("Intrinsic"))
1665 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001666
Chris Lattnerf1447252010-03-19 21:37:09 +00001667 if (Operator->isSubClassOf("SDNode"))
1668 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001669
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001670 if (Operator->isSubClassOf("PatFrags")) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001671 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1672 // the forward reference case where one pattern fragment references another
1673 // before it is processed.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001674 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
1675 // The number of results of a fragment with alternative records is the
1676 // maximum number of results across all alternatives.
1677 unsigned NumResults = 0;
1678 for (auto T : PFRec->getTrees())
1679 NumResults = std::max(NumResults, T->getNumTypes());
1680 return NumResults;
1681 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001682
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001683 ListInit *LI = Operator->getValueAsListInit("Fragments");
1684 assert(LI && "Invalid Fragment");
1685 unsigned NumResults = 0;
1686 for (Init *I : LI->getValues()) {
1687 Record *Op = nullptr;
1688 if (DagInit *Dag = dyn_cast<DagInit>(I))
1689 if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
1690 Op = DI->getDef();
1691 assert(Op && "Invalid Fragment");
1692 NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
1693 }
1694 return NumResults;
Chris Lattnerf1447252010-03-19 21:37:09 +00001695 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001696
Chris Lattnerf1447252010-03-19 21:37:09 +00001697 if (Operator->isSubClassOf("Instruction")) {
1698 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001699
Craig Topper3a8eb892015-03-20 05:09:06 +00001700 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1701
1702 // Subtract any defaulted outputs.
1703 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1704 Record *OperandNode = InstInfo.Operands[i].Rec;
1705
1706 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1707 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1708 --NumDefsToAdd;
1709 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001710
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001711 // Add on one implicit def if it has a resolvable type.
1712 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1713 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001714 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001715 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001716
Chris Lattnerf1447252010-03-19 21:37:09 +00001717 if (Operator->isSubClassOf("SDNodeXForm"))
1718 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001719
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001720 if (Operator->isSubClassOf("ValueType"))
1721 return 1; // A type-cast of one result.
1722
Tim Northoverc807a172014-05-20 11:52:46 +00001723 if (Operator->isSubClassOf("ComplexPattern"))
1724 return 1;
1725
Matthias Braun8c209aa2017-01-28 02:02:38 +00001726 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001727 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001728}
1729
1730void TreePatternNode::print(raw_ostream &OS) const {
1731 if (isLeaf())
1732 OS << *getLeafValue();
1733 else
1734 OS << '(' << getOperator()->getName();
1735
Zachary Turner249dc142017-09-20 18:01:40 +00001736 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1737 OS << ':';
1738 getExtType(i).writeToStream(OS);
1739 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001740
1741 if (!isLeaf()) {
1742 if (getNumChildren() != 0) {
1743 OS << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001744 getChild(0)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001745 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1746 OS << ", ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001747 getChild(i)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001748 }
1749 }
1750 OS << ")";
1751 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001752
Craig Topper306cb122015-11-22 20:46:24 +00001753 for (const TreePredicateFn &Pred : PredicateFns)
1754 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001755 if (TransformFn)
1756 OS << "<<X:" << TransformFn->getName() << ">>";
1757 if (!getName().empty())
1758 OS << ":$" << getName();
1759
1760}
1761void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001762 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001763}
1764
Scott Michel94420742008-03-05 17:49:05 +00001765/// isIsomorphicTo - Return true if this node is recursively
1766/// isomorphic to the specified node. For this comparison, the node's
1767/// entire state is considered. The assigned name is ignored, since
1768/// nodes with differing names are considered isomorphic. However, if
1769/// the assigned name is present in the dependent variable set, then
1770/// the assigned name is considered significant and the node is
1771/// isomorphic if the names match.
Florian Hahn6b1db822018-06-14 20:32:58 +00001772bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
Scott Michel94420742008-03-05 17:49:05 +00001773 const MultipleUseVarSet &DepVars) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001774 if (N == this) return true;
1775 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1776 getPredicateFns() != N->getPredicateFns() ||
1777 getTransformFn() != N->getTransformFn())
Chris Lattner8cab0212008-01-05 22:25:12 +00001778 return false;
1779
1780 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001781 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001782 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001783 return ((DI->getDef() == NDI->getDef())
1784 && (DepVars.find(getName()) == DepVars.end()
Florian Hahn6b1db822018-06-14 20:32:58 +00001785 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001786 }
1787 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001788 return getLeafValue() == N->getLeafValue();
Chris Lattner8cab0212008-01-05 22:25:12 +00001789 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001790
Florian Hahn6b1db822018-06-14 20:32:58 +00001791 if (N->getOperator() != getOperator() ||
1792 N->getNumChildren() != getNumChildren()) return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001793 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001794 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001795 return false;
1796 return true;
1797}
1798
1799/// clone - Make a copy of this tree and all of its children.
1800///
Florian Hahn75e87c32018-05-30 21:00:18 +00001801TreePatternNodePtr TreePatternNode::clone() const {
1802 TreePatternNodePtr New;
Chris Lattner8cab0212008-01-05 22:25:12 +00001803 if (isLeaf()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001804 New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001805 } else {
Florian Hahn75e87c32018-05-30 21:00:18 +00001806 std::vector<TreePatternNodePtr> CChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00001807 CChildren.reserve(Children.size());
1808 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001809 CChildren.push_back(getChild(i)->clone());
Craig Topper26fc06352018-07-15 06:52:49 +00001810 New = std::make_shared<TreePatternNode>(getOperator(), std::move(CChildren),
Florian Hahn75e87c32018-05-30 21:00:18 +00001811 getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001812 }
1813 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001814 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001815 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001816 New->setTransformFn(getTransformFn());
1817 return New;
1818}
1819
Chris Lattner53c39ba2010-02-14 22:22:58 +00001820/// RemoveAllTypes - Recursively strip all the types of this tree.
1821void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001822 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001823 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001824 if (isLeaf()) return;
1825 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001826 getChild(i)->RemoveAllTypes();
Chris Lattner53c39ba2010-02-14 22:22:58 +00001827}
1828
1829
Chris Lattner8cab0212008-01-05 22:25:12 +00001830/// SubstituteFormalArguments - Replace the formal arguments in this tree
1831/// with actual values specified by ArgMap.
Florian Hahn75e87c32018-05-30 21:00:18 +00001832void TreePatternNode::SubstituteFormalArguments(
1833 std::map<std::string, TreePatternNodePtr> &ArgMap) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001834 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001835
Chris Lattner8cab0212008-01-05 22:25:12 +00001836 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001837 TreePatternNode *Child = getChild(i);
1838 if (Child->isLeaf()) {
1839 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001840 // Note that, when substituting into an output pattern, Val might be an
1841 // UnsetInit.
1842 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1843 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001844 // We found a use of a formal argument, replace it with its value.
Florian Hahn6b1db822018-06-14 20:32:58 +00001845 TreePatternNodePtr NewChild = ArgMap[Child->getName()];
Dan Gohman6e979022008-10-15 06:17:21 +00001846 assert(NewChild && "Couldn't find formal argument!");
Florian Hahn6b1db822018-06-14 20:32:58 +00001847 assert((Child->getPredicateFns().empty() ||
1848 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
Dan Gohman6e979022008-10-15 06:17:21 +00001849 "Non-empty child predicate clobbered!");
Florian Hahn0a2e0b62018-06-14 11:56:19 +00001850 setChild(i, std::move(NewChild));
Chris Lattner8cab0212008-01-05 22:25:12 +00001851 }
1852 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00001853 getChild(i)->SubstituteFormalArguments(ArgMap);
Chris Lattner8cab0212008-01-05 22:25:12 +00001854 }
1855 }
1856}
1857
1858
1859/// InlinePatternFragments - If this pattern refers to any pattern
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001860/// fragments, return the set of inlined versions (this can be more than
1861/// one if a PatFrags record has multiple alternatives).
1862void TreePatternNode::InlinePatternFragments(
1863 TreePatternNodePtr T, TreePattern &TP,
1864 std::vector<TreePatternNodePtr> &OutAlternatives) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001865
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001866 if (TP.hasError())
1867 return;
1868
1869 if (isLeaf()) {
1870 OutAlternatives.push_back(T); // nothing to do.
1871 return;
1872 }
1873
Chris Lattner8cab0212008-01-05 22:25:12 +00001874 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001875
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001876 if (!Op->isSubClassOf("PatFrags")) {
1877 if (getNumChildren() == 0) {
1878 OutAlternatives.push_back(T);
1879 return;
1880 }
1881
1882 // Recursively inline children nodes.
1883 std::vector<std::vector<TreePatternNodePtr> > ChildAlternatives;
1884 ChildAlternatives.resize(getNumChildren());
Dan Gohman6e979022008-10-15 06:17:21 +00001885 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001886 TreePatternNodePtr Child = getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001887 Child->InlinePatternFragments(Child, TP, ChildAlternatives[i]);
1888 // If there are no alternatives for any child, there are no
1889 // alternatives for this expression as whole.
1890 if (ChildAlternatives[i].empty())
1891 return;
Dan Gohman6e979022008-10-15 06:17:21 +00001892
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001893 for (auto NewChild : ChildAlternatives[i])
1894 assert((Child->getPredicateFns().empty() ||
1895 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1896 "Non-empty child predicate clobbered!");
Dan Gohman6e979022008-10-15 06:17:21 +00001897 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001898
1899 // The end result is an all-pairs construction of the resultant pattern.
1900 std::vector<unsigned> Idxs;
1901 Idxs.resize(ChildAlternatives.size());
1902 bool NotDone;
1903 do {
1904 // Create the variant and add it to the output list.
1905 std::vector<TreePatternNodePtr> NewChildren;
1906 for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
1907 NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
1908 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00001909 getOperator(), std::move(NewChildren), getNumTypes());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001910
1911 // Copy over properties.
1912 R->setName(getName());
1913 R->setPredicateFns(getPredicateFns());
1914 R->setTransformFn(getTransformFn());
1915 for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
1916 R->setType(i, getExtType(i));
1917
1918 // Register alternative.
1919 OutAlternatives.push_back(R);
1920
1921 // Increment indices to the next permutation by incrementing the
1922 // indices from last index backward, e.g., generate the sequence
1923 // [0, 0], [0, 1], [1, 0], [1, 1].
1924 int IdxsIdx;
1925 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
1926 if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
1927 Idxs[IdxsIdx] = 0;
1928 else
1929 break;
1930 }
1931 NotDone = (IdxsIdx >= 0);
1932 } while (NotDone);
1933
1934 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00001935 }
1936
1937 // Otherwise, we found a reference to a fragment. First, look up its
1938 // TreePattern record.
1939 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001940
Chris Lattner8cab0212008-01-05 22:25:12 +00001941 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001942 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001943 TP.error("'" + Op->getName() + "' fragment requires " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001944 Twine(Frag->getNumArgs()) + " operands!");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001945 return;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001946 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001947
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001948 // Compute the map of formal to actual arguments.
1949 std::map<std::string, TreePatternNodePtr> ArgMap;
1950 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
1951 const TreePatternNodePtr &Child = getChildShared(i);
1952 ArgMap[Frag->getArgName(i)] = Child;
Chris Lattner8cab0212008-01-05 22:25:12 +00001953 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001954
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001955 // Loop over all fragment alternatives.
1956 for (auto Alternative : Frag->getTrees()) {
1957 TreePatternNodePtr FragTree = Alternative->clone();
Dan Gohman6e979022008-10-15 06:17:21 +00001958
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001959 TreePredicateFn PredFn(Frag);
1960 if (!PredFn.isAlwaysTrue())
1961 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001962
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001963 // Resolve formal arguments to their actual value.
1964 if (Frag->getNumArgs())
1965 FragTree->SubstituteFormalArguments(ArgMap);
1966
1967 // Transfer types. Note that the resolved alternative may have fewer
1968 // (but not more) results than the PatFrags node.
1969 FragTree->setName(getName());
1970 for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
1971 FragTree->UpdateNodeType(i, getExtType(i), TP);
1972
1973 // Transfer in the old predicates.
1974 for (const TreePredicateFn &Pred : getPredicateFns())
1975 FragTree->addPredicateFn(Pred);
1976
1977 // The fragment we inlined could have recursive inlining that is needed. See
1978 // if there are any pattern fragments in it and inline them as needed.
1979 FragTree->InlinePatternFragments(FragTree, TP, OutAlternatives);
1980 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001981}
1982
1983/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001984/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001985/// references from the register file information, for example.
1986///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001987/// When Unnamed is set, return the type of a DAG operand with no name, such as
1988/// the F8RC register class argument in:
1989///
1990/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1991///
1992/// When Unnamed is false, return the type of a named DAG operand such as the
1993/// GPR:$src operand above.
1994///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001995static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
1996 bool NotRegisters,
1997 bool Unnamed,
1998 TreePattern &TP) {
1999 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2000
Owen Andersona84be6c2011-06-27 21:06:21 +00002001 // Check to see if this is a register operand.
2002 if (R->isSubClassOf("RegisterOperand")) {
2003 assert(ResNo == 0 && "Regoperand ref only has one result!");
2004 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002005 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00002006 Record *RegClass = R->getValueAsDef("RegClass");
2007 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002008 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00002009 }
2010
Chris Lattnercabe0372010-03-15 06:00:16 +00002011 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00002012 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002013 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002014 // An unnamed register class represents itself as an i32 immediate, for
2015 // example on a COPY_TO_REGCLASS instruction.
2016 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002017 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002018
2019 // In a named operand, the register class provides the possible set of
2020 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002021 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002022 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00002023 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002024 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00002025 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002026
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002027 if (R->isSubClassOf("PatFrags")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002028 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00002029 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002030 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00002031 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002032
Chris Lattner6070ee22010-03-23 23:50:31 +00002033 if (R->isSubClassOf("Register")) {
2034 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002035 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002036 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002037 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002038 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00002039 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002040
2041 if (R->isSubClassOf("SubRegIndex")) {
2042 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002043 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002044 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002045
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002046 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002047 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002048 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2049 //
2050 // (sext_inreg GPR:$src, i16)
2051 // ~~~
2052 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002053 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002054 // With a name, the ValueType simply provides the type of the named
2055 // variable.
2056 //
2057 // (sext_inreg i32:$src, i16)
2058 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002059 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002060 return TypeSetByHwMode(); // Unknown.
2061 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2062 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002063 }
2064
2065 if (R->isSubClassOf("CondCode")) {
2066 assert(ResNo == 0 && "This node only has one result!");
2067 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002068 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00002069 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002070
Chris Lattner6070ee22010-03-23 23:50:31 +00002071 if (R->isSubClassOf("ComplexPattern")) {
2072 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002073 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002074 return TypeSetByHwMode(); // Unknown.
2075 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00002076 }
2077 if (R->isSubClassOf("PointerLikeRegClass")) {
2078 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002079 TypeSetByHwMode VTS(MVT::iPTR);
2080 TP.getInfer().expandOverloads(VTS);
2081 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00002082 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002083
Chris Lattner6070ee22010-03-23 23:50:31 +00002084 if (R->getName() == "node" || R->getName() == "srcvalue" ||
2085 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002086 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002087 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002088 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002089
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002090 if (R->isSubClassOf("Operand")) {
2091 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2092 Record *T = R->getValueAsDef("Type");
2093 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2094 }
Tim Northoverc807a172014-05-20 11:52:46 +00002095
Chris Lattner8cab0212008-01-05 22:25:12 +00002096 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002097 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00002098}
2099
Chris Lattner89c65662008-01-06 05:36:50 +00002100
2101/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2102/// CodeGenIntrinsic information for it, otherwise return a null pointer.
2103const CodeGenIntrinsic *TreePatternNode::
2104getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2105 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2106 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2107 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00002108 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002109
Florian Hahn6b1db822018-06-14 20:32:58 +00002110 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00002111 return &CDP.getIntrinsicInfo(IID);
2112}
2113
Chris Lattner53c39ba2010-02-14 22:22:58 +00002114/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2115/// return the ComplexPattern information, otherwise return null.
2116const ComplexPattern *
2117TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00002118 Record *Rec;
2119 if (isLeaf()) {
2120 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2121 if (!DI)
2122 return nullptr;
2123 Rec = DI->getDef();
2124 } else
2125 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002126
Tim Northoverc807a172014-05-20 11:52:46 +00002127 if (!Rec->isSubClassOf("ComplexPattern"))
2128 return nullptr;
2129 return &CGP.getComplexPattern(Rec);
2130}
2131
2132unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2133 // A ComplexPattern specifically declares how many results it fills in.
2134 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2135 return CP->getNumOperands();
2136
2137 // If MIOperandInfo is specified, that gives the count.
2138 if (isLeaf()) {
2139 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2140 if (DI && DI->getDef()->isSubClassOf("Operand")) {
2141 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2142 if (MIOps->getNumArgs())
2143 return MIOps->getNumArgs();
2144 }
2145 }
2146
2147 // Otherwise there is just one result.
2148 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00002149}
2150
2151/// NodeHasProperty - Return true if this node has the specified property.
2152bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002153 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002154 if (isLeaf()) {
2155 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2156 return CP->hasProperty(Property);
Matt Arsenault303327d2017-12-20 19:36:28 +00002157
Chris Lattner53c39ba2010-02-14 22:22:58 +00002158 return false;
2159 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002160
Matt Arsenault303327d2017-12-20 19:36:28 +00002161 if (Property != SDNPHasChain) {
2162 // The chain proprety is already present on the different intrinsic node
2163 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2164 // on the intrinsic. Anything else is specific to the individual intrinsic.
2165 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2166 return Int->hasProperty(Property);
2167 }
2168
2169 if (!Operator->isSubClassOf("SDPatternOperator"))
2170 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002171
Chris Lattner53c39ba2010-02-14 22:22:58 +00002172 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2173}
2174
2175
2176
2177
2178/// TreeHasProperty - Return true if any node in this tree has the specified
2179/// property.
2180bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002181 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002182 if (NodeHasProperty(Property, CGP))
2183 return true;
2184 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002185 if (getChild(i)->TreeHasProperty(Property, CGP))
Chris Lattner53c39ba2010-02-14 22:22:58 +00002186 return true;
2187 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002188}
Chris Lattner53c39ba2010-02-14 22:22:58 +00002189
Evan Cheng49bad4c2008-06-16 20:29:38 +00002190/// isCommutativeIntrinsic - Return true if the node corresponds to a
2191/// commutative intrinsic.
2192bool
2193TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2194 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2195 return Int->isCommutative;
2196 return false;
2197}
2198
Florian Hahn6b1db822018-06-14 20:32:58 +00002199static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2200 if (!N->isLeaf())
2201 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00002202
Florian Hahn6b1db822018-06-14 20:32:58 +00002203 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
Matt Arsenaulteb492162014-11-02 23:46:51 +00002204 if (DI && DI->getDef()->isSubClassOf(Class))
2205 return true;
2206
2207 return false;
2208}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002209
2210static void emitTooManyOperandsError(TreePattern &TP,
2211 StringRef InstName,
2212 unsigned Expected,
2213 unsigned Actual) {
2214 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2215 " operands but expected only " + Twine(Expected) + "!");
2216}
2217
2218static void emitTooFewOperandsError(TreePattern &TP,
2219 StringRef InstName,
2220 unsigned Actual) {
2221 TP.error("Instruction '" + InstName +
2222 "' expects more than the provided " + Twine(Actual) + " operands!");
2223}
2224
Bob Wilson1b97f3f2009-01-05 17:23:09 +00002225/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00002226/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002227/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00002228bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002229 if (TP.hasError())
2230 return false;
2231
Chris Lattnerab3242f2008-01-06 01:10:31 +00002232 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00002233 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002234 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002235 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00002236 bool MadeChange = false;
2237 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2238 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002239 NotRegisters,
2240 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002241 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00002242 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002243
Sean Silvafb509ed2012-10-10 20:24:43 +00002244 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002245 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002246
Chris Lattnerf1447252010-03-19 21:37:09 +00002247 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002248 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002249
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002250 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00002251 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002252
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002253 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2254 for (auto &P : VVT) {
2255 MVT::SimpleValueType VT = P.second.SimpleTy;
2256 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2257 continue;
2258 unsigned Size = MVT(VT).getSizeInBits();
2259 // Make sure that the value is representable for this type.
2260 if (Size >= 32)
2261 continue;
2262 // Check that the value doesn't use more bits than we have. It must
2263 // either be a sign- or zero-extended equivalent of the original.
2264 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2265 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2266 SignBitAndAbove == 1)
2267 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002268
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002269 TP.error("Integer value '" + Twine(II->getValue()) +
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002270 "' is out of range for type '" + getEnumName(VT) + "'!");
2271 break;
2272 }
2273 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002274 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002275
Chris Lattner8cab0212008-01-05 22:25:12 +00002276 return false;
2277 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002278
Chris Lattneree820ac2010-02-23 05:51:07 +00002279 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002280 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00002281
Chris Lattner8cab0212008-01-05 22:25:12 +00002282 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00002283 unsigned NumRetVTs = Int->IS.RetVTs.size();
2284 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002285
Bill Wendling91821472008-11-13 09:08:33 +00002286 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00002287 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00002288
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002289 if (getNumChildren() != NumParamVTs + 1) {
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002290 TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2291 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002292 return false;
2293 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002294
2295 // Apply type info to the intrinsic ID.
Florian Hahn6b1db822018-06-14 20:32:58 +00002296 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002297
Chris Lattnerf1447252010-03-19 21:37:09 +00002298 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002299 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002300
Chris Lattnerf1447252010-03-19 21:37:09 +00002301 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
Florian Hahn6b1db822018-06-14 20:32:58 +00002302 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2303 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002304 }
2305 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002306 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002307
Chris Lattneree820ac2010-02-23 05:51:07 +00002308 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002309 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002310
Chris Lattner135091b2010-03-28 08:48:47 +00002311 // Check that the number of operands is sane. Negative operands -> varargs.
2312 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002313 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00002314 TP.error(getOperator()->getName() + " node requires exactly " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002315 Twine(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002316 return false;
2317 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002318
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002319 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00002320 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002321 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2322 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002323 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002324 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002325
Chris Lattneree820ac2010-02-23 05:51:07 +00002326 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002327 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002328 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00002329 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002330
Chris Lattnerd44966f2010-03-27 19:15:02 +00002331 bool MadeChange = false;
2332
2333 // Apply the result types to the node, these come from the things in the
2334 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00002335 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2336 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002337 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2338 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002339
Chris Lattnerd44966f2010-03-27 19:15:02 +00002340 // If the instruction has implicit defs, we apply the first one as a result.
2341 // FIXME: This sucks, it should apply all implicit defs.
2342 if (!InstInfo.ImplicitDefs.empty()) {
2343 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002344
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002345 // FIXME: Generalize to multiple possible types and multiple possible
2346 // ImplicitDefs.
2347 MVT::SimpleValueType VT =
2348 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002349
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002350 if (VT != MVT::Other)
2351 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002352 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002353
Chris Lattnercabe0372010-03-15 06:00:16 +00002354 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2355 // be the same.
2356 if (getOperator()->getName() == "INSERT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00002357 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2358 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2359 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002360 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2361 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2362 // variadic.
2363
2364 unsigned NChild = getNumChildren();
2365 if (NChild < 3) {
2366 TP.error("REG_SEQUENCE requires at least 3 operands!");
2367 return false;
2368 }
2369
2370 if (NChild % 2 == 0) {
2371 TP.error("REG_SEQUENCE requires an odd number of operands!");
2372 return false;
2373 }
2374
2375 if (!isOperandClass(getChild(0), "RegisterClass")) {
2376 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2377 return false;
2378 }
2379
2380 for (unsigned I = 1; I < NChild; I += 2) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002381 TreePatternNode *SubIdxChild = getChild(I + 1);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002382 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2383 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002384 Twine(I + 1) + "!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00002385 return false;
2386 }
2387 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002388 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002389
2390 unsigned ChildNo = 0;
2391 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2392 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002393
Chris Lattner8cab0212008-01-05 22:25:12 +00002394 // If the instruction expects a predicate or optional def operand, we
2395 // codegen this by setting the operand to it's default value if it has a
2396 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00002397 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002398 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2399 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002400
Chris Lattner8cab0212008-01-05 22:25:12 +00002401 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002402 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002403 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002404 return false;
2405 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002406
Florian Hahn6b1db822018-06-14 20:32:58 +00002407 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002408 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002409
2410 // If the operand has sub-operands, they may be provided by distinct
2411 // child patterns, so attempt to match each sub-operand separately.
2412 if (OperandNode->isSubClassOf("Operand")) {
2413 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2414 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2415 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002416 // a single ComplexPattern-related Operand.
2417
2418 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002419 // Match first sub-operand against the child we already have.
2420 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2421 MadeChange |=
2422 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2423
2424 // And the remaining sub-operands against subsequent children.
2425 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2426 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002427 emitTooFewOperandsError(TP, getOperator()->getName(),
2428 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002429 return false;
2430 }
Florian Hahn6b1db822018-06-14 20:32:58 +00002431 Child = getChild(ChildNo++);
Ulrich Weigande618abd2013-03-19 19:51:09 +00002432
2433 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2434 MadeChange |=
2435 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2436 }
2437 continue;
2438 }
2439 }
2440 }
2441
2442 // If we didn't match by pieces above, attempt to match the whole
2443 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002444 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002445 }
Christopher Lamba7312392008-03-11 09:33:47 +00002446
Matt Arsenaulteb492162014-11-02 23:46:51 +00002447 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002448 emitTooManyOperandsError(TP, getOperator()->getName(),
2449 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002450 return false;
2451 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002452
Ulrich Weigande618abd2013-03-19 19:51:09 +00002453 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002454 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002455 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002456 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002457
Tim Northoverc807a172014-05-20 11:52:46 +00002458 if (getOperator()->isSubClassOf("ComplexPattern")) {
2459 bool MadeChange = false;
2460
2461 for (unsigned i = 0; i < getNumChildren(); ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002462 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Tim Northoverc807a172014-05-20 11:52:46 +00002463
2464 return MadeChange;
2465 }
2466
Chris Lattneree820ac2010-02-23 05:51:07 +00002467 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002468
Chris Lattneree820ac2010-02-23 05:51:07 +00002469 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002470 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002471 TP.error("Node transform '" + getOperator()->getName() +
2472 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002473 return false;
2474 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002475
Florian Hahn6b1db822018-06-14 20:32:58 +00002476 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002477 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002478}
2479
2480/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2481/// RHS of a commutative operation, not the on LHS.
Florian Hahn6b1db822018-06-14 20:32:58 +00002482static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2483 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
Chris Lattner8cab0212008-01-05 22:25:12 +00002484 return true;
Florian Hahn6b1db822018-06-14 20:32:58 +00002485 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002486 return true;
2487 return false;
2488}
2489
2490
2491/// canPatternMatch - If it is impossible for this pattern to match on this
2492/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002493/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002494/// that can never possibly work), and to prevent the pattern permuter from
2495/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002496bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002497 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002498 if (isLeaf()) return true;
2499
2500 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002501 if (!getChild(i)->canPatternMatch(Reason, CDP))
Chris Lattner8cab0212008-01-05 22:25:12 +00002502 return false;
2503
2504 // If this is an intrinsic, handle cases that would make it not match. For
2505 // example, if an operand is required to be an immediate.
2506 if (getOperator()->isSubClassOf("Intrinsic")) {
2507 // TODO:
2508 return true;
2509 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002510
Tim Northoverc807a172014-05-20 11:52:46 +00002511 if (getOperator()->isSubClassOf("ComplexPattern"))
2512 return true;
2513
Chris Lattner8cab0212008-01-05 22:25:12 +00002514 // If this node is a commutative operator, check that the LHS isn't an
2515 // immediate.
2516 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002517 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2518 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002519 // Scan all of the operands of the node and make sure that only the last one
2520 // is a constant node, unless the RHS also is.
2521 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002522 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002523 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002524 if (OnlyOnRHSOfCommutative(getChild(i))) {
2525 Reason="Immediate value must be on the RHS of commutative operators!";
2526 return false;
2527 }
2528 }
2529 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002530
Chris Lattner8cab0212008-01-05 22:25:12 +00002531 return true;
2532}
2533
2534//===----------------------------------------------------------------------===//
2535// TreePattern implementation
2536//
2537
David Greeneaf8ee2c2011-07-29 22:43:06 +00002538TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002539 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002540 isInputPattern(isInput), HasError(false),
2541 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002542 for (Init *I : RawPat->getValues())
2543 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002544}
2545
David Greeneaf8ee2c2011-07-29 22:43:06 +00002546TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002547 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002548 isInputPattern(isInput), HasError(false),
2549 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002550 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002551}
2552
Florian Hahn75e87c32018-05-30 21:00:18 +00002553TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
2554 CodeGenDAGPatterns &cdp)
2555 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2556 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002557 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002558}
2559
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002560void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002561 if (HasError)
2562 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002563 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002564 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2565 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002566}
2567
Chris Lattnercabe0372010-03-15 06:00:16 +00002568void TreePattern::ComputeNamedNodes() {
Florian Hahn6b1db822018-06-14 20:32:58 +00002569 for (TreePatternNodePtr &Tree : Trees)
2570 ComputeNamedNodes(Tree.get());
Chris Lattnercabe0372010-03-15 06:00:16 +00002571}
2572
Florian Hahn6b1db822018-06-14 20:32:58 +00002573void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002574 if (!N->getName().empty())
Florian Hahn6b1db822018-06-14 20:32:58 +00002575 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002576
Chris Lattnercabe0372010-03-15 06:00:16 +00002577 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002578 ComputeNamedNodes(N->getChild(i));
Chris Lattnercabe0372010-03-15 06:00:16 +00002579}
2580
Florian Hahn75e87c32018-05-30 21:00:18 +00002581TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
2582 StringRef OpName) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002583 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002584 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002585
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002586 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002587 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002588 /// (foo GPR, imm) -> (foo GPR, (imm))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002589 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
David Greenee32ebf22011-07-29 19:07:07 +00002590 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002591 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002592 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002593 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002594
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002595 // Input argument?
Florian Hahn75e87c32018-05-30 21:00:18 +00002596 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002597 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002598 if (OpName.empty())
2599 error("'node' argument requires a name to match with operand list");
2600 Args.push_back(OpName);
2601 }
2602
2603 Res->setName(OpName);
2604 return Res;
2605 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002606
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002607 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002608 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002609 if (OpName.empty())
2610 error("'?' argument requires a name to match with operand list");
Florian Hahn75e87c32018-05-30 21:00:18 +00002611 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002612 Args.push_back(OpName);
2613 Res->setName(OpName);
2614 return Res;
2615 }
2616
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002617 if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002618 if (!OpName.empty())
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002619 error("Constant int or bit argument should not have a name!");
2620 if (isa<BitInit>(TheInit))
2621 TheInit = TheInit->convertInitializerTo(IntRecTy::get());
2622 return std::make_shared<TreePatternNode>(TheInit, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002623 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002624
Sean Silvafb509ed2012-10-10 20:24:43 +00002625 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002626 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002627 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002628 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002629 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002630 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002631 }
2632
Sean Silvafb509ed2012-10-10 20:24:43 +00002633 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002634 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002635 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002636 error("Pattern has unexpected init kind!");
2637 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002638 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002639 if (!OpDef) error("Pattern has unexpected operator type!");
2640 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002641
Chris Lattner8cab0212008-01-05 22:25:12 +00002642 if (Operator->isSubClassOf("ValueType")) {
2643 // If the operator is a ValueType, then this must be "type cast" of a leaf
2644 // node.
2645 if (Dag->getNumArgs() != 1)
2646 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002647
Florian Hahn75e87c32018-05-30 21:00:18 +00002648 TreePatternNodePtr New =
2649 ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002650
Chris Lattner8cab0212008-01-05 22:25:12 +00002651 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002652 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002653 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2654 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002655
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002656 if (!OpName.empty())
2657 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002658 return New;
2659 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002660
Chris Lattner8cab0212008-01-05 22:25:12 +00002661 // Verify that this is something that makes sense for an operator.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002662 if (!Operator->isSubClassOf("PatFrags") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002663 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002664 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002665 !Operator->isSubClassOf("SDNodeXForm") &&
2666 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002667 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002668 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002669 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002670 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002671
Chris Lattner8cab0212008-01-05 22:25:12 +00002672 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002673 if (isInputPattern) {
2674 if (Operator->isSubClassOf("Instruction") ||
2675 Operator->isSubClassOf("SDNodeXForm"))
2676 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2677 } else {
2678 if (Operator->isSubClassOf("Intrinsic"))
2679 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002680
Chris Lattner2e9eae12010-03-28 06:57:56 +00002681 if (Operator->isSubClassOf("SDNode") &&
2682 Operator->getName() != "imm" &&
2683 Operator->getName() != "fpimm" &&
2684 Operator->getName() != "tglobaltlsaddr" &&
2685 Operator->getName() != "tconstpool" &&
2686 Operator->getName() != "tjumptable" &&
2687 Operator->getName() != "tframeindex" &&
2688 Operator->getName() != "texternalsym" &&
2689 Operator->getName() != "tblockaddress" &&
2690 Operator->getName() != "tglobaladdr" &&
2691 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002692 Operator->getName() != "vt" &&
2693 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002694 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2695 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002696
Florian Hahn75e87c32018-05-30 21:00:18 +00002697 std::vector<TreePatternNodePtr> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002698
2699 // Parse all the operands.
2700 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002701 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002702
Hal Finkel8b4bdfdb2018-01-03 11:35:09 +00002703 // Get the actual number of results before Operator is converted to an intrinsic
2704 // node (which is hard-coded to have either zero or one result).
2705 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2706
Fangrui Song956ee792018-03-30 22:22:31 +00002707 // If the operator is an intrinsic, then this is just syntactic sugar for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002708 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002709 // convert the intrinsic name to a number.
2710 if (Operator->isSubClassOf("Intrinsic")) {
2711 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2712 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2713
2714 // If this intrinsic returns void, it must have side-effects and thus a
2715 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002716 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002717 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002718 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002719 // Has side-effects, requires chain.
2720 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002721 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002722 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002723
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002724 Children.insert(Children.begin(),
2725 std::make_shared<TreePatternNode>(IntInit::get(IID), 1));
Chris Lattner8cab0212008-01-05 22:25:12 +00002726 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002727
Tim Northoverc807a172014-05-20 11:52:46 +00002728 if (Operator->isSubClassOf("ComplexPattern")) {
2729 for (unsigned i = 0; i < Children.size(); ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002730 TreePatternNodePtr Child = Children[i];
Tim Northoverc807a172014-05-20 11:52:46 +00002731
2732 if (Child->getName().empty())
2733 error("All arguments to a ComplexPattern must be named");
2734
2735 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2736 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2737 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2738 auto OperandId = std::make_pair(Operator, i);
2739 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2740 if (PrevOp != ComplexPatternOperands.end()) {
2741 if (PrevOp->getValue() != OperandId)
2742 error("All ComplexPattern operands must appear consistently: "
2743 "in the same order in just one ComplexPattern instance.");
2744 } else
2745 ComplexPatternOperands[Child->getName()] = OperandId;
2746 }
2747 }
2748
Florian Hahn6b1db822018-06-14 20:32:58 +00002749 TreePatternNodePtr Result =
Craig Topper26fc06352018-07-15 06:52:49 +00002750 std::make_shared<TreePatternNode>(Operator, std::move(Children),
2751 NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002752 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002753
Matthias Braun7cf3b112016-12-05 06:00:41 +00002754 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002755 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002756 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002757 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002758 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002759}
2760
Chris Lattnera787c9e2010-03-28 08:38:32 +00002761/// SimplifyTree - See if we can simplify this tree to eliminate something that
2762/// will never match in favor of something obvious that will. This is here
2763/// strictly as a convenience to target authors because it allows them to write
2764/// more type generic things and have useless type casts fold away.
2765///
2766/// This returns true if any change is made.
Florian Hahn75e87c32018-05-30 21:00:18 +00002767static bool SimplifyTree(TreePatternNodePtr &N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002768 if (N->isLeaf())
2769 return false;
2770
2771 // If we have a bitconvert with a resolved type and if the source and
2772 // destination types are the same, then the bitconvert is useless, remove it.
2773 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002774 N->getExtType(0).isValueTypeByHwMode(false) &&
Florian Hahn6b1db822018-06-14 20:32:58 +00002775 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002776 N->getName().empty()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002777 N = N->getChildShared(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002778 SimplifyTree(N);
2779 return true;
2780 }
2781
2782 // Walk all children.
2783 bool MadeChange = false;
2784 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002785 TreePatternNodePtr Child = N->getChildShared(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002786 MadeChange |= SimplifyTree(Child);
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002787 N->setChild(i, std::move(Child));
Chris Lattnera787c9e2010-03-28 08:38:32 +00002788 }
2789 return MadeChange;
2790}
2791
2792
2793
Chris Lattner8cab0212008-01-05 22:25:12 +00002794/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002795/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002796/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002797bool TreePattern::
2798InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2799 if (NamedNodes.empty())
2800 ComputeNamedNodes();
2801
Chris Lattner8cab0212008-01-05 22:25:12 +00002802 bool MadeChange = true;
2803 while (MadeChange) {
2804 MadeChange = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002805 for (TreePatternNodePtr &Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002806 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2807 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002808 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002809
2810 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002811 for (auto &Entry : NamedNodes) {
2812 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002813
Chris Lattnercabe0372010-03-15 06:00:16 +00002814 // If we have input named node types, propagate their types to the named
2815 // values here.
2816 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002817 if (!InNamedTypes->count(Entry.getKey())) {
2818 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002819 "' in output pattern but not input pattern");
2820 return true;
2821 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002822
2823 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002824 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002825
2826 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002827 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002828 // If this node is a register class, and it is the root of the pattern
2829 // then we're mapping something onto an input register. We allow
2830 // changing the type of the input register in this case. This allows
2831 // us to match things like:
2832 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Florian Hahn75e87c32018-05-30 21:00:18 +00002833 if (Node == Trees[0].get() && Node->isLeaf()) {
Craig Topper306cb122015-11-22 20:46:24 +00002834 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002835 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2836 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002837 continue;
2838 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002839
Craig Topper306cb122015-11-22 20:46:24 +00002840 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002841 InNodes[0]->getNumTypes() == 1 &&
2842 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002843 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2844 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002845 }
2846 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002847
Chris Lattnercabe0372010-03-15 06:00:16 +00002848 // If there are multiple nodes with the same name, they must all have the
2849 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002850 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002851 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002852 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002853 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002854 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002855
Chris Lattnerf1447252010-03-19 21:37:09 +00002856 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2857 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002858 }
2859 }
2860 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002861 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002862
Chris Lattner8cab0212008-01-05 22:25:12 +00002863 bool HasUnresolvedTypes = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002864 for (const TreePatternNodePtr &Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002865 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002866 return !HasUnresolvedTypes;
2867}
2868
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002869void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002870 OS << getRecord()->getName();
2871 if (!Args.empty()) {
2872 OS << "(" << Args[0];
2873 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2874 OS << ", " << Args[i];
2875 OS << ")";
2876 }
2877 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002878
Chris Lattner8cab0212008-01-05 22:25:12 +00002879 if (Trees.size() > 1)
2880 OS << "[\n";
Florian Hahn75e87c32018-05-30 21:00:18 +00002881 for (const TreePatternNodePtr &Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002882 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002883 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002884 OS << "\n";
2885 }
2886
2887 if (Trees.size() > 1)
2888 OS << "]\n";
2889}
2890
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002891void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002892
2893//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002894// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002895//
2896
Daniel Sanders7e523672017-11-11 03:23:44 +00002897CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
2898 PatternRewriterFn PatternRewriter)
2899 : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
2900 PatternRewriter(PatternRewriter) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002901
Justin Bogner92a8c612016-07-15 16:31:37 +00002902 Intrinsics = CodeGenIntrinsicTable(Records, false);
2903 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002904 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002905 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002906 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002907 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002908 ParseDefaultOperands();
2909 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002910 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002911 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002912
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002913 // Break patterns with parameterized types into a series of patterns,
2914 // where each one has a fixed type and is predicated on the conditions
2915 // of the associated HW mode.
2916 ExpandHwModeBasedTypes();
2917
Chris Lattner8cab0212008-01-05 22:25:12 +00002918 // Generate variants. For example, commutative patterns can match
2919 // multiple ways. Add them to PatternsToMatch as well.
2920 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002921
2922 // Infer instruction flags. For example, we can detect loads,
2923 // stores, and side effects in many cases by examining an
2924 // instruction's pattern.
2925 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002926
2927 // Verify that instruction flags match the patterns.
2928 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002929}
2930
Daniel Sanders9e0ae7b2017-10-13 19:00:01 +00002931Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002932 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002933 if (!N || !N->isSubClassOf("SDNode"))
2934 PrintFatalError("Error getting SDNode '" + Name + "'!");
2935
Chris Lattner8cab0212008-01-05 22:25:12 +00002936 return N;
2937}
2938
2939// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002940void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002941 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002942 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2943
Chris Lattner8cab0212008-01-05 22:25:12 +00002944 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002945 Record *R = Nodes.back();
2946 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002947 Nodes.pop_back();
2948 }
2949
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002950 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002951 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2952 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2953 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2954}
2955
2956/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2957/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002958void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002959 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2960 while (!Xforms.empty()) {
2961 Record *XFormNode = Xforms.back();
2962 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00002963 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002964 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002965
2966 Xforms.pop_back();
2967 }
2968}
2969
Chris Lattnerab3242f2008-01-06 01:10:31 +00002970void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002971 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2972 while (!AMs.empty()) {
2973 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2974 AMs.pop_back();
2975 }
2976}
2977
2978
2979/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2980/// file, building up the PatternFragments map. After we've collected them all,
2981/// inline fragments together as necessary, so that there are no references left
2982/// inside a pattern fragment to a pattern fragment.
2983///
Hal Finkel2756dc12014-02-28 00:26:56 +00002984void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002985 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrags");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002986
Chris Lattnere7170df2008-01-05 22:43:57 +00002987 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002988 for (Record *Frag : Fragments) {
2989 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002990 continue;
2991
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002992 ListInit *LI = Frag->getValueAsListInit("Fragments");
Hal Finkel2756dc12014-02-28 00:26:56 +00002993 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002994 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002995 Frag, LI, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002996 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002997
Chris Lattnere7170df2008-01-05 22:43:57 +00002998 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002999 std::vector<std::string> &Args = P->getArgList();
Zachary Turner249dc142017-09-20 18:01:40 +00003000 // Copy the args so we can take StringRefs to them.
3001 auto ArgsCopy = Args;
3002 SmallDenseSet<StringRef, 4> OperandsSet;
3003 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003004
Chris Lattnere7170df2008-01-05 22:43:57 +00003005 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00003006 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003007
Chris Lattner8cab0212008-01-05 22:25:12 +00003008 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00003009 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00003010 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00003011 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003012 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00003013 if (!OpsOp ||
3014 (OpsOp->getDef()->getName() != "ops" &&
3015 OpsOp->getDef()->getName() != "outs" &&
3016 OpsOp->getDef()->getName() != "ins"))
3017 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003018
3019 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00003020 Args.clear();
3021 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003022 if (!isa<DefInit>(OpsList->getArg(j)) ||
3023 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00003024 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00003025 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00003026 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00003027 StringRef ArgNameStr = OpsList->getArgNameStr(j);
3028 if (!OperandsSet.count(ArgNameStr))
3029 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00003030 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00003031 OperandsSet.erase(ArgNameStr);
3032 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003033 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003034
Chris Lattnere7170df2008-01-05 22:43:57 +00003035 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003036 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00003037 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003038
Chris Lattnere7170df2008-01-05 22:43:57 +00003039 // If there is a code init for this fragment, keep track of the fact that
3040 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00003041 TreePredicateFn PredFn(P);
3042 if (!PredFn.isAlwaysTrue())
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003043 for (auto T : P->getTrees())
3044 T->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003045
Chris Lattner8cab0212008-01-05 22:25:12 +00003046 // If there is a node transformation corresponding to this, keep track of
3047 // it.
Craig Topper306cb122015-11-22 20:46:24 +00003048 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00003049 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003050 for (auto T : P->getTrees())
3051 T->setTransformFn(Transform);
Chris Lattner8cab0212008-01-05 22:25:12 +00003052 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003053
Chris Lattner8cab0212008-01-05 22:25:12 +00003054 // Now that we've parsed all of the tree fragments, do a closure on them so
3055 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00003056 for (Record *Frag : Fragments) {
3057 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00003058 continue;
3059
Craig Topper306cb122015-11-22 20:46:24 +00003060 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00003061 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003062
Chris Lattner8cab0212008-01-05 22:25:12 +00003063 // Infer as many types as possible. Don't worry about it if we don't infer
Ulrich Weigand22b1af82018-07-13 16:42:15 +00003064 // all of them, some may depend on the inputs of the pattern. Also, don't
3065 // validate type sets; validation may cause spurious failures e.g. if a
3066 // fragment needs floating-point types but the current target does not have
3067 // any (this is only an error if that fragment is ever used!).
3068 {
3069 TypeInfer::SuppressValidation SV(ThePat.getInfer());
3070 ThePat.InferAllTypes();
3071 ThePat.resetError();
3072 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003073
Chris Lattner8cab0212008-01-05 22:25:12 +00003074 // If debugging, print out the pattern fragment result.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003075 LLVM_DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003076 }
3077}
3078
Chris Lattnerab3242f2008-01-06 01:10:31 +00003079void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00003080 std::vector<Record*> DefaultOps;
3081 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00003082
3083 // Find some SDNode.
3084 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00003085 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003086
Tom Stellardb7246a72012-09-06 14:15:52 +00003087 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3088 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003089
Tom Stellardb7246a72012-09-06 14:15:52 +00003090 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3091 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00003092 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00003093 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3094 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3095 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00003096 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003097
Tom Stellardb7246a72012-09-06 14:15:52 +00003098 // Create a TreePattern to parse this.
3099 TreePattern P(DefaultOps[i], DI, false, *this);
3100 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003101
Tom Stellardb7246a72012-09-06 14:15:52 +00003102 // Copy the operands over into a DAGDefaultOperand.
3103 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003104
Florian Hahn75e87c32018-05-30 21:00:18 +00003105 const TreePatternNodePtr &T = P.getTree(0);
Tom Stellardb7246a72012-09-06 14:15:52 +00003106 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
Florian Hahn75e87c32018-05-30 21:00:18 +00003107 TreePatternNodePtr TPN = T->getChildShared(op);
Tom Stellardb7246a72012-09-06 14:15:52 +00003108 while (TPN->ApplyTypeConstraints(P, false))
3109 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003110
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003111 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00003112 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3113 DefaultOps[i]->getName() +
3114 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003115 }
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003116 DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
Chris Lattner8cab0212008-01-05 22:25:12 +00003117 }
Tom Stellardb7246a72012-09-06 14:15:52 +00003118
3119 // Insert it into the DefaultOperands map so we can find it later.
3120 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00003121 }
3122}
3123
3124/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3125/// instruction input. Return true if this is a real use.
David Blaikie19b22d42018-06-11 22:14:43 +00003126static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003127 std::map<std::string, TreePatternNodePtr> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003128 // No name -> not interesting.
3129 if (Pat->getName().empty()) {
3130 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003131 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00003132 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3133 DI->getDef()->isSubClassOf("RegisterOperand")))
David Blaikie19b22d42018-06-11 22:14:43 +00003134 I.error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003135 }
3136 return false;
3137 }
3138
3139 Record *Rec;
3140 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003141 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
David Blaikie19b22d42018-06-11 22:14:43 +00003142 if (!DI)
3143 I.error("Input $" + Pat->getName() + " must be an identifier!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003144 Rec = DI->getDef();
3145 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00003146 Rec = Pat->getOperator();
3147 }
3148
3149 // SRCVALUE nodes are ignored.
3150 if (Rec->getName() == "srcvalue")
3151 return false;
3152
Florian Hahn75e87c32018-05-30 21:00:18 +00003153 TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
Chris Lattner8cab0212008-01-05 22:25:12 +00003154 if (!Slot) {
3155 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003156 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00003157 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003158 Record *SlotRec;
3159 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003160 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003161 } else {
3162 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3163 SlotRec = Slot->getOperator();
3164 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003165
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003166 // Ensure that the inputs agree if we've already seen this input.
3167 if (Rec != SlotRec)
David Blaikie19b22d42018-06-11 22:14:43 +00003168 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003169 // Ensure that the types can agree as well.
3170 Slot->UpdateNodeType(0, Pat->getExtType(0), I);
3171 Pat->UpdateNodeType(0, Slot->getExtType(0), I);
Chris Lattnerf1447252010-03-19 21:37:09 +00003172 if (Slot->getExtTypes() != Pat->getExtTypes())
David Blaikie19b22d42018-06-11 22:14:43 +00003173 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00003174 return true;
3175}
3176
3177/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3178/// part of "I", the instruction), computing the set of inputs and outputs of
3179/// the pattern. Report errors if we see anything naughty.
Florian Hahn75e87c32018-05-30 21:00:18 +00003180void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
Florian Hahn6b1db822018-06-14 20:32:58 +00003181 TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003182 std::map<std::string, TreePatternNodePtr> &InstInputs,
3183 std::map<std::string, TreePatternNodePtr> &InstResults,
3184 std::vector<Record *> &InstImpResults) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003185
3186 // The instruction pattern still has unresolved fragments. For *named*
3187 // nodes we must resolve those here. This may not result in multiple
3188 // alternatives.
3189 if (!Pat->getName().empty()) {
3190 TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3191 SrcPattern.InlinePatternFragments();
3192 SrcPattern.InferAllTypes();
3193 Pat = SrcPattern.getOnlyTree();
3194 }
3195
Chris Lattner8cab0212008-01-05 22:25:12 +00003196 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00003197 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00003198 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003199 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003200 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003201 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003202
Chris Lattnerf2d70992010-02-17 06:53:36 +00003203 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003204 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003205 TreePatternNode *Dest = Pat->getChild(i);
3206 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003207 I.error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003208
Florian Hahn6b1db822018-06-14 20:32:58 +00003209 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00003210 if (!Val || !Val->getDef()->isSubClassOf("Register"))
David Blaikie19b22d42018-06-11 22:14:43 +00003211 I.error("implicitly defined value should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003212 InstImpResults.push_back(Val->getDef());
3213 }
3214 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003215 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003216
Chris Lattnerf2d70992010-02-17 06:53:36 +00003217 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003218 // If this is not a set, verify that the children nodes are not void typed,
3219 // and recurse.
3220 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003221 if (Pat->getChild(i)->getNumTypes() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003222 I.error("Cannot have void nodes inside of patterns!");
Florian Hahn75e87c32018-05-30 21:00:18 +00003223 FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3224 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003225 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003226
Chris Lattner8cab0212008-01-05 22:25:12 +00003227 // If this is a non-leaf node with no children, treat it basically as if
3228 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00003229 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003230
Chris Lattner8cab0212008-01-05 22:25:12 +00003231 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003232 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003233 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003234 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003235
Chris Lattner8cab0212008-01-05 22:25:12 +00003236 // Otherwise, this is a set, validate and collect instruction results.
3237 if (Pat->getNumChildren() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003238 I.error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003239
Chris Lattner8cab0212008-01-05 22:25:12 +00003240 if (Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003241 I.error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003242
Chris Lattner8cab0212008-01-05 22:25:12 +00003243 // Check the set destinations.
3244 unsigned NumDests = Pat->getNumChildren()-1;
3245 for (unsigned i = 0; i != NumDests; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003246 TreePatternNodePtr Dest = Pat->getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003247 // For set destinations we also must resolve fragments here.
3248 TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3249 DestPattern.InlinePatternFragments();
3250 DestPattern.InferAllTypes();
3251 Dest = DestPattern.getOnlyTree();
3252
Chris Lattner8cab0212008-01-05 22:25:12 +00003253 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003254 I.error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003255
Sean Silvafb509ed2012-10-10 20:24:43 +00003256 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00003257 if (!Val) {
David Blaikie19b22d42018-06-11 22:14:43 +00003258 I.error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00003259 continue;
3260 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003261
3262 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003263 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00003264 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00003265 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003266 if (Dest->getName().empty())
David Blaikie19b22d42018-06-11 22:14:43 +00003267 I.error("set destination must have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003268 if (InstResults.count(Dest->getName()))
David Blaikie19b22d42018-06-11 22:14:43 +00003269 I.error("cannot set '" + Dest->getName() + "' multiple times");
Chris Lattner8cab0212008-01-05 22:25:12 +00003270 InstResults[Dest->getName()] = Dest;
3271 } else if (Val->getDef()->isSubClassOf("Register")) {
3272 InstImpResults.push_back(Val->getDef());
3273 } else {
David Blaikie19b22d42018-06-11 22:14:43 +00003274 I.error("set destination should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003275 }
3276 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003277
Chris Lattner8cab0212008-01-05 22:25:12 +00003278 // Verify and collect info from the computation.
Florian Hahn75e87c32018-05-30 21:00:18 +00003279 FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3280 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003281}
3282
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003283//===----------------------------------------------------------------------===//
3284// Instruction Analysis
3285//===----------------------------------------------------------------------===//
3286
3287class InstAnalyzer {
3288 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003289public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003290 bool hasSideEffects;
3291 bool mayStore;
3292 bool mayLoad;
3293 bool isBitcast;
3294 bool isVariadic;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003295 bool hasChain;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003296
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003297 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3298 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003299 isBitcast(false), isVariadic(false), hasChain(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003300
Craig Topper2a053a92017-06-20 16:34:37 +00003301 void Analyze(const PatternToMatch &Pat) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003302 const TreePatternNode *N = Pat.getSrcPattern();
3303 AnalyzeNode(N);
3304 // These properties are detected only on the root node.
3305 isBitcast = IsNodeBitcast(N);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003306 }
3307
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003308private:
Florian Hahn6b1db822018-06-14 20:32:58 +00003309 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003310 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00003311 return false;
3312
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003313 if (N->isLeaf())
3314 return false;
3315 if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
Evan Cheng880e299d2011-03-15 05:09:26 +00003316 return false;
3317
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003318 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
Evan Cheng880e299d2011-03-15 05:09:26 +00003319 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3320 return false;
3321 return OpInfo.getEnumName() == "ISD::BITCAST";
3322 }
3323
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003324public:
Florian Hahn6b1db822018-06-14 20:32:58 +00003325 void AnalyzeNode(const TreePatternNode *N) {
3326 if (N->isLeaf()) {
3327 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003328 Record *LeafRec = DI->getDef();
3329 // Handle ComplexPattern leaves.
3330 if (LeafRec->isSubClassOf("ComplexPattern")) {
3331 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3332 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3333 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003334 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003335 }
3336 }
3337 return;
3338 }
3339
3340 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00003341 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3342 AnalyzeNode(N->getChild(i));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003343
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003344 // Notice properties of the node.
Florian Hahn6b1db822018-06-14 20:32:58 +00003345 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3346 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3347 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3348 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003349 if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003350
Florian Hahn6b1db822018-06-14 20:32:58 +00003351 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003352 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003353 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003354 mayLoad = true;// These may load memory.
3355
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003356 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003357 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3358
Matt Arsenault868af922017-04-28 21:01:46 +00003359 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3360 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003361 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003362 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003363 }
3364 }
3365
3366};
3367
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003368static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003369 const InstAnalyzer &PatInfo,
3370 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003371 bool Error = false;
3372
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003373 // Remember where InstInfo got its flags.
3374 if (InstInfo.hasUndefFlags())
3375 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003376
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003377 // Check explicitly set flags for consistency.
3378 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3379 !InstInfo.hasSideEffects_Unset) {
3380 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3381 // the pattern has no side effects. That could be useful for div/rem
3382 // instructions that may trap.
3383 if (!InstInfo.hasSideEffects) {
3384 Error = true;
3385 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3386 Twine(InstInfo.hasSideEffects));
3387 }
3388 }
3389
3390 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3391 Error = true;
3392 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3393 Twine(InstInfo.mayStore));
3394 }
3395
3396 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3397 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003398 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003399 if (!InstInfo.mayLoad) {
3400 Error = true;
3401 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3402 Twine(InstInfo.mayLoad));
3403 }
3404 }
3405
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003406 // Transfer inferred flags.
3407 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3408 InstInfo.mayStore |= PatInfo.mayStore;
3409 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003410
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003411 // These flags are silently added without any verification.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003412 // FIXME: To match historical behavior of TableGen, for now add those flags
3413 // only when we're inferring from the primary instruction pattern.
3414 if (PatDef->isSubClassOf("Instruction")) {
3415 InstInfo.isBitcast |= PatInfo.isBitcast;
3416 InstInfo.hasChain |= PatInfo.hasChain;
3417 InstInfo.hasChain_Inferred = true;
3418 }
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003419
3420 // Don't infer isVariadic. This flag means something different on SDNodes and
3421 // instructions. For example, a CALL SDNode is variadic because it has the
3422 // call arguments as operands, but a CALL instruction is not variadic - it
3423 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003424
3425 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003426}
3427
Jim Grosbach514410b2012-07-17 00:47:06 +00003428/// hasNullFragReference - Return true if the DAG has any reference to the
3429/// null_frag operator.
3430static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003431 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003432 if (!OpDef) return false;
3433 Record *Operator = OpDef->getDef();
3434
3435 // If this is the null fragment, return true.
3436 if (Operator->getName() == "null_frag") return true;
3437 // If any of the arguments reference the null fragment, return true.
3438 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003439 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003440 if (Arg && hasNullFragReference(Arg))
3441 return true;
3442 }
3443
3444 return false;
3445}
3446
3447/// hasNullFragReference - Return true if any DAG in the list references
3448/// the null_frag operator.
3449static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003450 for (Init *I : LI->getValues()) {
3451 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003452 assert(DI && "non-dag in an instruction Pattern list?!");
3453 if (hasNullFragReference(DI))
3454 return true;
3455 }
3456 return false;
3457}
3458
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003459/// Get all the instructions in a tree.
3460static void
Florian Hahn6b1db822018-06-14 20:32:58 +00003461getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3462 if (Tree->isLeaf())
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003463 return;
Florian Hahn6b1db822018-06-14 20:32:58 +00003464 if (Tree->getOperator()->isSubClassOf("Instruction"))
3465 Instrs.push_back(Tree->getOperator());
3466 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3467 getInstructionsInTree(Tree->getChild(i), Instrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003468}
3469
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003470/// Check the class of a pattern leaf node against the instruction operand it
3471/// represents.
3472static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3473 Record *Leaf) {
3474 if (OI.Rec == Leaf)
3475 return true;
3476
3477 // Allow direct value types to be used in instruction set patterns.
3478 // The type will be checked later.
3479 if (Leaf->isSubClassOf("ValueType"))
3480 return true;
3481
3482 // Patterns can also be ComplexPattern instances.
3483 if (Leaf->isSubClassOf("ComplexPattern"))
3484 return true;
3485
3486 return false;
3487}
3488
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003489void CodeGenDAGPatterns::parseInstructionPattern(
Ahmed Bougacha14107512013-10-28 18:07:21 +00003490 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003491
Craig Topper0d1fb902015-03-10 03:25:04 +00003492 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003493
Craig Topper0d1fb902015-03-10 03:25:04 +00003494 // Parse the instruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003495 TreePattern I(CGI.TheDef, Pat, true, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003496
Craig Topper0d1fb902015-03-10 03:25:04 +00003497 // InstInputs - Keep track of all of the inputs of the instruction, along
3498 // with the record they are declared as.
Florian Hahn75e87c32018-05-30 21:00:18 +00003499 std::map<std::string, TreePatternNodePtr> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003500
Craig Topper0d1fb902015-03-10 03:25:04 +00003501 // InstResults - Keep track of all the virtual registers that are 'set'
3502 // in the instruction, including what reg class they are.
Florian Hahn75e87c32018-05-30 21:00:18 +00003503 std::map<std::string, TreePatternNodePtr> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003504
Craig Topper0d1fb902015-03-10 03:25:04 +00003505 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003506
Craig Topper0d1fb902015-03-10 03:25:04 +00003507 // Verify that the top-level forms in the instruction are of void type, and
3508 // fill in the InstResults map.
Zachary Turner249dc142017-09-20 18:01:40 +00003509 SmallString<32> TypesString;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003510 for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
Zachary Turner249dc142017-09-20 18:01:40 +00003511 TypesString.clear();
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003512 TreePatternNodePtr Pat = I.getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003513 if (Pat->getNumTypes() != 0) {
Zachary Turner249dc142017-09-20 18:01:40 +00003514 raw_svector_ostream OS(TypesString);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003515 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3516 if (k > 0)
Zachary Turner249dc142017-09-20 18:01:40 +00003517 OS << ", ";
3518 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003519 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003520 I.error("Top-level forms in instruction pattern should have"
Zachary Turner249dc142017-09-20 18:01:40 +00003521 " void types, has types " +
3522 OS.str());
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003523 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003524
Craig Topper0d1fb902015-03-10 03:25:04 +00003525 // Find inputs and outputs, and verify the structure of the uses/defs.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003526 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Craig Topper0d1fb902015-03-10 03:25:04 +00003527 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003528 }
3529
Craig Topper0d1fb902015-03-10 03:25:04 +00003530 // Now that we have inputs and outputs of the pattern, inspect the operands
3531 // list for the instruction. This determines the order that operands are
3532 // added to the machine instruction the node corresponds to.
3533 unsigned NumResults = InstResults.size();
3534
3535 // Parse the operands list from the (ops) list, validating it.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003536 assert(I.getArgList().empty() && "Args list should still be empty here!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003537
3538 // Check that all of the results occur first in the list.
3539 std::vector<Record*> Results;
Florian Hahn75e87c32018-05-30 21:00:18 +00003540 SmallVector<TreePatternNodePtr, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003541 for (unsigned i = 0; i != NumResults; ++i) {
3542 if (i == CGI.Operands.size())
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003543 I.error("'" + InstResults.begin()->first +
Craig Topper0d1fb902015-03-10 03:25:04 +00003544 "' set but does not appear in operand list!");
3545 const std::string &OpName = CGI.Operands[i].Name;
3546
3547 // Check that it exists in InstResults.
Florian Hahn75e87c32018-05-30 21:00:18 +00003548 TreePatternNodePtr RNode = InstResults[OpName];
Craig Topper0d1fb902015-03-10 03:25:04 +00003549 if (!RNode)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003550 I.error("Operand $" + OpName + " does not exist in operand list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003551
Craig Topper3a8eb892015-03-20 05:09:06 +00003552
Craig Topper0d1fb902015-03-10 03:25:04 +00003553 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003554 ResNodes.push_back(std::move(RNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003555 if (!R)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003556 I.error("Operand $" + OpName + " should be a set destination: all "
Craig Topper0d1fb902015-03-10 03:25:04 +00003557 "outputs must occur before inputs in operand list!");
3558
3559 if (!checkOperandClass(CGI.Operands[i], R))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003560 I.error("Operand $" + OpName + " class mismatch!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003561
3562 // Remember the return type.
3563 Results.push_back(CGI.Operands[i].Rec);
3564
3565 // Okay, this one checks out.
3566 InstResults.erase(OpName);
3567 }
3568
Craig Topper765b9202018-07-15 06:52:48 +00003569 // Loop over the inputs next.
Florian Hahn75e87c32018-05-30 21:00:18 +00003570 std::vector<TreePatternNodePtr> ResultNodeOperands;
Craig Topper0d1fb902015-03-10 03:25:04 +00003571 std::vector<Record*> Operands;
3572 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3573 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3574 const std::string &OpName = Op.Name;
3575 if (OpName.empty())
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003576 I.error("Operand #" + Twine(i) + " in operands list has no name!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003577
Craig Topper765b9202018-07-15 06:52:48 +00003578 if (!InstInputs.count(OpName)) {
Craig Topper0d1fb902015-03-10 03:25:04 +00003579 // If this is an operand with a DefaultOps set filled in, we can ignore
3580 // this. When we codegen it, we will do so as always executed.
3581 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3582 // Does it have a non-empty DefaultOps field? If so, ignore this
3583 // operand.
3584 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3585 continue;
3586 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003587 I.error("Operand $" + OpName +
Craig Topper0d1fb902015-03-10 03:25:04 +00003588 " does not appear in the instruction pattern");
3589 }
Craig Topper765b9202018-07-15 06:52:48 +00003590 TreePatternNodePtr InVal = InstInputs[OpName];
3591 InstInputs.erase(OpName); // It occurred, remove from map.
Craig Topper0d1fb902015-03-10 03:25:04 +00003592
3593 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3594 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3595 if (!checkOperandClass(Op, InRec))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003596 I.error("Operand $" + OpName + "'s register class disagrees"
Craig Topper0d1fb902015-03-10 03:25:04 +00003597 " between the operand and pattern");
3598 }
3599 Operands.push_back(Op.Rec);
3600
3601 // Construct the result for the dest-pattern operand list.
Florian Hahn75e87c32018-05-30 21:00:18 +00003602 TreePatternNodePtr OpNode = InVal->clone();
Craig Topper0d1fb902015-03-10 03:25:04 +00003603
3604 // No predicate is useful on the result.
3605 OpNode->clearPredicateFns();
3606
3607 // Promote the xform function to be an explicit node if set.
3608 if (Record *Xform = OpNode->getTransformFn()) {
3609 OpNode->setTransformFn(nullptr);
Florian Hahn75e87c32018-05-30 21:00:18 +00003610 std::vector<TreePatternNodePtr> Children;
Craig Topper0d1fb902015-03-10 03:25:04 +00003611 Children.push_back(OpNode);
Craig Topper26fc06352018-07-15 06:52:49 +00003612 OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
Florian Hahn6b1db822018-06-14 20:32:58 +00003613 OpNode->getNumTypes());
Craig Topper0d1fb902015-03-10 03:25:04 +00003614 }
3615
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003616 ResultNodeOperands.push_back(std::move(OpNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003617 }
3618
Craig Topper765b9202018-07-15 06:52:48 +00003619 if (!InstInputs.empty())
3620 I.error("Input operand $" + InstInputs.begin()->first +
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003621 " occurs in pattern but not in operands list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003622
Florian Hahn6b1db822018-06-14 20:32:58 +00003623 TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00003624 I.getRecord(), std::move(ResultNodeOperands),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003625 GetNumNodeResults(I.getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003626 // Copy fully inferred output node types to instruction result pattern.
3627 for (unsigned i = 0; i != NumResults; ++i) {
3628 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3629 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3630 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003631
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003632 // FIXME: Assume only the first tree is the pattern. The others are clobber
3633 // nodes.
3634 TreePatternNodePtr Pattern = I.getTree(0);
3635 TreePatternNodePtr SrcPattern;
3636 if (Pattern->getOperator()->getName() == "set") {
3637 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3638 } else{
3639 // Not a set (store or something?)
3640 SrcPattern = Pattern;
3641 }
3642
Craig Topper0d1fb902015-03-10 03:25:04 +00003643 // Create and insert the instruction.
3644 // FIXME: InstImpResults should not be part of DAGInstruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003645 Record *R = I.getRecord();
3646 DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
3647 std::forward_as_tuple(Results, Operands, InstImpResults,
3648 SrcPattern, ResultPattern));
Craig Topper0d1fb902015-03-10 03:25:04 +00003649
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003650 LLVM_DEBUG(I.dump());
Craig Topper0d1fb902015-03-10 03:25:04 +00003651}
3652
Ahmed Bougacha14107512013-10-28 18:07:21 +00003653/// ParseInstructions - Parse all of the instructions, inlining and resolving
3654/// any fragments involved. This populates the Instructions list with fully
3655/// resolved instructions.
3656void CodeGenDAGPatterns::ParseInstructions() {
3657 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3658
Craig Topper306cb122015-11-22 20:46:24 +00003659 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003660 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003661
Craig Topper306cb122015-11-22 20:46:24 +00003662 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3663 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003664
3665 // If there is no pattern, only collect minimal information about the
3666 // instruction for its operand list. We have to assume that there is one
3667 // result, as we have no detailed info. A pattern which references the
3668 // null_frag operator is as-if no pattern were specified. Normally this
3669 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3670 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003671 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003672 std::vector<Record*> Results;
3673 std::vector<Record*> Operands;
3674
Craig Topper306cb122015-11-22 20:46:24 +00003675 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003676
3677 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003678 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3679 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003680
Craig Topper3a8eb892015-03-20 05:09:06 +00003681 // The rest are inputs.
3682 for (unsigned j = InstInfo.Operands.NumDefs,
3683 e = InstInfo.Operands.size(); j < e; ++j)
3684 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003685 }
3686
3687 // Create and insert the instruction.
3688 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003689 Instructions.insert(std::make_pair(Instr,
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003690 DAGInstruction(Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003691 continue; // no pattern.
3692 }
3693
Craig Topper306cb122015-11-22 20:46:24 +00003694 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003695 parseInstructionPattern(CGI, LI, Instructions);
Chris Lattner8cab0212008-01-05 22:25:12 +00003696 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003697
Chris Lattner8cab0212008-01-05 22:25:12 +00003698 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003699 for (auto &Entry : Instructions) {
Craig Topper306cb122015-11-22 20:46:24 +00003700 Record *Instr = Entry.first;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003701 DAGInstruction &TheInst = Entry.second;
3702 TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
3703 TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
3704
3705 if (SrcPattern && ResultPattern) {
3706 TreePattern Pattern(Instr, SrcPattern, true, *this);
3707 TreePattern Result(Instr, ResultPattern, false, *this);
3708 ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
3709 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003710 }
3711}
3712
Florian Hahn6b1db822018-06-14 20:32:58 +00003713typedef std::pair<TreePatternNode *, unsigned> NameRecord;
Chris Lattnera7722b62010-02-23 06:55:24 +00003714
Florian Hahn6b1db822018-06-14 20:32:58 +00003715static void FindNames(TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003716 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003717 TreePattern *PatternTop) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003718 if (!P->getName().empty()) {
3719 NameRecord &Rec = Names[P->getName()];
Chris Lattnera7722b62010-02-23 06:55:24 +00003720 // If this is the first instance of the name, remember the node.
3721 if (Rec.second++ == 0)
Florian Hahn6b1db822018-06-14 20:32:58 +00003722 Rec.first = P;
3723 else if (Rec.first->getExtTypes() != P->getExtTypes())
3724 PatternTop->error("repetition of value: $" + P->getName() +
Chris Lattner5b0e2492010-02-23 07:22:28 +00003725 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003726 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003727
Florian Hahn6b1db822018-06-14 20:32:58 +00003728 if (!P->isLeaf()) {
3729 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3730 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003731 }
3732}
3733
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003734std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3735 std::vector<Predicate> Preds;
3736 for (Init *I : L->getValues()) {
3737 if (DefInit *Pred = dyn_cast<DefInit>(I))
3738 Preds.push_back(Pred->getDef());
3739 else
3740 llvm_unreachable("Non-def on the list");
3741 }
3742
3743 // Sort so that different orders get canonicalized to the same string.
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00003744 llvm::sort(Preds.begin(), Preds.end());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003745 return Preds;
3746}
3747
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003748void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003749 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003750 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003751 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003752 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3753 PrintWarning(Pattern->getRecord()->getLoc(),
3754 Twine("Pattern can never match: ") + Reason);
3755 return;
3756 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003757
Chris Lattner1e634e32010-03-01 22:29:19 +00003758 // If the source pattern's root is a complex pattern, that complex pattern
3759 // must specify the nodes it can potentially match.
3760 if (const ComplexPattern *CP =
3761 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3762 if (CP->getRootNodes().empty())
3763 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3764 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003765
3766
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003767 // Find all of the named values in the input and output, ensure they have the
3768 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003769 std::map<std::string, NameRecord> SrcNames, DstNames;
Florian Hahn6b1db822018-06-14 20:32:58 +00003770 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3771 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003772
3773 // Scan all of the named values in the destination pattern, rejecting them if
3774 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003775 for (const auto &Entry : DstNames) {
3776 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003777 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003778 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003779 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003780
Chris Lattnera7722b62010-02-23 06:55:24 +00003781 // Scan all of the named values in the source pattern, rejecting them if the
3782 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003783 for (const auto &Entry : SrcNames)
3784 if (DstNames[Entry.first].first == nullptr &&
3785 SrcNames[Entry.first].second == 1)
3786 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003787
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003788 PatternsToMatch.push_back(PTM);
Chris Lattner0c0baa92010-02-23 06:16:51 +00003789}
3790
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003791void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003792 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003793 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003794
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003795 unsigned Errors = 0;
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003796
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003797 // Try to infer flags from all patterns in PatternToMatch. These include
3798 // both the primary instruction patterns (which always come first) and
3799 // patterns defined outside the instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003800 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003801 // We can only infer from single-instruction patterns, otherwise we won't
3802 // know which instruction should get the flags.
3803 SmallVector<Record*, 8> PatInstrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003804 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003805 if (PatInstrs.size() != 1)
3806 continue;
3807
3808 // Get the single instruction.
3809 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3810
3811 // Only infer properties from the first pattern. We'll verify the others.
3812 if (InstInfo.InferredFrom)
3813 continue;
3814
3815 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003816 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003817 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3818 }
3819
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003820 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003821 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003822
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003823 // If requested by the target, guess any undefined properties.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003824 if (Target.guessInstructionProperties()) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003825 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3826 CodeGenInstruction *InstInfo =
3827 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003828 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003829 continue;
3830 // The mayLoad and mayStore flags default to false.
3831 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003832 if (InstInfo->hasSideEffects_Unset)
3833 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003834 }
3835 return;
3836 }
3837
3838 // Complain about any flags that are still undefined.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003839 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3840 CodeGenInstruction *InstInfo =
3841 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003842 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003843 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003844 if (InstInfo->hasSideEffects_Unset)
3845 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003846 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003847 if (InstInfo->mayStore_Unset)
3848 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003849 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003850 if (InstInfo->mayLoad_Unset)
3851 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003852 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003853 }
3854}
3855
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003856
3857/// Verify instruction flags against pattern node properties.
3858void CodeGenDAGPatterns::VerifyInstructionFlags() {
3859 unsigned Errors = 0;
3860 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3861 const PatternToMatch &PTM = *I;
3862 SmallVector<Record*, 8> Instrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003863 getInstructionsInTree(PTM.getDstPattern(), Instrs);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003864 if (Instrs.empty())
3865 continue;
3866
3867 // Count the number of instructions with each flag set.
3868 unsigned NumSideEffects = 0;
3869 unsigned NumStores = 0;
3870 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003871 for (const Record *Instr : Instrs) {
3872 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003873 NumSideEffects += InstInfo.hasSideEffects;
3874 NumStores += InstInfo.mayStore;
3875 NumLoads += InstInfo.mayLoad;
3876 }
3877
3878 // Analyze the source pattern.
3879 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003880 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003881
3882 // Collect error messages.
3883 SmallVector<std::string, 4> Msgs;
3884
3885 // Check for missing flags in the output.
3886 // Permit extra flags for now at least.
3887 if (PatInfo.hasSideEffects && !NumSideEffects)
3888 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3889
3890 // Don't verify store flags on instructions with side effects. At least for
3891 // intrinsics, side effects implies mayStore.
3892 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3893 Msgs.push_back("pattern may store, but mayStore isn't set");
3894
3895 // Similarly, mayStore implies mayLoad on intrinsics.
3896 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3897 Msgs.push_back("pattern may load, but mayLoad isn't set");
3898
3899 // Print error messages.
3900 if (Msgs.empty())
3901 continue;
3902 ++Errors;
3903
Craig Topper306cb122015-11-22 20:46:24 +00003904 for (const std::string &Msg : Msgs)
3905 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003906 (Instrs.size() == 1 ?
3907 "instruction" : "output instructions"));
3908 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003909 for (const Record *Instr : Instrs) {
3910 if (Instr != PTM.getSrcRecord())
3911 PrintError(Instr->getLoc(), "defined here");
3912 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003913 if (InstInfo.InferredFrom &&
3914 InstInfo.InferredFrom != InstInfo.TheDef &&
3915 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003916 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003917 }
3918 }
3919 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003920 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003921}
3922
Chris Lattnercabe0372010-03-15 06:00:16 +00003923/// Given a pattern result with an unresolved type, see if we can find one
3924/// instruction with an unresolved result type. Force this result type to an
3925/// arbitrary element if it's possible types to converge results.
Florian Hahn6b1db822018-06-14 20:32:58 +00003926static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3927 if (N->isLeaf())
Chris Lattnercabe0372010-03-15 06:00:16 +00003928 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003929
Chris Lattnercabe0372010-03-15 06:00:16 +00003930 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00003931 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3932 if (ForceArbitraryInstResultType(N->getChild(i), TP))
Chris Lattnercabe0372010-03-15 06:00:16 +00003933 return true;
3934
Florian Hahn6b1db822018-06-14 20:32:58 +00003935 if (!N->getOperator()->isSubClassOf("Instruction"))
Chris Lattnercabe0372010-03-15 06:00:16 +00003936 return false;
3937
3938 // If this type is already concrete or completely unknown we can't do
3939 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003940 TypeInfer &TI = TP.getInfer();
Florian Hahn6b1db822018-06-14 20:32:58 +00003941 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3942 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00003943 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003944
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003945 // Otherwise, force its type to an arbitrary choice.
Florian Hahn6b1db822018-06-14 20:32:58 +00003946 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00003947 return true;
3948 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003949
Chris Lattnerf1447252010-03-19 21:37:09 +00003950 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003951}
3952
Ulrich Weigand58a97862018-08-01 11:57:58 +00003953// Promote xform function to be an explicit node wherever set.
3954static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
3955 if (Record *Xform = N->getTransformFn()) {
3956 N->setTransformFn(nullptr);
3957 std::vector<TreePatternNodePtr> Children;
3958 Children.push_back(PromoteXForms(N));
3959 return std::make_shared<TreePatternNode>(Xform, std::move(Children),
3960 N->getNumTypes());
3961 }
3962
3963 if (!N->isLeaf())
3964 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3965 TreePatternNodePtr Child = N->getChildShared(i);
Ulrich Weigandf989cd72018-08-01 12:07:32 +00003966 N->setChild(i, PromoteXForms(Child));
Ulrich Weigand58a97862018-08-01 11:57:58 +00003967 }
3968 return N;
3969}
3970
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003971void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
3972 TreePattern &Pattern, TreePattern &Result,
3973 const std::vector<Record *> &InstImpResults) {
3974
3975 // Inline pattern fragments and expand multiple alternatives.
3976 Pattern.InlinePatternFragments();
3977 Result.InlinePatternFragments();
3978
3979 if (Result.getNumTrees() != 1)
3980 Result.error("Cannot use multi-alternative fragments in result pattern!");
3981
3982 // Infer types.
3983 bool IterateInference;
3984 bool InferredAllPatternTypes, InferredAllResultTypes;
3985 do {
3986 // Infer as many types as possible. If we cannot infer all of them, we
3987 // can never do anything with this pattern: report it to the user.
3988 InferredAllPatternTypes =
3989 Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
3990
3991 // Infer as many types as possible. If we cannot infer all of them, we
3992 // can never do anything with this pattern: report it to the user.
3993 InferredAllResultTypes =
3994 Result.InferAllTypes(&Pattern.getNamedNodesMap());
3995
3996 IterateInference = false;
3997
3998 // Apply the type of the result to the source pattern. This helps us
3999 // resolve cases where the input type is known to be a pointer type (which
4000 // is considered resolved), but the result knows it needs to be 32- or
4001 // 64-bits. Infer the other way for good measure.
4002 for (auto T : Pattern.getTrees())
4003 for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
4004 T->getNumTypes());
4005 i != e; ++i) {
4006 IterateInference |= T->UpdateNodeType(
4007 i, Result.getOnlyTree()->getExtType(i), Result);
4008 IterateInference |= Result.getOnlyTree()->UpdateNodeType(
4009 i, T->getExtType(i), Result);
4010 }
4011
4012 // If our iteration has converged and the input pattern's types are fully
4013 // resolved but the result pattern is not fully resolved, we may have a
4014 // situation where we have two instructions in the result pattern and
4015 // the instructions require a common register class, but don't care about
4016 // what actual MVT is used. This is actually a bug in our modelling:
4017 // output patterns should have register classes, not MVTs.
4018 //
4019 // In any case, to handle this, we just go through and disambiguate some
4020 // arbitrary types to the result pattern's nodes.
4021 if (!IterateInference && InferredAllPatternTypes &&
4022 !InferredAllResultTypes)
4023 IterateInference =
4024 ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
4025 } while (IterateInference);
4026
4027 // Verify that we inferred enough types that we can do something with the
4028 // pattern and result. If these fire the user has to add type casts.
4029 if (!InferredAllPatternTypes)
4030 Pattern.error("Could not infer all types in pattern!");
4031 if (!InferredAllResultTypes) {
4032 Pattern.dump();
4033 Result.error("Could not infer all types in pattern result!");
4034 }
4035
Ulrich Weigand58a97862018-08-01 11:57:58 +00004036 // Promote xform function to be an explicit node wherever set.
4037 TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004038
4039 TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4040 Temp.InferAllTypes();
4041
4042 ListInit *Preds = TheDef->getValueAsListInit("Predicates");
4043 int Complexity = TheDef->getValueAsInt("AddedComplexity");
4044
4045 if (PatternRewriter)
4046 PatternRewriter(&Pattern);
4047
4048 // A pattern may end up with an "impossible" type, i.e. a situation
4049 // where all types have been eliminated for some node in this pattern.
4050 // This could occur for intrinsics that only make sense for a specific
4051 // value type, and use a specific register class. If, for some mode,
4052 // that register class does not accept that type, the type inference
4053 // will lead to a contradiction, which is not an error however, but
4054 // a sign that this pattern will simply never match.
4055 if (Temp.getOnlyTree()->hasPossibleType())
4056 for (auto T : Pattern.getTrees())
4057 if (T->hasPossibleType())
4058 AddPatternToMatch(&Pattern,
4059 PatternToMatch(TheDef, makePredList(Preds),
4060 T, Temp.getOnlyTree(),
4061 InstImpResults, Complexity,
4062 TheDef->getID()));
4063}
4064
Chris Lattnerab3242f2008-01-06 01:10:31 +00004065void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00004066 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
4067
Craig Topper306cb122015-11-22 20:46:24 +00004068 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00004069 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00004070
4071 // If the pattern references the null_frag, there's nothing to do.
4072 if (hasNullFragReference(Tree))
4073 continue;
4074
Florian Hahn75e87c32018-05-30 21:00:18 +00004075 TreePattern Pattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00004076
David Greeneaf8ee2c2011-07-29 22:43:06 +00004077 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00004078 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004079
Chris Lattner8cab0212008-01-05 22:25:12 +00004080 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004081 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004082
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004083 if (Result.getNumTrees() != 1)
4084 Result.error("Cannot handle instructions producing instructions "
4085 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004086
Chris Lattner8cab0212008-01-05 22:25:12 +00004087 // Validate that the input pattern is correct.
Florian Hahn75e87c32018-05-30 21:00:18 +00004088 std::map<std::string, TreePatternNodePtr> InstInputs;
4089 std::map<std::string, TreePatternNodePtr> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00004090 std::vector<Record*> InstImpResults;
Florian Hahn75e87c32018-05-30 21:00:18 +00004091 for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
David Blaikie19b22d42018-06-11 22:14:43 +00004092 FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
Florian Hahn75e87c32018-05-30 21:00:18 +00004093 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004094
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004095 ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004096 }
4097}
4098
Florian Hahn6b1db822018-06-14 20:32:58 +00004099static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004100 for (const TypeSetByHwMode &VTS : N->getExtTypes())
4101 for (const auto &I : VTS)
4102 Modes.insert(I.first);
4103
4104 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00004105 collectModes(Modes, N->getChild(i));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004106}
4107
4108void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4109 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4110 std::map<unsigned,std::vector<Predicate>> ModeChecks;
4111 std::vector<PatternToMatch> Copy = PatternsToMatch;
4112 PatternsToMatch.clear();
4113
Florian Hahn75e87c32018-05-30 21:00:18 +00004114 auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) {
4115 TreePatternNodePtr NewSrc = P.SrcPattern->clone();
4116 TreePatternNodePtr NewDst = P.DstPattern->clone();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004117 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004118 return;
4119 }
4120
4121 std::vector<Predicate> Preds = P.Predicates;
4122 const std::vector<Predicate> &MC = ModeChecks[Mode];
4123 Preds.insert(Preds.end(), MC.begin(), MC.end());
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004124 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, std::move(NewSrc),
4125 std::move(NewDst), P.getDstRegs(),
4126 P.getAddedComplexity(), Record::getNewUID(),
4127 Mode);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004128 };
4129
4130 for (PatternToMatch &P : Copy) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004131 TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
Florian Hahn6b1db822018-06-14 20:32:58 +00004132 if (P.SrcPattern->hasProperTypeByHwMode())
4133 SrcP = P.SrcPattern;
4134 if (P.DstPattern->hasProperTypeByHwMode())
4135 DstP = P.DstPattern;
4136 if (!SrcP && !DstP) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004137 PatternsToMatch.push_back(P);
4138 continue;
4139 }
4140
4141 std::set<unsigned> Modes;
Florian Hahn6b1db822018-06-14 20:32:58 +00004142 if (SrcP)
4143 collectModes(Modes, SrcP.get());
4144 if (DstP)
4145 collectModes(Modes, DstP.get());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004146
4147 // The predicate for the default mode needs to be constructed for each
4148 // pattern separately.
4149 // Since not all modes must be present in each pattern, if a mode m is
4150 // absent, then there is no point in constructing a check for m. If such
4151 // a check was created, it would be equivalent to checking the default
4152 // mode, except not all modes' predicates would be a part of the checking
4153 // code. The subsequently generated check for the default mode would then
4154 // have the exact same patterns, but a different predicate code. To avoid
4155 // duplicated patterns with different predicate checks, construct the
4156 // default check as a negation of all predicates that are actually present
4157 // in the source/destination patterns.
4158 std::vector<Predicate> DefaultPred;
4159
4160 for (unsigned M : Modes) {
4161 if (M == DefaultMode)
4162 continue;
4163 if (ModeChecks.find(M) != ModeChecks.end())
4164 continue;
4165
4166 // Fill the map entry for this mode.
4167 const HwMode &HM = CGH.getMode(M);
4168 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4169
4170 // Add negations of the HM's predicates to the default predicate.
4171 DefaultPred.emplace_back(Predicate(HM.Features, false));
4172 }
4173
4174 for (unsigned M : Modes) {
4175 if (M == DefaultMode)
4176 continue;
4177 AppendPattern(P, M);
4178 }
4179
4180 bool HasDefault = Modes.count(DefaultMode);
4181 if (HasDefault)
4182 AppendPattern(P, DefaultMode);
4183 }
4184}
4185
4186/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turner249dc142017-09-20 18:01:40 +00004187typedef StringMap<int> DepVarMap;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004188
Florian Hahn6b1db822018-06-14 20:32:58 +00004189static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4190 if (N->isLeaf()) {
4191 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
4192 DepMap[N->getName()]++;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004193 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00004194 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4195 FindDepVarsOf(N->getChild(i), DepMap);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004196 }
4197}
4198
4199/// Find dependent variables within child patterns
Florian Hahn6b1db822018-06-14 20:32:58 +00004200static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004201 DepVarMap depcounts;
4202 FindDepVarsOf(N, depcounts);
Zachary Turner249dc142017-09-20 18:01:40 +00004203 for (const auto &Pair : depcounts) {
4204 if (Pair.getValue() > 1)
4205 DepVars.insert(Pair.getKey());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004206 }
4207}
4208
4209#ifndef NDEBUG
4210/// Dump the dependent variable set:
4211static void DumpDepVars(MultipleUseVarSet &DepVars) {
4212 if (DepVars.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004213 LLVM_DEBUG(errs() << "<empty set>");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004214 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004215 LLVM_DEBUG(errs() << "[ ");
Zachary Turner249dc142017-09-20 18:01:40 +00004216 for (const auto &DepVar : DepVars) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004217 LLVM_DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004218 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004219 LLVM_DEBUG(errs() << "]");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004220 }
4221}
4222#endif
4223
4224
Chris Lattner8cab0212008-01-05 22:25:12 +00004225/// CombineChildVariants - Given a bunch of permutations of each child of the
4226/// 'operator' node, put them together in all possible ways.
Florian Hahn75e87c32018-05-30 21:00:18 +00004227static void CombineChildVariants(
Florian Hahn6b1db822018-06-14 20:32:58 +00004228 TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004229 const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4230 std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4231 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004232 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00004233 for (const auto &Variants : ChildVariants)
4234 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00004235 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004236
Chris Lattner8cab0212008-01-05 22:25:12 +00004237 // The end result is an all-pairs construction of the resultant pattern.
4238 std::vector<unsigned> Idxs;
4239 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00004240 bool NotDone;
4241 do {
4242#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004243 LLVM_DEBUG(if (!Idxs.empty()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004244 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004245 for (unsigned Idx : Idxs) {
4246 errs() << Idx << " ";
4247 }
4248 errs() << "]\n";
4249 });
Scott Michel94420742008-03-05 17:49:05 +00004250#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00004251 // Create the variant and add it to the output list.
Florian Hahn75e87c32018-05-30 21:00:18 +00004252 std::vector<TreePatternNodePtr> NewChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004253 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4254 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Florian Hahn75e87c32018-05-30 21:00:18 +00004255 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00004256 Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004257
Chris Lattner8cab0212008-01-05 22:25:12 +00004258 // Copy over properties.
Florian Hahn6b1db822018-06-14 20:32:58 +00004259 R->setName(Orig->getName());
4260 R->setPredicateFns(Orig->getPredicateFns());
4261 R->setTransformFn(Orig->getTransformFn());
4262 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4263 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00004264
Scott Michel94420742008-03-05 17:49:05 +00004265 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00004266 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00004267 // Scan to see if this pattern has already been emitted. We can get
4268 // duplication due to things like commuting:
4269 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4270 // which are the same pattern. Ignore the dups.
4271 if (R->canPatternMatch(ErrString, CDP) &&
Florian Hahn75e87c32018-05-30 21:00:18 +00004272 none_of(OutVariants, [&](TreePatternNodePtr Variant) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004273 return R->isIsomorphicTo(Variant.get(), DepVars);
David Majnemer0a16c222016-08-11 21:15:00 +00004274 }))
Florian Hahn75e87c32018-05-30 21:00:18 +00004275 OutVariants.push_back(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004276
Scott Michel94420742008-03-05 17:49:05 +00004277 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004278 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00004279 // [0, 0], [0, 1], [1, 0], [1, 1].
4280 int IdxsIdx;
4281 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4282 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4283 Idxs[IdxsIdx] = 0;
4284 else
Chris Lattner8cab0212008-01-05 22:25:12 +00004285 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00004286 }
Scott Michel94420742008-03-05 17:49:05 +00004287 NotDone = (IdxsIdx >= 0);
4288 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00004289}
4290
4291/// CombineChildVariants - A helper function for binary operators.
4292///
Florian Hahn6b1db822018-06-14 20:32:58 +00004293static void CombineChildVariants(TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004294 const std::vector<TreePatternNodePtr> &LHS,
4295 const std::vector<TreePatternNodePtr> &RHS,
4296 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004297 CodeGenDAGPatterns &CDP,
4298 const MultipleUseVarSet &DepVars) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004299 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004300 ChildVariants.push_back(LHS);
4301 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00004302 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004303}
Chris Lattner8cab0212008-01-05 22:25:12 +00004304
Florian Hahn75e87c32018-05-30 21:00:18 +00004305static void
Florian Hahn6b1db822018-06-14 20:32:58 +00004306GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004307 std::vector<TreePatternNodePtr> &Children) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004308 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4309 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00004310
Chris Lattner8cab0212008-01-05 22:25:12 +00004311 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00004312 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00004313 N->getTransformFn()) {
4314 Children.push_back(N);
4315 return;
4316 }
4317
Florian Hahn6b1db822018-06-14 20:32:58 +00004318 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004319 Children.push_back(N->getChildShared(0));
Chris Lattner8cab0212008-01-05 22:25:12 +00004320 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004321 GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004322
Florian Hahn6b1db822018-06-14 20:32:58 +00004323 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004324 Children.push_back(N->getChildShared(1));
Chris Lattner8cab0212008-01-05 22:25:12 +00004325 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004326 GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004327}
4328
4329/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4330/// the (potentially recursive) pattern by using algebraic laws.
4331///
Florian Hahn6b1db822018-06-14 20:32:58 +00004332static void GenerateVariantsOf(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004333 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004334 CodeGenDAGPatterns &CDP,
4335 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00004336 // We cannot permute leaves or ComplexPattern uses.
4337 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004338 OutVariants.push_back(N);
4339 return;
4340 }
4341
4342 // Look up interesting info about the node.
4343 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4344
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004345 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00004346 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00004347 // Re-associate by pulling together all of the linked operators
Florian Hahn75e87c32018-05-30 21:00:18 +00004348 std::vector<TreePatternNodePtr> MaximalChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004349 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4350
4351 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4352 // permutations.
4353 if (MaximalChildren.size() == 3) {
4354 // Find the variants of all of our maximal children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004355 std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00004356 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4357 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4358 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004359
Chris Lattner8cab0212008-01-05 22:25:12 +00004360 // There are only two ways we can permute the tree:
4361 // (A op B) op C and A op (B op C)
4362 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004363
Chris Lattner8cab0212008-01-05 22:25:12 +00004364 // Generate legal pair permutations of A/B/C.
Florian Hahn75e87c32018-05-30 21:00:18 +00004365 std::vector<TreePatternNodePtr> ABVariants;
4366 std::vector<TreePatternNodePtr> BAVariants;
4367 std::vector<TreePatternNodePtr> ACVariants;
4368 std::vector<TreePatternNodePtr> CAVariants;
4369 std::vector<TreePatternNodePtr> BCVariants;
4370 std::vector<TreePatternNodePtr> CBVariants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004371 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4372 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4373 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4374 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4375 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4376 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004377
4378 // Combine those into the result: (x op x) op x
Florian Hahn6b1db822018-06-14 20:32:58 +00004379 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4380 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4381 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4382 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4383 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4384 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004385
4386 // Combine those into the result: x op (x op x)
Florian Hahn6b1db822018-06-14 20:32:58 +00004387 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4388 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4389 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4390 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4391 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4392 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004393 return;
4394 }
4395 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004396
Chris Lattner8cab0212008-01-05 22:25:12 +00004397 // Compute permutations of all children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004398 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004399 ChildVariants.resize(N->getNumChildren());
4400 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn75e87c32018-05-30 21:00:18 +00004401 GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004402
4403 // Build all permutations based on how the children were formed.
Florian Hahn6b1db822018-06-14 20:32:58 +00004404 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004405
4406 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004407 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4408 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004409 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004410 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004411 // Don't count children which are actually register references.
4412 unsigned NC = 0;
4413 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004414 TreePatternNode *Child = N->getChild(i);
4415 if (Child->isLeaf())
4416 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004417 Record *RR = DI->getDef();
4418 if (RR->isSubClassOf("Register"))
4419 continue;
4420 }
4421 NC++;
4422 }
4423 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004424 if (isCommIntrinsic) {
4425 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4426 // operands are the commutative operands, and there might be more operands
4427 // after those.
4428 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004429 "Commutative intrinsic should have at least 3 children!");
Florian Hahn75e87c32018-05-30 21:00:18 +00004430 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004431 Variants.push_back(std::move(ChildVariants[0])); // Intrinsic id.
4432 Variants.push_back(std::move(ChildVariants[2]));
4433 Variants.push_back(std::move(ChildVariants[1]));
Evan Cheng49bad4c2008-06-16 20:29:38 +00004434 for (unsigned i = 3; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004435 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004436 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004437 } else if (NC == N->getNumChildren()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004438 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004439 Variants.push_back(std::move(ChildVariants[1]));
4440 Variants.push_back(std::move(ChildVariants[0]));
Craig Topper98a96282017-09-04 03:44:33 +00004441 for (unsigned i = 2; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004442 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004443 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004444 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004445 }
4446}
4447
4448
4449// GenerateVariants - Generate variants. For example, commutative patterns can
4450// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004451void CodeGenDAGPatterns::GenerateVariants() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004452 LLVM_DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004453
Chris Lattner8cab0212008-01-05 22:25:12 +00004454 // Loop over all of the patterns we've collected, checking to see if we can
4455 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004456 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004457 // the .td file having to contain tons of variants of instructions.
4458 //
4459 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4460 // intentionally do not reconsider these. Any variants of added patterns have
4461 // already been added.
4462 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00004463 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00004464 MultipleUseVarSet DepVars;
Florian Hahn75e87c32018-05-30 21:00:18 +00004465 std::vector<TreePatternNodePtr> Variants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004466 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004467 LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4468 LLVM_DEBUG(DumpDepVars(DepVars));
4469 LLVM_DEBUG(errs() << "\n");
Florian Hahn75e87c32018-05-30 21:00:18 +00004470 GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4471 *this, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004472
4473 assert(!Variants.empty() && "Must create at least original variant!");
Krzysztof Parzyszekf7237762017-06-16 13:44:34 +00004474 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004475 continue;
4476
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004477 LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4478 PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004479
4480 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004481 TreePatternNodePtr Variant = Variants[v];
Chris Lattner8cab0212008-01-05 22:25:12 +00004482
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004483 LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump();
4484 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004485
Chris Lattner8cab0212008-01-05 22:25:12 +00004486 // Scan to see if an instruction or explicit pattern already matches this.
4487 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004488 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004489 // Skip if the top level predicates do not match.
Simon Pilgrimf19cdc62018-08-16 16:04:05 +00004490 if ((i != p) && (PatternsToMatch[i].getPredicates() !=
4491 PatternsToMatch[p].getPredicates()))
Evan Cheng34c8c742009-06-26 05:59:16 +00004492 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004493 // Check to see if this variant already exists.
Florian Hahn6b1db822018-06-14 20:32:58 +00004494 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004495 DepVars)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004496 LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004497 AlreadyExists = true;
4498 break;
4499 }
4500 }
4501 // If we already have it, ignore the variant.
4502 if (AlreadyExists) continue;
4503
4504 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004505 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004506 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
Florian Hahn75e87c32018-05-30 21:00:18 +00004507 Variant, PatternsToMatch[i].getDstPatternShared(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004508 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004509 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00004510 }
4511
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004512 LLVM_DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004513 }
4514}