blob: ed68b09c265fed48d51414abcc29360c33909b95 [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"
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +000016#include "llvm/ADT/BitVector.h"
Zachary Turner249dc142017-09-20 18:01:40 +000017#include "llvm/ADT/DenseSet.h"
Chris Lattnercabe0372010-03-15 06:00:16 +000018#include "llvm/ADT/STLExtras.h"
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000019#include "llvm/ADT/SmallSet.h"
Craig Topper3522ab32015-11-28 08:23:02 +000020#include "llvm/ADT/SmallString.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000021#include "llvm/ADT/StringExtras.h"
Craig Topperddfdd942017-09-21 04:55:03 +000022#include "llvm/ADT/StringMap.h"
Jim Grosbach3ae48a62012-04-18 17:46:41 +000023#include "llvm/ADT/Twine.h"
Chris Lattner8cab0212008-01-05 22:25:12 +000024#include "llvm/Support/Debug.h"
David Blaikieb48ed1a2012-01-17 04:43:56 +000025#include "llvm/Support/ErrorHandling.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000026#include "llvm/TableGen/Error.h"
27#include "llvm/TableGen/Record.h"
Chuck Rose IIIfe2714f2008-01-15 21:43:17 +000028#include <algorithm>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000029#include <cstdio>
30#include <set>
Chris Lattner8cab0212008-01-05 22:25:12 +000031using namespace llvm;
32
Chandler Carruthe96dd892014-04-21 22:55:11 +000033#define DEBUG_TYPE "dag-patterns"
34
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000035static inline bool isIntegerOrPtr(MVT VT) {
36 return VT.isInteger() || VT == MVT::iPTR;
Duncan Sands13237ac2008-06-06 12:08:01 +000037}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000038static inline bool isFloatingPoint(MVT VT) {
39 return VT.isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000040}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000041static inline bool isVector(MVT VT) {
42 return VT.isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000043}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000044static inline bool isScalar(MVT VT) {
45 return !VT.isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000046}
Duncan Sands13237ac2008-06-06 12:08:01 +000047
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000048template <typename Predicate>
49static bool berase_if(MachineValueTypeSet &S, Predicate P) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000050 bool Erased = false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000051 // It is ok to iterate over MachineValueTypeSet and remove elements from it
52 // at the same time.
53 for (MVT T : S) {
54 if (!P(T))
55 continue;
56 Erased = true;
57 S.erase(T);
Chris Lattnercabe0372010-03-15 06:00:16 +000058 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000059 return Erased;
Chris Lattner8cab0212008-01-05 22:25:12 +000060}
61
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000062// --- TypeSetByHwMode
Chris Lattnercabe0372010-03-15 06:00:16 +000063
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000064// This is a parameterized type-set class. For each mode there is a list
65// of types that are currently possible for a given tree node. Type
66// inference will apply to each mode separately.
Jim Grosbach65586fe2010-12-21 16:16:00 +000067
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000068TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
69 for (const ValueTypeByHwMode &VVT : VTList)
70 insert(VVT);
Chris Lattner8cab0212008-01-05 22:25:12 +000071}
72
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000073bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
74 for (const auto &I : *this) {
75 if (I.second.size() > 1)
76 return false;
77 if (!AllowEmpty && I.second.empty())
78 return false;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000079 }
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000080 return true;
81}
Chris Lattnercabe0372010-03-15 06:00:16 +000082
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000083ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
84 assert(isValueTypeByHwMode(true) &&
85 "The type set has multiple types for at least one HW mode");
86 ValueTypeByHwMode VVT;
87 for (const auto &I : *this) {
88 MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
89 VVT.getOrCreateTypeForMode(I.first, T);
Chris Lattnercabe0372010-03-15 06:00:16 +000090 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000091 return VVT;
Bob Wilson2cd5da82009-08-11 01:14:02 +000092}
Chris Lattnercabe0372010-03-15 06:00:16 +000093
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000094bool TypeSetByHwMode::isPossible() const {
95 for (const auto &I : *this)
96 if (!I.second.empty())
97 return true;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000098 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +000099}
100
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000101bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
102 bool Changed = false;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000103 bool ContainsDefault = false;
104 MVT DT = MVT::Other;
105
Zachary Turner249dc142017-09-20 18:01:40 +0000106 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000107 for (const auto &P : VVT) {
108 unsigned M = P.first;
109 Modes.insert(M);
110 // Make sure there exists a set for each specific mode from VVT.
111 Changed |= getOrCreate(M).insert(P.second).second;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000112 // Cache VVT's default mode.
113 if (DefaultMode == M) {
114 ContainsDefault = true;
115 DT = P.second;
116 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000117 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000118
119 // If VVT has a default mode, add the corresponding type to all
120 // modes in "this" that do not exist in VVT.
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000121 if (ContainsDefault)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000122 for (auto &I : *this)
123 if (!Modes.count(I.first))
124 Changed |= I.second.insert(DT).second;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000125
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000126 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000127}
128
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000129// Constrain the type set to be the intersection with VTS.
130bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
131 bool Changed = false;
132 if (hasDefault()) {
133 for (const auto &I : VTS) {
134 unsigned M = I.first;
135 if (M == DefaultMode || hasMode(M))
136 continue;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000137 Map.insert({M, Map.at(DefaultMode)});
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000138 Changed = true;
139 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000140 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000141
142 for (auto &I : *this) {
143 unsigned M = I.first;
144 SetType &S = I.second;
145 if (VTS.hasMode(M) || VTS.hasDefault()) {
146 Changed |= intersect(I.second, VTS.get(M));
147 } else if (!S.empty()) {
148 S.clear();
149 Changed = true;
150 }
151 }
152 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000153}
154
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000155template <typename Predicate>
156bool TypeSetByHwMode::constrain(Predicate P) {
157 bool Changed = false;
158 for (auto &I : *this)
Benjamin Kramere57308e2017-09-17 11:19:53 +0000159 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000160 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000161}
162
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000163template <typename Predicate>
164bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
165 assert(empty());
166 for (const auto &I : VTS) {
167 SetType &S = getOrCreate(I.first);
168 for (auto J : I.second)
169 if (P(J))
170 S.insert(J);
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000171 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000172 return !empty();
Chris Lattnercabe0372010-03-15 06:00:16 +0000173}
174
Zachary Turner249dc142017-09-20 18:01:40 +0000175void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
176 SmallVector<unsigned, 4> Modes;
177 Modes.reserve(Map.size());
Chris Lattnercabe0372010-03-15 06:00:16 +0000178
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000179 for (const auto &I : *this)
180 Modes.push_back(I.first);
Zachary Turner249dc142017-09-20 18:01:40 +0000181 if (Modes.empty()) {
182 OS << "{}";
183 return;
184 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000185 array_pod_sort(Modes.begin(), Modes.end());
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000186
Zachary Turner249dc142017-09-20 18:01:40 +0000187 OS << '{';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000188 for (unsigned M : Modes) {
Zachary Turner249dc142017-09-20 18:01:40 +0000189 OS << ' ' << getModeName(M) << ':';
190 writeToStream(get(M), OS);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000191 }
Zachary Turner249dc142017-09-20 18:01:40 +0000192 OS << " }";
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000193}
194
Zachary Turner249dc142017-09-20 18:01:40 +0000195void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
196 SmallVector<MVT, 4> Types(S.begin(), S.end());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000197 array_pod_sort(Types.begin(), Types.end());
198
Zachary Turner249dc142017-09-20 18:01:40 +0000199 OS << '[';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000200 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
Zachary Turner249dc142017-09-20 18:01:40 +0000201 OS << ValueTypeByHwMode::getMVTName(Types[i]);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000202 if (i != e-1)
Zachary Turner249dc142017-09-20 18:01:40 +0000203 OS << ' ';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000204 }
Zachary Turner249dc142017-09-20 18:01:40 +0000205 OS << ']';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000206}
207
208bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
Simon Pilgrim0e181332018-08-16 16:16:28 +0000209 // The isSimple call is much quicker than hasDefault - check this first.
210 bool IsSimple = isSimple();
211 bool VTSIsSimple = VTS.isSimple();
212 if (IsSimple && VTSIsSimple)
213 return *begin() == *VTS.begin();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000214
Simon Pilgrim0e181332018-08-16 16:16:28 +0000215 // Speedup: We have a default if the set is simple.
216 bool HaveDefault = IsSimple || hasDefault();
217 bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
218 if (HaveDefault != VTSHaveDefault)
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000219 return false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000220
Zachary Turner249dc142017-09-20 18:01:40 +0000221 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000222 for (auto &I : *this)
223 Modes.insert(I.first);
224 for (const auto &I : VTS)
225 Modes.insert(I.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000226
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000227 if (HaveDefault) {
228 // Both sets have default mode.
229 for (unsigned M : Modes) {
230 if (get(M) != VTS.get(M))
David Majnemerc7004902016-08-12 04:32:37 +0000231 return false;
Craig Topper5712d462015-11-24 08:20:47 +0000232 }
Scott Michel94420742008-03-05 17:49:05 +0000233 } else {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000234 // Neither set has default mode.
235 for (unsigned M : Modes) {
236 // If there is no default mode, an empty set is equivalent to not having
237 // the corresponding mode.
238 bool NoModeThis = !hasMode(M) || get(M).empty();
239 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
240 if (NoModeThis != NoModeVTS)
241 return false;
242 if (!NoModeThis)
243 if (get(M) != VTS.get(M))
244 return false;
245 }
Scott Michel94420742008-03-05 17:49:05 +0000246 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000247
248 return true;
Scott Michel94420742008-03-05 17:49:05 +0000249}
250
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000251namespace llvm {
252 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
253 T.writeToStream(OS);
254 return OS;
255 }
256}
257
Krzysztof Parzyszek426bf362017-09-12 15:31:26 +0000258LLVM_DUMP_METHOD
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000259void TypeSetByHwMode::dump() const {
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000260 dbgs() << *this << '\n';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000261}
262
263bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
264 bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
265 auto Int = [&In](MVT T) -> bool { return !In.count(T); };
266
267 if (OutP == InP)
268 return berase_if(Out, Int);
269
270 // Compute the intersection of scalars separately to account for only
271 // one set containing iPTR.
272 // The itersection of iPTR with a set of integer scalar types that does not
273 // include iPTR will result in the most specific scalar type:
274 // - iPTR is more specific than any set with two elements or more
275 // - iPTR is less specific than any single integer scalar type.
276 // For example
277 // { iPTR } * { i32 } -> { i32 }
278 // { iPTR } * { i32 i64 } -> { iPTR }
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000279 // and
280 // { iPTR i32 } * { i32 } -> { i32 }
281 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
282 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000283
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000284 // Compute the difference between the two sets in such a way that the
285 // iPTR is in the set that is being subtracted. This is to see if there
286 // are any extra scalars in the set without iPTR that are not in the
287 // set containing iPTR. Then the iPTR could be considered a "wildcard"
288 // matching these scalars. If there is only one such scalar, it would
289 // replace the iPTR, if there are more, the iPTR would be retained.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000290 SetType Diff;
291 if (InP) {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000292 Diff = Out;
293 berase_if(Diff, [&In](MVT T) { return In.count(T); });
294 // Pre-remove these elements and rely only on InP/OutP to determine
295 // whether a change has been made.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000296 berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
Scott Michel94420742008-03-05 17:49:05 +0000297 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000298 Diff = In;
299 berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000300 Out.erase(MVT::iPTR);
301 }
302
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000303 // The actual intersection.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000304 bool Changed = berase_if(Out, Int);
305 unsigned NumD = Diff.size();
306 if (NumD == 0)
307 return Changed;
308
309 if (NumD == 1) {
310 Out.insert(*Diff.begin());
311 // This is a change only if Out was the one with iPTR (which is now
312 // being replaced).
313 Changed |= OutP;
314 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000315 // Multiple elements from Out are now replaced with iPTR.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000316 Out.insert(MVT::iPTR);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000317 Changed |= !OutP;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000318 }
319 return Changed;
320}
321
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000322bool TypeSetByHwMode::validate() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000323#ifndef NDEBUG
324 if (empty())
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000325 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000326 bool AllEmpty = true;
327 for (const auto &I : *this)
328 AllEmpty &= I.second.empty();
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000329 return !AllEmpty;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000330#endif
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000331 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000332}
333
334// --- TypeInfer
335
336bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
337 const TypeSetByHwMode &In) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000338 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000339 In.validate();
340 if (In.empty() || Out == In || TP.hasError())
341 return false;
342 if (Out.empty()) {
343 Out = In;
344 return true;
345 }
346
347 bool Changed = Out.constrain(In);
348 if (Changed && Out.empty())
349 TP.error("Type contradiction");
350
351 return Changed;
352}
353
354bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000355 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000356 if (TP.hasError())
357 return false;
358 assert(!Out.empty() && "cannot pick from an empty set");
359
360 bool Changed = false;
361 for (auto &I : Out) {
362 TypeSetByHwMode::SetType &S = I.second;
363 if (S.size() <= 1)
364 continue;
365 MVT T = *S.begin(); // Pick the first element.
366 S.clear();
367 S.insert(T);
368 Changed = true;
369 }
370 return Changed;
371}
372
373bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000374 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000375 if (TP.hasError())
376 return false;
377 if (!Out.empty())
378 return Out.constrain(isIntegerOrPtr);
379
380 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
381}
382
383bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000384 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000385 if (TP.hasError())
386 return false;
387 if (!Out.empty())
388 return Out.constrain(isFloatingPoint);
389
390 return Out.assign_if(getLegalTypes(), isFloatingPoint);
391}
392
393bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000394 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000395 if (TP.hasError())
396 return false;
397 if (!Out.empty())
398 return Out.constrain(isScalar);
399
400 return Out.assign_if(getLegalTypes(), isScalar);
401}
402
403bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000404 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000405 if (TP.hasError())
406 return false;
407 if (!Out.empty())
408 return Out.constrain(isVector);
409
410 return Out.assign_if(getLegalTypes(), isVector);
411}
412
413bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000414 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000415 if (TP.hasError() || !Out.empty())
416 return false;
417
418 Out = getLegalTypes();
419 return true;
420}
421
422template <typename Iter, typename Pred, typename Less>
423static Iter min_if(Iter B, Iter E, Pred P, Less L) {
424 if (B == E)
425 return E;
426 Iter Min = E;
427 for (Iter I = B; I != E; ++I) {
428 if (!P(*I))
429 continue;
430 if (Min == E || L(*I, *Min))
431 Min = I;
432 }
433 return Min;
434}
435
436template <typename Iter, typename Pred, typename Less>
437static Iter max_if(Iter B, Iter E, Pred P, Less L) {
438 if (B == E)
439 return E;
440 Iter Max = E;
441 for (Iter I = B; I != E; ++I) {
442 if (!P(*I))
443 continue;
444 if (Max == E || L(*Max, *I))
445 Max = I;
446 }
447 return Max;
448}
449
450/// Make sure that for each type in Small, there exists a larger type in Big.
451bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
452 TypeSetByHwMode &Big) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000453 ValidateOnExit _1(Small, *this), _2(Big, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000454 if (TP.hasError())
455 return false;
456 bool Changed = false;
457
458 if (Small.empty())
459 Changed |= EnforceAny(Small);
460 if (Big.empty())
461 Changed |= EnforceAny(Big);
462
463 assert(Small.hasDefault() && Big.hasDefault());
464
465 std::vector<unsigned> Modes = union_modes(Small, Big);
466
467 // 1. Only allow integer or floating point types and make sure that
468 // both sides are both integer or both floating point.
469 // 2. Make sure that either both sides have vector types, or neither
470 // of them does.
471 for (unsigned M : Modes) {
472 TypeSetByHwMode::SetType &S = Small.get(M);
473 TypeSetByHwMode::SetType &B = Big.get(M);
474
475 if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000476 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000477 Changed |= berase_if(S, NotInt) |
478 berase_if(B, NotInt);
479 } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000480 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000481 Changed |= berase_if(S, NotFP) |
482 berase_if(B, NotFP);
483 } else if (S.empty() || B.empty()) {
484 Changed = !S.empty() || !B.empty();
485 S.clear();
486 B.clear();
487 } else {
488 TP.error("Incompatible types");
489 return Changed;
Scott Michel94420742008-03-05 17:49:05 +0000490 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000491
492 if (none_of(S, isVector) || none_of(B, isVector)) {
493 Changed |= berase_if(S, isVector) |
494 berase_if(B, isVector);
495 }
496 }
497
498 auto LT = [](MVT A, MVT B) -> bool {
499 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
500 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
501 A.getSizeInBits() < B.getSizeInBits());
502 };
503 auto LE = [](MVT A, MVT B) -> bool {
504 // This function is used when removing elements: when a vector is compared
505 // to a non-vector, it should return false (to avoid removal).
506 if (A.isVector() != B.isVector())
507 return false;
508
509 // Note on the < comparison below:
510 // X86 has patterns like
511 // (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))),
512 // where the truncated vector is given a type v16i8, while the source
513 // vector has type v4i32. They both have the same size in bits.
514 // The minimal type in the result is obviously v16i8, and when we remove
515 // all types from the source that are smaller-or-equal than v8i16, the
516 // only source type would also be removed (since it's equal in size).
517 return A.getScalarSizeInBits() <= B.getScalarSizeInBits() ||
518 A.getSizeInBits() < B.getSizeInBits();
519 };
520
521 for (unsigned M : Modes) {
522 TypeSetByHwMode::SetType &S = Small.get(M);
523 TypeSetByHwMode::SetType &B = Big.get(M);
524 // MinS = min scalar in Small, remove all scalars from Big that are
525 // smaller-or-equal than MinS.
526 auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000527 if (MinS != S.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000528 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000529
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000530 // MaxS = max scalar in Big, remove all scalars from Small that are
531 // larger than MaxS.
532 auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000533 if (MaxS != B.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000534 Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000535
536 // MinV = min vector in Small, remove all vectors from Big that are
537 // smaller-or-equal than MinV.
538 auto MinV = min_if(S.begin(), S.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000539 if (MinV != S.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000540 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000541
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000542 // MaxV = max vector in Big, remove all vectors from Small that are
543 // larger than MaxV.
544 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000545 if (MaxV != B.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000546 Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000547 }
548
549 return Changed;
550}
551
552/// 1. Ensure that for each type T in Vec, T is a vector type, and that
553/// for each type U in Elem, U is a scalar type.
554/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
555/// type T in Vec, such that U is the element type of T.
556bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
557 TypeSetByHwMode &Elem) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000558 ValidateOnExit _1(Vec, *this), _2(Elem, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000559 if (TP.hasError())
560 return false;
561 bool Changed = false;
562
563 if (Vec.empty())
564 Changed |= EnforceVector(Vec);
565 if (Elem.empty())
566 Changed |= EnforceScalar(Elem);
567
568 for (unsigned M : union_modes(Vec, Elem)) {
569 TypeSetByHwMode::SetType &V = Vec.get(M);
570 TypeSetByHwMode::SetType &E = Elem.get(M);
571
572 Changed |= berase_if(V, isScalar); // Scalar = !vector
573 Changed |= berase_if(E, isVector); // Vector = !scalar
574 assert(!V.empty() && !E.empty());
575
576 SmallSet<MVT,4> VT, ST;
577 // Collect element types from the "vector" set.
578 for (MVT T : V)
579 VT.insert(T.getVectorElementType());
580 // Collect scalar types from the "element" set.
581 for (MVT T : E)
582 ST.insert(T);
583
584 // Remove from V all (vector) types whose element type is not in S.
585 Changed |= berase_if(V, [&ST](MVT T) -> bool {
586 return !ST.count(T.getVectorElementType());
587 });
588 // Remove from E all (scalar) types, for which there is no corresponding
589 // type in V.
590 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000591 }
592
593 return Changed;
594}
595
596bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
597 const ValueTypeByHwMode &VVT) {
598 TypeSetByHwMode Tmp(VVT);
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000599 ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000600 return EnforceVectorEltTypeIs(Vec, Tmp);
601}
602
603/// Ensure that for each type T in Sub, T is a vector type, and there
604/// exists a type U in Vec such that U is a vector type with the same
605/// element type as T and at least as many elements as T.
606bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
607 TypeSetByHwMode &Sub) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000608 ValidateOnExit _1(Vec, *this), _2(Sub, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000609 if (TP.hasError())
610 return false;
611
612 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
613 auto IsSubVec = [](MVT B, MVT P) -> bool {
614 if (!B.isVector() || !P.isVector())
615 return false;
Florian Hahn603c6452017-11-07 10:43:56 +0000616 // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
617 // but until there are obvious use-cases for this, keep the
618 // types separate.
619 if (B.isScalableVector() != P.isScalableVector())
620 return false;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000621 if (B.getVectorElementType() != P.getVectorElementType())
622 return false;
623 return B.getVectorNumElements() < P.getVectorNumElements();
624 };
625
626 /// Return true if S has no element (vector type) that T is a sub-vector of,
627 /// i.e. has the same element type as T and more elements.
628 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
629 for (const auto &I : S)
630 if (IsSubVec(T, I))
631 return false;
632 return true;
633 };
634
635 /// Return true if S has no element (vector type) that T is a super-vector
636 /// of, i.e. has the same element type as T and fewer elements.
637 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
638 for (const auto &I : S)
639 if (IsSubVec(I, T))
640 return false;
641 return true;
642 };
643
644 bool Changed = false;
645
646 if (Vec.empty())
647 Changed |= EnforceVector(Vec);
648 if (Sub.empty())
649 Changed |= EnforceVector(Sub);
650
651 for (unsigned M : union_modes(Vec, Sub)) {
652 TypeSetByHwMode::SetType &S = Sub.get(M);
653 TypeSetByHwMode::SetType &V = Vec.get(M);
654
655 Changed |= berase_if(S, isScalar);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000656
657 // Erase all types from S that are not sub-vectors of a type in V.
658 Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000659
660 // Erase all types from V that are not super-vectors of a type in S.
661 Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000662 }
663
664 return Changed;
665}
666
667/// 1. Ensure that V has a scalar type iff W has a scalar type.
668/// 2. Ensure that for each vector type T in V, there exists a vector
669/// type U in W, such that T and U have the same number of elements.
670/// 3. Ensure that for each vector type U in W, there exists a vector
671/// type T in V, such that T and U have the same number of elements
672/// (reverse of 2).
673bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000674 ValidateOnExit _1(V, *this), _2(W, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000675 if (TP.hasError())
676 return false;
677
678 bool Changed = false;
679 if (V.empty())
680 Changed |= EnforceAny(V);
681 if (W.empty())
682 Changed |= EnforceAny(W);
683
684 // An actual vector type cannot have 0 elements, so we can treat scalars
685 // as zero-length vectors. This way both vectors and scalars can be
686 // processed identically.
687 auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
688 return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
689 };
690
691 for (unsigned M : union_modes(V, W)) {
692 TypeSetByHwMode::SetType &VS = V.get(M);
693 TypeSetByHwMode::SetType &WS = W.get(M);
694
695 SmallSet<unsigned,2> VN, WN;
696 for (MVT T : VS)
697 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
698 for (MVT T : WS)
699 WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
700
701 Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
702 Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
703 }
704 return Changed;
705}
706
707/// 1. Ensure that for each type T in A, there exists a type U in B,
708/// such that T and U have equal size in bits.
709/// 2. Ensure that for each type U in B, there exists a type T in A
710/// such that T and U have equal size in bits (reverse of 1).
711bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000712 ValidateOnExit _1(A, *this), _2(B, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000713 if (TP.hasError())
714 return false;
715 bool Changed = false;
716 if (A.empty())
717 Changed |= EnforceAny(A);
718 if (B.empty())
719 Changed |= EnforceAny(B);
720
721 auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
722 return !Sizes.count(T.getSizeInBits());
723 };
724
725 for (unsigned M : union_modes(A, B)) {
726 TypeSetByHwMode::SetType &AS = A.get(M);
727 TypeSetByHwMode::SetType &BS = B.get(M);
728 SmallSet<unsigned,2> AN, BN;
729
730 for (MVT T : AS)
731 AN.insert(T.getSizeInBits());
732 for (MVT T : BS)
733 BN.insert(T.getSizeInBits());
734
735 Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
736 Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
737 }
738
739 return Changed;
740}
741
742void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000743 ValidateOnExit _1(VTS, *this);
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000744 const TypeSetByHwMode &Legal = getLegalTypes();
745 assert(Legal.isDefaultOnly() && "Default-mode only expected");
746 const TypeSetByHwMode::SetType &LegalTypes = Legal.get(DefaultMode);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000747
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000748 for (auto &I : VTS)
749 expandOverloads(I.second, LegalTypes);
Scott Michel94420742008-03-05 17:49:05 +0000750}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000751
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000752void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
753 const TypeSetByHwMode::SetType &Legal) {
754 std::set<MVT> Ovs;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000755 for (MVT T : Out) {
756 if (!T.isOverloaded())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000757 continue;
Zachary Turner249dc142017-09-20 18:01:40 +0000758
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000759 Ovs.insert(T);
760 // MachineValueTypeSet allows iteration and erasing.
761 Out.erase(T);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000762 }
763
764 for (MVT Ov : Ovs) {
765 switch (Ov.SimpleTy) {
766 case MVT::iPTRAny:
767 Out.insert(MVT::iPTR);
768 return;
769 case MVT::iAny:
770 for (MVT T : MVT::integer_valuetypes())
771 if (Legal.count(T))
772 Out.insert(T);
773 for (MVT T : MVT::integer_vector_valuetypes())
774 if (Legal.count(T))
775 Out.insert(T);
776 return;
777 case MVT::fAny:
778 for (MVT T : MVT::fp_valuetypes())
779 if (Legal.count(T))
780 Out.insert(T);
781 for (MVT T : MVT::fp_vector_valuetypes())
782 if (Legal.count(T))
783 Out.insert(T);
784 return;
785 case MVT::vAny:
786 for (MVT T : MVT::vector_valuetypes())
787 if (Legal.count(T))
788 Out.insert(T);
789 return;
790 case MVT::Any:
791 for (MVT T : MVT::all_valuetypes())
792 if (Legal.count(T))
793 Out.insert(T);
794 return;
795 default:
796 break;
797 }
798 }
799}
800
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000801const TypeSetByHwMode &TypeInfer::getLegalTypes() {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000802 if (!LegalTypesCached) {
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000803 TypeSetByHwMode::SetType &LegalTypes = LegalCache.getOrCreate(DefaultMode);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000804 // Stuff all types from all modes into the default mode.
805 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
806 for (const auto &I : LTS)
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000807 LegalTypes.insert(I.second);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000808 LegalTypesCached = true;
809 }
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000810 assert(LegalCache.isDefaultOnly() && "Default-mode only expected");
811 return LegalCache;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000812}
Chris Lattner514e2922011-04-17 21:38:24 +0000813
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000814#ifndef NDEBUG
815TypeInfer::ValidateOnExit::~ValidateOnExit() {
Ulrich Weigand22b1af82018-07-13 16:42:15 +0000816 if (Infer.Validate && !VTS.validate()) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000817 dbgs() << "Type set is empty for each HW mode:\n"
818 "possible type contradiction in the pattern below "
819 "(use -print-records with llvm-tblgen to see all "
820 "expanded records).\n";
821 Infer.TP.dump();
822 llvm_unreachable(nullptr);
823 }
824}
825#endif
826
Chris Lattner514e2922011-04-17 21:38:24 +0000827//===----------------------------------------------------------------------===//
828// TreePredicateFn Implementation
829//===----------------------------------------------------------------------===//
830
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000831/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
832TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000833 assert(
834 (!hasPredCode() || !hasImmCode()) &&
835 ".td file corrupt: can't have a node predicate *and* an imm predicate");
836}
837
838bool TreePredicateFn::hasPredCode() const {
Daniel Sanders87d196c2017-11-13 22:26:13 +0000839 return isLoad() || isStore() || isAtomic() ||
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000840 !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000841}
842
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000843std::string TreePredicateFn::getPredCode() const {
844 std::string Code = "";
845
Daniel Sanders87d196c2017-11-13 22:26:13 +0000846 if (!isLoad() && !isStore() && !isAtomic()) {
847 Record *MemoryVT = getMemoryVT();
848
849 if (MemoryVT)
850 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
851 "MemoryVT requires IsLoad or IsStore");
852 }
853
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000854 if (!isLoad() && !isStore()) {
855 if (isUnindexed())
856 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
857 "IsUnindexed requires IsLoad or IsStore");
858
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000859 Record *ScalarMemoryVT = getScalarMemoryVT();
860
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000861 if (ScalarMemoryVT)
862 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
863 "ScalarMemoryVT requires IsLoad or IsStore");
864 }
865
Daniel Sanders87d196c2017-11-13 22:26:13 +0000866 if (isLoad() + isStore() + isAtomic() > 1)
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000867 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
Daniel Sanders87d196c2017-11-13 22:26:13 +0000868 "IsLoad, IsStore, and IsAtomic are mutually exclusive");
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000869
870 if (isLoad()) {
871 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
872 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
873 getScalarMemoryVT() == nullptr)
874 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
875 "IsLoad cannot be used by itself");
876 } else {
877 if (isNonExtLoad())
878 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
879 "IsNonExtLoad requires IsLoad");
880 if (isAnyExtLoad())
881 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
882 "IsAnyExtLoad requires IsLoad");
883 if (isSignExtLoad())
884 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
885 "IsSignExtLoad requires IsLoad");
886 if (isZeroExtLoad())
887 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
888 "IsZeroExtLoad requires IsLoad");
889 }
890
891 if (isStore()) {
892 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
893 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr)
894 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
895 "IsStore cannot be used by itself");
896 } else {
897 if (isNonTruncStore())
898 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
899 "IsNonTruncStore requires IsStore");
900 if (isTruncStore())
901 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
902 "IsTruncStore requires IsStore");
903 }
904
Daniel Sanders87d196c2017-11-13 22:26:13 +0000905 if (isAtomic()) {
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000906 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
907 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
908 !isAtomicOrderingAcquireRelease() &&
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000909 !isAtomicOrderingSequentiallyConsistent() &&
910 !isAtomicOrderingAcquireOrStronger() &&
911 !isAtomicOrderingReleaseOrStronger() &&
912 !isAtomicOrderingWeakerThanAcquire() &&
913 !isAtomicOrderingWeakerThanRelease())
Daniel Sanders87d196c2017-11-13 22:26:13 +0000914 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
915 "IsAtomic cannot be used by itself");
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000916 } else {
917 if (isAtomicOrderingMonotonic())
918 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
919 "IsAtomicOrderingMonotonic requires IsAtomic");
920 if (isAtomicOrderingAcquire())
921 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
922 "IsAtomicOrderingAcquire requires IsAtomic");
923 if (isAtomicOrderingRelease())
924 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
925 "IsAtomicOrderingRelease requires IsAtomic");
926 if (isAtomicOrderingAcquireRelease())
927 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
928 "IsAtomicOrderingAcquireRelease requires IsAtomic");
929 if (isAtomicOrderingSequentiallyConsistent())
930 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
931 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000932 if (isAtomicOrderingAcquireOrStronger())
933 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
934 "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
935 if (isAtomicOrderingReleaseOrStronger())
936 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
937 "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
938 if (isAtomicOrderingWeakerThanAcquire())
939 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
940 "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
Daniel Sanders87d196c2017-11-13 22:26:13 +0000941 }
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000942
Daniel Sanders87d196c2017-11-13 22:26:13 +0000943 if (isLoad() || isStore() || isAtomic()) {
944 StringRef SDNodeName =
945 isLoad() ? "LoadSDNode" : isStore() ? "StoreSDNode" : "AtomicSDNode";
946
947 Record *MemoryVT = getMemoryVT();
948
949 if (MemoryVT)
950 Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT() != MVT::" +
951 MemoryVT->getName() + ") return false;\n")
952 .str();
953 }
954
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000955 if (isAtomic() && isAtomicOrderingMonotonic())
956 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
957 "AtomicOrdering::Monotonic) return false;\n";
958 if (isAtomic() && isAtomicOrderingAcquire())
959 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
960 "AtomicOrdering::Acquire) return false;\n";
961 if (isAtomic() && isAtomicOrderingRelease())
962 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
963 "AtomicOrdering::Release) return false;\n";
964 if (isAtomic() && isAtomicOrderingAcquireRelease())
965 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
966 "AtomicOrdering::AcquireRelease) return false;\n";
967 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
968 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
969 "AtomicOrdering::SequentiallyConsistent) return false;\n";
970
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000971 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
972 Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
973 "return false;\n";
974 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
975 Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
976 "return false;\n";
977
978 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
979 Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
980 "return false;\n";
981 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
982 Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
983 "return false;\n";
984
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000985 if (isLoad() || isStore()) {
986 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
987
988 if (isUnindexed())
989 Code += ("if (cast<" + SDNodeName +
990 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
991 "return false;\n")
992 .str();
993
994 if (isLoad()) {
995 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
996 isZeroExtLoad()) > 1)
997 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
998 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
999 "IsZeroExtLoad are mutually exclusive");
1000 if (isNonExtLoad())
1001 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
1002 "ISD::NON_EXTLOAD) return false;\n";
1003 if (isAnyExtLoad())
1004 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1005 "return false;\n";
1006 if (isSignExtLoad())
1007 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1008 "return false;\n";
1009 if (isZeroExtLoad())
1010 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1011 "return false;\n";
1012 } else {
1013 if ((isNonTruncStore() + isTruncStore()) > 1)
1014 PrintFatalError(
1015 getOrigPatFragRecord()->getRecord()->getLoc(),
1016 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1017 if (isNonTruncStore())
1018 Code +=
1019 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1020 if (isTruncStore())
1021 Code +=
1022 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1023 }
1024
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001025 Record *ScalarMemoryVT = getScalarMemoryVT();
1026
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001027 if (ScalarMemoryVT)
1028 Code += ("if (cast<" + SDNodeName +
1029 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1030 ScalarMemoryVT->getName() + ") return false;\n")
1031 .str();
1032 }
1033
1034 std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
1035
1036 Code += PredicateCode;
1037
1038 if (PredicateCode.empty() && !Code.empty())
1039 Code += "return true;\n";
1040
1041 return Code;
Chris Lattner514e2922011-04-17 21:38:24 +00001042}
1043
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001044bool TreePredicateFn::hasImmCode() const {
1045 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1046}
1047
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001048std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00001049 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001050}
1051
Daniel Sanders649c5852017-10-13 20:42:18 +00001052bool TreePredicateFn::immCodeUsesAPInt() const {
1053 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1054}
1055
1056bool TreePredicateFn::immCodeUsesAPFloat() const {
1057 bool Unset;
1058 // The return value will be false when IsAPFloat is unset.
1059 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1060 Unset);
1061}
1062
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001063bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1064 bool Value) const {
1065 bool Unset;
1066 bool Result =
1067 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1068 if (Unset)
1069 return false;
1070 return Result == Value;
1071}
1072bool TreePredicateFn::isLoad() const {
1073 return isPredefinedPredicateEqualTo("IsLoad", true);
1074}
1075bool TreePredicateFn::isStore() const {
1076 return isPredefinedPredicateEqualTo("IsStore", true);
1077}
Daniel Sanders87d196c2017-11-13 22:26:13 +00001078bool TreePredicateFn::isAtomic() const {
1079 return isPredefinedPredicateEqualTo("IsAtomic", true);
1080}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001081bool TreePredicateFn::isUnindexed() const {
1082 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1083}
1084bool TreePredicateFn::isNonExtLoad() const {
1085 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1086}
1087bool TreePredicateFn::isAnyExtLoad() const {
1088 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1089}
1090bool TreePredicateFn::isSignExtLoad() const {
1091 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1092}
1093bool TreePredicateFn::isZeroExtLoad() const {
1094 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1095}
1096bool TreePredicateFn::isNonTruncStore() const {
1097 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1098}
1099bool TreePredicateFn::isTruncStore() const {
1100 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1101}
Daniel Sanders6d9d30a2017-11-13 23:03:47 +00001102bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1103 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1104}
1105bool TreePredicateFn::isAtomicOrderingAcquire() const {
1106 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1107}
1108bool TreePredicateFn::isAtomicOrderingRelease() const {
1109 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1110}
1111bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1112 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1113}
1114bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1115 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1116 true);
1117}
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001118bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1119 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1120}
1121bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1122 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1123}
1124bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1125 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1126}
1127bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1128 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1129}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001130Record *TreePredicateFn::getMemoryVT() const {
1131 Record *R = getOrigPatFragRecord()->getRecord();
1132 if (R->isValueUnset("MemoryVT"))
1133 return nullptr;
1134 return R->getValueAsDef("MemoryVT");
1135}
1136Record *TreePredicateFn::getScalarMemoryVT() const {
1137 Record *R = getOrigPatFragRecord()->getRecord();
1138 if (R->isValueUnset("ScalarMemoryVT"))
1139 return nullptr;
1140 return R->getValueAsDef("ScalarMemoryVT");
1141}
Daniel Sanders8ead1292018-06-15 23:13:43 +00001142bool TreePredicateFn::hasGISelPredicateCode() const {
1143 return !PatFragRec->getRecord()
1144 ->getValueAsString("GISelPredicateCode")
1145 .empty();
1146}
1147std::string TreePredicateFn::getGISelPredicateCode() const {
1148 return PatFragRec->getRecord()->getValueAsString("GISelPredicateCode");
1149}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001150
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001151StringRef TreePredicateFn::getImmType() const {
Daniel Sanders649c5852017-10-13 20:42:18 +00001152 if (immCodeUsesAPInt())
1153 return "const APInt &";
1154 if (immCodeUsesAPFloat())
1155 return "const APFloat &";
1156 return "int64_t";
1157}
Chris Lattner514e2922011-04-17 21:38:24 +00001158
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001159StringRef TreePredicateFn::getImmTypeIdentifier() const {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001160 if (immCodeUsesAPInt())
1161 return "APInt";
1162 else if (immCodeUsesAPFloat())
1163 return "APFloat";
1164 return "I64";
1165}
1166
Chris Lattner514e2922011-04-17 21:38:24 +00001167/// isAlwaysTrue - Return true if this is a noop predicate.
1168bool TreePredicateFn::isAlwaysTrue() const {
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001169 return !hasPredCode() && !hasImmCode();
Chris Lattner514e2922011-04-17 21:38:24 +00001170}
1171
1172/// Return the name to use in the generated code to reference this, this is
1173/// "Predicate_foo" if from a pattern fragment "foo".
1174std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +00001175 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +00001176}
1177
1178/// getCodeToRunOnSDNode - Return the code for the function body that
1179/// evaluates this predicate. The argument is expected to be in "Node",
1180/// not N. This handles casting and conversion to a concrete node type as
1181/// appropriate.
1182std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001183 // Handle immediate predicates first.
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001184 std::string ImmCode = getImmCode();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001185 if (!ImmCode.empty()) {
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001186 if (isLoad())
1187 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1188 "IsLoad cannot be used with ImmLeaf or its subclasses");
1189 if (isStore())
1190 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1191 "IsStore cannot be used with ImmLeaf or its subclasses");
1192 if (isUnindexed())
1193 PrintFatalError(
1194 getOrigPatFragRecord()->getRecord()->getLoc(),
1195 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1196 if (isNonExtLoad())
1197 PrintFatalError(
1198 getOrigPatFragRecord()->getRecord()->getLoc(),
1199 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1200 if (isAnyExtLoad())
1201 PrintFatalError(
1202 getOrigPatFragRecord()->getRecord()->getLoc(),
1203 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1204 if (isSignExtLoad())
1205 PrintFatalError(
1206 getOrigPatFragRecord()->getRecord()->getLoc(),
1207 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1208 if (isZeroExtLoad())
1209 PrintFatalError(
1210 getOrigPatFragRecord()->getRecord()->getLoc(),
1211 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1212 if (isNonTruncStore())
1213 PrintFatalError(
1214 getOrigPatFragRecord()->getRecord()->getLoc(),
1215 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1216 if (isTruncStore())
1217 PrintFatalError(
1218 getOrigPatFragRecord()->getRecord()->getLoc(),
1219 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1220 if (getMemoryVT())
1221 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1222 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1223 if (getScalarMemoryVT())
1224 PrintFatalError(
1225 getOrigPatFragRecord()->getRecord()->getLoc(),
1226 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1227
1228 std::string Result = (" " + getImmType() + " Imm = ").str();
Daniel Sanders649c5852017-10-13 20:42:18 +00001229 if (immCodeUsesAPFloat())
1230 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1231 else if (immCodeUsesAPInt())
1232 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1233 else
1234 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001235 return Result + ImmCode;
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001236 }
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001237
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001238 // Handle arbitrary node predicates.
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001239 assert(hasPredCode() && "Don't have any predicate code!");
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001240 StringRef ClassName;
Chris Lattner514e2922011-04-17 21:38:24 +00001241 if (PatFragRec->getOnlyTree()->isLeaf())
1242 ClassName = "SDNode";
1243 else {
1244 Record *Op = PatFragRec->getOnlyTree()->getOperator();
1245 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1246 }
1247 std::string Result;
1248 if (ClassName == "SDNode")
1249 Result = " SDNode *N = Node;\n";
1250 else
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001251 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001252
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001253 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +00001254}
1255
Chris Lattner8cab0212008-01-05 22:25:12 +00001256//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +00001257// PatternToMatch implementation
1258//
1259
Chris Lattner05925fe2010-03-29 01:40:38 +00001260/// getPatternSize - Return the 'size' of this pattern. We want to match large
1261/// patterns before small ones. This is used to determine the size of a
1262/// pattern.
Florian Hahn6b1db822018-06-14 20:32:58 +00001263static unsigned getPatternSize(const TreePatternNode *P,
Chris Lattner05925fe2010-03-29 01:40:38 +00001264 const CodeGenDAGPatterns &CGP) {
1265 unsigned Size = 3; // The node itself.
1266 // If the root node is a ConstantSDNode, increases its size.
1267 // e.g. (set R32:$dst, 0).
Florian Hahn6b1db822018-06-14 20:32:58 +00001268 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001269 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001270
Florian Hahn6b1db822018-06-14 20:32:58 +00001271 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001272 Size += AM->getComplexity();
Tim Northoverc807a172014-05-20 11:52:46 +00001273 // We don't want to count any children twice, so return early.
1274 return Size;
1275 }
1276
Chris Lattner05925fe2010-03-29 01:40:38 +00001277 // If this node has some predicate function that must match, it adds to the
1278 // complexity of this node.
Florian Hahn6b1db822018-06-14 20:32:58 +00001279 if (!P->getPredicateFns().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001280 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001281
Chris Lattner05925fe2010-03-29 01:40:38 +00001282 // Count children in the count if they are also nodes.
Florian Hahn6b1db822018-06-14 20:32:58 +00001283 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1284 const TreePatternNode *Child = P->getChild(i);
1285 if (!Child->isLeaf() && Child->getNumTypes()) {
Simon Pilgrimc3c14412018-08-15 20:41:19 +00001286 const TypeSetByHwMode &T0 = Child->getExtType(0);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001287 // At this point, all variable type sets should be simple, i.e. only
1288 // have a default mode.
1289 if (T0.getMachineValueType() != MVT::Other) {
1290 Size += getPatternSize(Child, CGP);
1291 continue;
1292 }
1293 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001294 if (Child->isLeaf()) {
1295 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001296 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Florian Hahn6b1db822018-06-14 20:32:58 +00001297 else if (Child->getComplexPatternInfo(CGP))
Chris Lattner05925fe2010-03-29 01:40:38 +00001298 Size += getPatternSize(Child, CGP);
Florian Hahn6b1db822018-06-14 20:32:58 +00001299 else if (!Child->getPredicateFns().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001300 ++Size;
1301 }
1302 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001303
Chris Lattner05925fe2010-03-29 01:40:38 +00001304 return Size;
1305}
1306
1307/// Compute the complexity metric for the input pattern. This roughly
1308/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +00001309int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +00001310getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001311 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
Chris Lattner05925fe2010-03-29 01:40:38 +00001312}
1313
Dan Gohman49e19e92008-08-22 00:20:26 +00001314/// getPredicateCheck - Return a single string containing all of this
1315/// pattern's predicates concatenated with "&&" operators.
1316///
1317std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001318 SmallVector<const Predicate*,4> PredList;
1319 for (const Predicate &P : Predicates)
1320 PredList.push_back(&P);
Fangrui Song0cac7262018-09-27 02:13:45 +00001321 llvm::sort(PredList, deref<llvm::less>());
Craig Topper8985efe2015-11-27 05:44:04 +00001322
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001323 std::string Check;
1324 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1325 if (i != 0)
1326 Check += " && ";
1327 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +00001328 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001329 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +00001330}
1331
1332//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00001333// SDTypeConstraint implementation
1334//
1335
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001336SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001337 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001338
Chris Lattner8cab0212008-01-05 22:25:12 +00001339 if (R->isSubClassOf("SDTCisVT")) {
1340 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001341 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1342 for (const auto &P : VVT)
1343 if (P.second == MVT::isVoid)
1344 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +00001345 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1346 ConstraintType = SDTCisPtrTy;
1347 } else if (R->isSubClassOf("SDTCisInt")) {
1348 ConstraintType = SDTCisInt;
1349 } else if (R->isSubClassOf("SDTCisFP")) {
1350 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +00001351 } else if (R->isSubClassOf("SDTCisVec")) {
1352 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001353 } else if (R->isSubClassOf("SDTCisSameAs")) {
1354 ConstraintType = SDTCisSameAs;
1355 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1356 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1357 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001358 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001359 R->getValueAsInt("OtherOperandNum");
1360 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1361 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001362 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001363 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001364 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1365 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001366 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001367 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1368 ConstraintType = SDTCisSubVecOfVec;
1369 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1370 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001371 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1372 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001373 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1374 for (const auto &P : VVT) {
1375 MVT T = P.second;
1376 if (T.isVector())
1377 PrintFatalError(R->getLoc(),
1378 "Cannot use vector type as SDTCVecEltisVT");
1379 if (!T.isInteger() && !T.isFloatingPoint())
1380 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1381 "as SDTCVecEltisVT");
1382 }
Craig Topper0be34582015-03-05 07:11:34 +00001383 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1384 ConstraintType = SDTCisSameNumEltsAs;
1385 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1386 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001387 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1388 ConstraintType = SDTCisSameSizeAs;
1389 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1390 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001391 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001392 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001393 }
1394}
1395
1396/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001397/// N, and the result number in ResNo.
Florian Hahn6b1db822018-06-14 20:32:58 +00001398static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
Chris Lattner2db7aba2010-03-19 21:56:21 +00001399 const SDNodeInfo &NodeInfo,
1400 unsigned &ResNo) {
1401 unsigned NumResults = NodeInfo.getNumResults();
1402 if (OpNo < NumResults) {
1403 ResNo = OpNo;
1404 return N;
1405 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001406
Chris Lattner2db7aba2010-03-19 21:56:21 +00001407 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001408
Florian Hahn6b1db822018-06-14 20:32:58 +00001409 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001410 std::string S;
1411 raw_string_ostream OS(S);
1412 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001413 << (OpNo+NumResults) << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001414 N->print(OS);
James Y Knighte452e272015-05-11 22:17:13 +00001415 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001416 }
1417
Florian Hahn6b1db822018-06-14 20:32:58 +00001418 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001419}
1420
1421/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1422/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001423/// change, false otherwise. If a type contradiction is found, flag an error.
Florian Hahn6b1db822018-06-14 20:32:58 +00001424bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
Chris Lattner8cab0212008-01-05 22:25:12 +00001425 const SDNodeInfo &NodeInfo,
1426 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001427 if (TP.hasError())
1428 return false;
1429
Chris Lattner2db7aba2010-03-19 21:56:21 +00001430 unsigned ResNo = 0; // The result number being referenced.
Florian Hahn6b1db822018-06-14 20:32:58 +00001431 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001432 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001433
Chris Lattner8cab0212008-01-05 22:25:12 +00001434 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001435 case SDTCisVT:
1436 // Operand must be a particular type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001437 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001438 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001439 // Operand must be same as target pointer type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001440 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001441 case SDTCisInt:
1442 // Require it to be one of the legal integer VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001443 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001444 case SDTCisFP:
1445 // Require it to be one of the legal fp VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001446 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001447 case SDTCisVec:
1448 // Require it to be one of the legal vector VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001449 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001450 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001451 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001452 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001453 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001454 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1455 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001456 }
1457 case SDTCisVTSmallerThanOp: {
1458 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1459 // have an integer type that is smaller than the VT.
Florian Hahn6b1db822018-06-14 20:32:58 +00001460 if (!NodeToApply->isLeaf() ||
1461 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1462 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001463 ->isSubClassOf("ValueType")) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001464 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001465 return false;
1466 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001467 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001468 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1469 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1470 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001471
Chris Lattner2db7aba2010-03-19 21:56:21 +00001472 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001473 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001474 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1475 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001476
Florian Hahn6b1db822018-06-14 20:32:58 +00001477 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001478 }
1479 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001480 unsigned BResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001481 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001482 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1483 BResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001484 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1485 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001486 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001487 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001488 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001489 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001490 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1491 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001492 // Filter vector types out of VecOperand that don't have the right element
1493 // type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001494 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1495 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001496 }
David Greene127fd1d2011-01-24 20:53:18 +00001497 case SDTCisSubVecOfVec: {
1498 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001499 TreePatternNode *BigVecOperand =
David Greene127fd1d2011-01-24 20:53:18 +00001500 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1501 VResNo);
1502
1503 // Filter vector types out of BigVecOperand that don't have the
1504 // right subvector type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001505 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1506 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001507 }
Craig Topper0be34582015-03-05 07:11:34 +00001508 case SDTCVecEltisVT: {
Florian Hahn6b1db822018-06-14 20:32:58 +00001509 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001510 }
1511 case SDTCisSameNumEltsAs: {
1512 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001513 TreePatternNode *OtherNode =
Craig Topper0be34582015-03-05 07:11:34 +00001514 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1515 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001516 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1517 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001518 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001519 case SDTCisSameSizeAs: {
1520 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001521 TreePatternNode *OtherNode =
Craig Topper9a44b3f2015-11-26 07:02:18 +00001522 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1523 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001524 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1525 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001526 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001527 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001528 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001529}
1530
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001531// Update the node type to match an instruction operand or result as specified
1532// in the ins or outs lists on the instruction definition. Return true if the
1533// type was actually changed.
1534bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1535 Record *Operand,
1536 TreePattern &TP) {
1537 // The 'unknown' operand indicates that types should be inferred from the
1538 // context.
1539 if (Operand->isSubClassOf("unknown_class"))
1540 return false;
1541
1542 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001543 if (Operand->isSubClassOf("Operand")) {
1544 Record *R = Operand->getValueAsDef("Type");
1545 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1546 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1547 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001548
1549 // PointerLikeRegClass has a type that is determined at runtime.
1550 if (Operand->isSubClassOf("PointerLikeRegClass"))
1551 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1552
1553 // Both RegisterClass and RegisterOperand operands derive their types from a
1554 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001555 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001556 if (Operand->isSubClassOf("RegisterClass"))
1557 RC = Operand;
1558 else if (Operand->isSubClassOf("RegisterOperand"))
1559 RC = Operand->getValueAsDef("RegClass");
1560
1561 assert(RC && "Unknown operand type");
1562 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1563 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1564}
1565
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001566bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1567 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1568 if (!TP.getInfer().isConcrete(Types[i], true))
1569 return true;
1570 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001571 if (getChild(i)->ContainsUnresolvedType(TP))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001572 return true;
1573 return false;
1574}
1575
1576bool TreePatternNode::hasProperTypeByHwMode() const {
1577 for (const TypeSetByHwMode &S : Types)
1578 if (!S.isDefaultOnly())
1579 return true;
Florian Hahn75e87c32018-05-30 21:00:18 +00001580 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001581 if (C->hasProperTypeByHwMode())
1582 return true;
1583 return false;
1584}
1585
1586bool TreePatternNode::hasPossibleType() const {
1587 for (const TypeSetByHwMode &S : Types)
1588 if (!S.isPossible())
1589 return false;
Florian Hahn75e87c32018-05-30 21:00:18 +00001590 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001591 if (!C->hasPossibleType())
1592 return false;
1593 return true;
1594}
1595
1596bool TreePatternNode::setDefaultMode(unsigned Mode) {
1597 for (TypeSetByHwMode &S : Types) {
1598 S.makeSimple(Mode);
1599 // Check if the selected mode had a type conflict.
1600 if (S.get(DefaultMode).empty())
1601 return false;
1602 }
Florian Hahn75e87c32018-05-30 21:00:18 +00001603 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001604 if (!C->setDefaultMode(Mode))
1605 return false;
1606 return true;
1607}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001608
Chris Lattner8cab0212008-01-05 22:25:12 +00001609//===----------------------------------------------------------------------===//
1610// SDNodeInfo implementation
1611//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001612SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001613 EnumName = R->getValueAsString("Opcode");
1614 SDClassName = R->getValueAsString("SDClass");
1615 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1616 NumResults = TypeProfile->getValueAsInt("NumResults");
1617 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001618
Chris Lattner8cab0212008-01-05 22:25:12 +00001619 // Parse the properties.
Matt Arsenault303327d2017-12-20 19:36:28 +00001620 Properties = parseSDPatternOperatorProperties(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001621
Chris Lattner8cab0212008-01-05 22:25:12 +00001622 // Parse the type constraints.
1623 std::vector<Record*> ConstraintList =
1624 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001625 for (Record *R : ConstraintList)
1626 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001627}
1628
Chris Lattner99e53b32010-02-28 00:22:30 +00001629/// getKnownType - If the type constraints on this node imply a fixed type
1630/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001631/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001632MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001633 unsigned NumResults = getNumResults();
1634 assert(NumResults <= 1 &&
1635 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001636 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001637
Craig Topper306cb122015-11-22 20:46:24 +00001638 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001639 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001640 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001641 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001642
Craig Topper306cb122015-11-22 20:46:24 +00001643 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001644 default: break;
1645 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001646 if (Constraint.VVT.isSimple())
1647 return Constraint.VVT.getSimple().SimpleTy;
1648 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001649 case SDTypeConstraint::SDTCisPtrTy:
1650 return MVT::iPTR;
1651 }
1652 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001653 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001654}
1655
Chris Lattner8cab0212008-01-05 22:25:12 +00001656//===----------------------------------------------------------------------===//
1657// TreePatternNode implementation
1658//
1659
Chris Lattnerf1447252010-03-19 21:37:09 +00001660static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1661 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001662 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001663 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001664
Chris Lattner2109cb42010-03-22 20:56:36 +00001665 if (Operator->isSubClassOf("Intrinsic"))
1666 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001667
Chris Lattnerf1447252010-03-19 21:37:09 +00001668 if (Operator->isSubClassOf("SDNode"))
1669 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001670
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001671 if (Operator->isSubClassOf("PatFrags")) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001672 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1673 // the forward reference case where one pattern fragment references another
1674 // before it is processed.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001675 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
1676 // The number of results of a fragment with alternative records is the
1677 // maximum number of results across all alternatives.
1678 unsigned NumResults = 0;
1679 for (auto T : PFRec->getTrees())
1680 NumResults = std::max(NumResults, T->getNumTypes());
1681 return NumResults;
1682 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001683
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001684 ListInit *LI = Operator->getValueAsListInit("Fragments");
1685 assert(LI && "Invalid Fragment");
1686 unsigned NumResults = 0;
1687 for (Init *I : LI->getValues()) {
1688 Record *Op = nullptr;
1689 if (DagInit *Dag = dyn_cast<DagInit>(I))
1690 if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
1691 Op = DI->getDef();
1692 assert(Op && "Invalid Fragment");
1693 NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
1694 }
1695 return NumResults;
Chris Lattnerf1447252010-03-19 21:37:09 +00001696 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001697
Chris Lattnerf1447252010-03-19 21:37:09 +00001698 if (Operator->isSubClassOf("Instruction")) {
1699 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001700
Craig Topper3a8eb892015-03-20 05:09:06 +00001701 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1702
1703 // Subtract any defaulted outputs.
1704 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1705 Record *OperandNode = InstInfo.Operands[i].Rec;
1706
1707 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1708 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1709 --NumDefsToAdd;
1710 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001711
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001712 // Add on one implicit def if it has a resolvable type.
1713 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1714 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001715 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001716 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001717
Chris Lattnerf1447252010-03-19 21:37:09 +00001718 if (Operator->isSubClassOf("SDNodeXForm"))
1719 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001720
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001721 if (Operator->isSubClassOf("ValueType"))
1722 return 1; // A type-cast of one result.
1723
Tim Northoverc807a172014-05-20 11:52:46 +00001724 if (Operator->isSubClassOf("ComplexPattern"))
1725 return 1;
1726
Matthias Braun8c209aa2017-01-28 02:02:38 +00001727 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001728 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001729}
1730
1731void TreePatternNode::print(raw_ostream &OS) const {
1732 if (isLeaf())
1733 OS << *getLeafValue();
1734 else
1735 OS << '(' << getOperator()->getName();
1736
Zachary Turner249dc142017-09-20 18:01:40 +00001737 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1738 OS << ':';
1739 getExtType(i).writeToStream(OS);
1740 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001741
1742 if (!isLeaf()) {
1743 if (getNumChildren() != 0) {
1744 OS << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001745 getChild(0)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001746 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1747 OS << ", ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001748 getChild(i)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001749 }
1750 }
1751 OS << ")";
1752 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001753
Craig Topper306cb122015-11-22 20:46:24 +00001754 for (const TreePredicateFn &Pred : PredicateFns)
1755 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001756 if (TransformFn)
1757 OS << "<<X:" << TransformFn->getName() << ">>";
1758 if (!getName().empty())
1759 OS << ":$" << getName();
1760
1761}
1762void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001763 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001764}
1765
Scott Michel94420742008-03-05 17:49:05 +00001766/// isIsomorphicTo - Return true if this node is recursively
1767/// isomorphic to the specified node. For this comparison, the node's
1768/// entire state is considered. The assigned name is ignored, since
1769/// nodes with differing names are considered isomorphic. However, if
1770/// the assigned name is present in the dependent variable set, then
1771/// the assigned name is considered significant and the node is
1772/// isomorphic if the names match.
Florian Hahn6b1db822018-06-14 20:32:58 +00001773bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
Scott Michel94420742008-03-05 17:49:05 +00001774 const MultipleUseVarSet &DepVars) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001775 if (N == this) return true;
1776 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
1777 getPredicateFns() != N->getPredicateFns() ||
1778 getTransformFn() != N->getTransformFn())
Chris Lattner8cab0212008-01-05 22:25:12 +00001779 return false;
1780
1781 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001782 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001783 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001784 return ((DI->getDef() == NDI->getDef())
1785 && (DepVars.find(getName()) == DepVars.end()
Florian Hahn6b1db822018-06-14 20:32:58 +00001786 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001787 }
1788 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001789 return getLeafValue() == N->getLeafValue();
Chris Lattner8cab0212008-01-05 22:25:12 +00001790 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001791
Florian Hahn6b1db822018-06-14 20:32:58 +00001792 if (N->getOperator() != getOperator() ||
1793 N->getNumChildren() != getNumChildren()) return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001794 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001795 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001796 return false;
1797 return true;
1798}
1799
1800/// clone - Make a copy of this tree and all of its children.
1801///
Florian Hahn75e87c32018-05-30 21:00:18 +00001802TreePatternNodePtr TreePatternNode::clone() const {
1803 TreePatternNodePtr New;
Chris Lattner8cab0212008-01-05 22:25:12 +00001804 if (isLeaf()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001805 New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001806 } else {
Florian Hahn75e87c32018-05-30 21:00:18 +00001807 std::vector<TreePatternNodePtr> CChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00001808 CChildren.reserve(Children.size());
1809 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001810 CChildren.push_back(getChild(i)->clone());
Craig Topper26fc06352018-07-15 06:52:49 +00001811 New = std::make_shared<TreePatternNode>(getOperator(), std::move(CChildren),
Florian Hahn75e87c32018-05-30 21:00:18 +00001812 getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001813 }
1814 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001815 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001816 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001817 New->setTransformFn(getTransformFn());
1818 return New;
1819}
1820
Chris Lattner53c39ba2010-02-14 22:22:58 +00001821/// RemoveAllTypes - Recursively strip all the types of this tree.
1822void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001823 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001824 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001825 if (isLeaf()) return;
1826 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001827 getChild(i)->RemoveAllTypes();
Chris Lattner53c39ba2010-02-14 22:22:58 +00001828}
1829
1830
Chris Lattner8cab0212008-01-05 22:25:12 +00001831/// SubstituteFormalArguments - Replace the formal arguments in this tree
1832/// with actual values specified by ArgMap.
Florian Hahn75e87c32018-05-30 21:00:18 +00001833void TreePatternNode::SubstituteFormalArguments(
1834 std::map<std::string, TreePatternNodePtr> &ArgMap) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001835 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001836
Chris Lattner8cab0212008-01-05 22:25:12 +00001837 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001838 TreePatternNode *Child = getChild(i);
1839 if (Child->isLeaf()) {
1840 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001841 // Note that, when substituting into an output pattern, Val might be an
1842 // UnsetInit.
1843 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1844 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001845 // We found a use of a formal argument, replace it with its value.
Florian Hahn6b1db822018-06-14 20:32:58 +00001846 TreePatternNodePtr NewChild = ArgMap[Child->getName()];
Dan Gohman6e979022008-10-15 06:17:21 +00001847 assert(NewChild && "Couldn't find formal argument!");
Florian Hahn6b1db822018-06-14 20:32:58 +00001848 assert((Child->getPredicateFns().empty() ||
1849 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
Dan Gohman6e979022008-10-15 06:17:21 +00001850 "Non-empty child predicate clobbered!");
Florian Hahn0a2e0b62018-06-14 11:56:19 +00001851 setChild(i, std::move(NewChild));
Chris Lattner8cab0212008-01-05 22:25:12 +00001852 }
1853 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00001854 getChild(i)->SubstituteFormalArguments(ArgMap);
Chris Lattner8cab0212008-01-05 22:25:12 +00001855 }
1856 }
1857}
1858
1859
1860/// InlinePatternFragments - If this pattern refers to any pattern
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001861/// fragments, return the set of inlined versions (this can be more than
1862/// one if a PatFrags record has multiple alternatives).
1863void TreePatternNode::InlinePatternFragments(
1864 TreePatternNodePtr T, TreePattern &TP,
1865 std::vector<TreePatternNodePtr> &OutAlternatives) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001866
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001867 if (TP.hasError())
1868 return;
1869
1870 if (isLeaf()) {
1871 OutAlternatives.push_back(T); // nothing to do.
1872 return;
1873 }
1874
Chris Lattner8cab0212008-01-05 22:25:12 +00001875 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001876
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001877 if (!Op->isSubClassOf("PatFrags")) {
1878 if (getNumChildren() == 0) {
1879 OutAlternatives.push_back(T);
1880 return;
1881 }
1882
1883 // Recursively inline children nodes.
1884 std::vector<std::vector<TreePatternNodePtr> > ChildAlternatives;
1885 ChildAlternatives.resize(getNumChildren());
Dan Gohman6e979022008-10-15 06:17:21 +00001886 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001887 TreePatternNodePtr Child = getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001888 Child->InlinePatternFragments(Child, TP, ChildAlternatives[i]);
1889 // If there are no alternatives for any child, there are no
1890 // alternatives for this expression as whole.
1891 if (ChildAlternatives[i].empty())
1892 return;
Dan Gohman6e979022008-10-15 06:17:21 +00001893
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001894 for (auto NewChild : ChildAlternatives[i])
1895 assert((Child->getPredicateFns().empty() ||
1896 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1897 "Non-empty child predicate clobbered!");
Dan Gohman6e979022008-10-15 06:17:21 +00001898 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001899
1900 // The end result is an all-pairs construction of the resultant pattern.
1901 std::vector<unsigned> Idxs;
1902 Idxs.resize(ChildAlternatives.size());
1903 bool NotDone;
1904 do {
1905 // Create the variant and add it to the output list.
1906 std::vector<TreePatternNodePtr> NewChildren;
1907 for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
1908 NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
1909 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00001910 getOperator(), std::move(NewChildren), getNumTypes());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001911
1912 // Copy over properties.
1913 R->setName(getName());
1914 R->setPredicateFns(getPredicateFns());
1915 R->setTransformFn(getTransformFn());
1916 for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
1917 R->setType(i, getExtType(i));
1918
1919 // Register alternative.
1920 OutAlternatives.push_back(R);
1921
1922 // Increment indices to the next permutation by incrementing the
1923 // indices from last index backward, e.g., generate the sequence
1924 // [0, 0], [0, 1], [1, 0], [1, 1].
1925 int IdxsIdx;
1926 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
1927 if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
1928 Idxs[IdxsIdx] = 0;
1929 else
1930 break;
1931 }
1932 NotDone = (IdxsIdx >= 0);
1933 } while (NotDone);
1934
1935 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00001936 }
1937
1938 // Otherwise, we found a reference to a fragment. First, look up its
1939 // TreePattern record.
1940 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001941
Chris Lattner8cab0212008-01-05 22:25:12 +00001942 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001943 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001944 TP.error("'" + Op->getName() + "' fragment requires " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001945 Twine(Frag->getNumArgs()) + " operands!");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001946 return;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001947 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001948
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001949 // Compute the map of formal to actual arguments.
1950 std::map<std::string, TreePatternNodePtr> ArgMap;
1951 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
1952 const TreePatternNodePtr &Child = getChildShared(i);
1953 ArgMap[Frag->getArgName(i)] = Child;
Chris Lattner8cab0212008-01-05 22:25:12 +00001954 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001955
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001956 // Loop over all fragment alternatives.
1957 for (auto Alternative : Frag->getTrees()) {
1958 TreePatternNodePtr FragTree = Alternative->clone();
Dan Gohman6e979022008-10-15 06:17:21 +00001959
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001960 TreePredicateFn PredFn(Frag);
1961 if (!PredFn.isAlwaysTrue())
1962 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001963
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001964 // Resolve formal arguments to their actual value.
1965 if (Frag->getNumArgs())
1966 FragTree->SubstituteFormalArguments(ArgMap);
1967
1968 // Transfer types. Note that the resolved alternative may have fewer
1969 // (but not more) results than the PatFrags node.
1970 FragTree->setName(getName());
1971 for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
1972 FragTree->UpdateNodeType(i, getExtType(i), TP);
1973
1974 // Transfer in the old predicates.
1975 for (const TreePredicateFn &Pred : getPredicateFns())
1976 FragTree->addPredicateFn(Pred);
1977
1978 // The fragment we inlined could have recursive inlining that is needed. See
1979 // if there are any pattern fragments in it and inline them as needed.
1980 FragTree->InlinePatternFragments(FragTree, TP, OutAlternatives);
1981 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001982}
1983
1984/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001985/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001986/// references from the register file information, for example.
1987///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001988/// When Unnamed is set, return the type of a DAG operand with no name, such as
1989/// the F8RC register class argument in:
1990///
1991/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1992///
1993/// When Unnamed is false, return the type of a named DAG operand such as the
1994/// GPR:$src operand above.
1995///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001996static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
1997 bool NotRegisters,
1998 bool Unnamed,
1999 TreePattern &TP) {
2000 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2001
Owen Andersona84be6c2011-06-27 21:06:21 +00002002 // Check to see if this is a register operand.
2003 if (R->isSubClassOf("RegisterOperand")) {
2004 assert(ResNo == 0 && "Regoperand ref only has one result!");
2005 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002006 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00002007 Record *RegClass = R->getValueAsDef("RegClass");
2008 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002009 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00002010 }
2011
Chris Lattnercabe0372010-03-15 06:00:16 +00002012 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00002013 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002014 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002015 // An unnamed register class represents itself as an i32 immediate, for
2016 // example on a COPY_TO_REGCLASS instruction.
2017 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002018 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002019
2020 // In a named operand, the register class provides the possible set of
2021 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002022 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002023 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00002024 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002025 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00002026 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002027
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002028 if (R->isSubClassOf("PatFrags")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002029 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00002030 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002031 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00002032 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002033
Chris Lattner6070ee22010-03-23 23:50:31 +00002034 if (R->isSubClassOf("Register")) {
2035 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002036 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002037 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002038 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002039 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00002040 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002041
2042 if (R->isSubClassOf("SubRegIndex")) {
2043 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002044 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002045 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002046
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002047 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002048 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002049 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2050 //
2051 // (sext_inreg GPR:$src, i16)
2052 // ~~~
2053 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002054 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002055 // With a name, the ValueType simply provides the type of the named
2056 // variable.
2057 //
2058 // (sext_inreg i32:$src, i16)
2059 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002060 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002061 return TypeSetByHwMode(); // Unknown.
2062 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2063 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002064 }
2065
2066 if (R->isSubClassOf("CondCode")) {
2067 assert(ResNo == 0 && "This node only has one result!");
2068 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002069 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00002070 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002071
Chris Lattner6070ee22010-03-23 23:50:31 +00002072 if (R->isSubClassOf("ComplexPattern")) {
2073 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002074 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002075 return TypeSetByHwMode(); // Unknown.
2076 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00002077 }
2078 if (R->isSubClassOf("PointerLikeRegClass")) {
2079 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002080 TypeSetByHwMode VTS(MVT::iPTR);
2081 TP.getInfer().expandOverloads(VTS);
2082 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00002083 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002084
Chris Lattner6070ee22010-03-23 23:50:31 +00002085 if (R->getName() == "node" || R->getName() == "srcvalue" ||
2086 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002087 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002088 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002089 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002090
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002091 if (R->isSubClassOf("Operand")) {
2092 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2093 Record *T = R->getValueAsDef("Type");
2094 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2095 }
Tim Northoverc807a172014-05-20 11:52:46 +00002096
Chris Lattner8cab0212008-01-05 22:25:12 +00002097 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002098 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00002099}
2100
Chris Lattner89c65662008-01-06 05:36:50 +00002101
2102/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2103/// CodeGenIntrinsic information for it, otherwise return a null pointer.
2104const CodeGenIntrinsic *TreePatternNode::
2105getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2106 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2107 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2108 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00002109 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002110
Florian Hahn6b1db822018-06-14 20:32:58 +00002111 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00002112 return &CDP.getIntrinsicInfo(IID);
2113}
2114
Chris Lattner53c39ba2010-02-14 22:22:58 +00002115/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2116/// return the ComplexPattern information, otherwise return null.
2117const ComplexPattern *
2118TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00002119 Record *Rec;
2120 if (isLeaf()) {
2121 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2122 if (!DI)
2123 return nullptr;
2124 Rec = DI->getDef();
2125 } else
2126 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002127
Tim Northoverc807a172014-05-20 11:52:46 +00002128 if (!Rec->isSubClassOf("ComplexPattern"))
2129 return nullptr;
2130 return &CGP.getComplexPattern(Rec);
2131}
2132
2133unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2134 // A ComplexPattern specifically declares how many results it fills in.
2135 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2136 return CP->getNumOperands();
2137
2138 // If MIOperandInfo is specified, that gives the count.
2139 if (isLeaf()) {
2140 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2141 if (DI && DI->getDef()->isSubClassOf("Operand")) {
2142 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2143 if (MIOps->getNumArgs())
2144 return MIOps->getNumArgs();
2145 }
2146 }
2147
2148 // Otherwise there is just one result.
2149 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00002150}
2151
2152/// NodeHasProperty - Return true if this node has the specified property.
2153bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002154 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002155 if (isLeaf()) {
2156 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2157 return CP->hasProperty(Property);
Matt Arsenault303327d2017-12-20 19:36:28 +00002158
Chris Lattner53c39ba2010-02-14 22:22:58 +00002159 return false;
2160 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002161
Matt Arsenault303327d2017-12-20 19:36:28 +00002162 if (Property != SDNPHasChain) {
2163 // The chain proprety is already present on the different intrinsic node
2164 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2165 // on the intrinsic. Anything else is specific to the individual intrinsic.
2166 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2167 return Int->hasProperty(Property);
2168 }
2169
2170 if (!Operator->isSubClassOf("SDPatternOperator"))
2171 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002172
Chris Lattner53c39ba2010-02-14 22:22:58 +00002173 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2174}
2175
2176
2177
2178
2179/// TreeHasProperty - Return true if any node in this tree has the specified
2180/// property.
2181bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002182 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002183 if (NodeHasProperty(Property, CGP))
2184 return true;
2185 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002186 if (getChild(i)->TreeHasProperty(Property, CGP))
Chris Lattner53c39ba2010-02-14 22:22:58 +00002187 return true;
2188 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002189}
Chris Lattner53c39ba2010-02-14 22:22:58 +00002190
Evan Cheng49bad4c2008-06-16 20:29:38 +00002191/// isCommutativeIntrinsic - Return true if the node corresponds to a
2192/// commutative intrinsic.
2193bool
2194TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2195 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2196 return Int->isCommutative;
2197 return false;
2198}
2199
Florian Hahn6b1db822018-06-14 20:32:58 +00002200static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2201 if (!N->isLeaf())
2202 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00002203
Florian Hahn6b1db822018-06-14 20:32:58 +00002204 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
Matt Arsenaulteb492162014-11-02 23:46:51 +00002205 if (DI && DI->getDef()->isSubClassOf(Class))
2206 return true;
2207
2208 return false;
2209}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002210
2211static void emitTooManyOperandsError(TreePattern &TP,
2212 StringRef InstName,
2213 unsigned Expected,
2214 unsigned Actual) {
2215 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2216 " operands but expected only " + Twine(Expected) + "!");
2217}
2218
2219static void emitTooFewOperandsError(TreePattern &TP,
2220 StringRef InstName,
2221 unsigned Actual) {
2222 TP.error("Instruction '" + InstName +
2223 "' expects more than the provided " + Twine(Actual) + " operands!");
2224}
2225
Bob Wilson1b97f3f2009-01-05 17:23:09 +00002226/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00002227/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002228/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00002229bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002230 if (TP.hasError())
2231 return false;
2232
Chris Lattnerab3242f2008-01-06 01:10:31 +00002233 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00002234 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002235 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002236 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00002237 bool MadeChange = false;
2238 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2239 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002240 NotRegisters,
2241 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002242 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00002243 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002244
Sean Silvafb509ed2012-10-10 20:24:43 +00002245 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002246 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002247
Chris Lattnerf1447252010-03-19 21:37:09 +00002248 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002249 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002250
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002251 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00002252 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002253
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002254 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2255 for (auto &P : VVT) {
2256 MVT::SimpleValueType VT = P.second.SimpleTy;
2257 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2258 continue;
2259 unsigned Size = MVT(VT).getSizeInBits();
2260 // Make sure that the value is representable for this type.
2261 if (Size >= 32)
2262 continue;
2263 // Check that the value doesn't use more bits than we have. It must
2264 // either be a sign- or zero-extended equivalent of the original.
2265 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2266 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2267 SignBitAndAbove == 1)
2268 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002269
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002270 TP.error("Integer value '" + Twine(II->getValue()) +
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002271 "' is out of range for type '" + getEnumName(VT) + "'!");
2272 break;
2273 }
2274 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002275 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002276
Chris Lattner8cab0212008-01-05 22:25:12 +00002277 return false;
2278 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002279
Chris Lattneree820ac2010-02-23 05:51:07 +00002280 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002281 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00002282
Chris Lattner8cab0212008-01-05 22:25:12 +00002283 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00002284 unsigned NumRetVTs = Int->IS.RetVTs.size();
2285 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002286
Bill Wendling91821472008-11-13 09:08:33 +00002287 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00002288 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00002289
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002290 if (getNumChildren() != NumParamVTs + 1) {
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002291 TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2292 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002293 return false;
2294 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002295
2296 // Apply type info to the intrinsic ID.
Florian Hahn6b1db822018-06-14 20:32:58 +00002297 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002298
Chris Lattnerf1447252010-03-19 21:37:09 +00002299 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002300 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002301
Chris Lattnerf1447252010-03-19 21:37:09 +00002302 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
Florian Hahn6b1db822018-06-14 20:32:58 +00002303 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2304 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002305 }
2306 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002307 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002308
Chris Lattneree820ac2010-02-23 05:51:07 +00002309 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002310 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002311
Chris Lattner135091b2010-03-28 08:48:47 +00002312 // Check that the number of operands is sane. Negative operands -> varargs.
2313 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002314 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00002315 TP.error(getOperator()->getName() + " node requires exactly " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002316 Twine(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002317 return false;
2318 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002319
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002320 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00002321 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002322 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2323 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002324 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002325 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002326
Chris Lattneree820ac2010-02-23 05:51:07 +00002327 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002328 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002329 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00002330 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002331
Chris Lattnerd44966f2010-03-27 19:15:02 +00002332 bool MadeChange = false;
2333
2334 // Apply the result types to the node, these come from the things in the
2335 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00002336 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2337 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002338 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2339 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002340
Chris Lattnerd44966f2010-03-27 19:15:02 +00002341 // If the instruction has implicit defs, we apply the first one as a result.
2342 // FIXME: This sucks, it should apply all implicit defs.
2343 if (!InstInfo.ImplicitDefs.empty()) {
2344 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002345
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002346 // FIXME: Generalize to multiple possible types and multiple possible
2347 // ImplicitDefs.
2348 MVT::SimpleValueType VT =
2349 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002350
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002351 if (VT != MVT::Other)
2352 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002353 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002354
Chris Lattnercabe0372010-03-15 06:00:16 +00002355 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2356 // be the same.
2357 if (getOperator()->getName() == "INSERT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00002358 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2359 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2360 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002361 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2362 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2363 // variadic.
2364
2365 unsigned NChild = getNumChildren();
2366 if (NChild < 3) {
2367 TP.error("REG_SEQUENCE requires at least 3 operands!");
2368 return false;
2369 }
2370
2371 if (NChild % 2 == 0) {
2372 TP.error("REG_SEQUENCE requires an odd number of operands!");
2373 return false;
2374 }
2375
2376 if (!isOperandClass(getChild(0), "RegisterClass")) {
2377 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2378 return false;
2379 }
2380
2381 for (unsigned I = 1; I < NChild; I += 2) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002382 TreePatternNode *SubIdxChild = getChild(I + 1);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002383 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2384 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002385 Twine(I + 1) + "!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00002386 return false;
2387 }
2388 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002389 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002390
2391 unsigned ChildNo = 0;
2392 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2393 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002394
Chris Lattner8cab0212008-01-05 22:25:12 +00002395 // If the instruction expects a predicate or optional def operand, we
2396 // codegen this by setting the operand to it's default value if it has a
2397 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00002398 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002399 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2400 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002401
Chris Lattner8cab0212008-01-05 22:25:12 +00002402 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002403 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002404 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002405 return false;
2406 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002407
Florian Hahn6b1db822018-06-14 20:32:58 +00002408 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002409 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002410
2411 // If the operand has sub-operands, they may be provided by distinct
2412 // child patterns, so attempt to match each sub-operand separately.
2413 if (OperandNode->isSubClassOf("Operand")) {
2414 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2415 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2416 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002417 // a single ComplexPattern-related Operand.
2418
2419 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002420 // Match first sub-operand against the child we already have.
2421 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2422 MadeChange |=
2423 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2424
2425 // And the remaining sub-operands against subsequent children.
2426 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2427 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002428 emitTooFewOperandsError(TP, getOperator()->getName(),
2429 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002430 return false;
2431 }
Florian Hahn6b1db822018-06-14 20:32:58 +00002432 Child = getChild(ChildNo++);
Ulrich Weigande618abd2013-03-19 19:51:09 +00002433
2434 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2435 MadeChange |=
2436 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2437 }
2438 continue;
2439 }
2440 }
2441 }
2442
2443 // If we didn't match by pieces above, attempt to match the whole
2444 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002445 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002446 }
Christopher Lamba7312392008-03-11 09:33:47 +00002447
Matt Arsenaulteb492162014-11-02 23:46:51 +00002448 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002449 emitTooManyOperandsError(TP, getOperator()->getName(),
2450 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002451 return false;
2452 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002453
Ulrich Weigande618abd2013-03-19 19:51:09 +00002454 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002455 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002456 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002457 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002458
Tim Northoverc807a172014-05-20 11:52:46 +00002459 if (getOperator()->isSubClassOf("ComplexPattern")) {
2460 bool MadeChange = false;
2461
2462 for (unsigned i = 0; i < getNumChildren(); ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002463 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Tim Northoverc807a172014-05-20 11:52:46 +00002464
2465 return MadeChange;
2466 }
2467
Chris Lattneree820ac2010-02-23 05:51:07 +00002468 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002469
Chris Lattneree820ac2010-02-23 05:51:07 +00002470 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002471 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002472 TP.error("Node transform '" + getOperator()->getName() +
2473 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002474 return false;
2475 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002476
Florian Hahn6b1db822018-06-14 20:32:58 +00002477 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002478 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002479}
2480
2481/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2482/// RHS of a commutative operation, not the on LHS.
Florian Hahn6b1db822018-06-14 20:32:58 +00002483static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2484 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
Chris Lattner8cab0212008-01-05 22:25:12 +00002485 return true;
Florian Hahn6b1db822018-06-14 20:32:58 +00002486 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002487 return true;
2488 return false;
2489}
2490
2491
2492/// canPatternMatch - If it is impossible for this pattern to match on this
2493/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002494/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002495/// that can never possibly work), and to prevent the pattern permuter from
2496/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002497bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002498 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002499 if (isLeaf()) return true;
2500
2501 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002502 if (!getChild(i)->canPatternMatch(Reason, CDP))
Chris Lattner8cab0212008-01-05 22:25:12 +00002503 return false;
2504
2505 // If this is an intrinsic, handle cases that would make it not match. For
2506 // example, if an operand is required to be an immediate.
2507 if (getOperator()->isSubClassOf("Intrinsic")) {
2508 // TODO:
2509 return true;
2510 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002511
Tim Northoverc807a172014-05-20 11:52:46 +00002512 if (getOperator()->isSubClassOf("ComplexPattern"))
2513 return true;
2514
Chris Lattner8cab0212008-01-05 22:25:12 +00002515 // If this node is a commutative operator, check that the LHS isn't an
2516 // immediate.
2517 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002518 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2519 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002520 // Scan all of the operands of the node and make sure that only the last one
2521 // is a constant node, unless the RHS also is.
2522 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002523 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002524 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002525 if (OnlyOnRHSOfCommutative(getChild(i))) {
2526 Reason="Immediate value must be on the RHS of commutative operators!";
2527 return false;
2528 }
2529 }
2530 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002531
Chris Lattner8cab0212008-01-05 22:25:12 +00002532 return true;
2533}
2534
2535//===----------------------------------------------------------------------===//
2536// TreePattern implementation
2537//
2538
David Greeneaf8ee2c2011-07-29 22:43:06 +00002539TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002540 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002541 isInputPattern(isInput), HasError(false),
2542 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002543 for (Init *I : RawPat->getValues())
2544 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002545}
2546
David Greeneaf8ee2c2011-07-29 22:43:06 +00002547TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002548 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002549 isInputPattern(isInput), HasError(false),
2550 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002551 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002552}
2553
Florian Hahn75e87c32018-05-30 21:00:18 +00002554TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
2555 CodeGenDAGPatterns &cdp)
2556 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2557 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002558 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002559}
2560
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002561void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002562 if (HasError)
2563 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002564 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002565 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2566 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002567}
2568
Chris Lattnercabe0372010-03-15 06:00:16 +00002569void TreePattern::ComputeNamedNodes() {
Florian Hahn6b1db822018-06-14 20:32:58 +00002570 for (TreePatternNodePtr &Tree : Trees)
2571 ComputeNamedNodes(Tree.get());
Chris Lattnercabe0372010-03-15 06:00:16 +00002572}
2573
Florian Hahn6b1db822018-06-14 20:32:58 +00002574void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002575 if (!N->getName().empty())
Florian Hahn6b1db822018-06-14 20:32:58 +00002576 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002577
Chris Lattnercabe0372010-03-15 06:00:16 +00002578 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002579 ComputeNamedNodes(N->getChild(i));
Chris Lattnercabe0372010-03-15 06:00:16 +00002580}
2581
Florian Hahn75e87c32018-05-30 21:00:18 +00002582TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
2583 StringRef OpName) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002584 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002585 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002586
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002587 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002588 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002589 /// (foo GPR, imm) -> (foo GPR, (imm))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002590 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
David Greenee32ebf22011-07-29 19:07:07 +00002591 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002592 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002593 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002594 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002595
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002596 // Input argument?
Florian Hahn75e87c32018-05-30 21:00:18 +00002597 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002598 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002599 if (OpName.empty())
2600 error("'node' argument requires a name to match with operand list");
2601 Args.push_back(OpName);
2602 }
2603
2604 Res->setName(OpName);
2605 return Res;
2606 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002607
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002608 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002609 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002610 if (OpName.empty())
2611 error("'?' argument requires a name to match with operand list");
Florian Hahn75e87c32018-05-30 21:00:18 +00002612 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002613 Args.push_back(OpName);
2614 Res->setName(OpName);
2615 return Res;
2616 }
2617
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002618 if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002619 if (!OpName.empty())
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002620 error("Constant int or bit argument should not have a name!");
2621 if (isa<BitInit>(TheInit))
2622 TheInit = TheInit->convertInitializerTo(IntRecTy::get());
2623 return std::make_shared<TreePatternNode>(TheInit, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002624 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002625
Sean Silvafb509ed2012-10-10 20:24:43 +00002626 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002627 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002628 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002629 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002630 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002631 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002632 }
2633
Sean Silvafb509ed2012-10-10 20:24:43 +00002634 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002635 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002636 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002637 error("Pattern has unexpected init kind!");
2638 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002639 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002640 if (!OpDef) error("Pattern has unexpected operator type!");
2641 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002642
Chris Lattner8cab0212008-01-05 22:25:12 +00002643 if (Operator->isSubClassOf("ValueType")) {
2644 // If the operator is a ValueType, then this must be "type cast" of a leaf
2645 // node.
2646 if (Dag->getNumArgs() != 1)
2647 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002648
Florian Hahn75e87c32018-05-30 21:00:18 +00002649 TreePatternNodePtr New =
2650 ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002651
Chris Lattner8cab0212008-01-05 22:25:12 +00002652 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002653 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002654 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2655 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002656
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002657 if (!OpName.empty())
2658 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002659 return New;
2660 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002661
Chris Lattner8cab0212008-01-05 22:25:12 +00002662 // Verify that this is something that makes sense for an operator.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002663 if (!Operator->isSubClassOf("PatFrags") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002664 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002665 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002666 !Operator->isSubClassOf("SDNodeXForm") &&
2667 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002668 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002669 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002670 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002671 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002672
Chris Lattner8cab0212008-01-05 22:25:12 +00002673 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002674 if (isInputPattern) {
2675 if (Operator->isSubClassOf("Instruction") ||
2676 Operator->isSubClassOf("SDNodeXForm"))
2677 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2678 } else {
2679 if (Operator->isSubClassOf("Intrinsic"))
2680 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002681
Chris Lattner2e9eae12010-03-28 06:57:56 +00002682 if (Operator->isSubClassOf("SDNode") &&
2683 Operator->getName() != "imm" &&
2684 Operator->getName() != "fpimm" &&
2685 Operator->getName() != "tglobaltlsaddr" &&
2686 Operator->getName() != "tconstpool" &&
2687 Operator->getName() != "tjumptable" &&
2688 Operator->getName() != "tframeindex" &&
2689 Operator->getName() != "texternalsym" &&
2690 Operator->getName() != "tblockaddress" &&
2691 Operator->getName() != "tglobaladdr" &&
2692 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002693 Operator->getName() != "vt" &&
2694 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002695 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2696 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002697
Florian Hahn75e87c32018-05-30 21:00:18 +00002698 std::vector<TreePatternNodePtr> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002699
2700 // Parse all the operands.
2701 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002702 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002703
Hal Finkel8b4bdfdb2018-01-03 11:35:09 +00002704 // Get the actual number of results before Operator is converted to an intrinsic
2705 // node (which is hard-coded to have either zero or one result).
2706 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2707
Fangrui Song956ee792018-03-30 22:22:31 +00002708 // If the operator is an intrinsic, then this is just syntactic sugar for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002709 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002710 // convert the intrinsic name to a number.
2711 if (Operator->isSubClassOf("Intrinsic")) {
2712 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2713 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2714
2715 // If this intrinsic returns void, it must have side-effects and thus a
2716 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002717 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002718 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002719 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002720 // Has side-effects, requires chain.
2721 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002722 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002723 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002724
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002725 Children.insert(Children.begin(),
2726 std::make_shared<TreePatternNode>(IntInit::get(IID), 1));
Chris Lattner8cab0212008-01-05 22:25:12 +00002727 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002728
Tim Northoverc807a172014-05-20 11:52:46 +00002729 if (Operator->isSubClassOf("ComplexPattern")) {
2730 for (unsigned i = 0; i < Children.size(); ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002731 TreePatternNodePtr Child = Children[i];
Tim Northoverc807a172014-05-20 11:52:46 +00002732
2733 if (Child->getName().empty())
2734 error("All arguments to a ComplexPattern must be named");
2735
2736 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2737 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2738 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2739 auto OperandId = std::make_pair(Operator, i);
2740 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2741 if (PrevOp != ComplexPatternOperands.end()) {
2742 if (PrevOp->getValue() != OperandId)
2743 error("All ComplexPattern operands must appear consistently: "
2744 "in the same order in just one ComplexPattern instance.");
2745 } else
2746 ComplexPatternOperands[Child->getName()] = OperandId;
2747 }
2748 }
2749
Florian Hahn6b1db822018-06-14 20:32:58 +00002750 TreePatternNodePtr Result =
Craig Topper26fc06352018-07-15 06:52:49 +00002751 std::make_shared<TreePatternNode>(Operator, std::move(Children),
2752 NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002753 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002754
Matthias Braun7cf3b112016-12-05 06:00:41 +00002755 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002756 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002757 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002758 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002759 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002760}
2761
Chris Lattnera787c9e2010-03-28 08:38:32 +00002762/// SimplifyTree - See if we can simplify this tree to eliminate something that
2763/// will never match in favor of something obvious that will. This is here
2764/// strictly as a convenience to target authors because it allows them to write
2765/// more type generic things and have useless type casts fold away.
2766///
2767/// This returns true if any change is made.
Florian Hahn75e87c32018-05-30 21:00:18 +00002768static bool SimplifyTree(TreePatternNodePtr &N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002769 if (N->isLeaf())
2770 return false;
2771
2772 // If we have a bitconvert with a resolved type and if the source and
2773 // destination types are the same, then the bitconvert is useless, remove it.
2774 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002775 N->getExtType(0).isValueTypeByHwMode(false) &&
Florian Hahn6b1db822018-06-14 20:32:58 +00002776 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002777 N->getName().empty()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002778 N = N->getChildShared(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002779 SimplifyTree(N);
2780 return true;
2781 }
2782
2783 // Walk all children.
2784 bool MadeChange = false;
2785 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002786 TreePatternNodePtr Child = N->getChildShared(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002787 MadeChange |= SimplifyTree(Child);
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002788 N->setChild(i, std::move(Child));
Chris Lattnera787c9e2010-03-28 08:38:32 +00002789 }
2790 return MadeChange;
2791}
2792
2793
2794
Chris Lattner8cab0212008-01-05 22:25:12 +00002795/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002796/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002797/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002798bool TreePattern::
2799InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2800 if (NamedNodes.empty())
2801 ComputeNamedNodes();
2802
Chris Lattner8cab0212008-01-05 22:25:12 +00002803 bool MadeChange = true;
2804 while (MadeChange) {
2805 MadeChange = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002806 for (TreePatternNodePtr &Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002807 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2808 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002809 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002810
2811 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002812 for (auto &Entry : NamedNodes) {
2813 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002814
Chris Lattnercabe0372010-03-15 06:00:16 +00002815 // If we have input named node types, propagate their types to the named
2816 // values here.
2817 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002818 if (!InNamedTypes->count(Entry.getKey())) {
2819 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002820 "' in output pattern but not input pattern");
2821 return true;
2822 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002823
2824 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002825 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002826
2827 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002828 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002829 // If this node is a register class, and it is the root of the pattern
2830 // then we're mapping something onto an input register. We allow
2831 // changing the type of the input register in this case. This allows
2832 // us to match things like:
2833 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Florian Hahn75e87c32018-05-30 21:00:18 +00002834 if (Node == Trees[0].get() && Node->isLeaf()) {
Craig Topper306cb122015-11-22 20:46:24 +00002835 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002836 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2837 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002838 continue;
2839 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002840
Craig Topper306cb122015-11-22 20:46:24 +00002841 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002842 InNodes[0]->getNumTypes() == 1 &&
2843 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002844 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2845 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002846 }
2847 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002848
Chris Lattnercabe0372010-03-15 06:00:16 +00002849 // If there are multiple nodes with the same name, they must all have the
2850 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002851 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002852 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002853 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002854 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002855 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002856
Chris Lattnerf1447252010-03-19 21:37:09 +00002857 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2858 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002859 }
2860 }
2861 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002862 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002863
Chris Lattner8cab0212008-01-05 22:25:12 +00002864 bool HasUnresolvedTypes = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002865 for (const TreePatternNodePtr &Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002866 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002867 return !HasUnresolvedTypes;
2868}
2869
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002870void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002871 OS << getRecord()->getName();
2872 if (!Args.empty()) {
2873 OS << "(" << Args[0];
2874 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2875 OS << ", " << Args[i];
2876 OS << ")";
2877 }
2878 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002879
Chris Lattner8cab0212008-01-05 22:25:12 +00002880 if (Trees.size() > 1)
2881 OS << "[\n";
Florian Hahn75e87c32018-05-30 21:00:18 +00002882 for (const TreePatternNodePtr &Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002883 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002884 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002885 OS << "\n";
2886 }
2887
2888 if (Trees.size() > 1)
2889 OS << "]\n";
2890}
2891
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002892void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002893
2894//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002895// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002896//
2897
Daniel Sanders7e523672017-11-11 03:23:44 +00002898CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
2899 PatternRewriterFn PatternRewriter)
2900 : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
2901 PatternRewriter(PatternRewriter) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002902
Justin Bogner92a8c612016-07-15 16:31:37 +00002903 Intrinsics = CodeGenIntrinsicTable(Records, false);
2904 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002905 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002906 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002907 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002908 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002909 ParseDefaultOperands();
2910 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002911 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002912 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002913
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002914 // Break patterns with parameterized types into a series of patterns,
2915 // where each one has a fixed type and is predicated on the conditions
2916 // of the associated HW mode.
2917 ExpandHwModeBasedTypes();
2918
Chris Lattner8cab0212008-01-05 22:25:12 +00002919 // Generate variants. For example, commutative patterns can match
2920 // multiple ways. Add them to PatternsToMatch as well.
2921 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002922
2923 // Infer instruction flags. For example, we can detect loads,
2924 // stores, and side effects in many cases by examining an
2925 // instruction's pattern.
2926 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002927
2928 // Verify that instruction flags match the patterns.
2929 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002930}
2931
Daniel Sanders9e0ae7b2017-10-13 19:00:01 +00002932Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002933 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002934 if (!N || !N->isSubClassOf("SDNode"))
2935 PrintFatalError("Error getting SDNode '" + Name + "'!");
2936
Chris Lattner8cab0212008-01-05 22:25:12 +00002937 return N;
2938}
2939
2940// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002941void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002942 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002943 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2944
Chris Lattner8cab0212008-01-05 22:25:12 +00002945 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002946 Record *R = Nodes.back();
2947 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002948 Nodes.pop_back();
2949 }
2950
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002951 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002952 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2953 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2954 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2955}
2956
2957/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2958/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002959void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002960 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2961 while (!Xforms.empty()) {
2962 Record *XFormNode = Xforms.back();
2963 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00002964 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002965 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002966
2967 Xforms.pop_back();
2968 }
2969}
2970
Chris Lattnerab3242f2008-01-06 01:10:31 +00002971void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002972 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2973 while (!AMs.empty()) {
2974 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2975 AMs.pop_back();
2976 }
2977}
2978
2979
2980/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2981/// file, building up the PatternFragments map. After we've collected them all,
2982/// inline fragments together as necessary, so that there are no references left
2983/// inside a pattern fragment to a pattern fragment.
2984///
Hal Finkel2756dc12014-02-28 00:26:56 +00002985void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002986 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrags");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002987
Chris Lattnere7170df2008-01-05 22:43:57 +00002988 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002989 for (Record *Frag : Fragments) {
2990 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002991 continue;
2992
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002993 ListInit *LI = Frag->getValueAsListInit("Fragments");
Hal Finkel2756dc12014-02-28 00:26:56 +00002994 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002995 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002996 Frag, LI, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002997 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002998
Chris Lattnere7170df2008-01-05 22:43:57 +00002999 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00003000 std::vector<std::string> &Args = P->getArgList();
Zachary Turner249dc142017-09-20 18:01:40 +00003001 // Copy the args so we can take StringRefs to them.
3002 auto ArgsCopy = Args;
3003 SmallDenseSet<StringRef, 4> OperandsSet;
3004 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003005
Chris Lattnere7170df2008-01-05 22:43:57 +00003006 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00003007 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003008
Chris Lattner8cab0212008-01-05 22:25:12 +00003009 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00003010 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00003011 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00003012 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003013 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00003014 if (!OpsOp ||
3015 (OpsOp->getDef()->getName() != "ops" &&
3016 OpsOp->getDef()->getName() != "outs" &&
3017 OpsOp->getDef()->getName() != "ins"))
3018 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003019
3020 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00003021 Args.clear();
3022 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003023 if (!isa<DefInit>(OpsList->getArg(j)) ||
3024 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00003025 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00003026 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00003027 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00003028 StringRef ArgNameStr = OpsList->getArgNameStr(j);
3029 if (!OperandsSet.count(ArgNameStr))
3030 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00003031 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00003032 OperandsSet.erase(ArgNameStr);
3033 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003034 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003035
Chris Lattnere7170df2008-01-05 22:43:57 +00003036 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003037 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00003038 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003039
Chris Lattnere7170df2008-01-05 22:43:57 +00003040 // If there is a code init for this fragment, keep track of the fact that
3041 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00003042 TreePredicateFn PredFn(P);
3043 if (!PredFn.isAlwaysTrue())
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003044 for (auto T : P->getTrees())
3045 T->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003046
Chris Lattner8cab0212008-01-05 22:25:12 +00003047 // If there is a node transformation corresponding to this, keep track of
3048 // it.
Craig Topper306cb122015-11-22 20:46:24 +00003049 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00003050 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003051 for (auto T : P->getTrees())
3052 T->setTransformFn(Transform);
Chris Lattner8cab0212008-01-05 22:25:12 +00003053 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003054
Chris Lattner8cab0212008-01-05 22:25:12 +00003055 // Now that we've parsed all of the tree fragments, do a closure on them so
3056 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00003057 for (Record *Frag : Fragments) {
3058 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00003059 continue;
3060
Craig Topper306cb122015-11-22 20:46:24 +00003061 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00003062 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003063
Chris Lattner8cab0212008-01-05 22:25:12 +00003064 // Infer as many types as possible. Don't worry about it if we don't infer
Ulrich Weigand22b1af82018-07-13 16:42:15 +00003065 // all of them, some may depend on the inputs of the pattern. Also, don't
3066 // validate type sets; validation may cause spurious failures e.g. if a
3067 // fragment needs floating-point types but the current target does not have
3068 // any (this is only an error if that fragment is ever used!).
3069 {
3070 TypeInfer::SuppressValidation SV(ThePat.getInfer());
3071 ThePat.InferAllTypes();
3072 ThePat.resetError();
3073 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003074
Chris Lattner8cab0212008-01-05 22:25:12 +00003075 // If debugging, print out the pattern fragment result.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003076 LLVM_DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003077 }
3078}
3079
Chris Lattnerab3242f2008-01-06 01:10:31 +00003080void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00003081 std::vector<Record*> DefaultOps;
3082 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00003083
3084 // Find some SDNode.
3085 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00003086 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003087
Tom Stellardb7246a72012-09-06 14:15:52 +00003088 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3089 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003090
Tom Stellardb7246a72012-09-06 14:15:52 +00003091 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3092 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00003093 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00003094 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3095 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3096 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00003097 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003098
Tom Stellardb7246a72012-09-06 14:15:52 +00003099 // Create a TreePattern to parse this.
3100 TreePattern P(DefaultOps[i], DI, false, *this);
3101 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003102
Tom Stellardb7246a72012-09-06 14:15:52 +00003103 // Copy the operands over into a DAGDefaultOperand.
3104 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003105
Florian Hahn75e87c32018-05-30 21:00:18 +00003106 const TreePatternNodePtr &T = P.getTree(0);
Tom Stellardb7246a72012-09-06 14:15:52 +00003107 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
Florian Hahn75e87c32018-05-30 21:00:18 +00003108 TreePatternNodePtr TPN = T->getChildShared(op);
Tom Stellardb7246a72012-09-06 14:15:52 +00003109 while (TPN->ApplyTypeConstraints(P, false))
3110 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003111
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003112 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00003113 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3114 DefaultOps[i]->getName() +
3115 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003116 }
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003117 DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
Chris Lattner8cab0212008-01-05 22:25:12 +00003118 }
Tom Stellardb7246a72012-09-06 14:15:52 +00003119
3120 // Insert it into the DefaultOperands map so we can find it later.
3121 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00003122 }
3123}
3124
3125/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3126/// instruction input. Return true if this is a real use.
David Blaikie19b22d42018-06-11 22:14:43 +00003127static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003128 std::map<std::string, TreePatternNodePtr> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003129 // No name -> not interesting.
3130 if (Pat->getName().empty()) {
3131 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003132 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00003133 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3134 DI->getDef()->isSubClassOf("RegisterOperand")))
David Blaikie19b22d42018-06-11 22:14:43 +00003135 I.error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003136 }
3137 return false;
3138 }
3139
3140 Record *Rec;
3141 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003142 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
David Blaikie19b22d42018-06-11 22:14:43 +00003143 if (!DI)
3144 I.error("Input $" + Pat->getName() + " must be an identifier!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003145 Rec = DI->getDef();
3146 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00003147 Rec = Pat->getOperator();
3148 }
3149
3150 // SRCVALUE nodes are ignored.
3151 if (Rec->getName() == "srcvalue")
3152 return false;
3153
Florian Hahn75e87c32018-05-30 21:00:18 +00003154 TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
Chris Lattner8cab0212008-01-05 22:25:12 +00003155 if (!Slot) {
3156 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003157 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00003158 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003159 Record *SlotRec;
3160 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003161 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003162 } else {
3163 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3164 SlotRec = Slot->getOperator();
3165 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003166
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003167 // Ensure that the inputs agree if we've already seen this input.
3168 if (Rec != SlotRec)
David Blaikie19b22d42018-06-11 22:14:43 +00003169 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003170 // Ensure that the types can agree as well.
3171 Slot->UpdateNodeType(0, Pat->getExtType(0), I);
3172 Pat->UpdateNodeType(0, Slot->getExtType(0), I);
Chris Lattnerf1447252010-03-19 21:37:09 +00003173 if (Slot->getExtTypes() != Pat->getExtTypes())
David Blaikie19b22d42018-06-11 22:14:43 +00003174 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00003175 return true;
3176}
3177
3178/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3179/// part of "I", the instruction), computing the set of inputs and outputs of
3180/// the pattern. Report errors if we see anything naughty.
Florian Hahn75e87c32018-05-30 21:00:18 +00003181void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
Florian Hahn6b1db822018-06-14 20:32:58 +00003182 TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003183 std::map<std::string, TreePatternNodePtr> &InstInputs,
3184 std::map<std::string, TreePatternNodePtr> &InstResults,
3185 std::vector<Record *> &InstImpResults) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003186
3187 // The instruction pattern still has unresolved fragments. For *named*
3188 // nodes we must resolve those here. This may not result in multiple
3189 // alternatives.
3190 if (!Pat->getName().empty()) {
3191 TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3192 SrcPattern.InlinePatternFragments();
3193 SrcPattern.InferAllTypes();
3194 Pat = SrcPattern.getOnlyTree();
3195 }
3196
Chris Lattner8cab0212008-01-05 22:25:12 +00003197 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00003198 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00003199 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003200 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003201 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003202 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003203
Chris Lattnerf2d70992010-02-17 06:53:36 +00003204 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003205 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003206 TreePatternNode *Dest = Pat->getChild(i);
3207 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003208 I.error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003209
Florian Hahn6b1db822018-06-14 20:32:58 +00003210 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00003211 if (!Val || !Val->getDef()->isSubClassOf("Register"))
David Blaikie19b22d42018-06-11 22:14:43 +00003212 I.error("implicitly defined value should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003213 InstImpResults.push_back(Val->getDef());
3214 }
3215 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003216 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003217
Chris Lattnerf2d70992010-02-17 06:53:36 +00003218 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003219 // If this is not a set, verify that the children nodes are not void typed,
3220 // and recurse.
3221 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003222 if (Pat->getChild(i)->getNumTypes() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003223 I.error("Cannot have void nodes inside of patterns!");
Florian Hahn75e87c32018-05-30 21:00:18 +00003224 FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3225 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003226 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003227
Chris Lattner8cab0212008-01-05 22:25:12 +00003228 // If this is a non-leaf node with no children, treat it basically as if
3229 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00003230 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003231
Chris Lattner8cab0212008-01-05 22:25:12 +00003232 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003233 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003234 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003235 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003236
Chris Lattner8cab0212008-01-05 22:25:12 +00003237 // Otherwise, this is a set, validate and collect instruction results.
3238 if (Pat->getNumChildren() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003239 I.error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003240
Chris Lattner8cab0212008-01-05 22:25:12 +00003241 if (Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003242 I.error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003243
Chris Lattner8cab0212008-01-05 22:25:12 +00003244 // Check the set destinations.
3245 unsigned NumDests = Pat->getNumChildren()-1;
3246 for (unsigned i = 0; i != NumDests; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003247 TreePatternNodePtr Dest = Pat->getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003248 // For set destinations we also must resolve fragments here.
3249 TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3250 DestPattern.InlinePatternFragments();
3251 DestPattern.InferAllTypes();
3252 Dest = DestPattern.getOnlyTree();
3253
Chris Lattner8cab0212008-01-05 22:25:12 +00003254 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003255 I.error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003256
Sean Silvafb509ed2012-10-10 20:24:43 +00003257 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00003258 if (!Val) {
David Blaikie19b22d42018-06-11 22:14:43 +00003259 I.error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00003260 continue;
3261 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003262
3263 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003264 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00003265 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00003266 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003267 if (Dest->getName().empty())
David Blaikie19b22d42018-06-11 22:14:43 +00003268 I.error("set destination must have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003269 if (InstResults.count(Dest->getName()))
David Blaikie19b22d42018-06-11 22:14:43 +00003270 I.error("cannot set '" + Dest->getName() + "' multiple times");
Chris Lattner8cab0212008-01-05 22:25:12 +00003271 InstResults[Dest->getName()] = Dest;
3272 } else if (Val->getDef()->isSubClassOf("Register")) {
3273 InstImpResults.push_back(Val->getDef());
3274 } else {
David Blaikie19b22d42018-06-11 22:14:43 +00003275 I.error("set destination should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003276 }
3277 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003278
Chris Lattner8cab0212008-01-05 22:25:12 +00003279 // Verify and collect info from the computation.
Florian Hahn75e87c32018-05-30 21:00:18 +00003280 FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3281 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003282}
3283
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003284//===----------------------------------------------------------------------===//
3285// Instruction Analysis
3286//===----------------------------------------------------------------------===//
3287
3288class InstAnalyzer {
3289 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003290public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003291 bool hasSideEffects;
3292 bool mayStore;
3293 bool mayLoad;
3294 bool isBitcast;
3295 bool isVariadic;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003296 bool hasChain;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003297
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003298 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3299 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003300 isBitcast(false), isVariadic(false), hasChain(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003301
Craig Topper2a053a92017-06-20 16:34:37 +00003302 void Analyze(const PatternToMatch &Pat) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003303 const TreePatternNode *N = Pat.getSrcPattern();
3304 AnalyzeNode(N);
3305 // These properties are detected only on the root node.
3306 isBitcast = IsNodeBitcast(N);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003307 }
3308
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003309private:
Florian Hahn6b1db822018-06-14 20:32:58 +00003310 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003311 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00003312 return false;
3313
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003314 if (N->isLeaf())
3315 return false;
3316 if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
Evan Cheng880e299d2011-03-15 05:09:26 +00003317 return false;
3318
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003319 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
Evan Cheng880e299d2011-03-15 05:09:26 +00003320 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3321 return false;
3322 return OpInfo.getEnumName() == "ISD::BITCAST";
3323 }
3324
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003325public:
Florian Hahn6b1db822018-06-14 20:32:58 +00003326 void AnalyzeNode(const TreePatternNode *N) {
3327 if (N->isLeaf()) {
3328 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003329 Record *LeafRec = DI->getDef();
3330 // Handle ComplexPattern leaves.
3331 if (LeafRec->isSubClassOf("ComplexPattern")) {
3332 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3333 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3334 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003335 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003336 }
3337 }
3338 return;
3339 }
3340
3341 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00003342 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3343 AnalyzeNode(N->getChild(i));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003344
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003345 // Notice properties of the node.
Florian Hahn6b1db822018-06-14 20:32:58 +00003346 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3347 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3348 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3349 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003350 if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003351
Florian Hahn6b1db822018-06-14 20:32:58 +00003352 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003353 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003354 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003355 mayLoad = true;// These may load memory.
3356
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003357 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003358 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3359
Matt Arsenault868af922017-04-28 21:01:46 +00003360 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3361 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003362 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003363 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003364 }
3365 }
3366
3367};
3368
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003369static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003370 const InstAnalyzer &PatInfo,
3371 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003372 bool Error = false;
3373
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003374 // Remember where InstInfo got its flags.
3375 if (InstInfo.hasUndefFlags())
3376 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003377
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003378 // Check explicitly set flags for consistency.
3379 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3380 !InstInfo.hasSideEffects_Unset) {
3381 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3382 // the pattern has no side effects. That could be useful for div/rem
3383 // instructions that may trap.
3384 if (!InstInfo.hasSideEffects) {
3385 Error = true;
3386 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3387 Twine(InstInfo.hasSideEffects));
3388 }
3389 }
3390
3391 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3392 Error = true;
3393 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3394 Twine(InstInfo.mayStore));
3395 }
3396
3397 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3398 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003399 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003400 if (!InstInfo.mayLoad) {
3401 Error = true;
3402 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3403 Twine(InstInfo.mayLoad));
3404 }
3405 }
3406
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003407 // Transfer inferred flags.
3408 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3409 InstInfo.mayStore |= PatInfo.mayStore;
3410 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003411
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003412 // These flags are silently added without any verification.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003413 // FIXME: To match historical behavior of TableGen, for now add those flags
3414 // only when we're inferring from the primary instruction pattern.
3415 if (PatDef->isSubClassOf("Instruction")) {
3416 InstInfo.isBitcast |= PatInfo.isBitcast;
3417 InstInfo.hasChain |= PatInfo.hasChain;
3418 InstInfo.hasChain_Inferred = true;
3419 }
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003420
3421 // Don't infer isVariadic. This flag means something different on SDNodes and
3422 // instructions. For example, a CALL SDNode is variadic because it has the
3423 // call arguments as operands, but a CALL instruction is not variadic - it
3424 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003425
3426 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003427}
3428
Jim Grosbach514410b2012-07-17 00:47:06 +00003429/// hasNullFragReference - Return true if the DAG has any reference to the
3430/// null_frag operator.
3431static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003432 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003433 if (!OpDef) return false;
3434 Record *Operator = OpDef->getDef();
3435
3436 // If this is the null fragment, return true.
3437 if (Operator->getName() == "null_frag") return true;
3438 // If any of the arguments reference the null fragment, return true.
3439 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003440 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003441 if (Arg && hasNullFragReference(Arg))
3442 return true;
3443 }
3444
3445 return false;
3446}
3447
3448/// hasNullFragReference - Return true if any DAG in the list references
3449/// the null_frag operator.
3450static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003451 for (Init *I : LI->getValues()) {
3452 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003453 assert(DI && "non-dag in an instruction Pattern list?!");
3454 if (hasNullFragReference(DI))
3455 return true;
3456 }
3457 return false;
3458}
3459
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003460/// Get all the instructions in a tree.
3461static void
Florian Hahn6b1db822018-06-14 20:32:58 +00003462getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3463 if (Tree->isLeaf())
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003464 return;
Florian Hahn6b1db822018-06-14 20:32:58 +00003465 if (Tree->getOperator()->isSubClassOf("Instruction"))
3466 Instrs.push_back(Tree->getOperator());
3467 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3468 getInstructionsInTree(Tree->getChild(i), Instrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003469}
3470
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003471/// Check the class of a pattern leaf node against the instruction operand it
3472/// represents.
3473static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3474 Record *Leaf) {
3475 if (OI.Rec == Leaf)
3476 return true;
3477
3478 // Allow direct value types to be used in instruction set patterns.
3479 // The type will be checked later.
3480 if (Leaf->isSubClassOf("ValueType"))
3481 return true;
3482
3483 // Patterns can also be ComplexPattern instances.
3484 if (Leaf->isSubClassOf("ComplexPattern"))
3485 return true;
3486
3487 return false;
3488}
3489
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003490void CodeGenDAGPatterns::parseInstructionPattern(
Ahmed Bougacha14107512013-10-28 18:07:21 +00003491 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003492
Craig Topper0d1fb902015-03-10 03:25:04 +00003493 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003494
Craig Topper0d1fb902015-03-10 03:25:04 +00003495 // Parse the instruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003496 TreePattern I(CGI.TheDef, Pat, true, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003497
Craig Topper0d1fb902015-03-10 03:25:04 +00003498 // InstInputs - Keep track of all of the inputs of the instruction, along
3499 // with the record they are declared as.
Florian Hahn75e87c32018-05-30 21:00:18 +00003500 std::map<std::string, TreePatternNodePtr> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003501
Craig Topper0d1fb902015-03-10 03:25:04 +00003502 // InstResults - Keep track of all the virtual registers that are 'set'
3503 // in the instruction, including what reg class they are.
Florian Hahn75e87c32018-05-30 21:00:18 +00003504 std::map<std::string, TreePatternNodePtr> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003505
Craig Topper0d1fb902015-03-10 03:25:04 +00003506 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003507
Craig Topper0d1fb902015-03-10 03:25:04 +00003508 // Verify that the top-level forms in the instruction are of void type, and
3509 // fill in the InstResults map.
Zachary Turner249dc142017-09-20 18:01:40 +00003510 SmallString<32> TypesString;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003511 for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
Zachary Turner249dc142017-09-20 18:01:40 +00003512 TypesString.clear();
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003513 TreePatternNodePtr Pat = I.getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003514 if (Pat->getNumTypes() != 0) {
Zachary Turner249dc142017-09-20 18:01:40 +00003515 raw_svector_ostream OS(TypesString);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003516 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3517 if (k > 0)
Zachary Turner249dc142017-09-20 18:01:40 +00003518 OS << ", ";
3519 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003520 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003521 I.error("Top-level forms in instruction pattern should have"
Zachary Turner249dc142017-09-20 18:01:40 +00003522 " void types, has types " +
3523 OS.str());
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003524 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003525
Craig Topper0d1fb902015-03-10 03:25:04 +00003526 // Find inputs and outputs, and verify the structure of the uses/defs.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003527 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Craig Topper0d1fb902015-03-10 03:25:04 +00003528 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003529 }
3530
Craig Topper0d1fb902015-03-10 03:25:04 +00003531 // Now that we have inputs and outputs of the pattern, inspect the operands
3532 // list for the instruction. This determines the order that operands are
3533 // added to the machine instruction the node corresponds to.
3534 unsigned NumResults = InstResults.size();
3535
3536 // Parse the operands list from the (ops) list, validating it.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003537 assert(I.getArgList().empty() && "Args list should still be empty here!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003538
3539 // Check that all of the results occur first in the list.
3540 std::vector<Record*> Results;
Florian Hahn75e87c32018-05-30 21:00:18 +00003541 SmallVector<TreePatternNodePtr, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003542 for (unsigned i = 0; i != NumResults; ++i) {
3543 if (i == CGI.Operands.size())
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003544 I.error("'" + InstResults.begin()->first +
Craig Topper0d1fb902015-03-10 03:25:04 +00003545 "' set but does not appear in operand list!");
3546 const std::string &OpName = CGI.Operands[i].Name;
3547
3548 // Check that it exists in InstResults.
Florian Hahn75e87c32018-05-30 21:00:18 +00003549 TreePatternNodePtr RNode = InstResults[OpName];
Craig Topper0d1fb902015-03-10 03:25:04 +00003550 if (!RNode)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003551 I.error("Operand $" + OpName + " does not exist in operand list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003552
Craig Topper3a8eb892015-03-20 05:09:06 +00003553
Craig Topper0d1fb902015-03-10 03:25:04 +00003554 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003555 ResNodes.push_back(std::move(RNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003556 if (!R)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003557 I.error("Operand $" + OpName + " should be a set destination: all "
Craig Topper0d1fb902015-03-10 03:25:04 +00003558 "outputs must occur before inputs in operand list!");
3559
3560 if (!checkOperandClass(CGI.Operands[i], R))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003561 I.error("Operand $" + OpName + " class mismatch!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003562
3563 // Remember the return type.
3564 Results.push_back(CGI.Operands[i].Rec);
3565
3566 // Okay, this one checks out.
3567 InstResults.erase(OpName);
3568 }
3569
Craig Topper765b9202018-07-15 06:52:48 +00003570 // Loop over the inputs next.
Florian Hahn75e87c32018-05-30 21:00:18 +00003571 std::vector<TreePatternNodePtr> ResultNodeOperands;
Craig Topper0d1fb902015-03-10 03:25:04 +00003572 std::vector<Record*> Operands;
3573 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3574 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3575 const std::string &OpName = Op.Name;
3576 if (OpName.empty())
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003577 I.error("Operand #" + Twine(i) + " in operands list has no name!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003578
Craig Topper765b9202018-07-15 06:52:48 +00003579 if (!InstInputs.count(OpName)) {
Craig Topper0d1fb902015-03-10 03:25:04 +00003580 // If this is an operand with a DefaultOps set filled in, we can ignore
3581 // this. When we codegen it, we will do so as always executed.
3582 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3583 // Does it have a non-empty DefaultOps field? If so, ignore this
3584 // operand.
3585 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3586 continue;
3587 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003588 I.error("Operand $" + OpName +
Craig Topper0d1fb902015-03-10 03:25:04 +00003589 " does not appear in the instruction pattern");
3590 }
Craig Topper765b9202018-07-15 06:52:48 +00003591 TreePatternNodePtr InVal = InstInputs[OpName];
3592 InstInputs.erase(OpName); // It occurred, remove from map.
Craig Topper0d1fb902015-03-10 03:25:04 +00003593
3594 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3595 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3596 if (!checkOperandClass(Op, InRec))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003597 I.error("Operand $" + OpName + "'s register class disagrees"
Craig Topper0d1fb902015-03-10 03:25:04 +00003598 " between the operand and pattern");
3599 }
3600 Operands.push_back(Op.Rec);
3601
3602 // Construct the result for the dest-pattern operand list.
Florian Hahn75e87c32018-05-30 21:00:18 +00003603 TreePatternNodePtr OpNode = InVal->clone();
Craig Topper0d1fb902015-03-10 03:25:04 +00003604
3605 // No predicate is useful on the result.
3606 OpNode->clearPredicateFns();
3607
3608 // Promote the xform function to be an explicit node if set.
3609 if (Record *Xform = OpNode->getTransformFn()) {
3610 OpNode->setTransformFn(nullptr);
Florian Hahn75e87c32018-05-30 21:00:18 +00003611 std::vector<TreePatternNodePtr> Children;
Craig Topper0d1fb902015-03-10 03:25:04 +00003612 Children.push_back(OpNode);
Craig Topper26fc06352018-07-15 06:52:49 +00003613 OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
Florian Hahn6b1db822018-06-14 20:32:58 +00003614 OpNode->getNumTypes());
Craig Topper0d1fb902015-03-10 03:25:04 +00003615 }
3616
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003617 ResultNodeOperands.push_back(std::move(OpNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003618 }
3619
Craig Topper765b9202018-07-15 06:52:48 +00003620 if (!InstInputs.empty())
3621 I.error("Input operand $" + InstInputs.begin()->first +
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003622 " occurs in pattern but not in operands list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003623
Florian Hahn6b1db822018-06-14 20:32:58 +00003624 TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00003625 I.getRecord(), std::move(ResultNodeOperands),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003626 GetNumNodeResults(I.getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003627 // Copy fully inferred output node types to instruction result pattern.
3628 for (unsigned i = 0; i != NumResults; ++i) {
3629 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3630 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3631 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003632
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003633 // FIXME: Assume only the first tree is the pattern. The others are clobber
3634 // nodes.
3635 TreePatternNodePtr Pattern = I.getTree(0);
3636 TreePatternNodePtr SrcPattern;
3637 if (Pattern->getOperator()->getName() == "set") {
3638 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3639 } else{
3640 // Not a set (store or something?)
3641 SrcPattern = Pattern;
3642 }
3643
Craig Topper0d1fb902015-03-10 03:25:04 +00003644 // Create and insert the instruction.
3645 // FIXME: InstImpResults should not be part of DAGInstruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003646 Record *R = I.getRecord();
3647 DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
3648 std::forward_as_tuple(Results, Operands, InstImpResults,
3649 SrcPattern, ResultPattern));
Craig Topper0d1fb902015-03-10 03:25:04 +00003650
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003651 LLVM_DEBUG(I.dump());
Craig Topper0d1fb902015-03-10 03:25:04 +00003652}
3653
Ahmed Bougacha14107512013-10-28 18:07:21 +00003654/// ParseInstructions - Parse all of the instructions, inlining and resolving
3655/// any fragments involved. This populates the Instructions list with fully
3656/// resolved instructions.
3657void CodeGenDAGPatterns::ParseInstructions() {
3658 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3659
Craig Topper306cb122015-11-22 20:46:24 +00003660 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003661 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003662
Craig Topper306cb122015-11-22 20:46:24 +00003663 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3664 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003665
3666 // If there is no pattern, only collect minimal information about the
3667 // instruction for its operand list. We have to assume that there is one
3668 // result, as we have no detailed info. A pattern which references the
3669 // null_frag operator is as-if no pattern were specified. Normally this
3670 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3671 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003672 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003673 std::vector<Record*> Results;
3674 std::vector<Record*> Operands;
3675
Craig Topper306cb122015-11-22 20:46:24 +00003676 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003677
3678 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003679 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3680 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003681
Craig Topper3a8eb892015-03-20 05:09:06 +00003682 // The rest are inputs.
3683 for (unsigned j = InstInfo.Operands.NumDefs,
3684 e = InstInfo.Operands.size(); j < e; ++j)
3685 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003686 }
3687
3688 // Create and insert the instruction.
3689 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003690 Instructions.insert(std::make_pair(Instr,
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003691 DAGInstruction(Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003692 continue; // no pattern.
3693 }
3694
Craig Topper306cb122015-11-22 20:46:24 +00003695 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003696 parseInstructionPattern(CGI, LI, Instructions);
Chris Lattner8cab0212008-01-05 22:25:12 +00003697 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003698
Chris Lattner8cab0212008-01-05 22:25:12 +00003699 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003700 for (auto &Entry : Instructions) {
Craig Topper306cb122015-11-22 20:46:24 +00003701 Record *Instr = Entry.first;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003702 DAGInstruction &TheInst = Entry.second;
3703 TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
3704 TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
3705
3706 if (SrcPattern && ResultPattern) {
3707 TreePattern Pattern(Instr, SrcPattern, true, *this);
3708 TreePattern Result(Instr, ResultPattern, false, *this);
3709 ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
3710 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003711 }
3712}
3713
Florian Hahn6b1db822018-06-14 20:32:58 +00003714typedef std::pair<TreePatternNode *, unsigned> NameRecord;
Chris Lattnera7722b62010-02-23 06:55:24 +00003715
Florian Hahn6b1db822018-06-14 20:32:58 +00003716static void FindNames(TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003717 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003718 TreePattern *PatternTop) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003719 if (!P->getName().empty()) {
3720 NameRecord &Rec = Names[P->getName()];
Chris Lattnera7722b62010-02-23 06:55:24 +00003721 // If this is the first instance of the name, remember the node.
3722 if (Rec.second++ == 0)
Florian Hahn6b1db822018-06-14 20:32:58 +00003723 Rec.first = P;
3724 else if (Rec.first->getExtTypes() != P->getExtTypes())
3725 PatternTop->error("repetition of value: $" + P->getName() +
Chris Lattner5b0e2492010-02-23 07:22:28 +00003726 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003727 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003728
Florian Hahn6b1db822018-06-14 20:32:58 +00003729 if (!P->isLeaf()) {
3730 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3731 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003732 }
3733}
3734
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003735std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3736 std::vector<Predicate> Preds;
3737 for (Init *I : L->getValues()) {
3738 if (DefInit *Pred = dyn_cast<DefInit>(I))
3739 Preds.push_back(Pred->getDef());
3740 else
3741 llvm_unreachable("Non-def on the list");
3742 }
3743
3744 // Sort so that different orders get canonicalized to the same string.
Fangrui Song0cac7262018-09-27 02:13:45 +00003745 llvm::sort(Preds);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003746 return Preds;
3747}
3748
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003749void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003750 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003751 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003752 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003753 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3754 PrintWarning(Pattern->getRecord()->getLoc(),
3755 Twine("Pattern can never match: ") + Reason);
3756 return;
3757 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003758
Chris Lattner1e634e32010-03-01 22:29:19 +00003759 // If the source pattern's root is a complex pattern, that complex pattern
3760 // must specify the nodes it can potentially match.
3761 if (const ComplexPattern *CP =
3762 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3763 if (CP->getRootNodes().empty())
3764 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3765 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003766
3767
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003768 // Find all of the named values in the input and output, ensure they have the
3769 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003770 std::map<std::string, NameRecord> SrcNames, DstNames;
Florian Hahn6b1db822018-06-14 20:32:58 +00003771 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3772 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003773
3774 // Scan all of the named values in the destination pattern, rejecting them if
3775 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003776 for (const auto &Entry : DstNames) {
3777 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003778 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003779 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003780 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003781
Chris Lattnera7722b62010-02-23 06:55:24 +00003782 // Scan all of the named values in the source pattern, rejecting them if the
3783 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003784 for (const auto &Entry : SrcNames)
3785 if (DstNames[Entry.first].first == nullptr &&
3786 SrcNames[Entry.first].second == 1)
3787 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003788
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003789 PatternsToMatch.push_back(PTM);
Chris Lattner0c0baa92010-02-23 06:16:51 +00003790}
3791
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003792void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003793 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003794 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003795
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003796 unsigned Errors = 0;
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003797
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003798 // Try to infer flags from all patterns in PatternToMatch. These include
3799 // both the primary instruction patterns (which always come first) and
3800 // patterns defined outside the instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003801 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003802 // We can only infer from single-instruction patterns, otherwise we won't
3803 // know which instruction should get the flags.
3804 SmallVector<Record*, 8> PatInstrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003805 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003806 if (PatInstrs.size() != 1)
3807 continue;
3808
3809 // Get the single instruction.
3810 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3811
3812 // Only infer properties from the first pattern. We'll verify the others.
3813 if (InstInfo.InferredFrom)
3814 continue;
3815
3816 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003817 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003818 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3819 }
3820
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003821 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003822 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003823
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003824 // If requested by the target, guess any undefined properties.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003825 if (Target.guessInstructionProperties()) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003826 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3827 CodeGenInstruction *InstInfo =
3828 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003829 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003830 continue;
3831 // The mayLoad and mayStore flags default to false.
3832 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003833 if (InstInfo->hasSideEffects_Unset)
3834 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003835 }
3836 return;
3837 }
3838
3839 // Complain about any flags that are still undefined.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003840 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3841 CodeGenInstruction *InstInfo =
3842 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003843 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003844 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003845 if (InstInfo->hasSideEffects_Unset)
3846 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003847 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003848 if (InstInfo->mayStore_Unset)
3849 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003850 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003851 if (InstInfo->mayLoad_Unset)
3852 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003853 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003854 }
3855}
3856
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003857
3858/// Verify instruction flags against pattern node properties.
3859void CodeGenDAGPatterns::VerifyInstructionFlags() {
3860 unsigned Errors = 0;
3861 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3862 const PatternToMatch &PTM = *I;
3863 SmallVector<Record*, 8> Instrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003864 getInstructionsInTree(PTM.getDstPattern(), Instrs);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003865 if (Instrs.empty())
3866 continue;
3867
3868 // Count the number of instructions with each flag set.
3869 unsigned NumSideEffects = 0;
3870 unsigned NumStores = 0;
3871 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003872 for (const Record *Instr : Instrs) {
3873 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003874 NumSideEffects += InstInfo.hasSideEffects;
3875 NumStores += InstInfo.mayStore;
3876 NumLoads += InstInfo.mayLoad;
3877 }
3878
3879 // Analyze the source pattern.
3880 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003881 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003882
3883 // Collect error messages.
3884 SmallVector<std::string, 4> Msgs;
3885
3886 // Check for missing flags in the output.
3887 // Permit extra flags for now at least.
3888 if (PatInfo.hasSideEffects && !NumSideEffects)
3889 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3890
3891 // Don't verify store flags on instructions with side effects. At least for
3892 // intrinsics, side effects implies mayStore.
3893 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3894 Msgs.push_back("pattern may store, but mayStore isn't set");
3895
3896 // Similarly, mayStore implies mayLoad on intrinsics.
3897 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3898 Msgs.push_back("pattern may load, but mayLoad isn't set");
3899
3900 // Print error messages.
3901 if (Msgs.empty())
3902 continue;
3903 ++Errors;
3904
Craig Topper306cb122015-11-22 20:46:24 +00003905 for (const std::string &Msg : Msgs)
3906 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003907 (Instrs.size() == 1 ?
3908 "instruction" : "output instructions"));
3909 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003910 for (const Record *Instr : Instrs) {
3911 if (Instr != PTM.getSrcRecord())
3912 PrintError(Instr->getLoc(), "defined here");
3913 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003914 if (InstInfo.InferredFrom &&
3915 InstInfo.InferredFrom != InstInfo.TheDef &&
3916 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003917 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003918 }
3919 }
3920 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003921 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003922}
3923
Chris Lattnercabe0372010-03-15 06:00:16 +00003924/// Given a pattern result with an unresolved type, see if we can find one
3925/// instruction with an unresolved result type. Force this result type to an
3926/// arbitrary element if it's possible types to converge results.
Florian Hahn6b1db822018-06-14 20:32:58 +00003927static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3928 if (N->isLeaf())
Chris Lattnercabe0372010-03-15 06:00:16 +00003929 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003930
Chris Lattnercabe0372010-03-15 06:00:16 +00003931 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00003932 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3933 if (ForceArbitraryInstResultType(N->getChild(i), TP))
Chris Lattnercabe0372010-03-15 06:00:16 +00003934 return true;
3935
Florian Hahn6b1db822018-06-14 20:32:58 +00003936 if (!N->getOperator()->isSubClassOf("Instruction"))
Chris Lattnercabe0372010-03-15 06:00:16 +00003937 return false;
3938
3939 // If this type is already concrete or completely unknown we can't do
3940 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003941 TypeInfer &TI = TP.getInfer();
Florian Hahn6b1db822018-06-14 20:32:58 +00003942 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3943 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00003944 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003945
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003946 // Otherwise, force its type to an arbitrary choice.
Florian Hahn6b1db822018-06-14 20:32:58 +00003947 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00003948 return true;
3949 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003950
Chris Lattnerf1447252010-03-19 21:37:09 +00003951 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003952}
3953
Ulrich Weigand58a97862018-08-01 11:57:58 +00003954// Promote xform function to be an explicit node wherever set.
3955static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
3956 if (Record *Xform = N->getTransformFn()) {
3957 N->setTransformFn(nullptr);
3958 std::vector<TreePatternNodePtr> Children;
3959 Children.push_back(PromoteXForms(N));
3960 return std::make_shared<TreePatternNode>(Xform, std::move(Children),
3961 N->getNumTypes());
3962 }
3963
3964 if (!N->isLeaf())
3965 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
3966 TreePatternNodePtr Child = N->getChildShared(i);
Ulrich Weigandf989cd72018-08-01 12:07:32 +00003967 N->setChild(i, PromoteXForms(Child));
Ulrich Weigand58a97862018-08-01 11:57:58 +00003968 }
3969 return N;
3970}
3971
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003972void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
3973 TreePattern &Pattern, TreePattern &Result,
3974 const std::vector<Record *> &InstImpResults) {
3975
3976 // Inline pattern fragments and expand multiple alternatives.
3977 Pattern.InlinePatternFragments();
3978 Result.InlinePatternFragments();
3979
3980 if (Result.getNumTrees() != 1)
3981 Result.error("Cannot use multi-alternative fragments in result pattern!");
3982
3983 // Infer types.
3984 bool IterateInference;
3985 bool InferredAllPatternTypes, InferredAllResultTypes;
3986 do {
3987 // Infer as many types as possible. If we cannot infer all of them, we
3988 // can never do anything with this pattern: report it to the user.
3989 InferredAllPatternTypes =
3990 Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
3991
3992 // Infer as many types as possible. If we cannot infer all of them, we
3993 // can never do anything with this pattern: report it to the user.
3994 InferredAllResultTypes =
3995 Result.InferAllTypes(&Pattern.getNamedNodesMap());
3996
3997 IterateInference = false;
3998
3999 // Apply the type of the result to the source pattern. This helps us
4000 // resolve cases where the input type is known to be a pointer type (which
4001 // is considered resolved), but the result knows it needs to be 32- or
4002 // 64-bits. Infer the other way for good measure.
4003 for (auto T : Pattern.getTrees())
4004 for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
4005 T->getNumTypes());
4006 i != e; ++i) {
4007 IterateInference |= T->UpdateNodeType(
4008 i, Result.getOnlyTree()->getExtType(i), Result);
4009 IterateInference |= Result.getOnlyTree()->UpdateNodeType(
4010 i, T->getExtType(i), Result);
4011 }
4012
4013 // If our iteration has converged and the input pattern's types are fully
4014 // resolved but the result pattern is not fully resolved, we may have a
4015 // situation where we have two instructions in the result pattern and
4016 // the instructions require a common register class, but don't care about
4017 // what actual MVT is used. This is actually a bug in our modelling:
4018 // output patterns should have register classes, not MVTs.
4019 //
4020 // In any case, to handle this, we just go through and disambiguate some
4021 // arbitrary types to the result pattern's nodes.
4022 if (!IterateInference && InferredAllPatternTypes &&
4023 !InferredAllResultTypes)
4024 IterateInference =
4025 ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
4026 } while (IterateInference);
4027
4028 // Verify that we inferred enough types that we can do something with the
4029 // pattern and result. If these fire the user has to add type casts.
4030 if (!InferredAllPatternTypes)
4031 Pattern.error("Could not infer all types in pattern!");
4032 if (!InferredAllResultTypes) {
4033 Pattern.dump();
4034 Result.error("Could not infer all types in pattern result!");
4035 }
4036
Ulrich Weigand58a97862018-08-01 11:57:58 +00004037 // Promote xform function to be an explicit node wherever set.
4038 TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004039
4040 TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4041 Temp.InferAllTypes();
4042
4043 ListInit *Preds = TheDef->getValueAsListInit("Predicates");
4044 int Complexity = TheDef->getValueAsInt("AddedComplexity");
4045
4046 if (PatternRewriter)
4047 PatternRewriter(&Pattern);
4048
4049 // A pattern may end up with an "impossible" type, i.e. a situation
4050 // where all types have been eliminated for some node in this pattern.
4051 // This could occur for intrinsics that only make sense for a specific
4052 // value type, and use a specific register class. If, for some mode,
4053 // that register class does not accept that type, the type inference
4054 // will lead to a contradiction, which is not an error however, but
4055 // a sign that this pattern will simply never match.
4056 if (Temp.getOnlyTree()->hasPossibleType())
4057 for (auto T : Pattern.getTrees())
4058 if (T->hasPossibleType())
4059 AddPatternToMatch(&Pattern,
4060 PatternToMatch(TheDef, makePredList(Preds),
4061 T, Temp.getOnlyTree(),
4062 InstImpResults, Complexity,
4063 TheDef->getID()));
4064}
4065
Chris Lattnerab3242f2008-01-06 01:10:31 +00004066void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00004067 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
4068
Craig Topper306cb122015-11-22 20:46:24 +00004069 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00004070 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00004071
4072 // If the pattern references the null_frag, there's nothing to do.
4073 if (hasNullFragReference(Tree))
4074 continue;
4075
Florian Hahn75e87c32018-05-30 21:00:18 +00004076 TreePattern Pattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00004077
David Greeneaf8ee2c2011-07-29 22:43:06 +00004078 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00004079 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004080
Chris Lattner8cab0212008-01-05 22:25:12 +00004081 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004082 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004083
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004084 if (Result.getNumTrees() != 1)
4085 Result.error("Cannot handle instructions producing instructions "
4086 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004087
Chris Lattner8cab0212008-01-05 22:25:12 +00004088 // Validate that the input pattern is correct.
Florian Hahn75e87c32018-05-30 21:00:18 +00004089 std::map<std::string, TreePatternNodePtr> InstInputs;
4090 std::map<std::string, TreePatternNodePtr> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00004091 std::vector<Record*> InstImpResults;
Florian Hahn75e87c32018-05-30 21:00:18 +00004092 for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
David Blaikie19b22d42018-06-11 22:14:43 +00004093 FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
Florian Hahn75e87c32018-05-30 21:00:18 +00004094 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004095
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004096 ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004097 }
4098}
4099
Florian Hahn6b1db822018-06-14 20:32:58 +00004100static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004101 for (const TypeSetByHwMode &VTS : N->getExtTypes())
4102 for (const auto &I : VTS)
4103 Modes.insert(I.first);
4104
4105 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00004106 collectModes(Modes, N->getChild(i));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004107}
4108
4109void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4110 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4111 std::map<unsigned,std::vector<Predicate>> ModeChecks;
4112 std::vector<PatternToMatch> Copy = PatternsToMatch;
4113 PatternsToMatch.clear();
4114
Florian Hahn75e87c32018-05-30 21:00:18 +00004115 auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) {
4116 TreePatternNodePtr NewSrc = P.SrcPattern->clone();
4117 TreePatternNodePtr NewDst = P.DstPattern->clone();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004118 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004119 return;
4120 }
4121
4122 std::vector<Predicate> Preds = P.Predicates;
4123 const std::vector<Predicate> &MC = ModeChecks[Mode];
4124 Preds.insert(Preds.end(), MC.begin(), MC.end());
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004125 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, std::move(NewSrc),
4126 std::move(NewDst), P.getDstRegs(),
4127 P.getAddedComplexity(), Record::getNewUID(),
4128 Mode);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004129 };
4130
4131 for (PatternToMatch &P : Copy) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004132 TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
Florian Hahn6b1db822018-06-14 20:32:58 +00004133 if (P.SrcPattern->hasProperTypeByHwMode())
4134 SrcP = P.SrcPattern;
4135 if (P.DstPattern->hasProperTypeByHwMode())
4136 DstP = P.DstPattern;
4137 if (!SrcP && !DstP) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004138 PatternsToMatch.push_back(P);
4139 continue;
4140 }
4141
4142 std::set<unsigned> Modes;
Florian Hahn6b1db822018-06-14 20:32:58 +00004143 if (SrcP)
4144 collectModes(Modes, SrcP.get());
4145 if (DstP)
4146 collectModes(Modes, DstP.get());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004147
4148 // The predicate for the default mode needs to be constructed for each
4149 // pattern separately.
4150 // Since not all modes must be present in each pattern, if a mode m is
4151 // absent, then there is no point in constructing a check for m. If such
4152 // a check was created, it would be equivalent to checking the default
4153 // mode, except not all modes' predicates would be a part of the checking
4154 // code. The subsequently generated check for the default mode would then
4155 // have the exact same patterns, but a different predicate code. To avoid
4156 // duplicated patterns with different predicate checks, construct the
4157 // default check as a negation of all predicates that are actually present
4158 // in the source/destination patterns.
4159 std::vector<Predicate> DefaultPred;
4160
4161 for (unsigned M : Modes) {
4162 if (M == DefaultMode)
4163 continue;
4164 if (ModeChecks.find(M) != ModeChecks.end())
4165 continue;
4166
4167 // Fill the map entry for this mode.
4168 const HwMode &HM = CGH.getMode(M);
4169 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4170
4171 // Add negations of the HM's predicates to the default predicate.
4172 DefaultPred.emplace_back(Predicate(HM.Features, false));
4173 }
4174
4175 for (unsigned M : Modes) {
4176 if (M == DefaultMode)
4177 continue;
4178 AppendPattern(P, M);
4179 }
4180
4181 bool HasDefault = Modes.count(DefaultMode);
4182 if (HasDefault)
4183 AppendPattern(P, DefaultMode);
4184 }
4185}
4186
4187/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turner249dc142017-09-20 18:01:40 +00004188typedef StringMap<int> DepVarMap;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004189
Florian Hahn6b1db822018-06-14 20:32:58 +00004190static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4191 if (N->isLeaf()) {
4192 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
4193 DepMap[N->getName()]++;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004194 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00004195 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4196 FindDepVarsOf(N->getChild(i), DepMap);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004197 }
4198}
4199
4200/// Find dependent variables within child patterns
Florian Hahn6b1db822018-06-14 20:32:58 +00004201static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004202 DepVarMap depcounts;
4203 FindDepVarsOf(N, depcounts);
Zachary Turner249dc142017-09-20 18:01:40 +00004204 for (const auto &Pair : depcounts) {
4205 if (Pair.getValue() > 1)
4206 DepVars.insert(Pair.getKey());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004207 }
4208}
4209
4210#ifndef NDEBUG
4211/// Dump the dependent variable set:
4212static void DumpDepVars(MultipleUseVarSet &DepVars) {
4213 if (DepVars.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004214 LLVM_DEBUG(errs() << "<empty set>");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004215 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004216 LLVM_DEBUG(errs() << "[ ");
Zachary Turner249dc142017-09-20 18:01:40 +00004217 for (const auto &DepVar : DepVars) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004218 LLVM_DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004219 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004220 LLVM_DEBUG(errs() << "]");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004221 }
4222}
4223#endif
4224
4225
Chris Lattner8cab0212008-01-05 22:25:12 +00004226/// CombineChildVariants - Given a bunch of permutations of each child of the
4227/// 'operator' node, put them together in all possible ways.
Florian Hahn75e87c32018-05-30 21:00:18 +00004228static void CombineChildVariants(
Florian Hahn6b1db822018-06-14 20:32:58 +00004229 TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004230 const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4231 std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4232 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004233 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00004234 for (const auto &Variants : ChildVariants)
4235 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00004236 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004237
Chris Lattner8cab0212008-01-05 22:25:12 +00004238 // The end result is an all-pairs construction of the resultant pattern.
4239 std::vector<unsigned> Idxs;
4240 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00004241 bool NotDone;
4242 do {
4243#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004244 LLVM_DEBUG(if (!Idxs.empty()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004245 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004246 for (unsigned Idx : Idxs) {
4247 errs() << Idx << " ";
4248 }
4249 errs() << "]\n";
4250 });
Scott Michel94420742008-03-05 17:49:05 +00004251#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00004252 // Create the variant and add it to the output list.
Florian Hahn75e87c32018-05-30 21:00:18 +00004253 std::vector<TreePatternNodePtr> NewChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004254 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4255 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Florian Hahn75e87c32018-05-30 21:00:18 +00004256 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00004257 Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004258
Chris Lattner8cab0212008-01-05 22:25:12 +00004259 // Copy over properties.
Florian Hahn6b1db822018-06-14 20:32:58 +00004260 R->setName(Orig->getName());
4261 R->setPredicateFns(Orig->getPredicateFns());
4262 R->setTransformFn(Orig->getTransformFn());
4263 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4264 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00004265
Scott Michel94420742008-03-05 17:49:05 +00004266 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00004267 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00004268 // Scan to see if this pattern has already been emitted. We can get
4269 // duplication due to things like commuting:
4270 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4271 // which are the same pattern. Ignore the dups.
4272 if (R->canPatternMatch(ErrString, CDP) &&
Florian Hahn75e87c32018-05-30 21:00:18 +00004273 none_of(OutVariants, [&](TreePatternNodePtr Variant) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004274 return R->isIsomorphicTo(Variant.get(), DepVars);
David Majnemer0a16c222016-08-11 21:15:00 +00004275 }))
Florian Hahn75e87c32018-05-30 21:00:18 +00004276 OutVariants.push_back(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004277
Scott Michel94420742008-03-05 17:49:05 +00004278 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004279 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00004280 // [0, 0], [0, 1], [1, 0], [1, 1].
4281 int IdxsIdx;
4282 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4283 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4284 Idxs[IdxsIdx] = 0;
4285 else
Chris Lattner8cab0212008-01-05 22:25:12 +00004286 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00004287 }
Scott Michel94420742008-03-05 17:49:05 +00004288 NotDone = (IdxsIdx >= 0);
4289 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00004290}
4291
4292/// CombineChildVariants - A helper function for binary operators.
4293///
Florian Hahn6b1db822018-06-14 20:32:58 +00004294static void CombineChildVariants(TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004295 const std::vector<TreePatternNodePtr> &LHS,
4296 const std::vector<TreePatternNodePtr> &RHS,
4297 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004298 CodeGenDAGPatterns &CDP,
4299 const MultipleUseVarSet &DepVars) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004300 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004301 ChildVariants.push_back(LHS);
4302 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00004303 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004304}
Chris Lattner8cab0212008-01-05 22:25:12 +00004305
Florian Hahn75e87c32018-05-30 21:00:18 +00004306static void
Florian Hahn6b1db822018-06-14 20:32:58 +00004307GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004308 std::vector<TreePatternNodePtr> &Children) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004309 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4310 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00004311
Chris Lattner8cab0212008-01-05 22:25:12 +00004312 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00004313 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00004314 N->getTransformFn()) {
4315 Children.push_back(N);
4316 return;
4317 }
4318
Florian Hahn6b1db822018-06-14 20:32:58 +00004319 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004320 Children.push_back(N->getChildShared(0));
Chris Lattner8cab0212008-01-05 22:25:12 +00004321 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004322 GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004323
Florian Hahn6b1db822018-06-14 20:32:58 +00004324 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004325 Children.push_back(N->getChildShared(1));
Chris Lattner8cab0212008-01-05 22:25:12 +00004326 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004327 GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004328}
4329
4330/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4331/// the (potentially recursive) pattern by using algebraic laws.
4332///
Florian Hahn6b1db822018-06-14 20:32:58 +00004333static void GenerateVariantsOf(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004334 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004335 CodeGenDAGPatterns &CDP,
4336 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00004337 // We cannot permute leaves or ComplexPattern uses.
4338 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004339 OutVariants.push_back(N);
4340 return;
4341 }
4342
4343 // Look up interesting info about the node.
4344 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4345
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004346 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00004347 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00004348 // Re-associate by pulling together all of the linked operators
Florian Hahn75e87c32018-05-30 21:00:18 +00004349 std::vector<TreePatternNodePtr> MaximalChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004350 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4351
4352 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4353 // permutations.
4354 if (MaximalChildren.size() == 3) {
4355 // Find the variants of all of our maximal children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004356 std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00004357 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4358 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4359 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004360
Chris Lattner8cab0212008-01-05 22:25:12 +00004361 // There are only two ways we can permute the tree:
4362 // (A op B) op C and A op (B op C)
4363 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004364
Chris Lattner8cab0212008-01-05 22:25:12 +00004365 // Generate legal pair permutations of A/B/C.
Florian Hahn75e87c32018-05-30 21:00:18 +00004366 std::vector<TreePatternNodePtr> ABVariants;
4367 std::vector<TreePatternNodePtr> BAVariants;
4368 std::vector<TreePatternNodePtr> ACVariants;
4369 std::vector<TreePatternNodePtr> CAVariants;
4370 std::vector<TreePatternNodePtr> BCVariants;
4371 std::vector<TreePatternNodePtr> CBVariants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004372 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4373 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4374 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4375 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4376 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4377 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004378
4379 // Combine those into the result: (x op x) op x
Florian Hahn6b1db822018-06-14 20:32:58 +00004380 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4381 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4382 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4383 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4384 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4385 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004386
4387 // Combine those into the result: x op (x op x)
Florian Hahn6b1db822018-06-14 20:32:58 +00004388 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4389 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4390 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4391 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4392 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4393 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004394 return;
4395 }
4396 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004397
Chris Lattner8cab0212008-01-05 22:25:12 +00004398 // Compute permutations of all children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004399 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004400 ChildVariants.resize(N->getNumChildren());
4401 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn75e87c32018-05-30 21:00:18 +00004402 GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004403
4404 // Build all permutations based on how the children were formed.
Florian Hahn6b1db822018-06-14 20:32:58 +00004405 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004406
4407 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004408 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4409 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004410 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004411 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004412 // Don't count children which are actually register references.
4413 unsigned NC = 0;
4414 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004415 TreePatternNode *Child = N->getChild(i);
4416 if (Child->isLeaf())
4417 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004418 Record *RR = DI->getDef();
4419 if (RR->isSubClassOf("Register"))
4420 continue;
4421 }
4422 NC++;
4423 }
4424 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004425 if (isCommIntrinsic) {
4426 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4427 // operands are the commutative operands, and there might be more operands
4428 // after those.
4429 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004430 "Commutative intrinsic should have at least 3 children!");
Florian Hahn75e87c32018-05-30 21:00:18 +00004431 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004432 Variants.push_back(std::move(ChildVariants[0])); // Intrinsic id.
4433 Variants.push_back(std::move(ChildVariants[2]));
4434 Variants.push_back(std::move(ChildVariants[1]));
Evan Cheng49bad4c2008-06-16 20:29:38 +00004435 for (unsigned i = 3; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004436 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004437 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004438 } else if (NC == N->getNumChildren()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004439 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004440 Variants.push_back(std::move(ChildVariants[1]));
4441 Variants.push_back(std::move(ChildVariants[0]));
Craig Topper98a96282017-09-04 03:44:33 +00004442 for (unsigned i = 2; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004443 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004444 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004445 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004446 }
4447}
4448
4449
4450// GenerateVariants - Generate variants. For example, commutative patterns can
4451// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004452void CodeGenDAGPatterns::GenerateVariants() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004453 LLVM_DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004454
Chris Lattner8cab0212008-01-05 22:25:12 +00004455 // Loop over all of the patterns we've collected, checking to see if we can
4456 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004457 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004458 // the .td file having to contain tons of variants of instructions.
4459 //
4460 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4461 // intentionally do not reconsider these. Any variants of added patterns have
4462 // already been added.
4463 //
Simon Pilgrim0621f562018-09-18 11:30:30 +00004464 const unsigned NumOriginalPatterns = PatternsToMatch.size();
4465 BitVector MatchedPatterns(NumOriginalPatterns);
4466 std::vector<BitVector> MatchedPredicates(NumOriginalPatterns,
4467 BitVector(NumOriginalPatterns));
4468
4469 typedef std::pair<MultipleUseVarSet, std::vector<TreePatternNodePtr>>
4470 DepsAndVariants;
4471 std::map<unsigned, DepsAndVariants> PatternsWithVariants;
4472
4473 // Collect patterns with more than one variant.
4474 for (unsigned i = 0; i != NumOriginalPatterns; ++i) {
4475 MultipleUseVarSet DepVars;
Florian Hahn75e87c32018-05-30 21:00:18 +00004476 std::vector<TreePatternNodePtr> Variants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004477 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004478 LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4479 LLVM_DEBUG(DumpDepVars(DepVars));
4480 LLVM_DEBUG(errs() << "\n");
Florian Hahn75e87c32018-05-30 21:00:18 +00004481 GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4482 *this, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004483
4484 assert(!Variants.empty() && "Must create at least original variant!");
Simon Pilgrim0621f562018-09-18 11:30:30 +00004485 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004486 continue;
4487
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004488 LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4489 PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004490
Simon Pilgrim0621f562018-09-18 11:30:30 +00004491 PatternsWithVariants[i] = std::make_pair(DepVars, Variants);
4492
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +00004493 // Cache matching predicates.
Simon Pilgrim0621f562018-09-18 11:30:30 +00004494 if (MatchedPatterns[i])
4495 continue;
4496
4497 const std::vector<Predicate> &Predicates =
4498 PatternsToMatch[i].getPredicates();
4499
4500 BitVector &Matches = MatchedPredicates[i];
Simon Pilgrim6d706772018-09-19 12:23:50 +00004501 MatchedPatterns.set(i);
4502 Matches.set(i);
Simon Pilgrim0621f562018-09-18 11:30:30 +00004503
4504 // Don't test patterns that have already been cached - it won't match.
4505 for (unsigned p = 0; p != NumOriginalPatterns; ++p)
4506 if (!MatchedPatterns[p])
4507 Matches[p] = (Predicates == PatternsToMatch[p].getPredicates());
4508
4509 // Copy this to all the matching patterns.
4510 for (int p = Matches.find_first(); p != -1; p = Matches.find_next(p))
Simon Pilgrime3c6f8d2018-09-18 12:01:25 +00004511 if (p != (int)i) {
Simon Pilgrim6d706772018-09-19 12:23:50 +00004512 MatchedPatterns.set(p);
Simon Pilgrim0621f562018-09-18 11:30:30 +00004513 MatchedPredicates[p] = Matches;
4514 }
4515 }
4516
4517 for (auto it : PatternsWithVariants) {
4518 unsigned i = it.first;
4519 const MultipleUseVarSet &DepVars = it.second.first;
4520 const std::vector<TreePatternNodePtr> &Variants = it.second.second;
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +00004521
Chris Lattner8cab0212008-01-05 22:25:12 +00004522 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004523 TreePatternNodePtr Variant = Variants[v];
Simon Pilgrim0621f562018-09-18 11:30:30 +00004524 BitVector &Matches = MatchedPredicates[i];
Chris Lattner8cab0212008-01-05 22:25:12 +00004525
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004526 LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump();
4527 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004528
Chris Lattner8cab0212008-01-05 22:25:12 +00004529 // Scan to see if an instruction or explicit pattern already matches this.
4530 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004531 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004532 // Skip if the top level predicates do not match.
Simon Pilgrim0621f562018-09-18 11:30:30 +00004533 if (!Matches[p])
Evan Cheng34c8c742009-06-26 05:59:16 +00004534 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004535 // Check to see if this variant already exists.
Florian Hahn6b1db822018-06-14 20:32:58 +00004536 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004537 DepVars)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004538 LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004539 AlreadyExists = true;
4540 break;
4541 }
4542 }
4543 // If we already have it, ignore the variant.
4544 if (AlreadyExists) continue;
4545
4546 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004547 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004548 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
Florian Hahn75e87c32018-05-30 21:00:18 +00004549 Variant, PatternsToMatch[i].getDstPatternShared(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004550 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004551 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Simon Pilgrim0621f562018-09-18 11:30:30 +00004552 MatchedPredicates.push_back(Matches);
4553
Simon Pilgrimb2444352018-09-18 14:05:07 +00004554 // Add a new match the same as this pattern.
Simon Pilgrimb2444352018-09-18 14:05:07 +00004555 for (auto &P : MatchedPredicates)
Simon Pilgrim429df292018-09-19 11:18:49 +00004556 P.push_back(P[i]);
Chris Lattner8cab0212008-01-05 22:25:12 +00004557 }
4558
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004559 LLVM_DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004560 }
4561}