blob: f1cde80952b39087258d65deefbb4a2d17d1a215 [file] [log] [blame]
Chris Lattnerab3242f2008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerab3242f2008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner8cab0212008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner78ac0742008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Zachary Turner249dc142017-09-20 18:01:40 +000016#include "llvm/ADT/DenseSet.h"
Chris Lattnercabe0372010-03-15 06:00:16 +000017#include "llvm/ADT/STLExtras.h"
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000018#include "llvm/ADT/SmallSet.h"
Craig Topper3522ab32015-11-28 08:23:02 +000019#include "llvm/ADT/SmallString.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000020#include "llvm/ADT/StringExtras.h"
Craig Topperddfdd942017-09-21 04:55:03 +000021#include "llvm/ADT/StringMap.h"
Jim Grosbach3ae48a62012-04-18 17:46:41 +000022#include "llvm/ADT/Twine.h"
Chris Lattner8cab0212008-01-05 22:25:12 +000023#include "llvm/Support/Debug.h"
David Blaikieb48ed1a2012-01-17 04:43:56 +000024#include "llvm/Support/ErrorHandling.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000025#include "llvm/TableGen/Error.h"
26#include "llvm/TableGen/Record.h"
Chuck Rose IIIfe2714f2008-01-15 21:43:17 +000027#include <algorithm>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000028#include <cstdio>
29#include <set>
Chris Lattner8cab0212008-01-05 22:25:12 +000030using namespace llvm;
31
Chandler Carruthe96dd892014-04-21 22:55:11 +000032#define DEBUG_TYPE "dag-patterns"
33
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000034static inline bool isIntegerOrPtr(MVT VT) {
35 return VT.isInteger() || VT == MVT::iPTR;
Duncan Sands13237ac2008-06-06 12:08:01 +000036}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000037static inline bool isFloatingPoint(MVT VT) {
38 return VT.isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000039}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000040static inline bool isVector(MVT VT) {
41 return VT.isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000042}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000043static inline bool isScalar(MVT VT) {
44 return !VT.isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000045}
Duncan Sands13237ac2008-06-06 12:08:01 +000046
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000047template <typename Predicate>
48static bool berase_if(MachineValueTypeSet &S, Predicate P) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000049 bool Erased = false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000050 // It is ok to iterate over MachineValueTypeSet and remove elements from it
51 // at the same time.
52 for (MVT T : S) {
53 if (!P(T))
54 continue;
55 Erased = true;
56 S.erase(T);
Chris Lattnercabe0372010-03-15 06:00:16 +000057 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000058 return Erased;
Chris Lattner8cab0212008-01-05 22:25:12 +000059}
60
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000061// --- TypeSetByHwMode
Chris Lattnercabe0372010-03-15 06:00:16 +000062
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000063// This is a parameterized type-set class. For each mode there is a list
64// of types that are currently possible for a given tree node. Type
65// inference will apply to each mode separately.
Jim Grosbach65586fe2010-12-21 16:16:00 +000066
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000067TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
68 for (const ValueTypeByHwMode &VVT : VTList)
69 insert(VVT);
Chris Lattner8cab0212008-01-05 22:25:12 +000070}
71
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000072bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
73 for (const auto &I : *this) {
74 if (I.second.size() > 1)
75 return false;
76 if (!AllowEmpty && I.second.empty())
77 return false;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000078 }
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000079 return true;
80}
Chris Lattnercabe0372010-03-15 06:00:16 +000081
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000082ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
83 assert(isValueTypeByHwMode(true) &&
84 "The type set has multiple types for at least one HW mode");
85 ValueTypeByHwMode VVT;
86 for (const auto &I : *this) {
87 MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
88 VVT.getOrCreateTypeForMode(I.first, T);
Chris Lattnercabe0372010-03-15 06:00:16 +000089 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000090 return VVT;
Bob Wilson2cd5da82009-08-11 01:14:02 +000091}
Chris Lattnercabe0372010-03-15 06:00:16 +000092
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000093bool TypeSetByHwMode::isPossible() const {
94 for (const auto &I : *this)
95 if (!I.second.empty())
96 return true;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000097 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +000098}
99
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000100bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
101 bool Changed = false;
Zachary Turner249dc142017-09-20 18:01:40 +0000102 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000103 for (const auto &P : VVT) {
104 unsigned M = P.first;
105 Modes.insert(M);
106 // Make sure there exists a set for each specific mode from VVT.
107 Changed |= getOrCreate(M).insert(P.second).second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000108 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000109
110 // If VVT has a default mode, add the corresponding type to all
111 // modes in "this" that do not exist in VVT.
112 if (Modes.count(DefaultMode)) {
113 MVT DT = VVT.getType(DefaultMode);
114 for (auto &I : *this)
115 if (!Modes.count(I.first))
116 Changed |= I.second.insert(DT).second;
117 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000118 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000119}
120
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000121// Constrain the type set to be the intersection with VTS.
122bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
123 bool Changed = false;
124 if (hasDefault()) {
125 for (const auto &I : VTS) {
126 unsigned M = I.first;
127 if (M == DefaultMode || hasMode(M))
128 continue;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000129 Map.insert({M, Map.at(DefaultMode)});
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000130 Changed = true;
131 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000132 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000133
134 for (auto &I : *this) {
135 unsigned M = I.first;
136 SetType &S = I.second;
137 if (VTS.hasMode(M) || VTS.hasDefault()) {
138 Changed |= intersect(I.second, VTS.get(M));
139 } else if (!S.empty()) {
140 S.clear();
141 Changed = true;
142 }
143 }
144 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000145}
146
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000147template <typename Predicate>
148bool TypeSetByHwMode::constrain(Predicate P) {
149 bool Changed = false;
150 for (auto &I : *this)
Benjamin Kramere57308e2017-09-17 11:19:53 +0000151 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000152 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000153}
154
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000155template <typename Predicate>
156bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
157 assert(empty());
158 for (const auto &I : VTS) {
159 SetType &S = getOrCreate(I.first);
160 for (auto J : I.second)
161 if (P(J))
162 S.insert(J);
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000163 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000164 return !empty();
Chris Lattnercabe0372010-03-15 06:00:16 +0000165}
166
Zachary Turner249dc142017-09-20 18:01:40 +0000167void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
168 SmallVector<unsigned, 4> Modes;
169 Modes.reserve(Map.size());
Chris Lattnercabe0372010-03-15 06:00:16 +0000170
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000171 for (const auto &I : *this)
172 Modes.push_back(I.first);
Zachary Turner249dc142017-09-20 18:01:40 +0000173 if (Modes.empty()) {
174 OS << "{}";
175 return;
176 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000177 array_pod_sort(Modes.begin(), Modes.end());
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000178
Zachary Turner249dc142017-09-20 18:01:40 +0000179 OS << '{';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000180 for (unsigned M : Modes) {
Zachary Turner249dc142017-09-20 18:01:40 +0000181 OS << ' ' << getModeName(M) << ':';
182 writeToStream(get(M), OS);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000183 }
Zachary Turner249dc142017-09-20 18:01:40 +0000184 OS << " }";
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000185}
186
Zachary Turner249dc142017-09-20 18:01:40 +0000187void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
188 SmallVector<MVT, 4> Types(S.begin(), S.end());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000189 array_pod_sort(Types.begin(), Types.end());
190
Zachary Turner249dc142017-09-20 18:01:40 +0000191 OS << '[';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000192 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
Zachary Turner249dc142017-09-20 18:01:40 +0000193 OS << ValueTypeByHwMode::getMVTName(Types[i]);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000194 if (i != e-1)
Zachary Turner249dc142017-09-20 18:01:40 +0000195 OS << ' ';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000196 }
Zachary Turner249dc142017-09-20 18:01:40 +0000197 OS << ']';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000198}
199
200bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
201 bool HaveDefault = hasDefault();
202 if (HaveDefault != VTS.hasDefault())
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000203 return false;
204
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000205 if (isSimple()) {
206 if (VTS.isSimple())
207 return *begin() == *VTS.begin();
208 return false;
209 }
210
Zachary Turner249dc142017-09-20 18:01:40 +0000211 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000212 for (auto &I : *this)
213 Modes.insert(I.first);
214 for (const auto &I : VTS)
215 Modes.insert(I.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000216
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000217 if (HaveDefault) {
218 // Both sets have default mode.
219 for (unsigned M : Modes) {
220 if (get(M) != VTS.get(M))
David Majnemerc7004902016-08-12 04:32:37 +0000221 return false;
Craig Topper5712d462015-11-24 08:20:47 +0000222 }
Scott Michel94420742008-03-05 17:49:05 +0000223 } else {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000224 // Neither set has default mode.
225 for (unsigned M : Modes) {
226 // If there is no default mode, an empty set is equivalent to not having
227 // the corresponding mode.
228 bool NoModeThis = !hasMode(M) || get(M).empty();
229 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
230 if (NoModeThis != NoModeVTS)
231 return false;
232 if (!NoModeThis)
233 if (get(M) != VTS.get(M))
234 return false;
235 }
Scott Michel94420742008-03-05 17:49:05 +0000236 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000237
238 return true;
Scott Michel94420742008-03-05 17:49:05 +0000239}
240
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000241namespace llvm {
242 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
243 T.writeToStream(OS);
244 return OS;
245 }
246}
247
Krzysztof Parzyszek426bf362017-09-12 15:31:26 +0000248LLVM_DUMP_METHOD
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000249void TypeSetByHwMode::dump() const {
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000250 dbgs() << *this << '\n';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000251}
252
253bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
254 bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
255 auto Int = [&In](MVT T) -> bool { return !In.count(T); };
256
257 if (OutP == InP)
258 return berase_if(Out, Int);
259
260 // Compute the intersection of scalars separately to account for only
261 // one set containing iPTR.
262 // The itersection of iPTR with a set of integer scalar types that does not
263 // include iPTR will result in the most specific scalar type:
264 // - iPTR is more specific than any set with two elements or more
265 // - iPTR is less specific than any single integer scalar type.
266 // For example
267 // { iPTR } * { i32 } -> { i32 }
268 // { iPTR } * { i32 i64 } -> { iPTR }
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000269 // and
270 // { iPTR i32 } * { i32 } -> { i32 }
271 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
272 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000273
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000274 // Compute the difference between the two sets in such a way that the
275 // iPTR is in the set that is being subtracted. This is to see if there
276 // are any extra scalars in the set without iPTR that are not in the
277 // set containing iPTR. Then the iPTR could be considered a "wildcard"
278 // matching these scalars. If there is only one such scalar, it would
279 // replace the iPTR, if there are more, the iPTR would be retained.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000280 SetType Diff;
281 if (InP) {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000282 Diff = Out;
283 berase_if(Diff, [&In](MVT T) { return In.count(T); });
284 // Pre-remove these elements and rely only on InP/OutP to determine
285 // whether a change has been made.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000286 berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
Scott Michel94420742008-03-05 17:49:05 +0000287 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000288 Diff = In;
289 berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000290 Out.erase(MVT::iPTR);
291 }
292
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000293 // The actual intersection.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000294 bool Changed = berase_if(Out, Int);
295 unsigned NumD = Diff.size();
296 if (NumD == 0)
297 return Changed;
298
299 if (NumD == 1) {
300 Out.insert(*Diff.begin());
301 // This is a change only if Out was the one with iPTR (which is now
302 // being replaced).
303 Changed |= OutP;
304 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000305 // Multiple elements from Out are now replaced with iPTR.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000306 Out.insert(MVT::iPTR);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000307 Changed |= !OutP;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000308 }
309 return Changed;
310}
311
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000312bool TypeSetByHwMode::validate() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000313#ifndef NDEBUG
314 if (empty())
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000315 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000316 bool AllEmpty = true;
317 for (const auto &I : *this)
318 AllEmpty &= I.second.empty();
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000319 return !AllEmpty;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000320#endif
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000321 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000322}
323
324// --- TypeInfer
325
326bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
327 const TypeSetByHwMode &In) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000328 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000329 In.validate();
330 if (In.empty() || Out == In || TP.hasError())
331 return false;
332 if (Out.empty()) {
333 Out = In;
334 return true;
335 }
336
337 bool Changed = Out.constrain(In);
338 if (Changed && Out.empty())
339 TP.error("Type contradiction");
340
341 return Changed;
342}
343
344bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000345 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000346 if (TP.hasError())
347 return false;
348 assert(!Out.empty() && "cannot pick from an empty set");
349
350 bool Changed = false;
351 for (auto &I : Out) {
352 TypeSetByHwMode::SetType &S = I.second;
353 if (S.size() <= 1)
354 continue;
355 MVT T = *S.begin(); // Pick the first element.
356 S.clear();
357 S.insert(T);
358 Changed = true;
359 }
360 return Changed;
361}
362
363bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000364 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000365 if (TP.hasError())
366 return false;
367 if (!Out.empty())
368 return Out.constrain(isIntegerOrPtr);
369
370 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
371}
372
373bool TypeInfer::EnforceFloatingPoint(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(isFloatingPoint);
379
380 return Out.assign_if(getLegalTypes(), isFloatingPoint);
381}
382
383bool TypeInfer::EnforceScalar(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(isScalar);
389
390 return Out.assign_if(getLegalTypes(), isScalar);
391}
392
393bool TypeInfer::EnforceVector(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(isVector);
399
400 return Out.assign_if(getLegalTypes(), isVector);
401}
402
403bool TypeInfer::EnforceAny(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() || !Out.empty())
406 return false;
407
408 Out = getLegalTypes();
409 return true;
410}
411
412template <typename Iter, typename Pred, typename Less>
413static Iter min_if(Iter B, Iter E, Pred P, Less L) {
414 if (B == E)
415 return E;
416 Iter Min = E;
417 for (Iter I = B; I != E; ++I) {
418 if (!P(*I))
419 continue;
420 if (Min == E || L(*I, *Min))
421 Min = I;
422 }
423 return Min;
424}
425
426template <typename Iter, typename Pred, typename Less>
427static Iter max_if(Iter B, Iter E, Pred P, Less L) {
428 if (B == E)
429 return E;
430 Iter Max = E;
431 for (Iter I = B; I != E; ++I) {
432 if (!P(*I))
433 continue;
434 if (Max == E || L(*Max, *I))
435 Max = I;
436 }
437 return Max;
438}
439
440/// Make sure that for each type in Small, there exists a larger type in Big.
441bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
442 TypeSetByHwMode &Big) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000443 ValidateOnExit _1(Small, *this), _2(Big, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000444 if (TP.hasError())
445 return false;
446 bool Changed = false;
447
448 if (Small.empty())
449 Changed |= EnforceAny(Small);
450 if (Big.empty())
451 Changed |= EnforceAny(Big);
452
453 assert(Small.hasDefault() && Big.hasDefault());
454
455 std::vector<unsigned> Modes = union_modes(Small, Big);
456
457 // 1. Only allow integer or floating point types and make sure that
458 // both sides are both integer or both floating point.
459 // 2. Make sure that either both sides have vector types, or neither
460 // of them does.
461 for (unsigned M : Modes) {
462 TypeSetByHwMode::SetType &S = Small.get(M);
463 TypeSetByHwMode::SetType &B = Big.get(M);
464
465 if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000466 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000467 Changed |= berase_if(S, NotInt) |
468 berase_if(B, NotInt);
469 } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000470 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000471 Changed |= berase_if(S, NotFP) |
472 berase_if(B, NotFP);
473 } else if (S.empty() || B.empty()) {
474 Changed = !S.empty() || !B.empty();
475 S.clear();
476 B.clear();
477 } else {
478 TP.error("Incompatible types");
479 return Changed;
Scott Michel94420742008-03-05 17:49:05 +0000480 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000481
482 if (none_of(S, isVector) || none_of(B, isVector)) {
483 Changed |= berase_if(S, isVector) |
484 berase_if(B, isVector);
485 }
486 }
487
488 auto LT = [](MVT A, MVT B) -> bool {
489 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
490 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
491 A.getSizeInBits() < B.getSizeInBits());
492 };
493 auto LE = [](MVT A, MVT B) -> bool {
494 // This function is used when removing elements: when a vector is compared
495 // to a non-vector, it should return false (to avoid removal).
496 if (A.isVector() != B.isVector())
497 return false;
498
499 // Note on the < comparison below:
500 // X86 has patterns like
501 // (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))),
502 // where the truncated vector is given a type v16i8, while the source
503 // vector has type v4i32. They both have the same size in bits.
504 // The minimal type in the result is obviously v16i8, and when we remove
505 // all types from the source that are smaller-or-equal than v8i16, the
506 // only source type would also be removed (since it's equal in size).
507 return A.getScalarSizeInBits() <= B.getScalarSizeInBits() ||
508 A.getSizeInBits() < B.getSizeInBits();
509 };
510
511 for (unsigned M : Modes) {
512 TypeSetByHwMode::SetType &S = Small.get(M);
513 TypeSetByHwMode::SetType &B = Big.get(M);
514 // MinS = min scalar in Small, remove all scalars from Big that are
515 // smaller-or-equal than MinS.
516 auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000517 if (MinS != S.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000518 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000519
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000520 // MaxS = max scalar in Big, remove all scalars from Small that are
521 // larger than MaxS.
522 auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000523 if (MaxS != B.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000524 Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000525
526 // MinV = min vector in Small, remove all vectors from Big that are
527 // smaller-or-equal than MinV.
528 auto MinV = min_if(S.begin(), S.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000529 if (MinV != S.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000530 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000531
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000532 // MaxV = max vector in Big, remove all vectors from Small that are
533 // larger than MaxV.
534 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000535 if (MaxV != B.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000536 Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000537 }
538
539 return Changed;
540}
541
542/// 1. Ensure that for each type T in Vec, T is a vector type, and that
543/// for each type U in Elem, U is a scalar type.
544/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
545/// type T in Vec, such that U is the element type of T.
546bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
547 TypeSetByHwMode &Elem) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000548 ValidateOnExit _1(Vec, *this), _2(Elem, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000549 if (TP.hasError())
550 return false;
551 bool Changed = false;
552
553 if (Vec.empty())
554 Changed |= EnforceVector(Vec);
555 if (Elem.empty())
556 Changed |= EnforceScalar(Elem);
557
558 for (unsigned M : union_modes(Vec, Elem)) {
559 TypeSetByHwMode::SetType &V = Vec.get(M);
560 TypeSetByHwMode::SetType &E = Elem.get(M);
561
562 Changed |= berase_if(V, isScalar); // Scalar = !vector
563 Changed |= berase_if(E, isVector); // Vector = !scalar
564 assert(!V.empty() && !E.empty());
565
566 SmallSet<MVT,4> VT, ST;
567 // Collect element types from the "vector" set.
568 for (MVT T : V)
569 VT.insert(T.getVectorElementType());
570 // Collect scalar types from the "element" set.
571 for (MVT T : E)
572 ST.insert(T);
573
574 // Remove from V all (vector) types whose element type is not in S.
575 Changed |= berase_if(V, [&ST](MVT T) -> bool {
576 return !ST.count(T.getVectorElementType());
577 });
578 // Remove from E all (scalar) types, for which there is no corresponding
579 // type in V.
580 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000581 }
582
583 return Changed;
584}
585
586bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
587 const ValueTypeByHwMode &VVT) {
588 TypeSetByHwMode Tmp(VVT);
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000589 ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000590 return EnforceVectorEltTypeIs(Vec, Tmp);
591}
592
593/// Ensure that for each type T in Sub, T is a vector type, and there
594/// exists a type U in Vec such that U is a vector type with the same
595/// element type as T and at least as many elements as T.
596bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
597 TypeSetByHwMode &Sub) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000598 ValidateOnExit _1(Vec, *this), _2(Sub, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000599 if (TP.hasError())
600 return false;
601
602 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
603 auto IsSubVec = [](MVT B, MVT P) -> bool {
604 if (!B.isVector() || !P.isVector())
605 return false;
Florian Hahn603c6452017-11-07 10:43:56 +0000606 // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
607 // but until there are obvious use-cases for this, keep the
608 // types separate.
609 if (B.isScalableVector() != P.isScalableVector())
610 return false;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000611 if (B.getVectorElementType() != P.getVectorElementType())
612 return false;
613 return B.getVectorNumElements() < P.getVectorNumElements();
614 };
615
616 /// Return true if S has no element (vector type) that T is a sub-vector of,
617 /// i.e. has the same element type as T and more elements.
618 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
619 for (const auto &I : S)
620 if (IsSubVec(T, I))
621 return false;
622 return true;
623 };
624
625 /// Return true if S has no element (vector type) that T is a super-vector
626 /// of, i.e. has the same element type as T and fewer elements.
627 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
628 for (const auto &I : S)
629 if (IsSubVec(I, T))
630 return false;
631 return true;
632 };
633
634 bool Changed = false;
635
636 if (Vec.empty())
637 Changed |= EnforceVector(Vec);
638 if (Sub.empty())
639 Changed |= EnforceVector(Sub);
640
641 for (unsigned M : union_modes(Vec, Sub)) {
642 TypeSetByHwMode::SetType &S = Sub.get(M);
643 TypeSetByHwMode::SetType &V = Vec.get(M);
644
645 Changed |= berase_if(S, isScalar);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000646
647 // Erase all types from S that are not sub-vectors of a type in V.
648 Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000649
650 // Erase all types from V that are not super-vectors of a type in S.
651 Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000652 }
653
654 return Changed;
655}
656
657/// 1. Ensure that V has a scalar type iff W has a scalar type.
658/// 2. Ensure that for each vector type T in V, there exists a vector
659/// type U in W, such that T and U have the same number of elements.
660/// 3. Ensure that for each vector type U in W, there exists a vector
661/// type T in V, such that T and U have the same number of elements
662/// (reverse of 2).
663bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000664 ValidateOnExit _1(V, *this), _2(W, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000665 if (TP.hasError())
666 return false;
667
668 bool Changed = false;
669 if (V.empty())
670 Changed |= EnforceAny(V);
671 if (W.empty())
672 Changed |= EnforceAny(W);
673
674 // An actual vector type cannot have 0 elements, so we can treat scalars
675 // as zero-length vectors. This way both vectors and scalars can be
676 // processed identically.
677 auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
678 return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
679 };
680
681 for (unsigned M : union_modes(V, W)) {
682 TypeSetByHwMode::SetType &VS = V.get(M);
683 TypeSetByHwMode::SetType &WS = W.get(M);
684
685 SmallSet<unsigned,2> VN, WN;
686 for (MVT T : VS)
687 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
688 for (MVT T : WS)
689 WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
690
691 Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
692 Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
693 }
694 return Changed;
695}
696
697/// 1. Ensure that for each type T in A, there exists a type U in B,
698/// such that T and U have equal size in bits.
699/// 2. Ensure that for each type U in B, there exists a type T in A
700/// such that T and U have equal size in bits (reverse of 1).
701bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000702 ValidateOnExit _1(A, *this), _2(B, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000703 if (TP.hasError())
704 return false;
705 bool Changed = false;
706 if (A.empty())
707 Changed |= EnforceAny(A);
708 if (B.empty())
709 Changed |= EnforceAny(B);
710
711 auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
712 return !Sizes.count(T.getSizeInBits());
713 };
714
715 for (unsigned M : union_modes(A, B)) {
716 TypeSetByHwMode::SetType &AS = A.get(M);
717 TypeSetByHwMode::SetType &BS = B.get(M);
718 SmallSet<unsigned,2> AN, BN;
719
720 for (MVT T : AS)
721 AN.insert(T.getSizeInBits());
722 for (MVT T : BS)
723 BN.insert(T.getSizeInBits());
724
725 Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
726 Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
727 }
728
729 return Changed;
730}
731
732void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000733 ValidateOnExit _1(VTS, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000734 TypeSetByHwMode Legal = getLegalTypes();
735 bool HaveLegalDef = Legal.hasDefault();
736
737 for (auto &I : VTS) {
738 unsigned M = I.first;
739 if (!Legal.hasMode(M) && !HaveLegalDef) {
740 TP.error("Invalid mode " + Twine(M));
741 return;
742 }
743 expandOverloads(I.second, Legal.get(M));
Scott Michel94420742008-03-05 17:49:05 +0000744 }
745}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000746
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000747void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
748 const TypeSetByHwMode::SetType &Legal) {
749 std::set<MVT> Ovs;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000750 for (MVT T : Out) {
751 if (!T.isOverloaded())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000752 continue;
Zachary Turner249dc142017-09-20 18:01:40 +0000753
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000754 Ovs.insert(T);
755 // MachineValueTypeSet allows iteration and erasing.
756 Out.erase(T);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000757 }
758
759 for (MVT Ov : Ovs) {
760 switch (Ov.SimpleTy) {
761 case MVT::iPTRAny:
762 Out.insert(MVT::iPTR);
763 return;
764 case MVT::iAny:
765 for (MVT T : MVT::integer_valuetypes())
766 if (Legal.count(T))
767 Out.insert(T);
768 for (MVT T : MVT::integer_vector_valuetypes())
769 if (Legal.count(T))
770 Out.insert(T);
771 return;
772 case MVT::fAny:
773 for (MVT T : MVT::fp_valuetypes())
774 if (Legal.count(T))
775 Out.insert(T);
776 for (MVT T : MVT::fp_vector_valuetypes())
777 if (Legal.count(T))
778 Out.insert(T);
779 return;
780 case MVT::vAny:
781 for (MVT T : MVT::vector_valuetypes())
782 if (Legal.count(T))
783 Out.insert(T);
784 return;
785 case MVT::Any:
786 for (MVT T : MVT::all_valuetypes())
787 if (Legal.count(T))
788 Out.insert(T);
789 return;
790 default:
791 break;
792 }
793 }
794}
795
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000796TypeSetByHwMode TypeInfer::getLegalTypes() {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000797 if (!LegalTypesCached) {
798 // Stuff all types from all modes into the default mode.
799 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
800 for (const auto &I : LTS)
801 LegalCache.insert(I.second);
802 LegalTypesCached = true;
803 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000804 TypeSetByHwMode VTS;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000805 VTS.getOrCreate(DefaultMode) = LegalCache;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000806 return VTS;
807}
Chris Lattner514e2922011-04-17 21:38:24 +0000808
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000809#ifndef NDEBUG
810TypeInfer::ValidateOnExit::~ValidateOnExit() {
811 if (!VTS.validate()) {
812 dbgs() << "Type set is empty for each HW mode:\n"
813 "possible type contradiction in the pattern below "
814 "(use -print-records with llvm-tblgen to see all "
815 "expanded records).\n";
816 Infer.TP.dump();
817 llvm_unreachable(nullptr);
818 }
819}
820#endif
821
Chris Lattner514e2922011-04-17 21:38:24 +0000822//===----------------------------------------------------------------------===//
823// TreePredicateFn Implementation
824//===----------------------------------------------------------------------===//
825
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000826/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
827TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000828 assert(
829 (!hasPredCode() || !hasImmCode()) &&
830 ".td file corrupt: can't have a node predicate *and* an imm predicate");
831}
832
833bool TreePredicateFn::hasPredCode() const {
Daniel Sanders87d196c2017-11-13 22:26:13 +0000834 return isLoad() || isStore() || isAtomic() ||
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000835 !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000836}
837
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000838std::string TreePredicateFn::getPredCode() const {
839 std::string Code = "";
840
Daniel Sanders87d196c2017-11-13 22:26:13 +0000841 if (!isLoad() && !isStore() && !isAtomic()) {
842 Record *MemoryVT = getMemoryVT();
843
844 if (MemoryVT)
845 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
846 "MemoryVT requires IsLoad or IsStore");
847 }
848
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000849 if (!isLoad() && !isStore()) {
850 if (isUnindexed())
851 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
852 "IsUnindexed requires IsLoad or IsStore");
853
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000854 Record *ScalarMemoryVT = getScalarMemoryVT();
855
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000856 if (ScalarMemoryVT)
857 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
858 "ScalarMemoryVT requires IsLoad or IsStore");
859 }
860
Daniel Sanders87d196c2017-11-13 22:26:13 +0000861 if (isLoad() + isStore() + isAtomic() > 1)
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000862 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
Daniel Sanders87d196c2017-11-13 22:26:13 +0000863 "IsLoad, IsStore, and IsAtomic are mutually exclusive");
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000864
865 if (isLoad()) {
866 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
867 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
868 getScalarMemoryVT() == nullptr)
869 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
870 "IsLoad cannot be used by itself");
871 } else {
872 if (isNonExtLoad())
873 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
874 "IsNonExtLoad requires IsLoad");
875 if (isAnyExtLoad())
876 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
877 "IsAnyExtLoad requires IsLoad");
878 if (isSignExtLoad())
879 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
880 "IsSignExtLoad requires IsLoad");
881 if (isZeroExtLoad())
882 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
883 "IsZeroExtLoad requires IsLoad");
884 }
885
886 if (isStore()) {
887 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
888 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr)
889 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
890 "IsStore cannot be used by itself");
891 } else {
892 if (isNonTruncStore())
893 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
894 "IsNonTruncStore requires IsStore");
895 if (isTruncStore())
896 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
897 "IsTruncStore requires IsStore");
898 }
899
Daniel Sanders87d196c2017-11-13 22:26:13 +0000900 if (isAtomic()) {
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000901 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
902 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
903 !isAtomicOrderingAcquireRelease() &&
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000904 !isAtomicOrderingSequentiallyConsistent() &&
905 !isAtomicOrderingAcquireOrStronger() &&
906 !isAtomicOrderingReleaseOrStronger() &&
907 !isAtomicOrderingWeakerThanAcquire() &&
908 !isAtomicOrderingWeakerThanRelease())
Daniel Sanders87d196c2017-11-13 22:26:13 +0000909 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
910 "IsAtomic cannot be used by itself");
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000911 } else {
912 if (isAtomicOrderingMonotonic())
913 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
914 "IsAtomicOrderingMonotonic requires IsAtomic");
915 if (isAtomicOrderingAcquire())
916 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
917 "IsAtomicOrderingAcquire requires IsAtomic");
918 if (isAtomicOrderingRelease())
919 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
920 "IsAtomicOrderingRelease requires IsAtomic");
921 if (isAtomicOrderingAcquireRelease())
922 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
923 "IsAtomicOrderingAcquireRelease requires IsAtomic");
924 if (isAtomicOrderingSequentiallyConsistent())
925 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
926 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000927 if (isAtomicOrderingAcquireOrStronger())
928 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
929 "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
930 if (isAtomicOrderingReleaseOrStronger())
931 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
932 "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
933 if (isAtomicOrderingWeakerThanAcquire())
934 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
935 "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
Daniel Sanders87d196c2017-11-13 22:26:13 +0000936 }
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000937
Daniel Sanders87d196c2017-11-13 22:26:13 +0000938 if (isLoad() || isStore() || isAtomic()) {
939 StringRef SDNodeName =
940 isLoad() ? "LoadSDNode" : isStore() ? "StoreSDNode" : "AtomicSDNode";
941
942 Record *MemoryVT = getMemoryVT();
943
944 if (MemoryVT)
945 Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT() != MVT::" +
946 MemoryVT->getName() + ") return false;\n")
947 .str();
948 }
949
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000950 if (isAtomic() && isAtomicOrderingMonotonic())
951 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
952 "AtomicOrdering::Monotonic) return false;\n";
953 if (isAtomic() && isAtomicOrderingAcquire())
954 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
955 "AtomicOrdering::Acquire) return false;\n";
956 if (isAtomic() && isAtomicOrderingRelease())
957 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
958 "AtomicOrdering::Release) return false;\n";
959 if (isAtomic() && isAtomicOrderingAcquireRelease())
960 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
961 "AtomicOrdering::AcquireRelease) return false;\n";
962 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
963 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
964 "AtomicOrdering::SequentiallyConsistent) return false;\n";
965
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000966 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
967 Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
968 "return false;\n";
969 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
970 Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
971 "return false;\n";
972
973 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
974 Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
975 "return false;\n";
976 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
977 Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
978 "return false;\n";
979
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000980 if (isLoad() || isStore()) {
981 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
982
983 if (isUnindexed())
984 Code += ("if (cast<" + SDNodeName +
985 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
986 "return false;\n")
987 .str();
988
989 if (isLoad()) {
990 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
991 isZeroExtLoad()) > 1)
992 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
993 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
994 "IsZeroExtLoad are mutually exclusive");
995 if (isNonExtLoad())
996 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
997 "ISD::NON_EXTLOAD) return false;\n";
998 if (isAnyExtLoad())
999 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1000 "return false;\n";
1001 if (isSignExtLoad())
1002 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1003 "return false;\n";
1004 if (isZeroExtLoad())
1005 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1006 "return false;\n";
1007 } else {
1008 if ((isNonTruncStore() + isTruncStore()) > 1)
1009 PrintFatalError(
1010 getOrigPatFragRecord()->getRecord()->getLoc(),
1011 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1012 if (isNonTruncStore())
1013 Code +=
1014 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1015 if (isTruncStore())
1016 Code +=
1017 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1018 }
1019
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001020 Record *ScalarMemoryVT = getScalarMemoryVT();
1021
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001022 if (ScalarMemoryVT)
1023 Code += ("if (cast<" + SDNodeName +
1024 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1025 ScalarMemoryVT->getName() + ") return false;\n")
1026 .str();
1027 }
1028
1029 std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
1030
1031 Code += PredicateCode;
1032
1033 if (PredicateCode.empty() && !Code.empty())
1034 Code += "return true;\n";
1035
1036 return Code;
Chris Lattner514e2922011-04-17 21:38:24 +00001037}
1038
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001039bool TreePredicateFn::hasImmCode() const {
1040 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1041}
1042
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001043std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00001044 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001045}
1046
Daniel Sanders649c5852017-10-13 20:42:18 +00001047bool TreePredicateFn::immCodeUsesAPInt() const {
1048 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1049}
1050
1051bool TreePredicateFn::immCodeUsesAPFloat() const {
1052 bool Unset;
1053 // The return value will be false when IsAPFloat is unset.
1054 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1055 Unset);
1056}
1057
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001058bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1059 bool Value) const {
1060 bool Unset;
1061 bool Result =
1062 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1063 if (Unset)
1064 return false;
1065 return Result == Value;
1066}
1067bool TreePredicateFn::isLoad() const {
1068 return isPredefinedPredicateEqualTo("IsLoad", true);
1069}
1070bool TreePredicateFn::isStore() const {
1071 return isPredefinedPredicateEqualTo("IsStore", true);
1072}
Daniel Sanders87d196c2017-11-13 22:26:13 +00001073bool TreePredicateFn::isAtomic() const {
1074 return isPredefinedPredicateEqualTo("IsAtomic", true);
1075}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001076bool TreePredicateFn::isUnindexed() const {
1077 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1078}
1079bool TreePredicateFn::isNonExtLoad() const {
1080 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1081}
1082bool TreePredicateFn::isAnyExtLoad() const {
1083 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1084}
1085bool TreePredicateFn::isSignExtLoad() const {
1086 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1087}
1088bool TreePredicateFn::isZeroExtLoad() const {
1089 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1090}
1091bool TreePredicateFn::isNonTruncStore() const {
1092 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1093}
1094bool TreePredicateFn::isTruncStore() const {
1095 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1096}
Daniel Sanders6d9d30a2017-11-13 23:03:47 +00001097bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1098 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1099}
1100bool TreePredicateFn::isAtomicOrderingAcquire() const {
1101 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1102}
1103bool TreePredicateFn::isAtomicOrderingRelease() const {
1104 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1105}
1106bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1107 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1108}
1109bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1110 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1111 true);
1112}
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001113bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1114 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1115}
1116bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1117 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1118}
1119bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1120 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1121}
1122bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1123 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1124}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001125Record *TreePredicateFn::getMemoryVT() const {
1126 Record *R = getOrigPatFragRecord()->getRecord();
1127 if (R->isValueUnset("MemoryVT"))
1128 return nullptr;
1129 return R->getValueAsDef("MemoryVT");
1130}
1131Record *TreePredicateFn::getScalarMemoryVT() const {
1132 Record *R = getOrigPatFragRecord()->getRecord();
1133 if (R->isValueUnset("ScalarMemoryVT"))
1134 return nullptr;
1135 return R->getValueAsDef("ScalarMemoryVT");
1136}
1137
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001138StringRef TreePredicateFn::getImmType() const {
Daniel Sanders649c5852017-10-13 20:42:18 +00001139 if (immCodeUsesAPInt())
1140 return "const APInt &";
1141 if (immCodeUsesAPFloat())
1142 return "const APFloat &";
1143 return "int64_t";
1144}
Chris Lattner514e2922011-04-17 21:38:24 +00001145
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001146StringRef TreePredicateFn::getImmTypeIdentifier() const {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001147 if (immCodeUsesAPInt())
1148 return "APInt";
1149 else if (immCodeUsesAPFloat())
1150 return "APFloat";
1151 return "I64";
1152}
1153
Chris Lattner514e2922011-04-17 21:38:24 +00001154/// isAlwaysTrue - Return true if this is a noop predicate.
1155bool TreePredicateFn::isAlwaysTrue() const {
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001156 return !hasPredCode() && !hasImmCode();
Chris Lattner514e2922011-04-17 21:38:24 +00001157}
1158
1159/// Return the name to use in the generated code to reference this, this is
1160/// "Predicate_foo" if from a pattern fragment "foo".
1161std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +00001162 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +00001163}
1164
1165/// getCodeToRunOnSDNode - Return the code for the function body that
1166/// evaluates this predicate. The argument is expected to be in "Node",
1167/// not N. This handles casting and conversion to a concrete node type as
1168/// appropriate.
1169std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001170 // Handle immediate predicates first.
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001171 std::string ImmCode = getImmCode();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001172 if (!ImmCode.empty()) {
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001173 if (isLoad())
1174 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1175 "IsLoad cannot be used with ImmLeaf or its subclasses");
1176 if (isStore())
1177 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1178 "IsStore cannot be used with ImmLeaf or its subclasses");
1179 if (isUnindexed())
1180 PrintFatalError(
1181 getOrigPatFragRecord()->getRecord()->getLoc(),
1182 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1183 if (isNonExtLoad())
1184 PrintFatalError(
1185 getOrigPatFragRecord()->getRecord()->getLoc(),
1186 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1187 if (isAnyExtLoad())
1188 PrintFatalError(
1189 getOrigPatFragRecord()->getRecord()->getLoc(),
1190 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1191 if (isSignExtLoad())
1192 PrintFatalError(
1193 getOrigPatFragRecord()->getRecord()->getLoc(),
1194 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1195 if (isZeroExtLoad())
1196 PrintFatalError(
1197 getOrigPatFragRecord()->getRecord()->getLoc(),
1198 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1199 if (isNonTruncStore())
1200 PrintFatalError(
1201 getOrigPatFragRecord()->getRecord()->getLoc(),
1202 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1203 if (isTruncStore())
1204 PrintFatalError(
1205 getOrigPatFragRecord()->getRecord()->getLoc(),
1206 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1207 if (getMemoryVT())
1208 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1209 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1210 if (getScalarMemoryVT())
1211 PrintFatalError(
1212 getOrigPatFragRecord()->getRecord()->getLoc(),
1213 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1214
1215 std::string Result = (" " + getImmType() + " Imm = ").str();
Daniel Sanders649c5852017-10-13 20:42:18 +00001216 if (immCodeUsesAPFloat())
1217 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1218 else if (immCodeUsesAPInt())
1219 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1220 else
1221 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001222 return Result + ImmCode;
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001223 }
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001224
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001225 // Handle arbitrary node predicates.
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001226 assert(hasPredCode() && "Don't have any predicate code!");
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001227 StringRef ClassName;
Chris Lattner514e2922011-04-17 21:38:24 +00001228 if (PatFragRec->getOnlyTree()->isLeaf())
1229 ClassName = "SDNode";
1230 else {
1231 Record *Op = PatFragRec->getOnlyTree()->getOperator();
1232 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1233 }
1234 std::string Result;
1235 if (ClassName == "SDNode")
1236 Result = " SDNode *N = Node;\n";
1237 else
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001238 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001239
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001240 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +00001241}
1242
Chris Lattner8cab0212008-01-05 22:25:12 +00001243//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +00001244// PatternToMatch implementation
1245//
1246
Chris Lattner05925fe2010-03-29 01:40:38 +00001247/// getPatternSize - Return the 'size' of this pattern. We want to match large
1248/// patterns before small ones. This is used to determine the size of a
1249/// pattern.
1250static unsigned getPatternSize(const TreePatternNode *P,
1251 const CodeGenDAGPatterns &CGP) {
1252 unsigned Size = 3; // The node itself.
1253 // If the root node is a ConstantSDNode, increases its size.
1254 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +00001255 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001256 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001257
Simon Pilgrim40687012017-09-26 12:59:01 +00001258 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001259 Size += AM->getComplexity();
Tim Northoverc807a172014-05-20 11:52:46 +00001260 // We don't want to count any children twice, so return early.
1261 return Size;
1262 }
1263
Chris Lattner05925fe2010-03-29 01:40:38 +00001264 // If this node has some predicate function that must match, it adds to the
1265 // complexity of this node.
1266 if (!P->getPredicateFns().empty())
1267 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001268
Chris Lattner05925fe2010-03-29 01:40:38 +00001269 // Count children in the count if they are also nodes.
1270 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
Simon Pilgrima932bfc2017-09-27 10:03:17 +00001271 const TreePatternNode *Child = P->getChild(i);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001272 if (!Child->isLeaf() && Child->getNumTypes()) {
1273 const TypeSetByHwMode &T0 = Child->getType(0);
1274 // At this point, all variable type sets should be simple, i.e. only
1275 // have a default mode.
1276 if (T0.getMachineValueType() != MVT::Other) {
1277 Size += getPatternSize(Child, CGP);
1278 continue;
1279 }
1280 }
1281 if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00001282 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001283 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
1284 else if (Child->getComplexPatternInfo(CGP))
1285 Size += getPatternSize(Child, CGP);
1286 else if (!Child->getPredicateFns().empty())
1287 ++Size;
1288 }
1289 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001290
Chris Lattner05925fe2010-03-29 01:40:38 +00001291 return Size;
1292}
1293
1294/// Compute the complexity metric for the input pattern. This roughly
1295/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +00001296int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +00001297getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
1298 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
1299}
1300
Dan Gohman49e19e92008-08-22 00:20:26 +00001301/// getPredicateCheck - Return a single string containing all of this
1302/// pattern's predicates concatenated with "&&" operators.
1303///
1304std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001305 SmallVector<const Predicate*,4> PredList;
1306 for (const Predicate &P : Predicates)
1307 PredList.push_back(&P);
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00001308 llvm::sort(PredList.begin(), PredList.end(), deref<llvm::less>());
Craig Topper8985efe2015-11-27 05:44:04 +00001309
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001310 std::string Check;
1311 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1312 if (i != 0)
1313 Check += " && ";
1314 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +00001315 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001316 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +00001317}
1318
1319//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00001320// SDTypeConstraint implementation
1321//
1322
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001323SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001324 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001325
Chris Lattner8cab0212008-01-05 22:25:12 +00001326 if (R->isSubClassOf("SDTCisVT")) {
1327 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001328 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1329 for (const auto &P : VVT)
1330 if (P.second == MVT::isVoid)
1331 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +00001332 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1333 ConstraintType = SDTCisPtrTy;
1334 } else if (R->isSubClassOf("SDTCisInt")) {
1335 ConstraintType = SDTCisInt;
1336 } else if (R->isSubClassOf("SDTCisFP")) {
1337 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +00001338 } else if (R->isSubClassOf("SDTCisVec")) {
1339 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001340 } else if (R->isSubClassOf("SDTCisSameAs")) {
1341 ConstraintType = SDTCisSameAs;
1342 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1343 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1344 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001345 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001346 R->getValueAsInt("OtherOperandNum");
1347 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1348 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001349 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001350 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001351 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1352 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001353 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001354 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1355 ConstraintType = SDTCisSubVecOfVec;
1356 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1357 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001358 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1359 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001360 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1361 for (const auto &P : VVT) {
1362 MVT T = P.second;
1363 if (T.isVector())
1364 PrintFatalError(R->getLoc(),
1365 "Cannot use vector type as SDTCVecEltisVT");
1366 if (!T.isInteger() && !T.isFloatingPoint())
1367 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1368 "as SDTCVecEltisVT");
1369 }
Craig Topper0be34582015-03-05 07:11:34 +00001370 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1371 ConstraintType = SDTCisSameNumEltsAs;
1372 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1373 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001374 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1375 ConstraintType = SDTCisSameSizeAs;
1376 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1377 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001378 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001379 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001380 }
1381}
1382
1383/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001384/// N, and the result number in ResNo.
1385static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
1386 const SDNodeInfo &NodeInfo,
1387 unsigned &ResNo) {
1388 unsigned NumResults = NodeInfo.getNumResults();
1389 if (OpNo < NumResults) {
1390 ResNo = OpNo;
1391 return N;
1392 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001393
Chris Lattner2db7aba2010-03-19 21:56:21 +00001394 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001395
Chris Lattner2db7aba2010-03-19 21:56:21 +00001396 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001397 std::string S;
1398 raw_string_ostream OS(S);
1399 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001400 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +00001401 N->print(OS);
1402 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001403 }
1404
Chris Lattner2db7aba2010-03-19 21:56:21 +00001405 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001406}
1407
1408/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1409/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001410/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001411bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
1412 const SDNodeInfo &NodeInfo,
1413 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001414 if (TP.hasError())
1415 return false;
1416
Chris Lattner2db7aba2010-03-19 21:56:21 +00001417 unsigned ResNo = 0; // The result number being referenced.
1418 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001419 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001420
Chris Lattner8cab0212008-01-05 22:25:12 +00001421 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001422 case SDTCisVT:
1423 // Operand must be a particular type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001424 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001425 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001426 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001427 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001428 case SDTCisInt:
1429 // Require it to be one of the legal integer VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001430 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001431 case SDTCisFP:
1432 // Require it to be one of the legal fp VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001433 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001434 case SDTCisVec:
1435 // Require it to be one of the legal vector VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001436 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001437 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001438 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001439 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001440 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +00001441 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1442 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001443 }
1444 case SDTCisVTSmallerThanOp: {
1445 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1446 // have an integer type that is smaller than the VT.
1447 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +00001448 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +00001449 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001450 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001451 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001452 return false;
1453 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001454 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
1455 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1456 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1457 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001458
Chris Lattner2db7aba2010-03-19 21:56:21 +00001459 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001460 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001461 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1462 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001463
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001464 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001465 }
1466 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001467 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001468 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001469 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1470 BResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001471 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1472 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001473 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001474 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001475 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +00001476 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001477 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1478 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001479 // Filter vector types out of VecOperand that don't have the right element
1480 // type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001481 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1482 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001483 }
David Greene127fd1d2011-01-24 20:53:18 +00001484 case SDTCisSubVecOfVec: {
1485 unsigned VResNo = 0;
1486 TreePatternNode *BigVecOperand =
1487 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1488 VResNo);
1489
1490 // Filter vector types out of BigVecOperand that don't have the
1491 // right subvector type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001492 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1493 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001494 }
Craig Topper0be34582015-03-05 07:11:34 +00001495 case SDTCVecEltisVT: {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001496 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001497 }
1498 case SDTCisSameNumEltsAs: {
1499 unsigned OResNo = 0;
1500 TreePatternNode *OtherNode =
1501 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1502 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001503 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1504 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001505 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001506 case SDTCisSameSizeAs: {
1507 unsigned OResNo = 0;
1508 TreePatternNode *OtherNode =
1509 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1510 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001511 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1512 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001513 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001514 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001515 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001516}
1517
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001518// Update the node type to match an instruction operand or result as specified
1519// in the ins or outs lists on the instruction definition. Return true if the
1520// type was actually changed.
1521bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1522 Record *Operand,
1523 TreePattern &TP) {
1524 // The 'unknown' operand indicates that types should be inferred from the
1525 // context.
1526 if (Operand->isSubClassOf("unknown_class"))
1527 return false;
1528
1529 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001530 if (Operand->isSubClassOf("Operand")) {
1531 Record *R = Operand->getValueAsDef("Type");
1532 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1533 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1534 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001535
1536 // PointerLikeRegClass has a type that is determined at runtime.
1537 if (Operand->isSubClassOf("PointerLikeRegClass"))
1538 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1539
1540 // Both RegisterClass and RegisterOperand operands derive their types from a
1541 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001542 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001543 if (Operand->isSubClassOf("RegisterClass"))
1544 RC = Operand;
1545 else if (Operand->isSubClassOf("RegisterOperand"))
1546 RC = Operand->getValueAsDef("RegClass");
1547
1548 assert(RC && "Unknown operand type");
1549 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1550 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1551}
1552
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001553bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1554 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1555 if (!TP.getInfer().isConcrete(Types[i], true))
1556 return true;
1557 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1558 if (getChild(i)->ContainsUnresolvedType(TP))
1559 return true;
1560 return false;
1561}
1562
1563bool TreePatternNode::hasProperTypeByHwMode() const {
1564 for (const TypeSetByHwMode &S : Types)
1565 if (!S.isDefaultOnly())
1566 return true;
Florian Hahn75e87c32018-05-30 21:00:18 +00001567 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001568 if (C->hasProperTypeByHwMode())
1569 return true;
1570 return false;
1571}
1572
1573bool TreePatternNode::hasPossibleType() const {
1574 for (const TypeSetByHwMode &S : Types)
1575 if (!S.isPossible())
1576 return false;
Florian Hahn75e87c32018-05-30 21:00:18 +00001577 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001578 if (!C->hasPossibleType())
1579 return false;
1580 return true;
1581}
1582
1583bool TreePatternNode::setDefaultMode(unsigned Mode) {
1584 for (TypeSetByHwMode &S : Types) {
1585 S.makeSimple(Mode);
1586 // Check if the selected mode had a type conflict.
1587 if (S.get(DefaultMode).empty())
1588 return false;
1589 }
Florian Hahn75e87c32018-05-30 21:00:18 +00001590 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001591 if (!C->setDefaultMode(Mode))
1592 return false;
1593 return true;
1594}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001595
Chris Lattner8cab0212008-01-05 22:25:12 +00001596//===----------------------------------------------------------------------===//
1597// SDNodeInfo implementation
1598//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001599SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001600 EnumName = R->getValueAsString("Opcode");
1601 SDClassName = R->getValueAsString("SDClass");
1602 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1603 NumResults = TypeProfile->getValueAsInt("NumResults");
1604 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001605
Chris Lattner8cab0212008-01-05 22:25:12 +00001606 // Parse the properties.
Matt Arsenault303327d2017-12-20 19:36:28 +00001607 Properties = parseSDPatternOperatorProperties(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001608
Chris Lattner8cab0212008-01-05 22:25:12 +00001609 // Parse the type constraints.
1610 std::vector<Record*> ConstraintList =
1611 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001612 for (Record *R : ConstraintList)
1613 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001614}
1615
Chris Lattner99e53b32010-02-28 00:22:30 +00001616/// getKnownType - If the type constraints on this node imply a fixed type
1617/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001618/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001619MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001620 unsigned NumResults = getNumResults();
1621 assert(NumResults <= 1 &&
1622 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001623 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001624
Craig Topper306cb122015-11-22 20:46:24 +00001625 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001626 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001627 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001628 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001629
Craig Topper306cb122015-11-22 20:46:24 +00001630 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001631 default: break;
1632 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001633 if (Constraint.VVT.isSimple())
1634 return Constraint.VVT.getSimple().SimpleTy;
1635 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001636 case SDTypeConstraint::SDTCisPtrTy:
1637 return MVT::iPTR;
1638 }
1639 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001640 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001641}
1642
Chris Lattner8cab0212008-01-05 22:25:12 +00001643//===----------------------------------------------------------------------===//
1644// TreePatternNode implementation
1645//
1646
Chris Lattnerf1447252010-03-19 21:37:09 +00001647static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1648 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001649 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001650 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001651
Chris Lattner2109cb42010-03-22 20:56:36 +00001652 if (Operator->isSubClassOf("Intrinsic"))
1653 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001654
Chris Lattnerf1447252010-03-19 21:37:09 +00001655 if (Operator->isSubClassOf("SDNode"))
1656 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001657
Chris Lattnerf1447252010-03-19 21:37:09 +00001658 if (Operator->isSubClassOf("PatFrag")) {
1659 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1660 // the forward reference case where one pattern fragment references another
1661 // before it is processed.
1662 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1663 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001664
Chris Lattnerf1447252010-03-19 21:37:09 +00001665 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001666 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001667 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001668 if (Tree)
1669 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1670 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001671 assert(Op && "Invalid Fragment");
1672 return GetNumNodeResults(Op, CDP);
1673 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001674
Chris Lattnerf1447252010-03-19 21:37:09 +00001675 if (Operator->isSubClassOf("Instruction")) {
1676 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001677
Craig Topper3a8eb892015-03-20 05:09:06 +00001678 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1679
1680 // Subtract any defaulted outputs.
1681 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1682 Record *OperandNode = InstInfo.Operands[i].Rec;
1683
1684 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1685 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1686 --NumDefsToAdd;
1687 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001688
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001689 // Add on one implicit def if it has a resolvable type.
1690 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1691 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001692 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001693 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001694
Chris Lattnerf1447252010-03-19 21:37:09 +00001695 if (Operator->isSubClassOf("SDNodeXForm"))
1696 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001697
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001698 if (Operator->isSubClassOf("ValueType"))
1699 return 1; // A type-cast of one result.
1700
Tim Northoverc807a172014-05-20 11:52:46 +00001701 if (Operator->isSubClassOf("ComplexPattern"))
1702 return 1;
1703
Matthias Braun8c209aa2017-01-28 02:02:38 +00001704 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001705 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001706}
1707
1708void TreePatternNode::print(raw_ostream &OS) const {
1709 if (isLeaf())
1710 OS << *getLeafValue();
1711 else
1712 OS << '(' << getOperator()->getName();
1713
Zachary Turner249dc142017-09-20 18:01:40 +00001714 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1715 OS << ':';
1716 getExtType(i).writeToStream(OS);
1717 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001718
1719 if (!isLeaf()) {
1720 if (getNumChildren() != 0) {
1721 OS << " ";
1722 getChild(0)->print(OS);
1723 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1724 OS << ", ";
1725 getChild(i)->print(OS);
1726 }
1727 }
1728 OS << ")";
1729 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001730
Craig Topper306cb122015-11-22 20:46:24 +00001731 for (const TreePredicateFn &Pred : PredicateFns)
1732 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001733 if (TransformFn)
1734 OS << "<<X:" << TransformFn->getName() << ">>";
1735 if (!getName().empty())
1736 OS << ":$" << getName();
1737
1738}
1739void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001740 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001741}
1742
Scott Michel94420742008-03-05 17:49:05 +00001743/// isIsomorphicTo - Return true if this node is recursively
1744/// isomorphic to the specified node. For this comparison, the node's
1745/// entire state is considered. The assigned name is ignored, since
1746/// nodes with differing names are considered isomorphic. However, if
1747/// the assigned name is present in the dependent variable set, then
1748/// the assigned name is considered significant and the node is
1749/// isomorphic if the names match.
1750bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1751 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001752 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001753 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001754 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001755 getTransformFn() != N->getTransformFn())
1756 return false;
1757
1758 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001759 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1760 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001761 return ((DI->getDef() == NDI->getDef())
1762 && (DepVars.find(getName()) == DepVars.end()
1763 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001764 }
1765 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001766 return getLeafValue() == N->getLeafValue();
1767 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001768
Chris Lattner8cab0212008-01-05 22:25:12 +00001769 if (N->getOperator() != getOperator() ||
1770 N->getNumChildren() != getNumChildren()) return false;
1771 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001772 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001773 return false;
1774 return true;
1775}
1776
1777/// clone - Make a copy of this tree and all of its children.
1778///
Florian Hahn75e87c32018-05-30 21:00:18 +00001779TreePatternNodePtr TreePatternNode::clone() const {
1780 TreePatternNodePtr New;
Chris Lattner8cab0212008-01-05 22:25:12 +00001781 if (isLeaf()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001782 New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001783 } else {
Florian Hahn75e87c32018-05-30 21:00:18 +00001784 std::vector<TreePatternNodePtr> CChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00001785 CChildren.reserve(Children.size());
1786 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1787 CChildren.push_back(getChild(i)->clone());
Florian Hahn75e87c32018-05-30 21:00:18 +00001788 New = std::make_shared<TreePatternNode>(getOperator(), CChildren,
1789 getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001790 }
1791 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001792 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001793 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001794 New->setTransformFn(getTransformFn());
1795 return New;
1796}
1797
Chris Lattner53c39ba2010-02-14 22:22:58 +00001798/// RemoveAllTypes - Recursively strip all the types of this tree.
1799void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001800 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001801 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001802 if (isLeaf()) return;
1803 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1804 getChild(i)->RemoveAllTypes();
1805}
1806
1807
Chris Lattner8cab0212008-01-05 22:25:12 +00001808/// SubstituteFormalArguments - Replace the formal arguments in this tree
1809/// with actual values specified by ArgMap.
Florian Hahn75e87c32018-05-30 21:00:18 +00001810void TreePatternNode::SubstituteFormalArguments(
1811 std::map<std::string, TreePatternNodePtr> &ArgMap) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001812 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001813
Chris Lattner8cab0212008-01-05 22:25:12 +00001814 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1815 TreePatternNode *Child = getChild(i);
1816 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001817 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001818 // Note that, when substituting into an output pattern, Val might be an
1819 // UnsetInit.
1820 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1821 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001822 // We found a use of a formal argument, replace it with its value.
Florian Hahn75e87c32018-05-30 21:00:18 +00001823 TreePatternNodePtr NewChild = ArgMap[Child->getName()];
Dan Gohman6e979022008-10-15 06:17:21 +00001824 assert(NewChild && "Couldn't find formal argument!");
1825 assert((Child->getPredicateFns().empty() ||
1826 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1827 "Non-empty child predicate clobbered!");
Florian Hahn53b14db2018-06-10 21:06:24 +00001828 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001829 }
1830 } else {
1831 getChild(i)->SubstituteFormalArguments(ArgMap);
1832 }
1833 }
1834}
1835
1836
1837/// InlinePatternFragments - If this pattern refers to any pattern
1838/// fragments, inline them into place, giving us a pattern without any
1839/// PatFrag references.
Florian Hahn75e87c32018-05-30 21:00:18 +00001840TreePatternNodePtr TreePatternNode::InlinePatternFragments(TreePatternNodePtr T,
1841 TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001842 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001843 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001844
1845 if (isLeaf())
Florian Hahn75e87c32018-05-30 21:00:18 +00001846 return T; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001847 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001848
Chris Lattner8cab0212008-01-05 22:25:12 +00001849 if (!Op->isSubClassOf("PatFrag")) {
1850 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001851 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001852 TreePatternNodePtr Child = getChildShared(i);
1853 TreePatternNodePtr NewChild = Child->InlinePatternFragments(Child, TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001854
1855 assert((Child->getPredicateFns().empty() ||
1856 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1857 "Non-empty child predicate clobbered!");
1858
Florian Hahn53b14db2018-06-10 21:06:24 +00001859 setChild(i, NewChild);
Dan Gohman6e979022008-10-15 06:17:21 +00001860 }
Florian Hahn75e87c32018-05-30 21:00:18 +00001861 return T;
Chris Lattner8cab0212008-01-05 22:25:12 +00001862 }
1863
1864 // Otherwise, we found a reference to a fragment. First, look up its
1865 // TreePattern record.
1866 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001867
Chris Lattner8cab0212008-01-05 22:25:12 +00001868 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001869 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001870 TP.error("'" + Op->getName() + "' fragment requires " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001871 Twine(Frag->getNumArgs()) + " operands!");
Florian Hahn75e87c32018-05-30 21:00:18 +00001872 return {nullptr};
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001873 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001874
Florian Hahn75e87c32018-05-30 21:00:18 +00001875 TreePatternNodePtr FragTree = Frag->getOnlyTree()->clone();
Chris Lattner8cab0212008-01-05 22:25:12 +00001876
Chris Lattner514e2922011-04-17 21:38:24 +00001877 TreePredicateFn PredFn(Frag);
1878 if (!PredFn.isAlwaysTrue())
1879 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001880
Chris Lattner8cab0212008-01-05 22:25:12 +00001881 // Resolve formal arguments to their actual value.
1882 if (Frag->getNumArgs()) {
1883 // Compute the map of formal to actual arguments.
Florian Hahn75e87c32018-05-30 21:00:18 +00001884 std::map<std::string, TreePatternNodePtr> ArgMap;
1885 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
1886 TreePatternNodePtr Child = getChildShared(i);
Florian Hahn53b14db2018-06-10 21:06:24 +00001887 ArgMap[Frag->getArgName(i)] = Child->InlinePatternFragments(Child, TP);
Florian Hahn75e87c32018-05-30 21:00:18 +00001888 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001889
Chris Lattner8cab0212008-01-05 22:25:12 +00001890 FragTree->SubstituteFormalArguments(ArgMap);
1891 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001892
Chris Lattner8cab0212008-01-05 22:25:12 +00001893 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001894 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1895 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001896
1897 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001898 for (const TreePredicateFn &Pred : getPredicateFns())
1899 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001900
Chris Lattner2e253b42008-06-30 03:02:03 +00001901 // The fragment we inlined could have recursive inlining that is needed. See
1902 // if there are any pattern fragments in it and inline them as needed.
Florian Hahn75e87c32018-05-30 21:00:18 +00001903 return FragTree->InlinePatternFragments(FragTree, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001904}
1905
1906/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001907/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001908/// references from the register file information, for example.
1909///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001910/// When Unnamed is set, return the type of a DAG operand with no name, such as
1911/// the F8RC register class argument in:
1912///
1913/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1914///
1915/// When Unnamed is false, return the type of a named DAG operand such as the
1916/// GPR:$src operand above.
1917///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001918static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
1919 bool NotRegisters,
1920 bool Unnamed,
1921 TreePattern &TP) {
1922 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1923
Owen Andersona84be6c2011-06-27 21:06:21 +00001924 // Check to see if this is a register operand.
1925 if (R->isSubClassOf("RegisterOperand")) {
1926 assert(ResNo == 0 && "Regoperand ref only has one result!");
1927 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001928 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00001929 Record *RegClass = R->getValueAsDef("RegClass");
1930 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001931 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00001932 }
1933
Chris Lattnercabe0372010-03-15 06:00:16 +00001934 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001935 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001936 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001937 // An unnamed register class represents itself as an i32 immediate, for
1938 // example on a COPY_TO_REGCLASS instruction.
1939 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001940 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001941
1942 // In a named operand, the register class provides the possible set of
1943 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001944 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001945 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00001946 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001947 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001948 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001949
Chris Lattner6070ee22010-03-23 23:50:31 +00001950 if (R->isSubClassOf("PatFrag")) {
1951 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001952 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001953 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001954 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001955
Chris Lattner6070ee22010-03-23 23:50:31 +00001956 if (R->isSubClassOf("Register")) {
1957 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001958 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001959 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001960 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001961 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001962 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001963
1964 if (R->isSubClassOf("SubRegIndex")) {
1965 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001966 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001967 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001968
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001969 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001970 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001971 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1972 //
1973 // (sext_inreg GPR:$src, i16)
1974 // ~~~
1975 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001976 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001977 // With a name, the ValueType simply provides the type of the named
1978 // variable.
1979 //
1980 // (sext_inreg i32:$src, i16)
1981 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001982 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001983 return TypeSetByHwMode(); // Unknown.
1984 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1985 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001986 }
1987
1988 if (R->isSubClassOf("CondCode")) {
1989 assert(ResNo == 0 && "This node only has one result!");
1990 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001991 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00001992 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001993
Chris Lattner6070ee22010-03-23 23:50:31 +00001994 if (R->isSubClassOf("ComplexPattern")) {
1995 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001996 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001997 return TypeSetByHwMode(); // Unknown.
1998 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00001999 }
2000 if (R->isSubClassOf("PointerLikeRegClass")) {
2001 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002002 TypeSetByHwMode VTS(MVT::iPTR);
2003 TP.getInfer().expandOverloads(VTS);
2004 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00002005 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002006
Chris Lattner6070ee22010-03-23 23:50:31 +00002007 if (R->getName() == "node" || R->getName() == "srcvalue" ||
2008 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002009 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002010 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002011 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002012
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002013 if (R->isSubClassOf("Operand")) {
2014 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2015 Record *T = R->getValueAsDef("Type");
2016 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2017 }
Tim Northoverc807a172014-05-20 11:52:46 +00002018
Chris Lattner8cab0212008-01-05 22:25:12 +00002019 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002020 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00002021}
2022
Chris Lattner89c65662008-01-06 05:36:50 +00002023
2024/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2025/// CodeGenIntrinsic information for it, otherwise return a null pointer.
2026const CodeGenIntrinsic *TreePatternNode::
2027getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2028 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2029 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2030 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00002031 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002032
Sean Silva88eb8dd2012-10-10 20:24:47 +00002033 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00002034 return &CDP.getIntrinsicInfo(IID);
2035}
2036
Chris Lattner53c39ba2010-02-14 22:22:58 +00002037/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2038/// return the ComplexPattern information, otherwise return null.
2039const ComplexPattern *
2040TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00002041 Record *Rec;
2042 if (isLeaf()) {
2043 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2044 if (!DI)
2045 return nullptr;
2046 Rec = DI->getDef();
2047 } else
2048 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002049
Tim Northoverc807a172014-05-20 11:52:46 +00002050 if (!Rec->isSubClassOf("ComplexPattern"))
2051 return nullptr;
2052 return &CGP.getComplexPattern(Rec);
2053}
2054
2055unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2056 // A ComplexPattern specifically declares how many results it fills in.
2057 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2058 return CP->getNumOperands();
2059
2060 // If MIOperandInfo is specified, that gives the count.
2061 if (isLeaf()) {
2062 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2063 if (DI && DI->getDef()->isSubClassOf("Operand")) {
2064 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2065 if (MIOps->getNumArgs())
2066 return MIOps->getNumArgs();
2067 }
2068 }
2069
2070 // Otherwise there is just one result.
2071 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00002072}
2073
2074/// NodeHasProperty - Return true if this node has the specified property.
2075bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002076 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002077 if (isLeaf()) {
2078 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2079 return CP->hasProperty(Property);
Matt Arsenault303327d2017-12-20 19:36:28 +00002080
Chris Lattner53c39ba2010-02-14 22:22:58 +00002081 return false;
2082 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002083
Matt Arsenault303327d2017-12-20 19:36:28 +00002084 if (Property != SDNPHasChain) {
2085 // The chain proprety is already present on the different intrinsic node
2086 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2087 // on the intrinsic. Anything else is specific to the individual intrinsic.
2088 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2089 return Int->hasProperty(Property);
2090 }
2091
2092 if (!Operator->isSubClassOf("SDPatternOperator"))
2093 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002094
Chris Lattner53c39ba2010-02-14 22:22:58 +00002095 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2096}
2097
2098
2099
2100
2101/// TreeHasProperty - Return true if any node in this tree has the specified
2102/// property.
2103bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002104 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002105 if (NodeHasProperty(Property, CGP))
2106 return true;
2107 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2108 if (getChild(i)->TreeHasProperty(Property, CGP))
2109 return true;
2110 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002111}
Chris Lattner53c39ba2010-02-14 22:22:58 +00002112
Evan Cheng49bad4c2008-06-16 20:29:38 +00002113/// isCommutativeIntrinsic - Return true if the node corresponds to a
2114/// commutative intrinsic.
2115bool
2116TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2117 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2118 return Int->isCommutative;
2119 return false;
2120}
2121
Matt Arsenaulteb492162014-11-02 23:46:51 +00002122static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2123 if (!N->isLeaf())
2124 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00002125
Matt Arsenaulteb492162014-11-02 23:46:51 +00002126 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
2127 if (DI && DI->getDef()->isSubClassOf(Class))
2128 return true;
2129
2130 return false;
2131}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002132
2133static void emitTooManyOperandsError(TreePattern &TP,
2134 StringRef InstName,
2135 unsigned Expected,
2136 unsigned Actual) {
2137 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2138 " operands but expected only " + Twine(Expected) + "!");
2139}
2140
2141static void emitTooFewOperandsError(TreePattern &TP,
2142 StringRef InstName,
2143 unsigned Actual) {
2144 TP.error("Instruction '" + InstName +
2145 "' expects more than the provided " + Twine(Actual) + " operands!");
2146}
2147
Bob Wilson1b97f3f2009-01-05 17:23:09 +00002148/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00002149/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002150/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00002151bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002152 if (TP.hasError())
2153 return false;
2154
Chris Lattnerab3242f2008-01-06 01:10:31 +00002155 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00002156 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002157 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002158 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00002159 bool MadeChange = false;
2160 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2161 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002162 NotRegisters,
2163 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002164 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00002165 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002166
Sean Silvafb509ed2012-10-10 20:24:43 +00002167 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002168 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002169
Chris Lattnerf1447252010-03-19 21:37:09 +00002170 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002171 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002172
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002173 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00002174 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002175
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002176 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2177 for (auto &P : VVT) {
2178 MVT::SimpleValueType VT = P.second.SimpleTy;
2179 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2180 continue;
2181 unsigned Size = MVT(VT).getSizeInBits();
2182 // Make sure that the value is representable for this type.
2183 if (Size >= 32)
2184 continue;
2185 // Check that the value doesn't use more bits than we have. It must
2186 // either be a sign- or zero-extended equivalent of the original.
2187 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2188 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2189 SignBitAndAbove == 1)
2190 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002191
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002192 TP.error("Integer value '" + Twine(II->getValue()) +
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002193 "' is out of range for type '" + getEnumName(VT) + "'!");
2194 break;
2195 }
2196 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002197 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002198
Chris Lattner8cab0212008-01-05 22:25:12 +00002199 return false;
2200 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002201
Chris Lattner8cab0212008-01-05 22:25:12 +00002202 // special handling for set, which isn't really an SDNode.
2203 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00002204 assert(getNumTypes() == 0 && "Set doesn't produce a value");
2205 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00002206 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002207
Chris Lattnerf1447252010-03-19 21:37:09 +00002208 TreePatternNode *SetVal = getChild(NC-1);
2209 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
2210
Elena Demikhovsky09954792015-03-01 08:23:41 +00002211 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002212 TreePatternNode *Child = getChild(i);
2213 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002214
Chris Lattner8cab0212008-01-05 22:25:12 +00002215 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00002216 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
2217 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002218 }
2219 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002220 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002221
Chris Lattner5c2182e2010-03-27 02:53:27 +00002222 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00002223 assert(getNumTypes() == 0 && "Node doesn't produce a value");
2224
Chris Lattner8cab0212008-01-05 22:25:12 +00002225 bool MadeChange = false;
2226 for (unsigned i = 0; i < getNumChildren(); ++i)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002227 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002228 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002229 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002230
Chris Lattneree820ac2010-02-23 05:51:07 +00002231 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002232 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00002233
Chris Lattner8cab0212008-01-05 22:25:12 +00002234 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00002235 unsigned NumRetVTs = Int->IS.RetVTs.size();
2236 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002237
Bill Wendling91821472008-11-13 09:08:33 +00002238 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00002239 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00002240
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002241 if (getNumChildren() != NumParamVTs + 1) {
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002242 TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2243 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002244 return false;
2245 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002246
2247 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00002248 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002249
Chris Lattnerf1447252010-03-19 21:37:09 +00002250 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
2251 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002252
Chris Lattnerf1447252010-03-19 21:37:09 +00002253 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
2254 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2255 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002256 }
2257 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002258 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002259
Chris Lattneree820ac2010-02-23 05:51:07 +00002260 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002261 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002262
Chris Lattner135091b2010-03-28 08:48:47 +00002263 // Check that the number of operands is sane. Negative operands -> varargs.
2264 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002265 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00002266 TP.error(getOperator()->getName() + " node requires exactly " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002267 Twine(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002268 return false;
2269 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002270
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002271 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00002272 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2273 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002274 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002275 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002276 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002277
Chris Lattneree820ac2010-02-23 05:51:07 +00002278 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002279 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002280 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00002281 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002282
Chris Lattnerd44966f2010-03-27 19:15:02 +00002283 bool MadeChange = false;
2284
2285 // Apply the result types to the node, these come from the things in the
2286 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00002287 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2288 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002289 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2290 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002291
Chris Lattnerd44966f2010-03-27 19:15:02 +00002292 // If the instruction has implicit defs, we apply the first one as a result.
2293 // FIXME: This sucks, it should apply all implicit defs.
2294 if (!InstInfo.ImplicitDefs.empty()) {
2295 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002296
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002297 // FIXME: Generalize to multiple possible types and multiple possible
2298 // ImplicitDefs.
2299 MVT::SimpleValueType VT =
2300 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002301
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002302 if (VT != MVT::Other)
2303 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002304 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002305
Chris Lattnercabe0372010-03-15 06:00:16 +00002306 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2307 // be the same.
2308 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00002309 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2310 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2311 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002312 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2313 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2314 // variadic.
2315
2316 unsigned NChild = getNumChildren();
2317 if (NChild < 3) {
2318 TP.error("REG_SEQUENCE requires at least 3 operands!");
2319 return false;
2320 }
2321
2322 if (NChild % 2 == 0) {
2323 TP.error("REG_SEQUENCE requires an odd number of operands!");
2324 return false;
2325 }
2326
2327 if (!isOperandClass(getChild(0), "RegisterClass")) {
2328 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2329 return false;
2330 }
2331
2332 for (unsigned I = 1; I < NChild; I += 2) {
2333 TreePatternNode *SubIdxChild = getChild(I + 1);
2334 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2335 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002336 Twine(I + 1) + "!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00002337 return false;
2338 }
2339 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002340 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002341
2342 unsigned ChildNo = 0;
2343 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2344 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002345
Chris Lattner8cab0212008-01-05 22:25:12 +00002346 // If the instruction expects a predicate or optional def operand, we
2347 // codegen this by setting the operand to it's default value if it has a
2348 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00002349 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002350 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2351 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002352
Chris Lattner8cab0212008-01-05 22:25:12 +00002353 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002354 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002355 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002356 return false;
2357 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002358
Chris Lattner8cab0212008-01-05 22:25:12 +00002359 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002360 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002361
2362 // If the operand has sub-operands, they may be provided by distinct
2363 // child patterns, so attempt to match each sub-operand separately.
2364 if (OperandNode->isSubClassOf("Operand")) {
2365 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2366 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2367 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002368 // a single ComplexPattern-related Operand.
2369
2370 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002371 // Match first sub-operand against the child we already have.
2372 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2373 MadeChange |=
2374 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2375
2376 // And the remaining sub-operands against subsequent children.
2377 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2378 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002379 emitTooFewOperandsError(TP, getOperator()->getName(),
2380 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002381 return false;
2382 }
2383 Child = getChild(ChildNo++);
2384
2385 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2386 MadeChange |=
2387 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2388 }
2389 continue;
2390 }
2391 }
2392 }
2393
2394 // If we didn't match by pieces above, attempt to match the whole
2395 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002396 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002397 }
Christopher Lamba7312392008-03-11 09:33:47 +00002398
Matt Arsenaulteb492162014-11-02 23:46:51 +00002399 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002400 emitTooManyOperandsError(TP, getOperator()->getName(),
2401 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002402 return false;
2403 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002404
Ulrich Weigande618abd2013-03-19 19:51:09 +00002405 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2406 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002407 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002408 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002409
Tim Northoverc807a172014-05-20 11:52:46 +00002410 if (getOperator()->isSubClassOf("ComplexPattern")) {
2411 bool MadeChange = false;
2412
2413 for (unsigned i = 0; i < getNumChildren(); ++i)
2414 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2415
2416 return MadeChange;
2417 }
2418
Chris Lattneree820ac2010-02-23 05:51:07 +00002419 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002420
Chris Lattneree820ac2010-02-23 05:51:07 +00002421 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002422 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002423 TP.error("Node transform '" + getOperator()->getName() +
2424 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002425 return false;
2426 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002427
Chris Lattnercabe0372010-03-15 06:00:16 +00002428 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002429 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002430}
2431
2432/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2433/// RHS of a commutative operation, not the on LHS.
2434static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2435 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
2436 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00002437 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002438 return true;
2439 return false;
2440}
2441
2442
2443/// canPatternMatch - If it is impossible for this pattern to match on this
2444/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002445/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002446/// that can never possibly work), and to prevent the pattern permuter from
2447/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002448bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002449 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002450 if (isLeaf()) return true;
2451
2452 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2453 if (!getChild(i)->canPatternMatch(Reason, CDP))
2454 return false;
2455
2456 // If this is an intrinsic, handle cases that would make it not match. For
2457 // example, if an operand is required to be an immediate.
2458 if (getOperator()->isSubClassOf("Intrinsic")) {
2459 // TODO:
2460 return true;
2461 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002462
Tim Northoverc807a172014-05-20 11:52:46 +00002463 if (getOperator()->isSubClassOf("ComplexPattern"))
2464 return true;
2465
Chris Lattner8cab0212008-01-05 22:25:12 +00002466 // If this node is a commutative operator, check that the LHS isn't an
2467 // immediate.
2468 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002469 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2470 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002471 // Scan all of the operands of the node and make sure that only the last one
2472 // is a constant node, unless the RHS also is.
2473 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002474 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002475 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002476 if (OnlyOnRHSOfCommutative(getChild(i))) {
2477 Reason="Immediate value must be on the RHS of commutative operators!";
2478 return false;
2479 }
2480 }
2481 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002482
Chris Lattner8cab0212008-01-05 22:25:12 +00002483 return true;
2484}
2485
2486//===----------------------------------------------------------------------===//
2487// TreePattern implementation
2488//
2489
David Greeneaf8ee2c2011-07-29 22:43:06 +00002490TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002491 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002492 isInputPattern(isInput), HasError(false),
2493 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002494 for (Init *I : RawPat->getValues())
2495 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002496}
2497
David Greeneaf8ee2c2011-07-29 22:43:06 +00002498TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002499 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002500 isInputPattern(isInput), HasError(false),
2501 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002502 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002503}
2504
Florian Hahn75e87c32018-05-30 21:00:18 +00002505TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
2506 CodeGenDAGPatterns &cdp)
2507 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2508 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002509 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002510}
2511
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002512void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002513 if (HasError)
2514 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002515 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002516 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2517 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002518}
2519
Chris Lattnercabe0372010-03-15 06:00:16 +00002520void TreePattern::ComputeNamedNodes() {
Florian Hahn75e87c32018-05-30 21:00:18 +00002521 for (TreePatternNodePtr &Tree : Trees)
2522 ComputeNamedNodes(Tree.get());
Chris Lattnercabe0372010-03-15 06:00:16 +00002523}
2524
2525void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2526 if (!N->getName().empty())
2527 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002528
Chris Lattnercabe0372010-03-15 06:00:16 +00002529 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2530 ComputeNamedNodes(N->getChild(i));
2531}
2532
Florian Hahn75e87c32018-05-30 21:00:18 +00002533TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
2534 StringRef OpName) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002535 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002536 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002537
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002538 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002539 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002540 /// (foo GPR, imm) -> (foo GPR, (imm))
2541 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002542 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002543 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002544 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002545 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002546
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002547 // Input argument?
Florian Hahn75e87c32018-05-30 21:00:18 +00002548 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002549 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002550 if (OpName.empty())
2551 error("'node' argument requires a name to match with operand list");
2552 Args.push_back(OpName);
2553 }
2554
2555 Res->setName(OpName);
2556 return Res;
2557 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002558
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002559 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002560 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002561 if (OpName.empty())
2562 error("'?' argument requires a name to match with operand list");
Florian Hahn75e87c32018-05-30 21:00:18 +00002563 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002564 Args.push_back(OpName);
2565 Res->setName(OpName);
2566 return Res;
2567 }
2568
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002569 if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002570 if (!OpName.empty())
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002571 error("Constant int or bit argument should not have a name!");
2572 if (isa<BitInit>(TheInit))
2573 TheInit = TheInit->convertInitializerTo(IntRecTy::get());
2574 return std::make_shared<TreePatternNode>(TheInit, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002575 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002576
Sean Silvafb509ed2012-10-10 20:24:43 +00002577 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002578 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002579 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002580 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002581 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002582 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002583 }
2584
Sean Silvafb509ed2012-10-10 20:24:43 +00002585 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002586 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002587 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002588 error("Pattern has unexpected init kind!");
2589 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002590 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002591 if (!OpDef) error("Pattern has unexpected operator type!");
2592 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002593
Chris Lattner8cab0212008-01-05 22:25:12 +00002594 if (Operator->isSubClassOf("ValueType")) {
2595 // If the operator is a ValueType, then this must be "type cast" of a leaf
2596 // node.
2597 if (Dag->getNumArgs() != 1)
2598 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002599
Florian Hahn75e87c32018-05-30 21:00:18 +00002600 TreePatternNodePtr New =
2601 ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002602
Chris Lattner8cab0212008-01-05 22:25:12 +00002603 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002604 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002605 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2606 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002607
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002608 if (!OpName.empty())
2609 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002610 return New;
2611 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002612
Chris Lattner8cab0212008-01-05 22:25:12 +00002613 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002614 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002615 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002616 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002617 !Operator->isSubClassOf("SDNodeXForm") &&
2618 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002619 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002620 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002621 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002622 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002623
Chris Lattner8cab0212008-01-05 22:25:12 +00002624 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002625 if (isInputPattern) {
2626 if (Operator->isSubClassOf("Instruction") ||
2627 Operator->isSubClassOf("SDNodeXForm"))
2628 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2629 } else {
2630 if (Operator->isSubClassOf("Intrinsic"))
2631 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002632
Chris Lattner2e9eae12010-03-28 06:57:56 +00002633 if (Operator->isSubClassOf("SDNode") &&
2634 Operator->getName() != "imm" &&
2635 Operator->getName() != "fpimm" &&
2636 Operator->getName() != "tglobaltlsaddr" &&
2637 Operator->getName() != "tconstpool" &&
2638 Operator->getName() != "tjumptable" &&
2639 Operator->getName() != "tframeindex" &&
2640 Operator->getName() != "texternalsym" &&
2641 Operator->getName() != "tblockaddress" &&
2642 Operator->getName() != "tglobaladdr" &&
2643 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002644 Operator->getName() != "vt" &&
2645 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002646 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2647 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002648
Florian Hahn75e87c32018-05-30 21:00:18 +00002649 std::vector<TreePatternNodePtr> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002650
2651 // Parse all the operands.
2652 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002653 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002654
Hal Finkel8b4bdfdb2018-01-03 11:35:09 +00002655 // Get the actual number of results before Operator is converted to an intrinsic
2656 // node (which is hard-coded to have either zero or one result).
2657 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2658
Fangrui Song956ee792018-03-30 22:22:31 +00002659 // If the operator is an intrinsic, then this is just syntactic sugar for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002660 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002661 // convert the intrinsic name to a number.
2662 if (Operator->isSubClassOf("Intrinsic")) {
2663 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2664 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2665
2666 // If this intrinsic returns void, it must have side-effects and thus a
2667 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002668 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002669 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002670 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002671 // Has side-effects, requires chain.
2672 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002673 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002674 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002675
Florian Hahn53b14db2018-06-10 21:06:24 +00002676 TreePatternNodePtr IIDNode =
2677 std::make_shared<TreePatternNode>(IntInit::get(IID), 1);
2678 Children.insert(Children.begin(), IIDNode);
Chris Lattner8cab0212008-01-05 22:25:12 +00002679 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002680
Tim Northoverc807a172014-05-20 11:52:46 +00002681 if (Operator->isSubClassOf("ComplexPattern")) {
2682 for (unsigned i = 0; i < Children.size(); ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002683 TreePatternNodePtr Child = Children[i];
Tim Northoverc807a172014-05-20 11:52:46 +00002684
2685 if (Child->getName().empty())
2686 error("All arguments to a ComplexPattern must be named");
2687
2688 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2689 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2690 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2691 auto OperandId = std::make_pair(Operator, i);
2692 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2693 if (PrevOp != ComplexPatternOperands.end()) {
2694 if (PrevOp->getValue() != OperandId)
2695 error("All ComplexPattern operands must appear consistently: "
2696 "in the same order in just one ComplexPattern instance.");
2697 } else
2698 ComplexPatternOperands[Child->getName()] = OperandId;
2699 }
2700 }
2701
Florian Hahn75e87c32018-05-30 21:00:18 +00002702 TreePatternNodePtr Result =
2703 std::make_shared<TreePatternNode>(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002704 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002705
Matthias Braun7cf3b112016-12-05 06:00:41 +00002706 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002707 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002708 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002709 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002710 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002711}
2712
Chris Lattnera787c9e2010-03-28 08:38:32 +00002713/// SimplifyTree - See if we can simplify this tree to eliminate something that
2714/// will never match in favor of something obvious that will. This is here
2715/// strictly as a convenience to target authors because it allows them to write
2716/// more type generic things and have useless type casts fold away.
2717///
2718/// This returns true if any change is made.
Florian Hahn75e87c32018-05-30 21:00:18 +00002719static bool SimplifyTree(TreePatternNodePtr &N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002720 if (N->isLeaf())
2721 return false;
2722
2723 // If we have a bitconvert with a resolved type and if the source and
2724 // destination types are the same, then the bitconvert is useless, remove it.
2725 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002726 N->getExtType(0).isValueTypeByHwMode(false) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002727 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2728 N->getName().empty()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002729 N = N->getChildShared(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002730 SimplifyTree(N);
2731 return true;
2732 }
2733
2734 // Walk all children.
2735 bool MadeChange = false;
2736 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002737 TreePatternNodePtr Child = N->getChildShared(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002738 MadeChange |= SimplifyTree(Child);
Florian Hahn53b14db2018-06-10 21:06:24 +00002739 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002740 }
2741 return MadeChange;
2742}
2743
2744
2745
Chris Lattner8cab0212008-01-05 22:25:12 +00002746/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002747/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002748/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002749bool TreePattern::
2750InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2751 if (NamedNodes.empty())
2752 ComputeNamedNodes();
2753
Chris Lattner8cab0212008-01-05 22:25:12 +00002754 bool MadeChange = true;
2755 while (MadeChange) {
2756 MadeChange = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002757 for (TreePatternNodePtr &Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002758 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2759 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002760 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002761
2762 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002763 for (auto &Entry : NamedNodes) {
2764 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002765
Chris Lattnercabe0372010-03-15 06:00:16 +00002766 // If we have input named node types, propagate their types to the named
2767 // values here.
2768 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002769 if (!InNamedTypes->count(Entry.getKey())) {
2770 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002771 "' in output pattern but not input pattern");
2772 return true;
2773 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002774
2775 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002776 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002777
2778 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002779 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002780 // If this node is a register class, and it is the root of the pattern
2781 // then we're mapping something onto an input register. We allow
2782 // changing the type of the input register in this case. This allows
2783 // us to match things like:
2784 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Florian Hahn75e87c32018-05-30 21:00:18 +00002785 if (Node == Trees[0].get() && Node->isLeaf()) {
Craig Topper306cb122015-11-22 20:46:24 +00002786 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002787 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2788 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002789 continue;
2790 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002791
Craig Topper306cb122015-11-22 20:46:24 +00002792 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002793 InNodes[0]->getNumTypes() == 1 &&
2794 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002795 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2796 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002797 }
2798 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002799
Chris Lattnercabe0372010-03-15 06:00:16 +00002800 // If there are multiple nodes with the same name, they must all have the
2801 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002802 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002803 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002804 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002805 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002806 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002807
Chris Lattnerf1447252010-03-19 21:37:09 +00002808 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2809 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002810 }
2811 }
2812 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002813 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002814
Chris Lattner8cab0212008-01-05 22:25:12 +00002815 bool HasUnresolvedTypes = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002816 for (const TreePatternNodePtr &Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002817 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002818 return !HasUnresolvedTypes;
2819}
2820
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002821void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002822 OS << getRecord()->getName();
2823 if (!Args.empty()) {
2824 OS << "(" << Args[0];
2825 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2826 OS << ", " << Args[i];
2827 OS << ")";
2828 }
2829 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002830
Chris Lattner8cab0212008-01-05 22:25:12 +00002831 if (Trees.size() > 1)
2832 OS << "[\n";
Florian Hahn75e87c32018-05-30 21:00:18 +00002833 for (const TreePatternNodePtr &Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002834 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002835 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002836 OS << "\n";
2837 }
2838
2839 if (Trees.size() > 1)
2840 OS << "]\n";
2841}
2842
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002843void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002844
2845//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002846// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002847//
2848
Daniel Sanders7e523672017-11-11 03:23:44 +00002849CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
2850 PatternRewriterFn PatternRewriter)
2851 : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
2852 PatternRewriter(PatternRewriter) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002853
Justin Bogner92a8c612016-07-15 16:31:37 +00002854 Intrinsics = CodeGenIntrinsicTable(Records, false);
2855 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002856 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002857 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002858 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002859 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002860 ParseDefaultOperands();
2861 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002862 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002863 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002864
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002865 // Break patterns with parameterized types into a series of patterns,
2866 // where each one has a fixed type and is predicated on the conditions
2867 // of the associated HW mode.
2868 ExpandHwModeBasedTypes();
2869
Chris Lattner8cab0212008-01-05 22:25:12 +00002870 // Generate variants. For example, commutative patterns can match
2871 // multiple ways. Add them to PatternsToMatch as well.
2872 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002873
2874 // Infer instruction flags. For example, we can detect loads,
2875 // stores, and side effects in many cases by examining an
2876 // instruction's pattern.
2877 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002878
2879 // Verify that instruction flags match the patterns.
2880 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002881}
2882
Daniel Sanders9e0ae7b2017-10-13 19:00:01 +00002883Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002884 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002885 if (!N || !N->isSubClassOf("SDNode"))
2886 PrintFatalError("Error getting SDNode '" + Name + "'!");
2887
Chris Lattner8cab0212008-01-05 22:25:12 +00002888 return N;
2889}
2890
2891// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002892void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002893 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002894 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2895
Chris Lattner8cab0212008-01-05 22:25:12 +00002896 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002897 Record *R = Nodes.back();
2898 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002899 Nodes.pop_back();
2900 }
2901
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002902 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002903 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2904 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2905 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2906}
2907
2908/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2909/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002910void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002911 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2912 while (!Xforms.empty()) {
2913 Record *XFormNode = Xforms.back();
2914 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00002915 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002916 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002917
2918 Xforms.pop_back();
2919 }
2920}
2921
Chris Lattnerab3242f2008-01-06 01:10:31 +00002922void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002923 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2924 while (!AMs.empty()) {
2925 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2926 AMs.pop_back();
2927 }
2928}
2929
2930
2931/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2932/// file, building up the PatternFragments map. After we've collected them all,
2933/// inline fragments together as necessary, so that there are no references left
2934/// inside a pattern fragment to a pattern fragment.
2935///
Hal Finkel2756dc12014-02-28 00:26:56 +00002936void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002937 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002938
Chris Lattnere7170df2008-01-05 22:43:57 +00002939 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002940 for (Record *Frag : Fragments) {
2941 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002942 continue;
2943
Craig Topper306cb122015-11-22 20:46:24 +00002944 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002945 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002946 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2947 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002948 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002949
Chris Lattnere7170df2008-01-05 22:43:57 +00002950 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002951 std::vector<std::string> &Args = P->getArgList();
Zachary Turner249dc142017-09-20 18:01:40 +00002952 // Copy the args so we can take StringRefs to them.
2953 auto ArgsCopy = Args;
2954 SmallDenseSet<StringRef, 4> OperandsSet;
2955 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002956
Chris Lattnere7170df2008-01-05 22:43:57 +00002957 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002958 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002959
Chris Lattner8cab0212008-01-05 22:25:12 +00002960 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002961 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002962 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002963 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002964 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002965 if (!OpsOp ||
2966 (OpsOp->getDef()->getName() != "ops" &&
2967 OpsOp->getDef()->getName() != "outs" &&
2968 OpsOp->getDef()->getName() != "ins"))
2969 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002970
2971 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002972 Args.clear();
2973 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002974 if (!isa<DefInit>(OpsList->getArg(j)) ||
2975 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002976 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00002977 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00002978 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00002979 StringRef ArgNameStr = OpsList->getArgNameStr(j);
2980 if (!OperandsSet.count(ArgNameStr))
2981 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00002982 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00002983 OperandsSet.erase(ArgNameStr);
2984 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00002985 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002986
Chris Lattnere7170df2008-01-05 22:43:57 +00002987 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002988 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002989 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002990
Chris Lattnere7170df2008-01-05 22:43:57 +00002991 // If there is a code init for this fragment, keep track of the fact that
2992 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002993 TreePredicateFn PredFn(P);
2994 if (!PredFn.isAlwaysTrue())
2995 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002996
Chris Lattner8cab0212008-01-05 22:25:12 +00002997 // If there is a node transformation corresponding to this, keep track of
2998 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002999 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00003000 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
3001 P->getOnlyTree()->setTransformFn(Transform);
3002 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003003
Chris Lattner8cab0212008-01-05 22:25:12 +00003004 // Now that we've parsed all of the tree fragments, do a closure on them so
3005 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00003006 for (Record *Frag : Fragments) {
3007 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00003008 continue;
3009
Craig Topper306cb122015-11-22 20:46:24 +00003010 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00003011 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003012
Chris Lattner8cab0212008-01-05 22:25:12 +00003013 // Infer as many types as possible. Don't worry about it if we don't infer
3014 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00003015 ThePat.InferAllTypes();
3016 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003017
Chris Lattner8cab0212008-01-05 22:25:12 +00003018 // If debugging, print out the pattern fragment result.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003019 LLVM_DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003020 }
3021}
3022
Chris Lattnerab3242f2008-01-06 01:10:31 +00003023void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00003024 std::vector<Record*> DefaultOps;
3025 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00003026
3027 // Find some SDNode.
3028 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00003029 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003030
Tom Stellardb7246a72012-09-06 14:15:52 +00003031 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3032 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003033
Tom Stellardb7246a72012-09-06 14:15:52 +00003034 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3035 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00003036 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00003037 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3038 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3039 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00003040 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003041
Tom Stellardb7246a72012-09-06 14:15:52 +00003042 // Create a TreePattern to parse this.
3043 TreePattern P(DefaultOps[i], DI, false, *this);
3044 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003045
Tom Stellardb7246a72012-09-06 14:15:52 +00003046 // Copy the operands over into a DAGDefaultOperand.
3047 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003048
Florian Hahn75e87c32018-05-30 21:00:18 +00003049 const TreePatternNodePtr &T = P.getTree(0);
Tom Stellardb7246a72012-09-06 14:15:52 +00003050 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
Florian Hahn75e87c32018-05-30 21:00:18 +00003051 TreePatternNodePtr TPN = T->getChildShared(op);
Tom Stellardb7246a72012-09-06 14:15:52 +00003052 while (TPN->ApplyTypeConstraints(P, false))
3053 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003054
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003055 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00003056 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3057 DefaultOps[i]->getName() +
3058 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003059 }
Florian Hahn53b14db2018-06-10 21:06:24 +00003060 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00003061 }
Tom Stellardb7246a72012-09-06 14:15:52 +00003062
3063 // Insert it into the DefaultOperands map so we can find it later.
3064 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00003065 }
3066}
3067
3068/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3069/// instruction input. Return true if this is a real use.
David Blaikie19b22d42018-06-11 22:14:43 +00003070static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003071 std::map<std::string, TreePatternNodePtr> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003072 // No name -> not interesting.
3073 if (Pat->getName().empty()) {
3074 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003075 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00003076 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3077 DI->getDef()->isSubClassOf("RegisterOperand")))
David Blaikie19b22d42018-06-11 22:14:43 +00003078 I.error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003079 }
3080 return false;
3081 }
3082
3083 Record *Rec;
3084 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003085 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
David Blaikie19b22d42018-06-11 22:14:43 +00003086 if (!DI)
3087 I.error("Input $" + Pat->getName() + " must be an identifier!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003088 Rec = DI->getDef();
3089 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00003090 Rec = Pat->getOperator();
3091 }
3092
3093 // SRCVALUE nodes are ignored.
3094 if (Rec->getName() == "srcvalue")
3095 return false;
3096
Florian Hahn75e87c32018-05-30 21:00:18 +00003097 TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
Chris Lattner8cab0212008-01-05 22:25:12 +00003098 if (!Slot) {
3099 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003100 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00003101 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003102 Record *SlotRec;
3103 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003104 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003105 } else {
3106 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3107 SlotRec = Slot->getOperator();
3108 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003109
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003110 // Ensure that the inputs agree if we've already seen this input.
3111 if (Rec != SlotRec)
David Blaikie19b22d42018-06-11 22:14:43 +00003112 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00003113 if (Slot->getExtTypes() != Pat->getExtTypes())
David Blaikie19b22d42018-06-11 22:14:43 +00003114 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00003115 return true;
3116}
3117
3118/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3119/// part of "I", the instruction), computing the set of inputs and outputs of
3120/// the pattern. Report errors if we see anything naughty.
Florian Hahn75e87c32018-05-30 21:00:18 +00003121void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
David Blaikie19b22d42018-06-11 22:14:43 +00003122 TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003123 std::map<std::string, TreePatternNodePtr> &InstInputs,
3124 std::map<std::string, TreePatternNodePtr> &InstResults,
3125 std::vector<Record *> &InstImpResults) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003126 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00003127 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00003128 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003129 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003130 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003131 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003132
Chris Lattnerf2d70992010-02-17 06:53:36 +00003133 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003134 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3135 TreePatternNode *Dest = Pat->getChild(i);
3136 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003137 I.error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003138
Sean Silvafb509ed2012-10-10 20:24:43 +00003139 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00003140 if (!Val || !Val->getDef()->isSubClassOf("Register"))
David Blaikie19b22d42018-06-11 22:14:43 +00003141 I.error("implicitly defined value should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003142 InstImpResults.push_back(Val->getDef());
3143 }
3144 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003145 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003146
Chris Lattnerf2d70992010-02-17 06:53:36 +00003147 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003148 // If this is not a set, verify that the children nodes are not void typed,
3149 // and recurse.
3150 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00003151 if (Pat->getChild(i)->getNumTypes() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003152 I.error("Cannot have void nodes inside of patterns!");
Florian Hahn75e87c32018-05-30 21:00:18 +00003153 FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3154 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003155 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003156
Chris Lattner8cab0212008-01-05 22:25:12 +00003157 // If this is a non-leaf node with no children, treat it basically as if
3158 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00003159 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003160
Chris Lattner8cab0212008-01-05 22:25:12 +00003161 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003162 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003163 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003164 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003165
Chris Lattner8cab0212008-01-05 22:25:12 +00003166 // Otherwise, this is a set, validate and collect instruction results.
3167 if (Pat->getNumChildren() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003168 I.error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003169
Chris Lattner8cab0212008-01-05 22:25:12 +00003170 if (Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003171 I.error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003172
Chris Lattner8cab0212008-01-05 22:25:12 +00003173 // Check the set destinations.
3174 unsigned NumDests = Pat->getNumChildren()-1;
3175 for (unsigned i = 0; i != NumDests; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00003176 TreePatternNodePtr Dest = Pat->getChildShared(i);
Chris Lattner8cab0212008-01-05 22:25:12 +00003177 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003178 I.error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003179
Sean Silvafb509ed2012-10-10 20:24:43 +00003180 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00003181 if (!Val) {
David Blaikie19b22d42018-06-11 22:14:43 +00003182 I.error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00003183 continue;
3184 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003185
3186 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003187 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00003188 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00003189 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003190 if (Dest->getName().empty())
David Blaikie19b22d42018-06-11 22:14:43 +00003191 I.error("set destination must have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003192 if (InstResults.count(Dest->getName()))
David Blaikie19b22d42018-06-11 22:14:43 +00003193 I.error("cannot set '" + Dest->getName() + "' multiple times");
Chris Lattner8cab0212008-01-05 22:25:12 +00003194 InstResults[Dest->getName()] = Dest;
3195 } else if (Val->getDef()->isSubClassOf("Register")) {
3196 InstImpResults.push_back(Val->getDef());
3197 } else {
David Blaikie19b22d42018-06-11 22:14:43 +00003198 I.error("set destination should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003199 }
3200 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003201
Chris Lattner8cab0212008-01-05 22:25:12 +00003202 // Verify and collect info from the computation.
Florian Hahn75e87c32018-05-30 21:00:18 +00003203 FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3204 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003205}
3206
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003207//===----------------------------------------------------------------------===//
3208// Instruction Analysis
3209//===----------------------------------------------------------------------===//
3210
3211class InstAnalyzer {
3212 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003213public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003214 bool hasSideEffects;
3215 bool mayStore;
3216 bool mayLoad;
3217 bool isBitcast;
3218 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003219
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003220 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3221 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
3222 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003223
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003224 void Analyze(const TreePattern *Pat) {
3225 // Assume only the first tree is the pattern. The others are clobber nodes.
Florian Hahn75e87c32018-05-30 21:00:18 +00003226 AnalyzeNode(Pat->getTree(0).get());
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003227 }
3228
Craig Topper2a053a92017-06-20 16:34:37 +00003229 void Analyze(const PatternToMatch &Pat) {
3230 AnalyzeNode(Pat.getSrcPattern());
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003231 }
3232
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003233private:
Evan Cheng880e299d2011-03-15 05:09:26 +00003234 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003235 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00003236 return false;
3237
3238 if (N->getNumChildren() != 2)
3239 return false;
3240
3241 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00003242 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00003243 return false;
3244
3245 const TreePatternNode *N1 = N->getChild(1);
3246 if (N1->isLeaf())
3247 return false;
3248 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
3249 return false;
3250
3251 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
3252 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3253 return false;
3254 return OpInfo.getEnumName() == "ISD::BITCAST";
3255 }
3256
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003257public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003258 void AnalyzeNode(const TreePatternNode *N) {
3259 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003260 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003261 Record *LeafRec = DI->getDef();
3262 // Handle ComplexPattern leaves.
3263 if (LeafRec->isSubClassOf("ComplexPattern")) {
3264 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3265 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3266 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003267 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003268 }
3269 }
3270 return;
3271 }
3272
3273 // Analyze children.
3274 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3275 AnalyzeNode(N->getChild(i));
3276
3277 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00003278 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003279 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003280 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00003281 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003282
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003283 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00003284 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3285 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3286 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3287 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003288
3289 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
3290 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003291 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003292 mayLoad = true;// These may load memory.
3293
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003294 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003295 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3296
Matt Arsenault868af922017-04-28 21:01:46 +00003297 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3298 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003299 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003300 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003301 }
3302 }
3303
3304};
3305
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003306static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003307 const InstAnalyzer &PatInfo,
3308 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003309 bool Error = false;
3310
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003311 // Remember where InstInfo got its flags.
3312 if (InstInfo.hasUndefFlags())
3313 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003314
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003315 // Check explicitly set flags for consistency.
3316 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3317 !InstInfo.hasSideEffects_Unset) {
3318 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3319 // the pattern has no side effects. That could be useful for div/rem
3320 // instructions that may trap.
3321 if (!InstInfo.hasSideEffects) {
3322 Error = true;
3323 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3324 Twine(InstInfo.hasSideEffects));
3325 }
3326 }
3327
3328 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3329 Error = true;
3330 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3331 Twine(InstInfo.mayStore));
3332 }
3333
3334 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3335 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003336 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003337 if (!InstInfo.mayLoad) {
3338 Error = true;
3339 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3340 Twine(InstInfo.mayLoad));
3341 }
3342 }
3343
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003344 // Transfer inferred flags.
3345 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3346 InstInfo.mayStore |= PatInfo.mayStore;
3347 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003348
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003349 // These flags are silently added without any verification.
3350 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003351
3352 // Don't infer isVariadic. This flag means something different on SDNodes and
3353 // instructions. For example, a CALL SDNode is variadic because it has the
3354 // call arguments as operands, but a CALL instruction is not variadic - it
3355 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003356
3357 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003358}
3359
Jim Grosbach514410b2012-07-17 00:47:06 +00003360/// hasNullFragReference - Return true if the DAG has any reference to the
3361/// null_frag operator.
3362static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003363 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003364 if (!OpDef) return false;
3365 Record *Operator = OpDef->getDef();
3366
3367 // If this is the null fragment, return true.
3368 if (Operator->getName() == "null_frag") return true;
3369 // If any of the arguments reference the null fragment, return true.
3370 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003371 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003372 if (Arg && hasNullFragReference(Arg))
3373 return true;
3374 }
3375
3376 return false;
3377}
3378
3379/// hasNullFragReference - Return true if any DAG in the list references
3380/// the null_frag operator.
3381static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003382 for (Init *I : LI->getValues()) {
3383 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003384 assert(DI && "non-dag in an instruction Pattern list?!");
3385 if (hasNullFragReference(DI))
3386 return true;
3387 }
3388 return false;
3389}
3390
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003391/// Get all the instructions in a tree.
3392static void
3393getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3394 if (Tree->isLeaf())
3395 return;
3396 if (Tree->getOperator()->isSubClassOf("Instruction"))
3397 Instrs.push_back(Tree->getOperator());
3398 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3399 getInstructionsInTree(Tree->getChild(i), Instrs);
3400}
3401
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003402/// Check the class of a pattern leaf node against the instruction operand it
3403/// represents.
3404static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3405 Record *Leaf) {
3406 if (OI.Rec == Leaf)
3407 return true;
3408
3409 // Allow direct value types to be used in instruction set patterns.
3410 // The type will be checked later.
3411 if (Leaf->isSubClassOf("ValueType"))
3412 return true;
3413
3414 // Patterns can also be ComplexPattern instances.
3415 if (Leaf->isSubClassOf("ComplexPattern"))
3416 return true;
3417
3418 return false;
3419}
3420
Ahmed Bougacha14107512013-10-28 18:07:21 +00003421const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
3422 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003423
Craig Topper0d1fb902015-03-10 03:25:04 +00003424 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003425
Craig Topper0d1fb902015-03-10 03:25:04 +00003426 // Parse the instruction.
Florian Hahn84e6ef02018-06-08 09:54:04 +00003427 auto I = llvm::make_unique<TreePattern>(CGI.TheDef, Pat, true, *this);
Craig Topper0d1fb902015-03-10 03:25:04 +00003428 // Inline pattern fragments into it.
3429 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003430
Craig Topper0d1fb902015-03-10 03:25:04 +00003431 // Infer as many types as possible. If we cannot infer all of them, we can
3432 // never do anything with this instruction pattern: report it to the user.
3433 if (!I->InferAllTypes())
3434 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003435
Craig Topper0d1fb902015-03-10 03:25:04 +00003436 // InstInputs - Keep track of all of the inputs of the instruction, along
3437 // with the record they are declared as.
Florian Hahn75e87c32018-05-30 21:00:18 +00003438 std::map<std::string, TreePatternNodePtr> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003439
Craig Topper0d1fb902015-03-10 03:25:04 +00003440 // InstResults - Keep track of all the virtual registers that are 'set'
3441 // in the instruction, including what reg class they are.
Florian Hahn75e87c32018-05-30 21:00:18 +00003442 std::map<std::string, TreePatternNodePtr> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003443
Craig Topper0d1fb902015-03-10 03:25:04 +00003444 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003445
Craig Topper0d1fb902015-03-10 03:25:04 +00003446 // Verify that the top-level forms in the instruction are of void type, and
3447 // fill in the InstResults map.
Zachary Turner249dc142017-09-20 18:01:40 +00003448 SmallString<32> TypesString;
Craig Topper0d1fb902015-03-10 03:25:04 +00003449 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
Zachary Turner249dc142017-09-20 18:01:40 +00003450 TypesString.clear();
Florian Hahn75e87c32018-05-30 21:00:18 +00003451 TreePatternNodePtr Pat = I->getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003452 if (Pat->getNumTypes() != 0) {
Zachary Turner249dc142017-09-20 18:01:40 +00003453 raw_svector_ostream OS(TypesString);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003454 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3455 if (k > 0)
Zachary Turner249dc142017-09-20 18:01:40 +00003456 OS << ", ";
3457 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003458 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003459 I->error("Top-level forms in instruction pattern should have"
Zachary Turner249dc142017-09-20 18:01:40 +00003460 " void types, has types " +
3461 OS.str());
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003462 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003463
Craig Topper0d1fb902015-03-10 03:25:04 +00003464 // Find inputs and outputs, and verify the structure of the uses/defs.
David Blaikie19b22d42018-06-11 22:14:43 +00003465 FindPatternInputsAndOutputs(*I, Pat, InstInputs, InstResults,
Craig Topper0d1fb902015-03-10 03:25:04 +00003466 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003467 }
3468
Craig Topper0d1fb902015-03-10 03:25:04 +00003469 // Now that we have inputs and outputs of the pattern, inspect the operands
3470 // list for the instruction. This determines the order that operands are
3471 // added to the machine instruction the node corresponds to.
3472 unsigned NumResults = InstResults.size();
3473
3474 // Parse the operands list from the (ops) list, validating it.
3475 assert(I->getArgList().empty() && "Args list should still be empty here!");
3476
3477 // Check that all of the results occur first in the list.
3478 std::vector<Record*> Results;
Florian Hahn75e87c32018-05-30 21:00:18 +00003479 SmallVector<TreePatternNodePtr, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003480 for (unsigned i = 0; i != NumResults; ++i) {
3481 if (i == CGI.Operands.size())
3482 I->error("'" + InstResults.begin()->first +
3483 "' set but does not appear in operand list!");
3484 const std::string &OpName = CGI.Operands[i].Name;
3485
3486 // Check that it exists in InstResults.
Florian Hahn75e87c32018-05-30 21:00:18 +00003487 TreePatternNodePtr RNode = InstResults[OpName];
Craig Topper0d1fb902015-03-10 03:25:04 +00003488 if (!RNode)
3489 I->error("Operand $" + OpName + " does not exist in operand list!");
3490
Florian Hahn53b14db2018-06-10 21:06:24 +00003491 ResNodes.push_back(RNode);
Craig Topper3a8eb892015-03-20 05:09:06 +00003492
Craig Topper0d1fb902015-03-10 03:25:04 +00003493 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3494 if (!R)
3495 I->error("Operand $" + OpName + " should be a set destination: all "
3496 "outputs must occur before inputs in operand list!");
3497
3498 if (!checkOperandClass(CGI.Operands[i], R))
3499 I->error("Operand $" + OpName + " class mismatch!");
3500
3501 // Remember the return type.
3502 Results.push_back(CGI.Operands[i].Rec);
3503
3504 // Okay, this one checks out.
3505 InstResults.erase(OpName);
3506 }
3507
3508 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3509 // the copy while we're checking the inputs.
Florian Hahn75e87c32018-05-30 21:00:18 +00003510 std::map<std::string, TreePatternNodePtr> InstInputsCheck(InstInputs);
Craig Topper0d1fb902015-03-10 03:25:04 +00003511
Florian Hahn75e87c32018-05-30 21:00:18 +00003512 std::vector<TreePatternNodePtr> ResultNodeOperands;
Craig Topper0d1fb902015-03-10 03:25:04 +00003513 std::vector<Record*> Operands;
3514 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3515 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3516 const std::string &OpName = Op.Name;
3517 if (OpName.empty())
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00003518 I->error("Operand #" + Twine(i) + " in operands list has no name!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003519
3520 if (!InstInputsCheck.count(OpName)) {
3521 // If this is an operand with a DefaultOps set filled in, we can ignore
3522 // this. When we codegen it, we will do so as always executed.
3523 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3524 // Does it have a non-empty DefaultOps field? If so, ignore this
3525 // operand.
3526 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3527 continue;
3528 }
3529 I->error("Operand $" + OpName +
3530 " does not appear in the instruction pattern");
3531 }
Florian Hahn75e87c32018-05-30 21:00:18 +00003532 TreePatternNodePtr InVal = InstInputsCheck[OpName];
Craig Topper0d1fb902015-03-10 03:25:04 +00003533 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3534
3535 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3536 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3537 if (!checkOperandClass(Op, InRec))
3538 I->error("Operand $" + OpName + "'s register class disagrees"
3539 " between the operand and pattern");
3540 }
3541 Operands.push_back(Op.Rec);
3542
3543 // Construct the result for the dest-pattern operand list.
Florian Hahn75e87c32018-05-30 21:00:18 +00003544 TreePatternNodePtr OpNode = InVal->clone();
Craig Topper0d1fb902015-03-10 03:25:04 +00003545
3546 // No predicate is useful on the result.
3547 OpNode->clearPredicateFns();
3548
3549 // Promote the xform function to be an explicit node if set.
3550 if (Record *Xform = OpNode->getTransformFn()) {
3551 OpNode->setTransformFn(nullptr);
Florian Hahn75e87c32018-05-30 21:00:18 +00003552 std::vector<TreePatternNodePtr> Children;
Craig Topper0d1fb902015-03-10 03:25:04 +00003553 Children.push_back(OpNode);
Florian Hahn75e87c32018-05-30 21:00:18 +00003554 OpNode = std::make_shared<TreePatternNode>(Xform, Children,
3555 OpNode->getNumTypes());
Craig Topper0d1fb902015-03-10 03:25:04 +00003556 }
3557
Florian Hahn53b14db2018-06-10 21:06:24 +00003558 ResultNodeOperands.push_back(OpNode);
Craig Topper0d1fb902015-03-10 03:25:04 +00003559 }
3560
3561 if (!InstInputsCheck.empty())
3562 I->error("Input operand $" + InstInputsCheck.begin()->first +
3563 " occurs in pattern but not in operands list!");
3564
Florian Hahn75e87c32018-05-30 21:00:18 +00003565 TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
3566 I->getRecord(), ResultNodeOperands,
3567 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003568 // Copy fully inferred output node types to instruction result pattern.
3569 for (unsigned i = 0; i != NumResults; ++i) {
3570 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3571 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3572 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003573
3574 // Create and insert the instruction.
3575 // FIXME: InstImpResults should not be part of DAGInstruction.
Craig Topper08f5c7b2018-06-10 23:15:49 +00003576 Record *R = I->getRecord();
3577 DAGInstruction &TheInst =
3578 DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
3579 std::forward_as_tuple(std::move(I), Results, Operands,
3580 InstImpResults)).first->second;
Craig Topper0d1fb902015-03-10 03:25:04 +00003581
3582 // Use a temporary tree pattern to infer all types and make sure that the
3583 // constructed result is correct. This depends on the instruction already
3584 // being inserted into the DAGInsts map.
Craig Topper08f5c7b2018-06-10 23:15:49 +00003585 TreePattern Temp(TheInst.getPattern()->getRecord(), ResultPattern, false,
3586 *this);
3587 Temp.InferAllTypes(&TheInst.getPattern()->getNamedNodesMap());
Craig Topper0d1fb902015-03-10 03:25:04 +00003588
Craig Topper08f5c7b2018-06-10 23:15:49 +00003589 TheInst.setResultPattern(Temp.getOnlyTree());
Craig Topper0d1fb902015-03-10 03:25:04 +00003590
Craig Topper08f5c7b2018-06-10 23:15:49 +00003591 return TheInst;
Craig Topper0d1fb902015-03-10 03:25:04 +00003592}
3593
Ahmed Bougacha14107512013-10-28 18:07:21 +00003594/// ParseInstructions - Parse all of the instructions, inlining and resolving
3595/// any fragments involved. This populates the Instructions list with fully
3596/// resolved instructions.
3597void CodeGenDAGPatterns::ParseInstructions() {
3598 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3599
Craig Topper306cb122015-11-22 20:46:24 +00003600 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003601 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003602
Craig Topper306cb122015-11-22 20:46:24 +00003603 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3604 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003605
3606 // If there is no pattern, only collect minimal information about the
3607 // instruction for its operand list. We have to assume that there is one
3608 // result, as we have no detailed info. A pattern which references the
3609 // null_frag operator is as-if no pattern were specified. Normally this
3610 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3611 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003612 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003613 std::vector<Record*> Results;
3614 std::vector<Record*> Operands;
3615
Craig Topper306cb122015-11-22 20:46:24 +00003616 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003617
3618 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003619 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3620 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003621
Craig Topper3a8eb892015-03-20 05:09:06 +00003622 // The rest are inputs.
3623 for (unsigned j = InstInfo.Operands.NumDefs,
3624 e = InstInfo.Operands.size(); j < e; ++j)
3625 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003626 }
3627
3628 // Create and insert the instruction.
3629 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003630 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003631 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003632 continue; // no pattern.
3633 }
3634
Craig Topper306cb122015-11-22 20:46:24 +00003635 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003636 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3637
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003638 (void)DI;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003639 LLVM_DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003640 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003641
Chris Lattner8cab0212008-01-05 22:25:12 +00003642 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003643 for (auto &Entry : Instructions) {
3644 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003645 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003646 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003647
Daniel Sanders7e523672017-11-11 03:23:44 +00003648 if (PatternRewriter)
3649 PatternRewriter(I);
Chris Lattner8cab0212008-01-05 22:25:12 +00003650 // FIXME: Assume only the first tree is the pattern. The others are clobber
3651 // nodes.
Florian Hahn75e87c32018-05-30 21:00:18 +00003652 TreePatternNodePtr Pattern = I->getTree(0);
3653 TreePatternNodePtr SrcPattern;
Chris Lattner8cab0212008-01-05 22:25:12 +00003654 if (Pattern->getOperator()->getName() == "set") {
3655 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3656 } else{
3657 // Not a set (store or something?)
3658 SrcPattern = Pattern;
3659 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003660
Craig Topper306cb122015-11-22 20:46:24 +00003661 Record *Instr = Entry.first;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003662 ListInit *Preds = Instr->getValueAsListInit("Predicates");
3663 int Complexity = Instr->getValueAsInt("AddedComplexity");
3664 AddPatternToMatch(
3665 I,
3666 PatternToMatch(Instr, makePredList(Preds), SrcPattern,
3667 TheInst.getResultPattern(), TheInst.getImpResults(),
3668 Complexity, Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003669 }
3670}
3671
Florian Hahn75e87c32018-05-30 21:00:18 +00003672typedef std::pair<TreePatternNode *, unsigned> NameRecord;
Chris Lattnera7722b62010-02-23 06:55:24 +00003673
Florian Hahn75e87c32018-05-30 21:00:18 +00003674static void FindNames(TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003675 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003676 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003677 if (!P->getName().empty()) {
3678 NameRecord &Rec = Names[P->getName()];
3679 // If this is the first instance of the name, remember the node.
3680 if (Rec.second++ == 0)
3681 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003682 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003683 PatternTop->error("repetition of value: $" + P->getName() +
3684 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003685 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003686
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003687 if (!P->isLeaf()) {
3688 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003689 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003690 }
3691}
3692
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003693std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3694 std::vector<Predicate> Preds;
3695 for (Init *I : L->getValues()) {
3696 if (DefInit *Pred = dyn_cast<DefInit>(I))
3697 Preds.push_back(Pred->getDef());
3698 else
3699 llvm_unreachable("Non-def on the list");
3700 }
3701
3702 // Sort so that different orders get canonicalized to the same string.
Mandeep Singh Grang1b0e2f22018-04-06 20:18:05 +00003703 llvm::sort(Preds.begin(), Preds.end());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003704 return Preds;
3705}
3706
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003707void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003708 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003709 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003710 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003711 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3712 PrintWarning(Pattern->getRecord()->getLoc(),
3713 Twine("Pattern can never match: ") + Reason);
3714 return;
3715 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003716
Chris Lattner1e634e32010-03-01 22:29:19 +00003717 // If the source pattern's root is a complex pattern, that complex pattern
3718 // must specify the nodes it can potentially match.
3719 if (const ComplexPattern *CP =
3720 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3721 if (CP->getRootNodes().empty())
3722 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3723 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003724
3725
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003726 // Find all of the named values in the input and output, ensure they have the
3727 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003728 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003729 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3730 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003731
3732 // Scan all of the named values in the destination pattern, rejecting them if
3733 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003734 for (const auto &Entry : DstNames) {
3735 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003736 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003737 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003738 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003739
Chris Lattnera7722b62010-02-23 06:55:24 +00003740 // Scan all of the named values in the source pattern, rejecting them if the
3741 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003742 for (const auto &Entry : SrcNames)
3743 if (DstNames[Entry.first].first == nullptr &&
3744 SrcNames[Entry.first].second == 1)
3745 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003746
Craig Topper18e6b572017-06-25 17:33:49 +00003747 PatternsToMatch.push_back(std::move(PTM));
Chris Lattner0c0baa92010-02-23 06:16:51 +00003748}
3749
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003750void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003751 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003752 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003753
3754 // First try to infer flags from the primary instruction pattern, if any.
3755 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003756 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003757 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3758 CodeGenInstruction &InstInfo =
3759 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003760
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003761 // Get the primary instruction pattern.
3762 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3763 if (!Pattern) {
3764 if (InstInfo.hasUndefFlags())
3765 Revisit.push_back(&InstInfo);
3766 continue;
3767 }
3768 InstAnalyzer PatInfo(*this);
3769 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003770 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003771 }
3772
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003773 // Second, look for single-instruction patterns defined outside the
3774 // instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003775 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003776 // We can only infer from single-instruction patterns, otherwise we won't
3777 // know which instruction should get the flags.
3778 SmallVector<Record*, 8> PatInstrs;
3779 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3780 if (PatInstrs.size() != 1)
3781 continue;
3782
3783 // Get the single instruction.
3784 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3785
3786 // Only infer properties from the first pattern. We'll verify the others.
3787 if (InstInfo.InferredFrom)
3788 continue;
3789
3790 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003791 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003792 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3793 }
3794
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003795 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003796 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003797
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003798 // Revisit instructions with undefined flags and no pattern.
3799 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003800 for (CodeGenInstruction *InstInfo : Revisit) {
3801 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003802 continue;
3803 // The mayLoad and mayStore flags default to false.
3804 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003805 if (InstInfo->hasSideEffects_Unset)
3806 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003807 }
3808 return;
3809 }
3810
3811 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003812 for (CodeGenInstruction *InstInfo : Revisit) {
3813 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003814 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003815 if (InstInfo->hasSideEffects_Unset)
3816 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003817 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003818 if (InstInfo->mayStore_Unset)
3819 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003820 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003821 if (InstInfo->mayLoad_Unset)
3822 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003823 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003824 }
3825}
3826
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003827
3828/// Verify instruction flags against pattern node properties.
3829void CodeGenDAGPatterns::VerifyInstructionFlags() {
3830 unsigned Errors = 0;
3831 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3832 const PatternToMatch &PTM = *I;
3833 SmallVector<Record*, 8> Instrs;
3834 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3835 if (Instrs.empty())
3836 continue;
3837
3838 // Count the number of instructions with each flag set.
3839 unsigned NumSideEffects = 0;
3840 unsigned NumStores = 0;
3841 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003842 for (const Record *Instr : Instrs) {
3843 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003844 NumSideEffects += InstInfo.hasSideEffects;
3845 NumStores += InstInfo.mayStore;
3846 NumLoads += InstInfo.mayLoad;
3847 }
3848
3849 // Analyze the source pattern.
3850 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003851 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003852
3853 // Collect error messages.
3854 SmallVector<std::string, 4> Msgs;
3855
3856 // Check for missing flags in the output.
3857 // Permit extra flags for now at least.
3858 if (PatInfo.hasSideEffects && !NumSideEffects)
3859 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3860
3861 // Don't verify store flags on instructions with side effects. At least for
3862 // intrinsics, side effects implies mayStore.
3863 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3864 Msgs.push_back("pattern may store, but mayStore isn't set");
3865
3866 // Similarly, mayStore implies mayLoad on intrinsics.
3867 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3868 Msgs.push_back("pattern may load, but mayLoad isn't set");
3869
3870 // Print error messages.
3871 if (Msgs.empty())
3872 continue;
3873 ++Errors;
3874
Craig Topper306cb122015-11-22 20:46:24 +00003875 for (const std::string &Msg : Msgs)
3876 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003877 (Instrs.size() == 1 ?
3878 "instruction" : "output instructions"));
3879 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003880 for (const Record *Instr : Instrs) {
3881 if (Instr != PTM.getSrcRecord())
3882 PrintError(Instr->getLoc(), "defined here");
3883 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003884 if (InstInfo.InferredFrom &&
3885 InstInfo.InferredFrom != InstInfo.TheDef &&
3886 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003887 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003888 }
3889 }
3890 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003891 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003892}
3893
Chris Lattnercabe0372010-03-15 06:00:16 +00003894/// Given a pattern result with an unresolved type, see if we can find one
3895/// instruction with an unresolved result type. Force this result type to an
3896/// arbitrary element if it's possible types to converge results.
3897static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3898 if (N->isLeaf())
3899 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003900
Chris Lattnercabe0372010-03-15 06:00:16 +00003901 // Analyze children.
3902 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3903 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3904 return true;
3905
3906 if (!N->getOperator()->isSubClassOf("Instruction"))
3907 return false;
3908
3909 // If this type is already concrete or completely unknown we can't do
3910 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003911 TypeInfer &TI = TP.getInfer();
Chris Lattnerf1447252010-03-19 21:37:09 +00003912 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003913 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00003914 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003915
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003916 // Otherwise, force its type to an arbitrary choice.
3917 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00003918 return true;
3919 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003920
Chris Lattnerf1447252010-03-19 21:37:09 +00003921 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003922}
3923
Chris Lattnerab3242f2008-01-06 01:10:31 +00003924void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003925 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3926
Craig Topper306cb122015-11-22 20:46:24 +00003927 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003928 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003929
3930 // If the pattern references the null_frag, there's nothing to do.
3931 if (hasNullFragReference(Tree))
3932 continue;
3933
Florian Hahn75e87c32018-05-30 21:00:18 +00003934 TreePattern Pattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003935
3936 // Inline pattern fragments into it.
Florian Hahn75e87c32018-05-30 21:00:18 +00003937 Pattern.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003938
David Greeneaf8ee2c2011-07-29 22:43:06 +00003939 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003940 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003941
Chris Lattner8cab0212008-01-05 22:25:12 +00003942 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003943 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003944
Chris Lattner8cab0212008-01-05 22:25:12 +00003945 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003946 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003947
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003948 if (Result.getNumTrees() != 1)
3949 Result.error("Cannot handle instructions producing instructions "
3950 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003951
Chris Lattner8cab0212008-01-05 22:25:12 +00003952 bool IterateInference;
3953 bool InferredAllPatternTypes, InferredAllResultTypes;
3954 do {
3955 // Infer as many types as possible. If we cannot infer all of them, we
3956 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003957 InferredAllPatternTypes =
Florian Hahn75e87c32018-05-30 21:00:18 +00003958 Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003959
Chris Lattner8cab0212008-01-05 22:25:12 +00003960 // Infer as many types as possible. If we cannot infer all of them, we
3961 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003962 InferredAllResultTypes =
Florian Hahn75e87c32018-05-30 21:00:18 +00003963 Result.InferAllTypes(&Pattern.getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003964
Chris Lattnerfdc20712010-03-18 23:15:10 +00003965 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003966
Chris Lattner8cab0212008-01-05 22:25:12 +00003967 // Apply the type of the result to the source pattern. This helps us
3968 // resolve cases where the input type is known to be a pointer type (which
3969 // is considered resolved), but the result knows it needs to be 32- or
3970 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003971 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Florian Hahn75e87c32018-05-30 21:00:18 +00003972 Pattern.getTree(0)->getNumTypes());
Chris Lattnerf1447252010-03-19 21:37:09 +00003973 i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00003974 IterateInference = Pattern.getTree(0)->UpdateNodeType(
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003975 i, Result.getTree(0)->getExtType(i), Result);
3976 IterateInference |= Result.getTree(0)->UpdateNodeType(
Florian Hahn75e87c32018-05-30 21:00:18 +00003977 i, Pattern.getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003978 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003979
Chris Lattnercabe0372010-03-15 06:00:16 +00003980 // If our iteration has converged and the input pattern's types are fully
3981 // resolved but the result pattern is not fully resolved, we may have a
3982 // situation where we have two instructions in the result pattern and
3983 // the instructions require a common register class, but don't care about
3984 // what actual MVT is used. This is actually a bug in our modelling:
3985 // output patterns should have register classes, not MVTs.
3986 //
3987 // In any case, to handle this, we just go through and disambiguate some
3988 // arbitrary types to the result pattern's nodes.
3989 if (!IterateInference && InferredAllPatternTypes &&
3990 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003991 IterateInference =
Florian Hahn75e87c32018-05-30 21:00:18 +00003992 ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003993 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003994
Chris Lattner8cab0212008-01-05 22:25:12 +00003995 // Verify that we inferred enough types that we can do something with the
3996 // pattern and result. If these fire the user has to add type casts.
3997 if (!InferredAllPatternTypes)
Florian Hahn75e87c32018-05-30 21:00:18 +00003998 Pattern.error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003999 if (!InferredAllResultTypes) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004000 Pattern.dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004001 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00004002 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004003
Chris Lattner8cab0212008-01-05 22:25:12 +00004004 // Validate that the input pattern is correct.
Florian Hahn75e87c32018-05-30 21:00:18 +00004005 std::map<std::string, TreePatternNodePtr> InstInputs;
4006 std::map<std::string, TreePatternNodePtr> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00004007 std::vector<Record*> InstImpResults;
Florian Hahn75e87c32018-05-30 21:00:18 +00004008 for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
David Blaikie19b22d42018-06-11 22:14:43 +00004009 FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
Florian Hahn75e87c32018-05-30 21:00:18 +00004010 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004011
4012 // Promote the xform function to be an explicit node if set.
Florian Hahn4dd569c2018-06-13 20:59:53 +00004013 const TreePatternNodePtr &DstPattern = Result.getOnlyTree();
Florian Hahn75e87c32018-05-30 21:00:18 +00004014 std::vector<TreePatternNodePtr> ResultNodeOperands;
Chris Lattner8cab0212008-01-05 22:25:12 +00004015 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004016 TreePatternNodePtr OpNode = DstPattern->getChildShared(ii);
Chris Lattner8cab0212008-01-05 22:25:12 +00004017 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00004018 OpNode->setTransformFn(nullptr);
Florian Hahn75e87c32018-05-30 21:00:18 +00004019 std::vector<TreePatternNodePtr> Children;
Chris Lattner8cab0212008-01-05 22:25:12 +00004020 Children.push_back(OpNode);
Florian Hahn75e87c32018-05-30 21:00:18 +00004021 OpNode = std::make_shared<TreePatternNode>(Xform, Children,
4022 OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00004023 }
4024 ResultNodeOperands.push_back(OpNode);
4025 }
Florian Hahn4dd569c2018-06-13 20:59:53 +00004026
4027 TreePatternNodePtr DstShared =
4028 DstPattern->isLeaf()
4029 ? DstPattern
4030 : std::make_shared<TreePatternNode>(DstPattern->getOperator(),
4031 ResultNodeOperands,
4032 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004033
David Blaikiecf195302014-11-17 22:55:41 +00004034 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
Florian Hahn4dd569c2018-06-13 20:59:53 +00004035 DstShared->setType(i, Result.getOnlyTree()->getExtType(i));
David Blaikiecf195302014-11-17 22:55:41 +00004036
Florian Hahn4dd569c2018-06-13 20:59:53 +00004037 TreePattern Temp(Result.getRecord(), DstShared, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00004038 Temp.InferAllTypes();
4039
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004040 // A pattern may end up with an "impossible" type, i.e. a situation
4041 // where all types have been eliminated for some node in this pattern.
4042 // This could occur for intrinsics that only make sense for a specific
4043 // value type, and use a specific register class. If, for some mode,
4044 // that register class does not accept that type, the type inference
4045 // will lead to a contradiction, which is not an error however, but
4046 // a sign that this pattern will simply never match.
Florian Hahn75e87c32018-05-30 21:00:18 +00004047 if (Pattern.getTree(0)->hasPossibleType() &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004048 Temp.getOnlyTree()->hasPossibleType()) {
4049 ListInit *Preds = CurPattern->getValueAsListInit("Predicates");
4050 int Complexity = CurPattern->getValueAsInt("AddedComplexity");
Daniel Sanders7e523672017-11-11 03:23:44 +00004051 if (PatternRewriter)
Florian Hahn75e87c32018-05-30 21:00:18 +00004052 PatternRewriter(&Pattern);
4053 AddPatternToMatch(&Pattern,
4054 PatternToMatch(CurPattern, makePredList(Preds),
4055 Pattern.getTree(0), Temp.getOnlyTree(),
4056 std::move(InstImpResults), Complexity,
4057 CurPattern->getID()));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004058 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004059 }
4060}
4061
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004062static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
4063 for (const TypeSetByHwMode &VTS : N->getExtTypes())
4064 for (const auto &I : VTS)
4065 Modes.insert(I.first);
4066
4067 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4068 collectModes(Modes, N->getChild(i));
4069}
4070
4071void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4072 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4073 std::map<unsigned,std::vector<Predicate>> ModeChecks;
4074 std::vector<PatternToMatch> Copy = PatternsToMatch;
4075 PatternsToMatch.clear();
4076
Florian Hahn75e87c32018-05-30 21:00:18 +00004077 auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) {
4078 TreePatternNodePtr NewSrc = P.SrcPattern->clone();
4079 TreePatternNodePtr NewDst = P.DstPattern->clone();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004080 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004081 return;
4082 }
4083
4084 std::vector<Predicate> Preds = P.Predicates;
4085 const std::vector<Predicate> &MC = ModeChecks[Mode];
4086 Preds.insert(Preds.end(), MC.begin(), MC.end());
Florian Hahn53b14db2018-06-10 21:06:24 +00004087 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, NewSrc, NewDst,
4088 P.getDstRegs(), P.getAddedComplexity(),
4089 Record::getNewUID(), Mode);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004090 };
4091
4092 for (PatternToMatch &P : Copy) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004093 TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004094 if (P.SrcPattern->hasProperTypeByHwMode())
4095 SrcP = P.SrcPattern;
4096 if (P.DstPattern->hasProperTypeByHwMode())
4097 DstP = P.DstPattern;
4098 if (!SrcP && !DstP) {
4099 PatternsToMatch.push_back(P);
4100 continue;
4101 }
4102
4103 std::set<unsigned> Modes;
4104 if (SrcP)
Florian Hahn75e87c32018-05-30 21:00:18 +00004105 collectModes(Modes, SrcP.get());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004106 if (DstP)
Florian Hahn75e87c32018-05-30 21:00:18 +00004107 collectModes(Modes, DstP.get());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004108
4109 // The predicate for the default mode needs to be constructed for each
4110 // pattern separately.
4111 // Since not all modes must be present in each pattern, if a mode m is
4112 // absent, then there is no point in constructing a check for m. If such
4113 // a check was created, it would be equivalent to checking the default
4114 // mode, except not all modes' predicates would be a part of the checking
4115 // code. The subsequently generated check for the default mode would then
4116 // have the exact same patterns, but a different predicate code. To avoid
4117 // duplicated patterns with different predicate checks, construct the
4118 // default check as a negation of all predicates that are actually present
4119 // in the source/destination patterns.
4120 std::vector<Predicate> DefaultPred;
4121
4122 for (unsigned M : Modes) {
4123 if (M == DefaultMode)
4124 continue;
4125 if (ModeChecks.find(M) != ModeChecks.end())
4126 continue;
4127
4128 // Fill the map entry for this mode.
4129 const HwMode &HM = CGH.getMode(M);
4130 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4131
4132 // Add negations of the HM's predicates to the default predicate.
4133 DefaultPred.emplace_back(Predicate(HM.Features, false));
4134 }
4135
4136 for (unsigned M : Modes) {
4137 if (M == DefaultMode)
4138 continue;
4139 AppendPattern(P, M);
4140 }
4141
4142 bool HasDefault = Modes.count(DefaultMode);
4143 if (HasDefault)
4144 AppendPattern(P, DefaultMode);
4145 }
4146}
4147
4148/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turner249dc142017-09-20 18:01:40 +00004149typedef StringMap<int> DepVarMap;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004150
4151static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4152 if (N->isLeaf()) {
Zachary Turner249dc142017-09-20 18:01:40 +00004153 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004154 DepMap[N->getName()]++;
4155 } else {
4156 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4157 FindDepVarsOf(N->getChild(i), DepMap);
4158 }
4159}
4160
4161/// Find dependent variables within child patterns
4162static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
4163 DepVarMap depcounts;
4164 FindDepVarsOf(N, depcounts);
Zachary Turner249dc142017-09-20 18:01:40 +00004165 for (const auto &Pair : depcounts) {
4166 if (Pair.getValue() > 1)
4167 DepVars.insert(Pair.getKey());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004168 }
4169}
4170
4171#ifndef NDEBUG
4172/// Dump the dependent variable set:
4173static void DumpDepVars(MultipleUseVarSet &DepVars) {
4174 if (DepVars.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004175 LLVM_DEBUG(errs() << "<empty set>");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004176 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004177 LLVM_DEBUG(errs() << "[ ");
Zachary Turner249dc142017-09-20 18:01:40 +00004178 for (const auto &DepVar : DepVars) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004179 LLVM_DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004180 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004181 LLVM_DEBUG(errs() << "]");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004182 }
4183}
4184#endif
4185
4186
Chris Lattner8cab0212008-01-05 22:25:12 +00004187/// CombineChildVariants - Given a bunch of permutations of each child of the
4188/// 'operator' node, put them together in all possible ways.
Florian Hahn75e87c32018-05-30 21:00:18 +00004189static void CombineChildVariants(
4190 TreePatternNodePtr Orig,
4191 const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4192 std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4193 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004194 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00004195 for (const auto &Variants : ChildVariants)
4196 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00004197 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004198
Chris Lattner8cab0212008-01-05 22:25:12 +00004199 // The end result is an all-pairs construction of the resultant pattern.
4200 std::vector<unsigned> Idxs;
4201 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00004202 bool NotDone;
4203 do {
4204#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004205 LLVM_DEBUG(if (!Idxs.empty()) {
4206 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
4207 for (unsigned Idx : Idxs) {
4208 errs() << Idx << " ";
4209 }
4210 errs() << "]\n";
4211 });
Scott Michel94420742008-03-05 17:49:05 +00004212#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00004213 // Create the variant and add it to the output list.
Florian Hahn75e87c32018-05-30 21:00:18 +00004214 std::vector<TreePatternNodePtr> NewChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004215 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4216 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Florian Hahn75e87c32018-05-30 21:00:18 +00004217 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
David Blaikiefda69dd2015-11-22 20:11:21 +00004218 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004219
Chris Lattner8cab0212008-01-05 22:25:12 +00004220 // Copy over properties.
4221 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00004222 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00004223 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00004224 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4225 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00004226
Scott Michel94420742008-03-05 17:49:05 +00004227 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00004228 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00004229 // Scan to see if this pattern has already been emitted. We can get
4230 // duplication due to things like commuting:
4231 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4232 // which are the same pattern. Ignore the dups.
4233 if (R->canPatternMatch(ErrString, CDP) &&
Florian Hahn75e87c32018-05-30 21:00:18 +00004234 none_of(OutVariants, [&](TreePatternNodePtr Variant) {
4235 return R->isIsomorphicTo(Variant.get(), DepVars);
David Majnemer0a16c222016-08-11 21:15:00 +00004236 }))
Florian Hahn75e87c32018-05-30 21:00:18 +00004237 OutVariants.push_back(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004238
Scott Michel94420742008-03-05 17:49:05 +00004239 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004240 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00004241 // [0, 0], [0, 1], [1, 0], [1, 1].
4242 int IdxsIdx;
4243 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4244 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4245 Idxs[IdxsIdx] = 0;
4246 else
Chris Lattner8cab0212008-01-05 22:25:12 +00004247 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00004248 }
Scott Michel94420742008-03-05 17:49:05 +00004249 NotDone = (IdxsIdx >= 0);
4250 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00004251}
4252
4253/// CombineChildVariants - A helper function for binary operators.
4254///
Florian Hahn75e87c32018-05-30 21:00:18 +00004255static void CombineChildVariants(TreePatternNodePtr Orig,
4256 const std::vector<TreePatternNodePtr> &LHS,
4257 const std::vector<TreePatternNodePtr> &RHS,
4258 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004259 CodeGenDAGPatterns &CDP,
4260 const MultipleUseVarSet &DepVars) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004261 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004262 ChildVariants.push_back(LHS);
4263 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00004264 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004265}
Chris Lattner8cab0212008-01-05 22:25:12 +00004266
Florian Hahn75e87c32018-05-30 21:00:18 +00004267static void
4268GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
4269 std::vector<TreePatternNodePtr> &Children) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004270 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4271 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00004272
Chris Lattner8cab0212008-01-05 22:25:12 +00004273 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00004274 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00004275 N->getTransformFn()) {
4276 Children.push_back(N);
4277 return;
4278 }
4279
4280 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004281 Children.push_back(N->getChildShared(0));
Chris Lattner8cab0212008-01-05 22:25:12 +00004282 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004283 GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004284
4285 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004286 Children.push_back(N->getChildShared(1));
Chris Lattner8cab0212008-01-05 22:25:12 +00004287 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004288 GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004289}
4290
4291/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4292/// the (potentially recursive) pattern by using algebraic laws.
4293///
Florian Hahn75e87c32018-05-30 21:00:18 +00004294static void GenerateVariantsOf(TreePatternNodePtr N,
4295 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004296 CodeGenDAGPatterns &CDP,
4297 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00004298 // We cannot permute leaves or ComplexPattern uses.
4299 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004300 OutVariants.push_back(N);
4301 return;
4302 }
4303
4304 // Look up interesting info about the node.
4305 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4306
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004307 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00004308 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00004309 // Re-associate by pulling together all of the linked operators
Florian Hahn75e87c32018-05-30 21:00:18 +00004310 std::vector<TreePatternNodePtr> MaximalChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004311 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4312
4313 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4314 // permutations.
4315 if (MaximalChildren.size() == 3) {
4316 // Find the variants of all of our maximal children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004317 std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00004318 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4319 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4320 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004321
Chris Lattner8cab0212008-01-05 22:25:12 +00004322 // There are only two ways we can permute the tree:
4323 // (A op B) op C and A op (B op C)
4324 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004325
Chris Lattner8cab0212008-01-05 22:25:12 +00004326 // Generate legal pair permutations of A/B/C.
Florian Hahn75e87c32018-05-30 21:00:18 +00004327 std::vector<TreePatternNodePtr> ABVariants;
4328 std::vector<TreePatternNodePtr> BAVariants;
4329 std::vector<TreePatternNodePtr> ACVariants;
4330 std::vector<TreePatternNodePtr> CAVariants;
4331 std::vector<TreePatternNodePtr> BCVariants;
4332 std::vector<TreePatternNodePtr> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00004333 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4334 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4335 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4336 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4337 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4338 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004339
4340 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00004341 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4342 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4343 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4344 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4345 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4346 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004347
4348 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00004349 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4350 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4351 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4352 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4353 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4354 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004355 return;
4356 }
4357 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004358
Chris Lattner8cab0212008-01-05 22:25:12 +00004359 // Compute permutations of all children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004360 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004361 ChildVariants.resize(N->getNumChildren());
4362 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn75e87c32018-05-30 21:00:18 +00004363 GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004364
4365 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00004366 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004367
4368 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004369 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4370 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004371 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004372 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004373 // Don't count children which are actually register references.
4374 unsigned NC = 0;
4375 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4376 TreePatternNode *Child = N->getChild(i);
4377 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00004378 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004379 Record *RR = DI->getDef();
4380 if (RR->isSubClassOf("Register"))
4381 continue;
4382 }
4383 NC++;
4384 }
4385 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004386 if (isCommIntrinsic) {
4387 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4388 // operands are the commutative operands, and there might be more operands
4389 // after those.
4390 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004391 "Commutative intrinsic should have at least 3 children!");
Florian Hahn75e87c32018-05-30 21:00:18 +00004392 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn53b14db2018-06-10 21:06:24 +00004393 Variants.push_back(ChildVariants[0]); // Intrinsic id.
4394 Variants.push_back(ChildVariants[2]);
4395 Variants.push_back(ChildVariants[1]);
Evan Cheng49bad4c2008-06-16 20:29:38 +00004396 for (unsigned i = 3; i != NC; ++i)
Florian Hahn53b14db2018-06-10 21:06:24 +00004397 Variants.push_back(ChildVariants[i]);
Evan Cheng49bad4c2008-06-16 20:29:38 +00004398 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004399 } else if (NC == N->getNumChildren()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004400 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn53b14db2018-06-10 21:06:24 +00004401 Variants.push_back(ChildVariants[1]);
4402 Variants.push_back(ChildVariants[0]);
Craig Topper98a96282017-09-04 03:44:33 +00004403 for (unsigned i = 2; i != NC; ++i)
Florian Hahn53b14db2018-06-10 21:06:24 +00004404 Variants.push_back(ChildVariants[i]);
Craig Topper98a96282017-09-04 03:44:33 +00004405 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4406 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004407 }
4408}
4409
4410
4411// GenerateVariants - Generate variants. For example, commutative patterns can
4412// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004413void CodeGenDAGPatterns::GenerateVariants() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004414 LLVM_DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004415
Chris Lattner8cab0212008-01-05 22:25:12 +00004416 // Loop over all of the patterns we've collected, checking to see if we can
4417 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004418 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004419 // the .td file having to contain tons of variants of instructions.
4420 //
4421 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4422 // intentionally do not reconsider these. Any variants of added patterns have
4423 // already been added.
4424 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00004425 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00004426 MultipleUseVarSet DepVars;
Florian Hahn75e87c32018-05-30 21:00:18 +00004427 std::vector<TreePatternNodePtr> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004428 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004429 LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4430 LLVM_DEBUG(DumpDepVars(DepVars));
4431 LLVM_DEBUG(errs() << "\n");
Florian Hahn75e87c32018-05-30 21:00:18 +00004432 GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4433 *this, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004434
4435 assert(!Variants.empty() && "Must create at least original variant!");
Krzysztof Parzyszekf7237762017-06-16 13:44:34 +00004436 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004437 continue;
4438
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004439 LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4440 PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004441
4442 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004443 TreePatternNodePtr Variant = Variants[v];
Chris Lattner8cab0212008-01-05 22:25:12 +00004444
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004445 LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump();
4446 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004447
Chris Lattner8cab0212008-01-05 22:25:12 +00004448 // Scan to see if an instruction or explicit pattern already matches this.
4449 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004450 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004451 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004452 if (PatternsToMatch[i].getPredicates() !=
4453 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00004454 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004455 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004456 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4457 DepVars)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004458 LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004459 AlreadyExists = true;
4460 break;
4461 }
4462 }
4463 // If we already have it, ignore the variant.
4464 if (AlreadyExists) continue;
4465
4466 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004467 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004468 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
Florian Hahn75e87c32018-05-30 21:00:18 +00004469 Variant, PatternsToMatch[i].getDstPatternShared(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004470 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004471 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00004472 }
4473
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004474 LLVM_DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004475 }
4476}