blob: 9e98da1d107f457d501aaaff8bf2f99bd134d9ba [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
312void TypeSetByHwMode::validate() const {
313#ifndef NDEBUG
314 if (empty())
315 return;
316 bool AllEmpty = true;
317 for (const auto &I : *this)
318 AllEmpty &= I.second.empty();
319 assert(!AllEmpty &&
320 "type set is empty for each HW mode: type contradiction?");
321#endif
322}
323
324// --- TypeInfer
325
326bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
327 const TypeSetByHwMode &In) {
328 ValidateOnExit _1(Out);
329 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) {
345 ValidateOnExit _1(Out);
346 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) {
364 ValidateOnExit _1(Out);
365 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) {
374 ValidateOnExit _1(Out);
375 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) {
384 ValidateOnExit _1(Out);
385 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) {
394 ValidateOnExit _1(Out);
395 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) {
404 ValidateOnExit _1(Out);
405 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) {
443 ValidateOnExit _1(Small), _2(Big);
444 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);
517 if (MinS != S.end()) {
518 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
519 if (B.empty()) {
520 TP.error("Type contradiction in " +
521 Twine(__func__) + ":" + Twine(__LINE__));
522 return Changed;
523 }
524 }
525 // MaxS = max scalar in Big, remove all scalars from Small that are
526 // larger than MaxS.
527 auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
528 if (MaxS != B.end()) {
529 Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
530 if (B.empty()) {
531 TP.error("Type contradiction in " +
532 Twine(__func__) + ":" + Twine(__LINE__));
533 return Changed;
534 }
535 }
536
537 // MinV = min vector in Small, remove all vectors from Big that are
538 // smaller-or-equal than MinV.
539 auto MinV = min_if(S.begin(), S.end(), isVector, LT);
540 if (MinV != S.end()) {
541 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
542 if (B.empty()) {
543 TP.error("Type contradiction in " +
544 Twine(__func__) + ":" + Twine(__LINE__));
545 return Changed;
546 }
547 }
548 // MaxV = max vector in Big, remove all vectors from Small that are
549 // larger than MaxV.
550 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
551 if (MaxV != B.end()) {
552 Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
553 if (B.empty()) {
554 TP.error("Type contradiction in " +
555 Twine(__func__) + ":" + Twine(__LINE__));
556 return Changed;
557 }
558 }
559 }
560
561 return Changed;
562}
563
564/// 1. Ensure that for each type T in Vec, T is a vector type, and that
565/// for each type U in Elem, U is a scalar type.
566/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
567/// type T in Vec, such that U is the element type of T.
568bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
569 TypeSetByHwMode &Elem) {
570 ValidateOnExit _1(Vec), _2(Elem);
571 if (TP.hasError())
572 return false;
573 bool Changed = false;
574
575 if (Vec.empty())
576 Changed |= EnforceVector(Vec);
577 if (Elem.empty())
578 Changed |= EnforceScalar(Elem);
579
580 for (unsigned M : union_modes(Vec, Elem)) {
581 TypeSetByHwMode::SetType &V = Vec.get(M);
582 TypeSetByHwMode::SetType &E = Elem.get(M);
583
584 Changed |= berase_if(V, isScalar); // Scalar = !vector
585 Changed |= berase_if(E, isVector); // Vector = !scalar
586 assert(!V.empty() && !E.empty());
587
588 SmallSet<MVT,4> VT, ST;
589 // Collect element types from the "vector" set.
590 for (MVT T : V)
591 VT.insert(T.getVectorElementType());
592 // Collect scalar types from the "element" set.
593 for (MVT T : E)
594 ST.insert(T);
595
596 // Remove from V all (vector) types whose element type is not in S.
597 Changed |= berase_if(V, [&ST](MVT T) -> bool {
598 return !ST.count(T.getVectorElementType());
599 });
600 // Remove from E all (scalar) types, for which there is no corresponding
601 // type in V.
602 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
603
604 if (V.empty() || E.empty()) {
605 TP.error("Type contradiction in " +
606 Twine(__func__) + ":" + Twine(__LINE__));
607 return Changed;
608 }
609 }
610
611 return Changed;
612}
613
614bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
615 const ValueTypeByHwMode &VVT) {
616 TypeSetByHwMode Tmp(VVT);
617 ValidateOnExit _1(Vec), _2(Tmp);
618 return EnforceVectorEltTypeIs(Vec, Tmp);
619}
620
621/// Ensure that for each type T in Sub, T is a vector type, and there
622/// exists a type U in Vec such that U is a vector type with the same
623/// element type as T and at least as many elements as T.
624bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
625 TypeSetByHwMode &Sub) {
626 ValidateOnExit _1(Vec), _2(Sub);
627 if (TP.hasError())
628 return false;
629
630 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
631 auto IsSubVec = [](MVT B, MVT P) -> bool {
632 if (!B.isVector() || !P.isVector())
633 return false;
634 if (B.getVectorElementType() != P.getVectorElementType())
635 return false;
636 return B.getVectorNumElements() < P.getVectorNumElements();
637 };
638
639 /// Return true if S has no element (vector type) that T is a sub-vector of,
640 /// i.e. has the same element type as T and more elements.
641 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
642 for (const auto &I : S)
643 if (IsSubVec(T, I))
644 return false;
645 return true;
646 };
647
648 /// Return true if S has no element (vector type) that T is a super-vector
649 /// of, i.e. has the same element type as T and fewer elements.
650 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
651 for (const auto &I : S)
652 if (IsSubVec(I, T))
653 return false;
654 return true;
655 };
656
657 bool Changed = false;
658
659 if (Vec.empty())
660 Changed |= EnforceVector(Vec);
661 if (Sub.empty())
662 Changed |= EnforceVector(Sub);
663
664 for (unsigned M : union_modes(Vec, Sub)) {
665 TypeSetByHwMode::SetType &S = Sub.get(M);
666 TypeSetByHwMode::SetType &V = Vec.get(M);
667
668 Changed |= berase_if(S, isScalar);
669 if (S.empty()) {
670 TP.error("Type contradiction in " +
671 Twine(__func__) + ":" + Twine(__LINE__));
672 return Changed;
673 }
674
675 // Erase all types from S that are not sub-vectors of a type in V.
676 Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
677 if (S.empty()) {
678 TP.error("Type contradiction in " +
679 Twine(__func__) + ":" + Twine(__LINE__));
680 return Changed;
681 }
682
683 // Erase all types from V that are not super-vectors of a type in S.
684 Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
685 if (V.empty()) {
686 TP.error("Type contradiction in " +
687 Twine(__func__) + ":" + Twine(__LINE__));
688 return Changed;
689 }
690 }
691
692 return Changed;
693}
694
695/// 1. Ensure that V has a scalar type iff W has a scalar type.
696/// 2. Ensure that for each vector type T in V, there exists a vector
697/// type U in W, such that T and U have the same number of elements.
698/// 3. Ensure that for each vector type U in W, there exists a vector
699/// type T in V, such that T and U have the same number of elements
700/// (reverse of 2).
701bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
702 ValidateOnExit _1(V), _2(W);
703 if (TP.hasError())
704 return false;
705
706 bool Changed = false;
707 if (V.empty())
708 Changed |= EnforceAny(V);
709 if (W.empty())
710 Changed |= EnforceAny(W);
711
712 // An actual vector type cannot have 0 elements, so we can treat scalars
713 // as zero-length vectors. This way both vectors and scalars can be
714 // processed identically.
715 auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
716 return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
717 };
718
719 for (unsigned M : union_modes(V, W)) {
720 TypeSetByHwMode::SetType &VS = V.get(M);
721 TypeSetByHwMode::SetType &WS = W.get(M);
722
723 SmallSet<unsigned,2> VN, WN;
724 for (MVT T : VS)
725 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
726 for (MVT T : WS)
727 WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
728
729 Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
730 Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
731 }
732 return Changed;
733}
734
735/// 1. Ensure that for each type T in A, there exists a type U in B,
736/// such that T and U have equal size in bits.
737/// 2. Ensure that for each type U in B, there exists a type T in A
738/// such that T and U have equal size in bits (reverse of 1).
739bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
740 ValidateOnExit _1(A), _2(B);
741 if (TP.hasError())
742 return false;
743 bool Changed = false;
744 if (A.empty())
745 Changed |= EnforceAny(A);
746 if (B.empty())
747 Changed |= EnforceAny(B);
748
749 auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
750 return !Sizes.count(T.getSizeInBits());
751 };
752
753 for (unsigned M : union_modes(A, B)) {
754 TypeSetByHwMode::SetType &AS = A.get(M);
755 TypeSetByHwMode::SetType &BS = B.get(M);
756 SmallSet<unsigned,2> AN, BN;
757
758 for (MVT T : AS)
759 AN.insert(T.getSizeInBits());
760 for (MVT T : BS)
761 BN.insert(T.getSizeInBits());
762
763 Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
764 Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
765 }
766
767 return Changed;
768}
769
770void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
771 ValidateOnExit _1(VTS);
772 TypeSetByHwMode Legal = getLegalTypes();
773 bool HaveLegalDef = Legal.hasDefault();
774
775 for (auto &I : VTS) {
776 unsigned M = I.first;
777 if (!Legal.hasMode(M) && !HaveLegalDef) {
778 TP.error("Invalid mode " + Twine(M));
779 return;
780 }
781 expandOverloads(I.second, Legal.get(M));
Scott Michel94420742008-03-05 17:49:05 +0000782 }
783}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000784
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000785void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
786 const TypeSetByHwMode::SetType &Legal) {
787 std::set<MVT> Ovs;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000788 for (MVT T : Out) {
789 if (!T.isOverloaded())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000790 continue;
Zachary Turner249dc142017-09-20 18:01:40 +0000791
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000792 Ovs.insert(T);
793 // MachineValueTypeSet allows iteration and erasing.
794 Out.erase(T);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000795 }
796
797 for (MVT Ov : Ovs) {
798 switch (Ov.SimpleTy) {
799 case MVT::iPTRAny:
800 Out.insert(MVT::iPTR);
801 return;
802 case MVT::iAny:
803 for (MVT T : MVT::integer_valuetypes())
804 if (Legal.count(T))
805 Out.insert(T);
806 for (MVT T : MVT::integer_vector_valuetypes())
807 if (Legal.count(T))
808 Out.insert(T);
809 return;
810 case MVT::fAny:
811 for (MVT T : MVT::fp_valuetypes())
812 if (Legal.count(T))
813 Out.insert(T);
814 for (MVT T : MVT::fp_vector_valuetypes())
815 if (Legal.count(T))
816 Out.insert(T);
817 return;
818 case MVT::vAny:
819 for (MVT T : MVT::vector_valuetypes())
820 if (Legal.count(T))
821 Out.insert(T);
822 return;
823 case MVT::Any:
824 for (MVT T : MVT::all_valuetypes())
825 if (Legal.count(T))
826 Out.insert(T);
827 return;
828 default:
829 break;
830 }
831 }
832}
833
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000834TypeSetByHwMode TypeInfer::getLegalTypes() {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000835 if (!LegalTypesCached) {
836 // Stuff all types from all modes into the default mode.
837 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
838 for (const auto &I : LTS)
839 LegalCache.insert(I.second);
840 LegalTypesCached = true;
841 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000842 TypeSetByHwMode VTS;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000843 VTS.getOrCreate(DefaultMode) = LegalCache;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000844 return VTS;
845}
Chris Lattner514e2922011-04-17 21:38:24 +0000846
847//===----------------------------------------------------------------------===//
848// TreePredicateFn Implementation
849//===----------------------------------------------------------------------===//
850
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000851/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
852TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
853 assert((getPredCode().empty() || getImmCode().empty()) &&
854 ".td file corrupt: can't have a node predicate *and* an imm predicate");
855}
856
Chris Lattner514e2922011-04-17 21:38:24 +0000857std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000858 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000859}
860
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000861std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000862 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000863}
864
Chris Lattner514e2922011-04-17 21:38:24 +0000865
866/// isAlwaysTrue - Return true if this is a noop predicate.
867bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000868 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000869}
870
871/// Return the name to use in the generated code to reference this, this is
872/// "Predicate_foo" if from a pattern fragment "foo".
873std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +0000874 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +0000875}
876
877/// getCodeToRunOnSDNode - Return the code for the function body that
878/// evaluates this predicate. The argument is expected to be in "Node",
879/// not N. This handles casting and conversion to a concrete node type as
880/// appropriate.
881std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000882 // Handle immediate predicates first.
883 std::string ImmCode = getImmCode();
884 if (!ImmCode.empty()) {
885 std::string Result =
886 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000887 return Result + ImmCode;
888 }
Simon Pilgrim8c4d0612017-09-22 16:57:28 +0000889
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000890 // Handle arbitrary node predicates.
891 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000892 std::string ClassName;
893 if (PatFragRec->getOnlyTree()->isLeaf())
894 ClassName = "SDNode";
895 else {
896 Record *Op = PatFragRec->getOnlyTree()->getOperator();
897 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
898 }
899 std::string Result;
900 if (ClassName == "SDNode")
901 Result = " SDNode *N = Node;\n";
902 else
Craig Topper5b0f57d2015-10-11 16:59:29 +0000903 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
Simon Pilgrim8c4d0612017-09-22 16:57:28 +0000904
Chris Lattner514e2922011-04-17 21:38:24 +0000905 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000906}
907
Chris Lattner8cab0212008-01-05 22:25:12 +0000908//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000909// PatternToMatch implementation
910//
911
Chris Lattner05925fe2010-03-29 01:40:38 +0000912/// getPatternSize - Return the 'size' of this pattern. We want to match large
913/// patterns before small ones. This is used to determine the size of a
914/// pattern.
915static unsigned getPatternSize(const TreePatternNode *P,
916 const CodeGenDAGPatterns &CGP) {
917 unsigned Size = 3; // The node itself.
918 // If the root node is a ConstantSDNode, increases its size.
919 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000920 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000921 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000922
Simon Pilgrim40687012017-09-26 12:59:01 +0000923 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +0000924 Size += AM->getComplexity();
Tim Northoverc807a172014-05-20 11:52:46 +0000925 // We don't want to count any children twice, so return early.
926 return Size;
927 }
928
Chris Lattner05925fe2010-03-29 01:40:38 +0000929 // If this node has some predicate function that must match, it adds to the
930 // complexity of this node.
931 if (!P->getPredicateFns().empty())
932 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000933
Chris Lattner05925fe2010-03-29 01:40:38 +0000934 // Count children in the count if they are also nodes.
935 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
936 TreePatternNode *Child = P->getChild(i);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000937 if (!Child->isLeaf() && Child->getNumTypes()) {
938 const TypeSetByHwMode &T0 = Child->getType(0);
939 // At this point, all variable type sets should be simple, i.e. only
940 // have a default mode.
941 if (T0.getMachineValueType() != MVT::Other) {
942 Size += getPatternSize(Child, CGP);
943 continue;
944 }
945 }
946 if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000947 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000948 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
949 else if (Child->getComplexPatternInfo(CGP))
950 Size += getPatternSize(Child, CGP);
951 else if (!Child->getPredicateFns().empty())
952 ++Size;
953 }
954 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000955
Chris Lattner05925fe2010-03-29 01:40:38 +0000956 return Size;
957}
958
959/// Compute the complexity metric for the input pattern. This roughly
960/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000961int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000962getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
963 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
964}
965
Dan Gohman49e19e92008-08-22 00:20:26 +0000966/// getPredicateCheck - Return a single string containing all of this
967/// pattern's predicates concatenated with "&&" operators.
968///
969std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000970 SmallVector<const Predicate*,4> PredList;
971 for (const Predicate &P : Predicates)
972 PredList.push_back(&P);
973 std::sort(PredList.begin(), PredList.end(), deref<llvm::less>());
Craig Topper8985efe2015-11-27 05:44:04 +0000974
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000975 std::string Check;
976 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
977 if (i != 0)
978 Check += " && ";
979 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +0000980 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000981 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +0000982}
983
984//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000985// SDTypeConstraint implementation
986//
987
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000988SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000989 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000990
Chris Lattner8cab0212008-01-05 22:25:12 +0000991 if (R->isSubClassOf("SDTCisVT")) {
992 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000993 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
994 for (const auto &P : VVT)
995 if (P.second == MVT::isVoid)
996 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +0000997 } else if (R->isSubClassOf("SDTCisPtrTy")) {
998 ConstraintType = SDTCisPtrTy;
999 } else if (R->isSubClassOf("SDTCisInt")) {
1000 ConstraintType = SDTCisInt;
1001 } else if (R->isSubClassOf("SDTCisFP")) {
1002 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +00001003 } else if (R->isSubClassOf("SDTCisVec")) {
1004 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001005 } else if (R->isSubClassOf("SDTCisSameAs")) {
1006 ConstraintType = SDTCisSameAs;
1007 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1008 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1009 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001010 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001011 R->getValueAsInt("OtherOperandNum");
1012 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1013 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001014 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001015 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001016 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1017 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001018 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001019 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1020 ConstraintType = SDTCisSubVecOfVec;
1021 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1022 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001023 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1024 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001025 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1026 for (const auto &P : VVT) {
1027 MVT T = P.second;
1028 if (T.isVector())
1029 PrintFatalError(R->getLoc(),
1030 "Cannot use vector type as SDTCVecEltisVT");
1031 if (!T.isInteger() && !T.isFloatingPoint())
1032 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1033 "as SDTCVecEltisVT");
1034 }
Craig Topper0be34582015-03-05 07:11:34 +00001035 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1036 ConstraintType = SDTCisSameNumEltsAs;
1037 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1038 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001039 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1040 ConstraintType = SDTCisSameSizeAs;
1041 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1042 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001043 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001044 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001045 }
1046}
1047
1048/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001049/// N, and the result number in ResNo.
1050static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
1051 const SDNodeInfo &NodeInfo,
1052 unsigned &ResNo) {
1053 unsigned NumResults = NodeInfo.getNumResults();
1054 if (OpNo < NumResults) {
1055 ResNo = OpNo;
1056 return N;
1057 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001058
Chris Lattner2db7aba2010-03-19 21:56:21 +00001059 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001060
Chris Lattner2db7aba2010-03-19 21:56:21 +00001061 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001062 std::string S;
1063 raw_string_ostream OS(S);
1064 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001065 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +00001066 N->print(OS);
1067 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001068 }
1069
Chris Lattner2db7aba2010-03-19 21:56:21 +00001070 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001071}
1072
1073/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1074/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001075/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001076bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
1077 const SDNodeInfo &NodeInfo,
1078 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001079 if (TP.hasError())
1080 return false;
1081
Chris Lattner2db7aba2010-03-19 21:56:21 +00001082 unsigned ResNo = 0; // The result number being referenced.
1083 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001084 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001085
Chris Lattner8cab0212008-01-05 22:25:12 +00001086 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001087 case SDTCisVT:
1088 // Operand must be a particular type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001089 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001090 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001091 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001092 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001093 case SDTCisInt:
1094 // Require it to be one of the legal integer VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001095 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001096 case SDTCisFP:
1097 // Require it to be one of the legal fp VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001098 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001099 case SDTCisVec:
1100 // Require it to be one of the legal vector VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001101 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001102 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001103 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001104 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001105 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +00001106 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1107 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001108 }
1109 case SDTCisVTSmallerThanOp: {
1110 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1111 // have an integer type that is smaller than the VT.
1112 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +00001113 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +00001114 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001115 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001116 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001117 return false;
1118 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001119 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
1120 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1121 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1122 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001123
Chris Lattner2db7aba2010-03-19 21:56:21 +00001124 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001125 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001126 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1127 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001128
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001129 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001130 }
1131 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001132 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001133 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001134 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1135 BResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001136 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1137 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001138 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001139 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001140 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +00001141 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001142 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1143 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001144 // Filter vector types out of VecOperand that don't have the right element
1145 // type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001146 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1147 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001148 }
David Greene127fd1d2011-01-24 20:53:18 +00001149 case SDTCisSubVecOfVec: {
1150 unsigned VResNo = 0;
1151 TreePatternNode *BigVecOperand =
1152 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1153 VResNo);
1154
1155 // Filter vector types out of BigVecOperand that don't have the
1156 // right subvector type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001157 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1158 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001159 }
Craig Topper0be34582015-03-05 07:11:34 +00001160 case SDTCVecEltisVT: {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001161 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001162 }
1163 case SDTCisSameNumEltsAs: {
1164 unsigned OResNo = 0;
1165 TreePatternNode *OtherNode =
1166 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1167 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001168 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1169 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001170 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001171 case SDTCisSameSizeAs: {
1172 unsigned OResNo = 0;
1173 TreePatternNode *OtherNode =
1174 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1175 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001176 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1177 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001178 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001179 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001180 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001181}
1182
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001183// Update the node type to match an instruction operand or result as specified
1184// in the ins or outs lists on the instruction definition. Return true if the
1185// type was actually changed.
1186bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1187 Record *Operand,
1188 TreePattern &TP) {
1189 // The 'unknown' operand indicates that types should be inferred from the
1190 // context.
1191 if (Operand->isSubClassOf("unknown_class"))
1192 return false;
1193
1194 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001195 if (Operand->isSubClassOf("Operand")) {
1196 Record *R = Operand->getValueAsDef("Type");
1197 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1198 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1199 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001200
1201 // PointerLikeRegClass has a type that is determined at runtime.
1202 if (Operand->isSubClassOf("PointerLikeRegClass"))
1203 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1204
1205 // Both RegisterClass and RegisterOperand operands derive their types from a
1206 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001207 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001208 if (Operand->isSubClassOf("RegisterClass"))
1209 RC = Operand;
1210 else if (Operand->isSubClassOf("RegisterOperand"))
1211 RC = Operand->getValueAsDef("RegClass");
1212
1213 assert(RC && "Unknown operand type");
1214 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1215 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1216}
1217
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001218bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1219 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1220 if (!TP.getInfer().isConcrete(Types[i], true))
1221 return true;
1222 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1223 if (getChild(i)->ContainsUnresolvedType(TP))
1224 return true;
1225 return false;
1226}
1227
1228bool TreePatternNode::hasProperTypeByHwMode() const {
1229 for (const TypeSetByHwMode &S : Types)
1230 if (!S.isDefaultOnly())
1231 return true;
1232 for (TreePatternNode *C : Children)
1233 if (C->hasProperTypeByHwMode())
1234 return true;
1235 return false;
1236}
1237
1238bool TreePatternNode::hasPossibleType() const {
1239 for (const TypeSetByHwMode &S : Types)
1240 if (!S.isPossible())
1241 return false;
1242 for (TreePatternNode *C : Children)
1243 if (!C->hasPossibleType())
1244 return false;
1245 return true;
1246}
1247
1248bool TreePatternNode::setDefaultMode(unsigned Mode) {
1249 for (TypeSetByHwMode &S : Types) {
1250 S.makeSimple(Mode);
1251 // Check if the selected mode had a type conflict.
1252 if (S.get(DefaultMode).empty())
1253 return false;
1254 }
1255 for (TreePatternNode *C : Children)
1256 if (!C->setDefaultMode(Mode))
1257 return false;
1258 return true;
1259}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001260
Chris Lattner8cab0212008-01-05 22:25:12 +00001261//===----------------------------------------------------------------------===//
1262// SDNodeInfo implementation
1263//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001264SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001265 EnumName = R->getValueAsString("Opcode");
1266 SDClassName = R->getValueAsString("SDClass");
1267 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1268 NumResults = TypeProfile->getValueAsInt("NumResults");
1269 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001270
Chris Lattner8cab0212008-01-05 22:25:12 +00001271 // Parse the properties.
1272 Properties = 0;
Craig Topper306cb122015-11-22 20:46:24 +00001273 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1274 if (Property->getName() == "SDNPCommutative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001275 Properties |= 1 << SDNPCommutative;
Craig Topper306cb122015-11-22 20:46:24 +00001276 } else if (Property->getName() == "SDNPAssociative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001277 Properties |= 1 << SDNPAssociative;
Craig Topper306cb122015-11-22 20:46:24 +00001278 } else if (Property->getName() == "SDNPHasChain") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001279 Properties |= 1 << SDNPHasChain;
Craig Topper306cb122015-11-22 20:46:24 +00001280 } else if (Property->getName() == "SDNPOutGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001281 Properties |= 1 << SDNPOutGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001282 } else if (Property->getName() == "SDNPInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001283 Properties |= 1 << SDNPInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001284 } else if (Property->getName() == "SDNPOptInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001285 Properties |= 1 << SDNPOptInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001286 } else if (Property->getName() == "SDNPMayStore") {
Chris Lattnera348f552008-01-06 06:44:58 +00001287 Properties |= 1 << SDNPMayStore;
Craig Topper306cb122015-11-22 20:46:24 +00001288 } else if (Property->getName() == "SDNPMayLoad") {
Chris Lattner1ca20682008-01-10 04:38:57 +00001289 Properties |= 1 << SDNPMayLoad;
Craig Topper306cb122015-11-22 20:46:24 +00001290 } else if (Property->getName() == "SDNPSideEffect") {
Chris Lattner42c63ef2008-01-10 05:39:30 +00001291 Properties |= 1 << SDNPSideEffect;
Craig Topper306cb122015-11-22 20:46:24 +00001292 } else if (Property->getName() == "SDNPMemOperand") {
Mon P Wang6a490372008-06-25 08:15:39 +00001293 Properties |= 1 << SDNPMemOperand;
Craig Topper306cb122015-11-22 20:46:24 +00001294 } else if (Property->getName() == "SDNPVariadic") {
Chris Lattner83aeaab2010-03-19 05:07:09 +00001295 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001296 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001297 PrintFatalError("Unknown SD Node property '" +
Craig Topper306cb122015-11-22 20:46:24 +00001298 Property->getName() + "' on node '" +
James Y Knighte452e272015-05-11 22:17:13 +00001299 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001300 }
1301 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001302
1303
Chris Lattner8cab0212008-01-05 22:25:12 +00001304 // Parse the type constraints.
1305 std::vector<Record*> ConstraintList =
1306 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001307 for (Record *R : ConstraintList)
1308 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001309}
1310
Chris Lattner99e53b32010-02-28 00:22:30 +00001311/// getKnownType - If the type constraints on this node imply a fixed type
1312/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001313/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001314MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001315 unsigned NumResults = getNumResults();
1316 assert(NumResults <= 1 &&
1317 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001318 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001319
Craig Topper306cb122015-11-22 20:46:24 +00001320 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001321 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001322 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001323 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001324
Craig Topper306cb122015-11-22 20:46:24 +00001325 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001326 default: break;
1327 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001328 if (Constraint.VVT.isSimple())
1329 return Constraint.VVT.getSimple().SimpleTy;
1330 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001331 case SDTypeConstraint::SDTCisPtrTy:
1332 return MVT::iPTR;
1333 }
1334 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001335 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001336}
1337
Chris Lattner8cab0212008-01-05 22:25:12 +00001338//===----------------------------------------------------------------------===//
1339// TreePatternNode implementation
1340//
1341
1342TreePatternNode::~TreePatternNode() {
1343#if 0 // FIXME: implement refcounted tree nodes!
1344 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1345 delete getChild(i);
1346#endif
1347}
1348
Chris Lattnerf1447252010-03-19 21:37:09 +00001349static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1350 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001351 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001352 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001353
Chris Lattner2109cb42010-03-22 20:56:36 +00001354 if (Operator->isSubClassOf("Intrinsic"))
1355 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001356
Chris Lattnerf1447252010-03-19 21:37:09 +00001357 if (Operator->isSubClassOf("SDNode"))
1358 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001359
Chris Lattnerf1447252010-03-19 21:37:09 +00001360 if (Operator->isSubClassOf("PatFrag")) {
1361 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1362 // the forward reference case where one pattern fragment references another
1363 // before it is processed.
1364 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1365 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001366
Chris Lattnerf1447252010-03-19 21:37:09 +00001367 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001368 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001369 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001370 if (Tree)
1371 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1372 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001373 assert(Op && "Invalid Fragment");
1374 return GetNumNodeResults(Op, CDP);
1375 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001376
Chris Lattnerf1447252010-03-19 21:37:09 +00001377 if (Operator->isSubClassOf("Instruction")) {
1378 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001379
Craig Topper3a8eb892015-03-20 05:09:06 +00001380 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1381
1382 // Subtract any defaulted outputs.
1383 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1384 Record *OperandNode = InstInfo.Operands[i].Rec;
1385
1386 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1387 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1388 --NumDefsToAdd;
1389 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001390
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001391 // Add on one implicit def if it has a resolvable type.
1392 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1393 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001394 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001395 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001396
Chris Lattnerf1447252010-03-19 21:37:09 +00001397 if (Operator->isSubClassOf("SDNodeXForm"))
1398 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001399
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001400 if (Operator->isSubClassOf("ValueType"))
1401 return 1; // A type-cast of one result.
1402
Tim Northoverc807a172014-05-20 11:52:46 +00001403 if (Operator->isSubClassOf("ComplexPattern"))
1404 return 1;
1405
Matthias Braun8c209aa2017-01-28 02:02:38 +00001406 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001407 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001408}
1409
1410void TreePatternNode::print(raw_ostream &OS) const {
1411 if (isLeaf())
1412 OS << *getLeafValue();
1413 else
1414 OS << '(' << getOperator()->getName();
1415
Zachary Turner249dc142017-09-20 18:01:40 +00001416 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1417 OS << ':';
1418 getExtType(i).writeToStream(OS);
1419 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001420
1421 if (!isLeaf()) {
1422 if (getNumChildren() != 0) {
1423 OS << " ";
1424 getChild(0)->print(OS);
1425 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1426 OS << ", ";
1427 getChild(i)->print(OS);
1428 }
1429 }
1430 OS << ")";
1431 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001432
Craig Topper306cb122015-11-22 20:46:24 +00001433 for (const TreePredicateFn &Pred : PredicateFns)
1434 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001435 if (TransformFn)
1436 OS << "<<X:" << TransformFn->getName() << ">>";
1437 if (!getName().empty())
1438 OS << ":$" << getName();
1439
1440}
1441void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001442 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001443}
1444
Scott Michel94420742008-03-05 17:49:05 +00001445/// isIsomorphicTo - Return true if this node is recursively
1446/// isomorphic to the specified node. For this comparison, the node's
1447/// entire state is considered. The assigned name is ignored, since
1448/// nodes with differing names are considered isomorphic. However, if
1449/// the assigned name is present in the dependent variable set, then
1450/// the assigned name is considered significant and the node is
1451/// isomorphic if the names match.
1452bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1453 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001454 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001455 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001456 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001457 getTransformFn() != N->getTransformFn())
1458 return false;
1459
1460 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001461 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1462 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001463 return ((DI->getDef() == NDI->getDef())
1464 && (DepVars.find(getName()) == DepVars.end()
1465 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001466 }
1467 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001468 return getLeafValue() == N->getLeafValue();
1469 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001470
Chris Lattner8cab0212008-01-05 22:25:12 +00001471 if (N->getOperator() != getOperator() ||
1472 N->getNumChildren() != getNumChildren()) return false;
1473 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001474 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001475 return false;
1476 return true;
1477}
1478
1479/// clone - Make a copy of this tree and all of its children.
1480///
1481TreePatternNode *TreePatternNode::clone() const {
1482 TreePatternNode *New;
1483 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001484 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001485 } else {
1486 std::vector<TreePatternNode*> CChildren;
1487 CChildren.reserve(Children.size());
1488 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1489 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001490 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001491 }
1492 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001493 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001494 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001495 New->setTransformFn(getTransformFn());
1496 return New;
1497}
1498
Chris Lattner53c39ba2010-02-14 22:22:58 +00001499/// RemoveAllTypes - Recursively strip all the types of this tree.
1500void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001501 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001502 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001503 if (isLeaf()) return;
1504 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1505 getChild(i)->RemoveAllTypes();
1506}
1507
1508
Chris Lattner8cab0212008-01-05 22:25:12 +00001509/// SubstituteFormalArguments - Replace the formal arguments in this tree
1510/// with actual values specified by ArgMap.
1511void TreePatternNode::
1512SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1513 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001514
Chris Lattner8cab0212008-01-05 22:25:12 +00001515 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1516 TreePatternNode *Child = getChild(i);
1517 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001518 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001519 // Note that, when substituting into an output pattern, Val might be an
1520 // UnsetInit.
1521 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1522 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001523 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001524 TreePatternNode *NewChild = ArgMap[Child->getName()];
1525 assert(NewChild && "Couldn't find formal argument!");
1526 assert((Child->getPredicateFns().empty() ||
1527 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1528 "Non-empty child predicate clobbered!");
1529 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001530 }
1531 } else {
1532 getChild(i)->SubstituteFormalArguments(ArgMap);
1533 }
1534 }
1535}
1536
1537
1538/// InlinePatternFragments - If this pattern refers to any pattern
1539/// fragments, inline them into place, giving us a pattern without any
1540/// PatFrag references.
1541TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001542 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001543 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001544
1545 if (isLeaf())
1546 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001547 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001548
Chris Lattner8cab0212008-01-05 22:25:12 +00001549 if (!Op->isSubClassOf("PatFrag")) {
1550 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001551 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1552 TreePatternNode *Child = getChild(i);
1553 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1554
1555 assert((Child->getPredicateFns().empty() ||
1556 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1557 "Non-empty child predicate clobbered!");
1558
1559 setChild(i, NewChild);
1560 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001561 return this;
1562 }
1563
1564 // Otherwise, we found a reference to a fragment. First, look up its
1565 // TreePattern record.
1566 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001567
Chris Lattner8cab0212008-01-05 22:25:12 +00001568 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001569 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001570 TP.error("'" + Op->getName() + "' fragment requires " +
1571 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001572 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001573 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001574
1575 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1576
Chris Lattner514e2922011-04-17 21:38:24 +00001577 TreePredicateFn PredFn(Frag);
1578 if (!PredFn.isAlwaysTrue())
1579 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001580
Chris Lattner8cab0212008-01-05 22:25:12 +00001581 // Resolve formal arguments to their actual value.
1582 if (Frag->getNumArgs()) {
1583 // Compute the map of formal to actual arguments.
1584 std::map<std::string, TreePatternNode*> ArgMap;
1585 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1586 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001587
Chris Lattner8cab0212008-01-05 22:25:12 +00001588 FragTree->SubstituteFormalArguments(ArgMap);
1589 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001590
Chris Lattner8cab0212008-01-05 22:25:12 +00001591 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001592 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1593 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001594
1595 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001596 for (const TreePredicateFn &Pred : getPredicateFns())
1597 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001598
Chris Lattner8cab0212008-01-05 22:25:12 +00001599 // Get a new copy of this fragment to stitch into here.
1600 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001601
Chris Lattner2e253b42008-06-30 03:02:03 +00001602 // The fragment we inlined could have recursive inlining that is needed. See
1603 // if there are any pattern fragments in it and inline them as needed.
1604 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001605}
1606
1607/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001608/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001609/// references from the register file information, for example.
1610///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001611/// When Unnamed is set, return the type of a DAG operand with no name, such as
1612/// the F8RC register class argument in:
1613///
1614/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1615///
1616/// When Unnamed is false, return the type of a named DAG operand such as the
1617/// GPR:$src operand above.
1618///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001619static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
1620 bool NotRegisters,
1621 bool Unnamed,
1622 TreePattern &TP) {
1623 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1624
Owen Andersona84be6c2011-06-27 21:06:21 +00001625 // Check to see if this is a register operand.
1626 if (R->isSubClassOf("RegisterOperand")) {
1627 assert(ResNo == 0 && "Regoperand ref only has one result!");
1628 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001629 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00001630 Record *RegClass = R->getValueAsDef("RegClass");
1631 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001632 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00001633 }
1634
Chris Lattnercabe0372010-03-15 06:00:16 +00001635 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001636 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001637 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001638 // An unnamed register class represents itself as an i32 immediate, for
1639 // example on a COPY_TO_REGCLASS instruction.
1640 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001641 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001642
1643 // In a named operand, the register class provides the possible set of
1644 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001645 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001646 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00001647 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001648 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001649 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001650
Chris Lattner6070ee22010-03-23 23:50:31 +00001651 if (R->isSubClassOf("PatFrag")) {
1652 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001653 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001654 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001655 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001656
Chris Lattner6070ee22010-03-23 23:50:31 +00001657 if (R->isSubClassOf("Register")) {
1658 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001659 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001660 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001661 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001662 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001663 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001664
1665 if (R->isSubClassOf("SubRegIndex")) {
1666 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001667 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001668 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001669
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001670 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001671 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001672 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1673 //
1674 // (sext_inreg GPR:$src, i16)
1675 // ~~~
1676 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001677 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001678 // With a name, the ValueType simply provides the type of the named
1679 // variable.
1680 //
1681 // (sext_inreg i32:$src, i16)
1682 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001683 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001684 return TypeSetByHwMode(); // Unknown.
1685 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1686 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001687 }
1688
1689 if (R->isSubClassOf("CondCode")) {
1690 assert(ResNo == 0 && "This node only has one result!");
1691 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001692 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00001693 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001694
Chris Lattner6070ee22010-03-23 23:50:31 +00001695 if (R->isSubClassOf("ComplexPattern")) {
1696 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001697 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001698 return TypeSetByHwMode(); // Unknown.
1699 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00001700 }
1701 if (R->isSubClassOf("PointerLikeRegClass")) {
1702 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001703 TypeSetByHwMode VTS(MVT::iPTR);
1704 TP.getInfer().expandOverloads(VTS);
1705 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00001706 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001707
Chris Lattner6070ee22010-03-23 23:50:31 +00001708 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1709 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001710 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001711 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001712 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001713
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001714 if (R->isSubClassOf("Operand")) {
1715 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1716 Record *T = R->getValueAsDef("Type");
1717 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
1718 }
Tim Northoverc807a172014-05-20 11:52:46 +00001719
Chris Lattner8cab0212008-01-05 22:25:12 +00001720 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001721 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00001722}
1723
Chris Lattner89c65662008-01-06 05:36:50 +00001724
1725/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1726/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1727const CodeGenIntrinsic *TreePatternNode::
1728getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1729 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1730 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1731 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001732 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001733
Sean Silva88eb8dd2012-10-10 20:24:47 +00001734 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001735 return &CDP.getIntrinsicInfo(IID);
1736}
1737
Chris Lattner53c39ba2010-02-14 22:22:58 +00001738/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1739/// return the ComplexPattern information, otherwise return null.
1740const ComplexPattern *
1741TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001742 Record *Rec;
1743 if (isLeaf()) {
1744 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1745 if (!DI)
1746 return nullptr;
1747 Rec = DI->getDef();
1748 } else
1749 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001750
Tim Northoverc807a172014-05-20 11:52:46 +00001751 if (!Rec->isSubClassOf("ComplexPattern"))
1752 return nullptr;
1753 return &CGP.getComplexPattern(Rec);
1754}
1755
1756unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1757 // A ComplexPattern specifically declares how many results it fills in.
1758 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1759 return CP->getNumOperands();
1760
1761 // If MIOperandInfo is specified, that gives the count.
1762 if (isLeaf()) {
1763 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1764 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1765 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1766 if (MIOps->getNumArgs())
1767 return MIOps->getNumArgs();
1768 }
1769 }
1770
1771 // Otherwise there is just one result.
1772 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001773}
1774
1775/// NodeHasProperty - Return true if this node has the specified property.
1776bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001777 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001778 if (isLeaf()) {
1779 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1780 return CP->hasProperty(Property);
1781 return false;
1782 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001783
Chris Lattner53c39ba2010-02-14 22:22:58 +00001784 Record *Operator = getOperator();
1785 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001786
Chris Lattner53c39ba2010-02-14 22:22:58 +00001787 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1788}
1789
1790
1791
1792
1793/// TreeHasProperty - Return true if any node in this tree has the specified
1794/// property.
1795bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001796 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001797 if (NodeHasProperty(Property, CGP))
1798 return true;
1799 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1800 if (getChild(i)->TreeHasProperty(Property, CGP))
1801 return true;
1802 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001803}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001804
Evan Cheng49bad4c2008-06-16 20:29:38 +00001805/// isCommutativeIntrinsic - Return true if the node corresponds to a
1806/// commutative intrinsic.
1807bool
1808TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1809 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1810 return Int->isCommutative;
1811 return false;
1812}
1813
Matt Arsenaulteb492162014-11-02 23:46:51 +00001814static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1815 if (!N->isLeaf())
1816 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001817
Matt Arsenaulteb492162014-11-02 23:46:51 +00001818 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1819 if (DI && DI->getDef()->isSubClassOf(Class))
1820 return true;
1821
1822 return false;
1823}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001824
1825static void emitTooManyOperandsError(TreePattern &TP,
1826 StringRef InstName,
1827 unsigned Expected,
1828 unsigned Actual) {
1829 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1830 " operands but expected only " + Twine(Expected) + "!");
1831}
1832
1833static void emitTooFewOperandsError(TreePattern &TP,
1834 StringRef InstName,
1835 unsigned Actual) {
1836 TP.error("Instruction '" + InstName +
1837 "' expects more than the provided " + Twine(Actual) + " operands!");
1838}
1839
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001840/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001841/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001842/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001843bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001844 if (TP.hasError())
1845 return false;
1846
Chris Lattnerab3242f2008-01-06 01:10:31 +00001847 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001848 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001849 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001850 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001851 bool MadeChange = false;
1852 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1853 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001854 NotRegisters,
1855 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001856 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001857 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001858
Sean Silvafb509ed2012-10-10 20:24:43 +00001859 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001860 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001861
Chris Lattnerf1447252010-03-19 21:37:09 +00001862 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001863 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001864
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001865 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00001866 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001867
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001868 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
1869 for (auto &P : VVT) {
1870 MVT::SimpleValueType VT = P.second.SimpleTy;
1871 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1872 continue;
1873 unsigned Size = MVT(VT).getSizeInBits();
1874 // Make sure that the value is representable for this type.
1875 if (Size >= 32)
1876 continue;
1877 // Check that the value doesn't use more bits than we have. It must
1878 // either be a sign- or zero-extended equivalent of the original.
1879 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1880 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
1881 SignBitAndAbove == 1)
1882 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001883
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001884 TP.error("Integer value '" + itostr(II->getValue()) +
1885 "' is out of range for type '" + getEnumName(VT) + "'!");
1886 break;
1887 }
1888 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001889 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001890
Chris Lattner8cab0212008-01-05 22:25:12 +00001891 return false;
1892 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001893
Chris Lattner8cab0212008-01-05 22:25:12 +00001894 // special handling for set, which isn't really an SDNode.
1895 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001896 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1897 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001898 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001899
Chris Lattnerf1447252010-03-19 21:37:09 +00001900 TreePatternNode *SetVal = getChild(NC-1);
1901 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1902
Elena Demikhovsky09954792015-03-01 08:23:41 +00001903 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001904 TreePatternNode *Child = getChild(i);
1905 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001906
Chris Lattner8cab0212008-01-05 22:25:12 +00001907 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001908 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1909 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001910 }
1911 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001912 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001913
Chris Lattner5c2182e2010-03-27 02:53:27 +00001914 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001915 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1916
Chris Lattner8cab0212008-01-05 22:25:12 +00001917 bool MadeChange = false;
1918 for (unsigned i = 0; i < getNumChildren(); ++i)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001919 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001920 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001921 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001922
Chris Lattneree820ac2010-02-23 05:51:07 +00001923 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001924 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001925
Chris Lattner8cab0212008-01-05 22:25:12 +00001926 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001927 unsigned NumRetVTs = Int->IS.RetVTs.size();
1928 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001929
Bill Wendling91821472008-11-13 09:08:33 +00001930 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001931 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001932
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001933 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001934 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001935 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001936 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001937 return false;
1938 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001939
1940 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001941 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001942
Chris Lattnerf1447252010-03-19 21:37:09 +00001943 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1944 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001945
Chris Lattnerf1447252010-03-19 21:37:09 +00001946 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1947 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1948 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001949 }
1950 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001951 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001952
Chris Lattneree820ac2010-02-23 05:51:07 +00001953 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001954 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001955
Chris Lattner135091b2010-03-28 08:48:47 +00001956 // Check that the number of operands is sane. Negative operands -> varargs.
1957 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001958 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001959 TP.error(getOperator()->getName() + " node requires exactly " +
1960 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001961 return false;
1962 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001963
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001964 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001965 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1966 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001967 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001968 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001969 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001970
Chris Lattneree820ac2010-02-23 05:51:07 +00001971 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001972 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001973 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001974 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001975
Chris Lattnerd44966f2010-03-27 19:15:02 +00001976 bool MadeChange = false;
1977
1978 // Apply the result types to the node, these come from the things in the
1979 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00001980 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1981 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001982 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1983 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001984
Chris Lattnerd44966f2010-03-27 19:15:02 +00001985 // If the instruction has implicit defs, we apply the first one as a result.
1986 // FIXME: This sucks, it should apply all implicit defs.
1987 if (!InstInfo.ImplicitDefs.empty()) {
1988 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001989
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001990 // FIXME: Generalize to multiple possible types and multiple possible
1991 // ImplicitDefs.
1992 MVT::SimpleValueType VT =
1993 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001994
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001995 if (VT != MVT::Other)
1996 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001997 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001998
Chris Lattnercabe0372010-03-15 06:00:16 +00001999 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2000 // be the same.
2001 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00002002 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2003 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2004 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002005 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2006 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2007 // variadic.
2008
2009 unsigned NChild = getNumChildren();
2010 if (NChild < 3) {
2011 TP.error("REG_SEQUENCE requires at least 3 operands!");
2012 return false;
2013 }
2014
2015 if (NChild % 2 == 0) {
2016 TP.error("REG_SEQUENCE requires an odd number of operands!");
2017 return false;
2018 }
2019
2020 if (!isOperandClass(getChild(0), "RegisterClass")) {
2021 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2022 return false;
2023 }
2024
2025 for (unsigned I = 1; I < NChild; I += 2) {
2026 TreePatternNode *SubIdxChild = getChild(I + 1);
2027 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2028 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2029 itostr(I + 1) + "!");
2030 return false;
2031 }
2032 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002033 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002034
2035 unsigned ChildNo = 0;
2036 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2037 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002038
Chris Lattner8cab0212008-01-05 22:25:12 +00002039 // If the instruction expects a predicate or optional def operand, we
2040 // codegen this by setting the operand to it's default value if it has a
2041 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00002042 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002043 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2044 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002045
Chris Lattner8cab0212008-01-05 22:25:12 +00002046 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002047 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002048 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002049 return false;
2050 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002051
Chris Lattner8cab0212008-01-05 22:25:12 +00002052 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002053 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002054
2055 // If the operand has sub-operands, they may be provided by distinct
2056 // child patterns, so attempt to match each sub-operand separately.
2057 if (OperandNode->isSubClassOf("Operand")) {
2058 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2059 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2060 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002061 // a single ComplexPattern-related Operand.
2062
2063 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002064 // Match first sub-operand against the child we already have.
2065 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2066 MadeChange |=
2067 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2068
2069 // And the remaining sub-operands against subsequent children.
2070 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2071 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002072 emitTooFewOperandsError(TP, getOperator()->getName(),
2073 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002074 return false;
2075 }
2076 Child = getChild(ChildNo++);
2077
2078 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2079 MadeChange |=
2080 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2081 }
2082 continue;
2083 }
2084 }
2085 }
2086
2087 // If we didn't match by pieces above, attempt to match the whole
2088 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002089 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002090 }
Christopher Lamba7312392008-03-11 09:33:47 +00002091
Matt Arsenaulteb492162014-11-02 23:46:51 +00002092 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002093 emitTooManyOperandsError(TP, getOperator()->getName(),
2094 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002095 return false;
2096 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002097
Ulrich Weigande618abd2013-03-19 19:51:09 +00002098 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2099 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002100 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002101 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002102
Tim Northoverc807a172014-05-20 11:52:46 +00002103 if (getOperator()->isSubClassOf("ComplexPattern")) {
2104 bool MadeChange = false;
2105
2106 for (unsigned i = 0; i < getNumChildren(); ++i)
2107 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2108
2109 return MadeChange;
2110 }
2111
Chris Lattneree820ac2010-02-23 05:51:07 +00002112 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002113
Chris Lattneree820ac2010-02-23 05:51:07 +00002114 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002115 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002116 TP.error("Node transform '" + getOperator()->getName() +
2117 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002118 return false;
2119 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002120
Chris Lattnercabe0372010-03-15 06:00:16 +00002121 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002122 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002123}
2124
2125/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2126/// RHS of a commutative operation, not the on LHS.
2127static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2128 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
2129 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00002130 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002131 return true;
2132 return false;
2133}
2134
2135
2136/// canPatternMatch - If it is impossible for this pattern to match on this
2137/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002138/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002139/// that can never possibly work), and to prevent the pattern permuter from
2140/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002141bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002142 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002143 if (isLeaf()) return true;
2144
2145 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2146 if (!getChild(i)->canPatternMatch(Reason, CDP))
2147 return false;
2148
2149 // If this is an intrinsic, handle cases that would make it not match. For
2150 // example, if an operand is required to be an immediate.
2151 if (getOperator()->isSubClassOf("Intrinsic")) {
2152 // TODO:
2153 return true;
2154 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002155
Tim Northoverc807a172014-05-20 11:52:46 +00002156 if (getOperator()->isSubClassOf("ComplexPattern"))
2157 return true;
2158
Chris Lattner8cab0212008-01-05 22:25:12 +00002159 // If this node is a commutative operator, check that the LHS isn't an
2160 // immediate.
2161 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002162 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2163 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002164 // Scan all of the operands of the node and make sure that only the last one
2165 // is a constant node, unless the RHS also is.
2166 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002167 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002168 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002169 if (OnlyOnRHSOfCommutative(getChild(i))) {
2170 Reason="Immediate value must be on the RHS of commutative operators!";
2171 return false;
2172 }
2173 }
2174 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002175
Chris Lattner8cab0212008-01-05 22:25:12 +00002176 return true;
2177}
2178
2179//===----------------------------------------------------------------------===//
2180// TreePattern implementation
2181//
2182
David Greeneaf8ee2c2011-07-29 22:43:06 +00002183TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002184 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002185 isInputPattern(isInput), HasError(false),
2186 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002187 for (Init *I : RawPat->getValues())
2188 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002189}
2190
David Greeneaf8ee2c2011-07-29 22:43:06 +00002191TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002192 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002193 isInputPattern(isInput), HasError(false),
2194 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002195 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002196}
2197
David Blaikiecf195302014-11-17 22:55:41 +00002198TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002199 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002200 isInputPattern(isInput), HasError(false),
2201 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002202 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002203}
2204
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002205void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002206 if (HasError)
2207 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002208 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002209 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2210 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002211}
2212
Chris Lattnercabe0372010-03-15 06:00:16 +00002213void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00002214 for (TreePatternNode *Tree : Trees)
2215 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00002216}
2217
2218void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2219 if (!N->getName().empty())
2220 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002221
Chris Lattnercabe0372010-03-15 06:00:16 +00002222 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2223 ComputeNamedNodes(N->getChild(i));
2224}
2225
David Blaikiecf195302014-11-17 22:55:41 +00002226
2227TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002228 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002229 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002230
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002231 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002232 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002233 /// (foo GPR, imm) -> (foo GPR, (imm))
2234 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002235 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002236 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002237 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002238 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002239
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002240 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002241 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002242 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002243 if (OpName.empty())
2244 error("'node' argument requires a name to match with operand list");
2245 Args.push_back(OpName);
2246 }
2247
2248 Res->setName(OpName);
2249 return Res;
2250 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002251
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002252 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002253 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002254 if (OpName.empty())
2255 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002256 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002257 Args.push_back(OpName);
2258 Res->setName(OpName);
2259 return Res;
2260 }
2261
Sean Silvafb509ed2012-10-10 20:24:43 +00002262 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002263 if (!OpName.empty())
2264 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002265 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002266 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002267
Sean Silvafb509ed2012-10-10 20:24:43 +00002268 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002269 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002270 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002271 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002272 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002273 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002274 }
2275
Sean Silvafb509ed2012-10-10 20:24:43 +00002276 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002277 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002278 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002279 error("Pattern has unexpected init kind!");
2280 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002281 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002282 if (!OpDef) error("Pattern has unexpected operator type!");
2283 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002284
Chris Lattner8cab0212008-01-05 22:25:12 +00002285 if (Operator->isSubClassOf("ValueType")) {
2286 // If the operator is a ValueType, then this must be "type cast" of a leaf
2287 // node.
2288 if (Dag->getNumArgs() != 1)
2289 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002290
Matthias Braunbb053162016-12-05 06:00:46 +00002291 TreePatternNode *New = ParseTreePattern(Dag->getArg(0),
2292 Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002293
Chris Lattner8cab0212008-01-05 22:25:12 +00002294 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002295 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002296 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2297 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002298
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002299 if (!OpName.empty())
2300 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002301 return New;
2302 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002303
Chris Lattner8cab0212008-01-05 22:25:12 +00002304 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002305 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002306 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002307 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002308 !Operator->isSubClassOf("SDNodeXForm") &&
2309 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002310 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002311 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002312 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002313 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002314
Chris Lattner8cab0212008-01-05 22:25:12 +00002315 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002316 if (isInputPattern) {
2317 if (Operator->isSubClassOf("Instruction") ||
2318 Operator->isSubClassOf("SDNodeXForm"))
2319 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2320 } else {
2321 if (Operator->isSubClassOf("Intrinsic"))
2322 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002323
Chris Lattner2e9eae12010-03-28 06:57:56 +00002324 if (Operator->isSubClassOf("SDNode") &&
2325 Operator->getName() != "imm" &&
2326 Operator->getName() != "fpimm" &&
2327 Operator->getName() != "tglobaltlsaddr" &&
2328 Operator->getName() != "tconstpool" &&
2329 Operator->getName() != "tjumptable" &&
2330 Operator->getName() != "tframeindex" &&
2331 Operator->getName() != "texternalsym" &&
2332 Operator->getName() != "tblockaddress" &&
2333 Operator->getName() != "tglobaladdr" &&
2334 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002335 Operator->getName() != "vt" &&
2336 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002337 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2338 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002339
Chris Lattner8cab0212008-01-05 22:25:12 +00002340 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002341
2342 // Parse all the operands.
2343 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002344 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002345
Chris Lattner8cab0212008-01-05 22:25:12 +00002346 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002347 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002348 // convert the intrinsic name to a number.
2349 if (Operator->isSubClassOf("Intrinsic")) {
2350 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2351 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2352
2353 // If this intrinsic returns void, it must have side-effects and thus a
2354 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002355 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002356 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002357 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002358 // Has side-effects, requires chain.
2359 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002360 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002361 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002362
David Greenee32ebf22011-07-29 19:07:07 +00002363 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002364 Children.insert(Children.begin(), IIDNode);
2365 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002366
Tim Northoverc807a172014-05-20 11:52:46 +00002367 if (Operator->isSubClassOf("ComplexPattern")) {
2368 for (unsigned i = 0; i < Children.size(); ++i) {
2369 TreePatternNode *Child = Children[i];
2370
2371 if (Child->getName().empty())
2372 error("All arguments to a ComplexPattern must be named");
2373
2374 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2375 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2376 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2377 auto OperandId = std::make_pair(Operator, i);
2378 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2379 if (PrevOp != ComplexPatternOperands.end()) {
2380 if (PrevOp->getValue() != OperandId)
2381 error("All ComplexPattern operands must appear consistently: "
2382 "in the same order in just one ComplexPattern instance.");
2383 } else
2384 ComplexPatternOperands[Child->getName()] = OperandId;
2385 }
2386 }
2387
Chris Lattnerf1447252010-03-19 21:37:09 +00002388 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002389 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002390 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002391
Matthias Braun7cf3b112016-12-05 06:00:41 +00002392 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002393 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002394 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002395 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002396 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002397}
2398
Chris Lattnera787c9e2010-03-28 08:38:32 +00002399/// SimplifyTree - See if we can simplify this tree to eliminate something that
2400/// will never match in favor of something obvious that will. This is here
2401/// strictly as a convenience to target authors because it allows them to write
2402/// more type generic things and have useless type casts fold away.
2403///
2404/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002405static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002406 if (N->isLeaf())
2407 return false;
2408
2409 // If we have a bitconvert with a resolved type and if the source and
2410 // destination types are the same, then the bitconvert is useless, remove it.
2411 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002412 N->getExtType(0).isValueTypeByHwMode(false) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002413 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2414 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002415 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002416 SimplifyTree(N);
2417 return true;
2418 }
2419
2420 // Walk all children.
2421 bool MadeChange = false;
2422 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002423 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002424 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002425 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002426 }
2427 return MadeChange;
2428}
2429
2430
2431
Chris Lattner8cab0212008-01-05 22:25:12 +00002432/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002433/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002434/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002435bool TreePattern::
2436InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2437 if (NamedNodes.empty())
2438 ComputeNamedNodes();
2439
Chris Lattner8cab0212008-01-05 22:25:12 +00002440 bool MadeChange = true;
2441 while (MadeChange) {
2442 MadeChange = false;
Craig Topper3f7864e2017-08-30 02:05:03 +00002443 for (TreePatternNode *&Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002444 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2445 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002446 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002447
2448 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002449 for (auto &Entry : NamedNodes) {
2450 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002451
Chris Lattnercabe0372010-03-15 06:00:16 +00002452 // If we have input named node types, propagate their types to the named
2453 // values here.
2454 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002455 if (!InNamedTypes->count(Entry.getKey())) {
2456 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002457 "' in output pattern but not input pattern");
2458 return true;
2459 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002460
2461 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002462 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002463
2464 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002465 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002466 // If this node is a register class, and it is the root of the pattern
2467 // then we're mapping something onto an input register. We allow
2468 // changing the type of the input register in this case. This allows
2469 // us to match things like:
2470 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002471 if (Node == Trees[0] && Node->isLeaf()) {
2472 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002473 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2474 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002475 continue;
2476 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002477
Craig Topper306cb122015-11-22 20:46:24 +00002478 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002479 InNodes[0]->getNumTypes() == 1 &&
2480 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002481 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2482 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002483 }
2484 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002485
Chris Lattnercabe0372010-03-15 06:00:16 +00002486 // If there are multiple nodes with the same name, they must all have the
2487 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002488 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002489 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002490 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002491 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002492 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002493
Chris Lattnerf1447252010-03-19 21:37:09 +00002494 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2495 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002496 }
2497 }
2498 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002499 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002500
Chris Lattner8cab0212008-01-05 22:25:12 +00002501 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002502 for (const TreePatternNode *Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002503 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002504 return !HasUnresolvedTypes;
2505}
2506
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002507void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002508 OS << getRecord()->getName();
2509 if (!Args.empty()) {
2510 OS << "(" << Args[0];
2511 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2512 OS << ", " << Args[i];
2513 OS << ")";
2514 }
2515 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002516
Chris Lattner8cab0212008-01-05 22:25:12 +00002517 if (Trees.size() > 1)
2518 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002519 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002520 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002521 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002522 OS << "\n";
2523 }
2524
2525 if (Trees.size() > 1)
2526 OS << "]\n";
2527}
2528
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002529void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002530
2531//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002532// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002533//
2534
Jim Grosbach65586fe2010-12-21 16:16:00 +00002535CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002536 Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002537
Justin Bogner92a8c612016-07-15 16:31:37 +00002538 Intrinsics = CodeGenIntrinsicTable(Records, false);
2539 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002540 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002541 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002542 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002543 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002544 ParseDefaultOperands();
2545 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002546 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002547 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002548
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002549 // Break patterns with parameterized types into a series of patterns,
2550 // where each one has a fixed type and is predicated on the conditions
2551 // of the associated HW mode.
2552 ExpandHwModeBasedTypes();
2553
Chris Lattner8cab0212008-01-05 22:25:12 +00002554 // Generate variants. For example, commutative patterns can match
2555 // multiple ways. Add them to PatternsToMatch as well.
2556 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002557
2558 // Infer instruction flags. For example, we can detect loads,
2559 // stores, and side effects in many cases by examining an
2560 // instruction's pattern.
2561 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002562
2563 // Verify that instruction flags match the patterns.
2564 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002565}
2566
Chris Lattnerab3242f2008-01-06 01:10:31 +00002567Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002568 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002569 if (!N || !N->isSubClassOf("SDNode"))
2570 PrintFatalError("Error getting SDNode '" + Name + "'!");
2571
Chris Lattner8cab0212008-01-05 22:25:12 +00002572 return N;
2573}
2574
2575// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002576void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002577 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002578 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2579
Chris Lattner8cab0212008-01-05 22:25:12 +00002580 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002581 Record *R = Nodes.back();
2582 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002583 Nodes.pop_back();
2584 }
2585
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002586 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002587 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2588 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2589 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2590}
2591
2592/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2593/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002594void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002595 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2596 while (!Xforms.empty()) {
2597 Record *XFormNode = Xforms.back();
2598 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00002599 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002600 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002601
2602 Xforms.pop_back();
2603 }
2604}
2605
Chris Lattnerab3242f2008-01-06 01:10:31 +00002606void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002607 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2608 while (!AMs.empty()) {
2609 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2610 AMs.pop_back();
2611 }
2612}
2613
2614
2615/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2616/// file, building up the PatternFragments map. After we've collected them all,
2617/// inline fragments together as necessary, so that there are no references left
2618/// inside a pattern fragment to a pattern fragment.
2619///
Hal Finkel2756dc12014-02-28 00:26:56 +00002620void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002621 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002622
Chris Lattnere7170df2008-01-05 22:43:57 +00002623 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002624 for (Record *Frag : Fragments) {
2625 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002626 continue;
2627
Craig Topper306cb122015-11-22 20:46:24 +00002628 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002629 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002630 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2631 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002632 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002633
Chris Lattnere7170df2008-01-05 22:43:57 +00002634 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002635 std::vector<std::string> &Args = P->getArgList();
Zachary Turner249dc142017-09-20 18:01:40 +00002636 // Copy the args so we can take StringRefs to them.
2637 auto ArgsCopy = Args;
2638 SmallDenseSet<StringRef, 4> OperandsSet;
2639 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002640
Chris Lattnere7170df2008-01-05 22:43:57 +00002641 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002642 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002643
Chris Lattner8cab0212008-01-05 22:25:12 +00002644 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002645 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002646 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002647 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002648 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002649 if (!OpsOp ||
2650 (OpsOp->getDef()->getName() != "ops" &&
2651 OpsOp->getDef()->getName() != "outs" &&
2652 OpsOp->getDef()->getName() != "ins"))
2653 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002654
2655 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002656 Args.clear();
2657 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002658 if (!isa<DefInit>(OpsList->getArg(j)) ||
2659 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002660 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00002661 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00002662 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00002663 StringRef ArgNameStr = OpsList->getArgNameStr(j);
2664 if (!OperandsSet.count(ArgNameStr))
2665 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00002666 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00002667 OperandsSet.erase(ArgNameStr);
2668 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00002669 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002670
Chris Lattnere7170df2008-01-05 22:43:57 +00002671 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002672 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002673 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002674
Chris Lattnere7170df2008-01-05 22:43:57 +00002675 // If there is a code init for this fragment, keep track of the fact that
2676 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002677 TreePredicateFn PredFn(P);
2678 if (!PredFn.isAlwaysTrue())
2679 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002680
Chris Lattner8cab0212008-01-05 22:25:12 +00002681 // If there is a node transformation corresponding to this, keep track of
2682 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002683 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002684 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2685 P->getOnlyTree()->setTransformFn(Transform);
2686 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002687
Chris Lattner8cab0212008-01-05 22:25:12 +00002688 // Now that we've parsed all of the tree fragments, do a closure on them so
2689 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002690 for (Record *Frag : Fragments) {
2691 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002692 continue;
2693
Craig Topper306cb122015-11-22 20:46:24 +00002694 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002695 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002696
Chris Lattner8cab0212008-01-05 22:25:12 +00002697 // Infer as many types as possible. Don't worry about it if we don't infer
2698 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002699 ThePat.InferAllTypes();
2700 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002701
Chris Lattner8cab0212008-01-05 22:25:12 +00002702 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002703 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002704 }
2705}
2706
Chris Lattnerab3242f2008-01-06 01:10:31 +00002707void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002708 std::vector<Record*> DefaultOps;
2709 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002710
2711 // Find some SDNode.
2712 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002713 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002714
Tom Stellardb7246a72012-09-06 14:15:52 +00002715 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2716 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002717
Tom Stellardb7246a72012-09-06 14:15:52 +00002718 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2719 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00002720 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00002721 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2722 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2723 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00002724 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002725
Tom Stellardb7246a72012-09-06 14:15:52 +00002726 // Create a TreePattern to parse this.
2727 TreePattern P(DefaultOps[i], DI, false, *this);
2728 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002729
Tom Stellardb7246a72012-09-06 14:15:52 +00002730 // Copy the operands over into a DAGDefaultOperand.
2731 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002732
Tom Stellardb7246a72012-09-06 14:15:52 +00002733 TreePatternNode *T = P.getTree(0);
2734 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2735 TreePatternNode *TPN = T->getChild(op);
2736 while (TPN->ApplyTypeConstraints(P, false))
2737 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002738
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002739 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002740 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2741 DefaultOps[i]->getName() +
2742 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002743 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002744 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002745 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002746
2747 // Insert it into the DefaultOperands map so we can find it later.
2748 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002749 }
2750}
2751
2752/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2753/// instruction input. Return true if this is a real use.
2754static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002755 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002756 // No name -> not interesting.
2757 if (Pat->getName().empty()) {
2758 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002759 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002760 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2761 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002762 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002763 }
2764 return false;
2765 }
2766
2767 Record *Rec;
2768 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002769 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002770 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2771 Rec = DI->getDef();
2772 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002773 Rec = Pat->getOperator();
2774 }
2775
2776 // SRCVALUE nodes are ignored.
2777 if (Rec->getName() == "srcvalue")
2778 return false;
2779
2780 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2781 if (!Slot) {
2782 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002783 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002784 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002785 Record *SlotRec;
2786 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002787 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002788 } else {
2789 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2790 SlotRec = Slot->getOperator();
2791 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002792
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002793 // Ensure that the inputs agree if we've already seen this input.
2794 if (Rec != SlotRec)
2795 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002796 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002797 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002798 return true;
2799}
2800
2801/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2802/// part of "I", the instruction), computing the set of inputs and outputs of
2803/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002804void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002805FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2806 std::map<std::string, TreePatternNode*> &InstInputs,
2807 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002808 std::vector<Record*> &InstImpResults) {
2809 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002810 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002811 if (!isUse && Pat->getTransformFn())
2812 I->error("Cannot specify a transform function for a non-input value!");
2813 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002814 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002815
Chris Lattnerf2d70992010-02-17 06:53:36 +00002816 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002817 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2818 TreePatternNode *Dest = Pat->getChild(i);
2819 if (!Dest->isLeaf())
2820 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002821
Sean Silvafb509ed2012-10-10 20:24:43 +00002822 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002823 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2824 I->error("implicitly defined value should be a register!");
2825 InstImpResults.push_back(Val->getDef());
2826 }
2827 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002828 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002829
Chris Lattnerf2d70992010-02-17 06:53:36 +00002830 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002831 // If this is not a set, verify that the children nodes are not void typed,
2832 // and recurse.
2833 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002834 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002835 I->error("Cannot have void nodes inside of patterns!");
2836 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002837 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002838 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002839
Chris Lattner8cab0212008-01-05 22:25:12 +00002840 // If this is a non-leaf node with no children, treat it basically as if
2841 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002842 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002843
Chris Lattner8cab0212008-01-05 22:25:12 +00002844 if (!isUse && Pat->getTransformFn())
2845 I->error("Cannot specify a transform function for a non-input value!");
2846 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002847 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002848
Chris Lattner8cab0212008-01-05 22:25:12 +00002849 // Otherwise, this is a set, validate and collect instruction results.
2850 if (Pat->getNumChildren() == 0)
2851 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002852
Chris Lattner8cab0212008-01-05 22:25:12 +00002853 if (Pat->getTransformFn())
2854 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002855
Chris Lattner8cab0212008-01-05 22:25:12 +00002856 // Check the set destinations.
2857 unsigned NumDests = Pat->getNumChildren()-1;
2858 for (unsigned i = 0; i != NumDests; ++i) {
2859 TreePatternNode *Dest = Pat->getChild(i);
2860 if (!Dest->isLeaf())
2861 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002862
Sean Silvafb509ed2012-10-10 20:24:43 +00002863 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002864 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002865 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002866 continue;
2867 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002868
2869 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002870 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002871 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002872 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002873 if (Dest->getName().empty())
2874 I->error("set destination must have a name!");
2875 if (InstResults.count(Dest->getName()))
2876 I->error("cannot set '" + Dest->getName() +"' multiple times");
2877 InstResults[Dest->getName()] = Dest;
2878 } else if (Val->getDef()->isSubClassOf("Register")) {
2879 InstImpResults.push_back(Val->getDef());
2880 } else {
2881 I->error("set destination should be a register!");
2882 }
2883 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002884
Chris Lattner8cab0212008-01-05 22:25:12 +00002885 // Verify and collect info from the computation.
2886 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002887 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002888}
2889
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002890//===----------------------------------------------------------------------===//
2891// Instruction Analysis
2892//===----------------------------------------------------------------------===//
2893
2894class InstAnalyzer {
2895 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002896public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002897 bool hasSideEffects;
2898 bool mayStore;
2899 bool mayLoad;
2900 bool isBitcast;
2901 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002902
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002903 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2904 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2905 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002906
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002907 void Analyze(const TreePattern *Pat) {
2908 // Assume only the first tree is the pattern. The others are clobber nodes.
2909 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002910 }
2911
Craig Topper2a053a92017-06-20 16:34:37 +00002912 void Analyze(const PatternToMatch &Pat) {
2913 AnalyzeNode(Pat.getSrcPattern());
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002914 }
2915
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002916private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002917 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002918 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002919 return false;
2920
2921 if (N->getNumChildren() != 2)
2922 return false;
2923
2924 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002925 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002926 return false;
2927
2928 const TreePatternNode *N1 = N->getChild(1);
2929 if (N1->isLeaf())
2930 return false;
2931 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2932 return false;
2933
2934 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2935 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2936 return false;
2937 return OpInfo.getEnumName() == "ISD::BITCAST";
2938 }
2939
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002940public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002941 void AnalyzeNode(const TreePatternNode *N) {
2942 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002943 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002944 Record *LeafRec = DI->getDef();
2945 // Handle ComplexPattern leaves.
2946 if (LeafRec->isSubClassOf("ComplexPattern")) {
2947 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2948 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2949 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002950 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002951 }
2952 }
2953 return;
2954 }
2955
2956 // Analyze children.
2957 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2958 AnalyzeNode(N->getChild(i));
2959
2960 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002961 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002962 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002963 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002964 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002965
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002966 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002967 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2968 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2969 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2970 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002971
2972 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2973 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002974 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002975 mayLoad = true;// These may load memory.
2976
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002977 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002978 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2979
Matt Arsenault868af922017-04-28 21:01:46 +00002980 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
2981 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002982 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002983 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002984 }
2985 }
2986
2987};
2988
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002989static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002990 const InstAnalyzer &PatInfo,
2991 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002992 bool Error = false;
2993
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002994 // Remember where InstInfo got its flags.
2995 if (InstInfo.hasUndefFlags())
2996 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002997
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002998 // Check explicitly set flags for consistency.
2999 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3000 !InstInfo.hasSideEffects_Unset) {
3001 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3002 // the pattern has no side effects. That could be useful for div/rem
3003 // instructions that may trap.
3004 if (!InstInfo.hasSideEffects) {
3005 Error = true;
3006 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3007 Twine(InstInfo.hasSideEffects));
3008 }
3009 }
3010
3011 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3012 Error = true;
3013 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3014 Twine(InstInfo.mayStore));
3015 }
3016
3017 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3018 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003019 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003020 if (!InstInfo.mayLoad) {
3021 Error = true;
3022 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3023 Twine(InstInfo.mayLoad));
3024 }
3025 }
3026
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003027 // Transfer inferred flags.
3028 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3029 InstInfo.mayStore |= PatInfo.mayStore;
3030 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003031
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003032 // These flags are silently added without any verification.
3033 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003034
3035 // Don't infer isVariadic. This flag means something different on SDNodes and
3036 // instructions. For example, a CALL SDNode is variadic because it has the
3037 // call arguments as operands, but a CALL instruction is not variadic - it
3038 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003039
3040 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003041}
3042
Jim Grosbach514410b2012-07-17 00:47:06 +00003043/// hasNullFragReference - Return true if the DAG has any reference to the
3044/// null_frag operator.
3045static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003046 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003047 if (!OpDef) return false;
3048 Record *Operator = OpDef->getDef();
3049
3050 // If this is the null fragment, return true.
3051 if (Operator->getName() == "null_frag") return true;
3052 // If any of the arguments reference the null fragment, return true.
3053 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003054 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003055 if (Arg && hasNullFragReference(Arg))
3056 return true;
3057 }
3058
3059 return false;
3060}
3061
3062/// hasNullFragReference - Return true if any DAG in the list references
3063/// the null_frag operator.
3064static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003065 for (Init *I : LI->getValues()) {
3066 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003067 assert(DI && "non-dag in an instruction Pattern list?!");
3068 if (hasNullFragReference(DI))
3069 return true;
3070 }
3071 return false;
3072}
3073
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003074/// Get all the instructions in a tree.
3075static void
3076getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3077 if (Tree->isLeaf())
3078 return;
3079 if (Tree->getOperator()->isSubClassOf("Instruction"))
3080 Instrs.push_back(Tree->getOperator());
3081 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3082 getInstructionsInTree(Tree->getChild(i), Instrs);
3083}
3084
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003085/// Check the class of a pattern leaf node against the instruction operand it
3086/// represents.
3087static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3088 Record *Leaf) {
3089 if (OI.Rec == Leaf)
3090 return true;
3091
3092 // Allow direct value types to be used in instruction set patterns.
3093 // The type will be checked later.
3094 if (Leaf->isSubClassOf("ValueType"))
3095 return true;
3096
3097 // Patterns can also be ComplexPattern instances.
3098 if (Leaf->isSubClassOf("ComplexPattern"))
3099 return true;
3100
3101 return false;
3102}
3103
Ahmed Bougacha14107512013-10-28 18:07:21 +00003104const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
3105 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003106
Craig Topper0d1fb902015-03-10 03:25:04 +00003107 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003108
Craig Topper0d1fb902015-03-10 03:25:04 +00003109 // Parse the instruction.
3110 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
3111 // Inline pattern fragments into it.
3112 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003113
Craig Topper0d1fb902015-03-10 03:25:04 +00003114 // Infer as many types as possible. If we cannot infer all of them, we can
3115 // never do anything with this instruction pattern: report it to the user.
3116 if (!I->InferAllTypes())
3117 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003118
Craig Topper0d1fb902015-03-10 03:25:04 +00003119 // InstInputs - Keep track of all of the inputs of the instruction, along
3120 // with the record they are declared as.
3121 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003122
Craig Topper0d1fb902015-03-10 03:25:04 +00003123 // InstResults - Keep track of all the virtual registers that are 'set'
3124 // in the instruction, including what reg class they are.
3125 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003126
Craig Topper0d1fb902015-03-10 03:25:04 +00003127 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003128
Craig Topper0d1fb902015-03-10 03:25:04 +00003129 // Verify that the top-level forms in the instruction are of void type, and
3130 // fill in the InstResults map.
Zachary Turner249dc142017-09-20 18:01:40 +00003131 SmallString<32> TypesString;
Craig Topper0d1fb902015-03-10 03:25:04 +00003132 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
Zachary Turner249dc142017-09-20 18:01:40 +00003133 TypesString.clear();
Craig Topper0d1fb902015-03-10 03:25:04 +00003134 TreePatternNode *Pat = I->getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003135 if (Pat->getNumTypes() != 0) {
Zachary Turner249dc142017-09-20 18:01:40 +00003136 raw_svector_ostream OS(TypesString);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003137 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3138 if (k > 0)
Zachary Turner249dc142017-09-20 18:01:40 +00003139 OS << ", ";
3140 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003141 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003142 I->error("Top-level forms in instruction pattern should have"
Zachary Turner249dc142017-09-20 18:01:40 +00003143 " void types, has types " +
3144 OS.str());
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003145 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003146
Craig Topper0d1fb902015-03-10 03:25:04 +00003147 // Find inputs and outputs, and verify the structure of the uses/defs.
3148 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3149 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003150 }
3151
Craig Topper0d1fb902015-03-10 03:25:04 +00003152 // Now that we have inputs and outputs of the pattern, inspect the operands
3153 // list for the instruction. This determines the order that operands are
3154 // added to the machine instruction the node corresponds to.
3155 unsigned NumResults = InstResults.size();
3156
3157 // Parse the operands list from the (ops) list, validating it.
3158 assert(I->getArgList().empty() && "Args list should still be empty here!");
3159
3160 // Check that all of the results occur first in the list.
3161 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00003162 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003163 for (unsigned i = 0; i != NumResults; ++i) {
3164 if (i == CGI.Operands.size())
3165 I->error("'" + InstResults.begin()->first +
3166 "' set but does not appear in operand list!");
3167 const std::string &OpName = CGI.Operands[i].Name;
3168
3169 // Check that it exists in InstResults.
3170 TreePatternNode *RNode = InstResults[OpName];
3171 if (!RNode)
3172 I->error("Operand $" + OpName + " does not exist in operand list!");
3173
Craig Topper3a8eb892015-03-20 05:09:06 +00003174 ResNodes.push_back(RNode);
3175
Craig Topper0d1fb902015-03-10 03:25:04 +00003176 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3177 if (!R)
3178 I->error("Operand $" + OpName + " should be a set destination: all "
3179 "outputs must occur before inputs in operand list!");
3180
3181 if (!checkOperandClass(CGI.Operands[i], R))
3182 I->error("Operand $" + OpName + " class mismatch!");
3183
3184 // Remember the return type.
3185 Results.push_back(CGI.Operands[i].Rec);
3186
3187 // Okay, this one checks out.
3188 InstResults.erase(OpName);
3189 }
3190
3191 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3192 // the copy while we're checking the inputs.
3193 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3194
3195 std::vector<TreePatternNode*> ResultNodeOperands;
3196 std::vector<Record*> Operands;
3197 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3198 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3199 const std::string &OpName = Op.Name;
3200 if (OpName.empty())
3201 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3202
3203 if (!InstInputsCheck.count(OpName)) {
3204 // If this is an operand with a DefaultOps set filled in, we can ignore
3205 // this. When we codegen it, we will do so as always executed.
3206 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3207 // Does it have a non-empty DefaultOps field? If so, ignore this
3208 // operand.
3209 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3210 continue;
3211 }
3212 I->error("Operand $" + OpName +
3213 " does not appear in the instruction pattern");
3214 }
3215 TreePatternNode *InVal = InstInputsCheck[OpName];
3216 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3217
3218 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3219 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3220 if (!checkOperandClass(Op, InRec))
3221 I->error("Operand $" + OpName + "'s register class disagrees"
3222 " between the operand and pattern");
3223 }
3224 Operands.push_back(Op.Rec);
3225
3226 // Construct the result for the dest-pattern operand list.
3227 TreePatternNode *OpNode = InVal->clone();
3228
3229 // No predicate is useful on the result.
3230 OpNode->clearPredicateFns();
3231
3232 // Promote the xform function to be an explicit node if set.
3233 if (Record *Xform = OpNode->getTransformFn()) {
3234 OpNode->setTransformFn(nullptr);
3235 std::vector<TreePatternNode*> Children;
3236 Children.push_back(OpNode);
3237 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3238 }
3239
3240 ResultNodeOperands.push_back(OpNode);
3241 }
3242
3243 if (!InstInputsCheck.empty())
3244 I->error("Input operand $" + InstInputsCheck.begin()->first +
3245 " occurs in pattern but not in operands list!");
3246
3247 TreePatternNode *ResultPattern =
3248 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3249 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003250 // Copy fully inferred output node types to instruction result pattern.
3251 for (unsigned i = 0; i != NumResults; ++i) {
3252 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3253 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3254 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003255
3256 // Create and insert the instruction.
3257 // FIXME: InstImpResults should not be part of DAGInstruction.
3258 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3259 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3260
3261 // Use a temporary tree pattern to infer all types and make sure that the
3262 // constructed result is correct. This depends on the instruction already
3263 // being inserted into the DAGInsts map.
3264 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3265 Temp.InferAllTypes(&I->getNamedNodesMap());
3266
3267 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3268 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3269
3270 return TheInsertedInst;
3271}
3272
Ahmed Bougacha14107512013-10-28 18:07:21 +00003273/// ParseInstructions - Parse all of the instructions, inlining and resolving
3274/// any fragments involved. This populates the Instructions list with fully
3275/// resolved instructions.
3276void CodeGenDAGPatterns::ParseInstructions() {
3277 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3278
Craig Topper306cb122015-11-22 20:46:24 +00003279 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003280 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003281
Craig Topper306cb122015-11-22 20:46:24 +00003282 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3283 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003284
3285 // If there is no pattern, only collect minimal information about the
3286 // instruction for its operand list. We have to assume that there is one
3287 // result, as we have no detailed info. A pattern which references the
3288 // null_frag operator is as-if no pattern were specified. Normally this
3289 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3290 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003291 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003292 std::vector<Record*> Results;
3293 std::vector<Record*> Operands;
3294
Craig Topper306cb122015-11-22 20:46:24 +00003295 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003296
3297 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003298 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3299 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003300
Craig Topper3a8eb892015-03-20 05:09:06 +00003301 // The rest are inputs.
3302 for (unsigned j = InstInfo.Operands.NumDefs,
3303 e = InstInfo.Operands.size(); j < e; ++j)
3304 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003305 }
3306
3307 // Create and insert the instruction.
3308 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003309 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003310 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003311 continue; // no pattern.
3312 }
3313
Craig Topper306cb122015-11-22 20:46:24 +00003314 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003315 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3316
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003317 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003318 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003319 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003320
Chris Lattner8cab0212008-01-05 22:25:12 +00003321 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003322 for (auto &Entry : Instructions) {
3323 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003324 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003325 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003326
3327 // FIXME: Assume only the first tree is the pattern. The others are clobber
3328 // nodes.
3329 TreePatternNode *Pattern = I->getTree(0);
3330 TreePatternNode *SrcPattern;
3331 if (Pattern->getOperator()->getName() == "set") {
3332 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3333 } else{
3334 // Not a set (store or something?)
3335 SrcPattern = Pattern;
3336 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003337
Craig Topper306cb122015-11-22 20:46:24 +00003338 Record *Instr = Entry.first;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003339 ListInit *Preds = Instr->getValueAsListInit("Predicates");
3340 int Complexity = Instr->getValueAsInt("AddedComplexity");
3341 AddPatternToMatch(
3342 I,
3343 PatternToMatch(Instr, makePredList(Preds), SrcPattern,
3344 TheInst.getResultPattern(), TheInst.getImpResults(),
3345 Complexity, Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003346 }
3347}
3348
Chris Lattnera7722b62010-02-23 06:55:24 +00003349
3350typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3351
Jim Grosbach65586fe2010-12-21 16:16:00 +00003352static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003353 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003354 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003355 if (!P->getName().empty()) {
3356 NameRecord &Rec = Names[P->getName()];
3357 // If this is the first instance of the name, remember the node.
3358 if (Rec.second++ == 0)
3359 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003360 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003361 PatternTop->error("repetition of value: $" + P->getName() +
3362 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003363 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003364
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003365 if (!P->isLeaf()) {
3366 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003367 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003368 }
3369}
3370
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003371std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3372 std::vector<Predicate> Preds;
3373 for (Init *I : L->getValues()) {
3374 if (DefInit *Pred = dyn_cast<DefInit>(I))
3375 Preds.push_back(Pred->getDef());
3376 else
3377 llvm_unreachable("Non-def on the list");
3378 }
3379
3380 // Sort so that different orders get canonicalized to the same string.
3381 std::sort(Preds.begin(), Preds.end());
3382 return Preds;
3383}
3384
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003385void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003386 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003387 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003388 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003389 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3390 PrintWarning(Pattern->getRecord()->getLoc(),
3391 Twine("Pattern can never match: ") + Reason);
3392 return;
3393 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003394
Chris Lattner1e634e32010-03-01 22:29:19 +00003395 // If the source pattern's root is a complex pattern, that complex pattern
3396 // must specify the nodes it can potentially match.
3397 if (const ComplexPattern *CP =
3398 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3399 if (CP->getRootNodes().empty())
3400 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3401 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003402
3403
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003404 // Find all of the named values in the input and output, ensure they have the
3405 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003406 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003407 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3408 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003409
3410 // Scan all of the named values in the destination pattern, rejecting them if
3411 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003412 for (const auto &Entry : DstNames) {
3413 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003414 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003415 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003416 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003417
Chris Lattnera7722b62010-02-23 06:55:24 +00003418 // Scan all of the named values in the source pattern, rejecting them if the
3419 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003420 for (const auto &Entry : SrcNames)
3421 if (DstNames[Entry.first].first == nullptr &&
3422 SrcNames[Entry.first].second == 1)
3423 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003424
Craig Topper18e6b572017-06-25 17:33:49 +00003425 PatternsToMatch.push_back(std::move(PTM));
Chris Lattner0c0baa92010-02-23 06:16:51 +00003426}
3427
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003428void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003429 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003430 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003431
3432 // First try to infer flags from the primary instruction pattern, if any.
3433 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003434 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003435 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3436 CodeGenInstruction &InstInfo =
3437 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003438
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003439 // Get the primary instruction pattern.
3440 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3441 if (!Pattern) {
3442 if (InstInfo.hasUndefFlags())
3443 Revisit.push_back(&InstInfo);
3444 continue;
3445 }
3446 InstAnalyzer PatInfo(*this);
3447 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003448 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003449 }
3450
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003451 // Second, look for single-instruction patterns defined outside the
3452 // instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003453 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003454 // We can only infer from single-instruction patterns, otherwise we won't
3455 // know which instruction should get the flags.
3456 SmallVector<Record*, 8> PatInstrs;
3457 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3458 if (PatInstrs.size() != 1)
3459 continue;
3460
3461 // Get the single instruction.
3462 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3463
3464 // Only infer properties from the first pattern. We'll verify the others.
3465 if (InstInfo.InferredFrom)
3466 continue;
3467
3468 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003469 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003470 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3471 }
3472
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003473 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003474 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003475
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003476 // Revisit instructions with undefined flags and no pattern.
3477 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003478 for (CodeGenInstruction *InstInfo : Revisit) {
3479 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003480 continue;
3481 // The mayLoad and mayStore flags default to false.
3482 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003483 if (InstInfo->hasSideEffects_Unset)
3484 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003485 }
3486 return;
3487 }
3488
3489 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003490 for (CodeGenInstruction *InstInfo : Revisit) {
3491 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003492 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003493 if (InstInfo->hasSideEffects_Unset)
3494 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003495 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003496 if (InstInfo->mayStore_Unset)
3497 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003498 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003499 if (InstInfo->mayLoad_Unset)
3500 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003501 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003502 }
3503}
3504
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003505
3506/// Verify instruction flags against pattern node properties.
3507void CodeGenDAGPatterns::VerifyInstructionFlags() {
3508 unsigned Errors = 0;
3509 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3510 const PatternToMatch &PTM = *I;
3511 SmallVector<Record*, 8> Instrs;
3512 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3513 if (Instrs.empty())
3514 continue;
3515
3516 // Count the number of instructions with each flag set.
3517 unsigned NumSideEffects = 0;
3518 unsigned NumStores = 0;
3519 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003520 for (const Record *Instr : Instrs) {
3521 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003522 NumSideEffects += InstInfo.hasSideEffects;
3523 NumStores += InstInfo.mayStore;
3524 NumLoads += InstInfo.mayLoad;
3525 }
3526
3527 // Analyze the source pattern.
3528 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003529 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003530
3531 // Collect error messages.
3532 SmallVector<std::string, 4> Msgs;
3533
3534 // Check for missing flags in the output.
3535 // Permit extra flags for now at least.
3536 if (PatInfo.hasSideEffects && !NumSideEffects)
3537 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3538
3539 // Don't verify store flags on instructions with side effects. At least for
3540 // intrinsics, side effects implies mayStore.
3541 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3542 Msgs.push_back("pattern may store, but mayStore isn't set");
3543
3544 // Similarly, mayStore implies mayLoad on intrinsics.
3545 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3546 Msgs.push_back("pattern may load, but mayLoad isn't set");
3547
3548 // Print error messages.
3549 if (Msgs.empty())
3550 continue;
3551 ++Errors;
3552
Craig Topper306cb122015-11-22 20:46:24 +00003553 for (const std::string &Msg : Msgs)
3554 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003555 (Instrs.size() == 1 ?
3556 "instruction" : "output instructions"));
3557 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003558 for (const Record *Instr : Instrs) {
3559 if (Instr != PTM.getSrcRecord())
3560 PrintError(Instr->getLoc(), "defined here");
3561 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003562 if (InstInfo.InferredFrom &&
3563 InstInfo.InferredFrom != InstInfo.TheDef &&
3564 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003565 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003566 }
3567 }
3568 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003569 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003570}
3571
Chris Lattnercabe0372010-03-15 06:00:16 +00003572/// Given a pattern result with an unresolved type, see if we can find one
3573/// instruction with an unresolved result type. Force this result type to an
3574/// arbitrary element if it's possible types to converge results.
3575static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3576 if (N->isLeaf())
3577 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003578
Chris Lattnercabe0372010-03-15 06:00:16 +00003579 // Analyze children.
3580 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3581 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3582 return true;
3583
3584 if (!N->getOperator()->isSubClassOf("Instruction"))
3585 return false;
3586
3587 // If this type is already concrete or completely unknown we can't do
3588 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003589 TypeInfer &TI = TP.getInfer();
Chris Lattnerf1447252010-03-19 21:37:09 +00003590 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003591 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00003592 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003593
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003594 // Otherwise, force its type to an arbitrary choice.
3595 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00003596 return true;
3597 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003598
Chris Lattnerf1447252010-03-19 21:37:09 +00003599 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003600}
3601
Chris Lattnerab3242f2008-01-06 01:10:31 +00003602void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003603 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3604
Craig Topper306cb122015-11-22 20:46:24 +00003605 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003606 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003607
3608 // If the pattern references the null_frag, there's nothing to do.
3609 if (hasNullFragReference(Tree))
3610 continue;
3611
Chris Lattner5c2182e2010-03-27 02:53:27 +00003612 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003613
3614 // Inline pattern fragments into it.
3615 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003616
David Greeneaf8ee2c2011-07-29 22:43:06 +00003617 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003618 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003619
Chris Lattner8cab0212008-01-05 22:25:12 +00003620 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003621 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003622
Chris Lattner8cab0212008-01-05 22:25:12 +00003623 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003624 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003625
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003626 if (Result.getNumTrees() != 1)
3627 Result.error("Cannot handle instructions producing instructions "
3628 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003629
Chris Lattner8cab0212008-01-05 22:25:12 +00003630 bool IterateInference;
3631 bool InferredAllPatternTypes, InferredAllResultTypes;
3632 do {
3633 // Infer as many types as possible. If we cannot infer all of them, we
3634 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003635 InferredAllPatternTypes =
3636 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003637
Chris Lattner8cab0212008-01-05 22:25:12 +00003638 // Infer as many types as possible. If we cannot infer all of them, we
3639 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003640 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003641 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003642
Chris Lattnerfdc20712010-03-18 23:15:10 +00003643 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003644
Chris Lattner8cab0212008-01-05 22:25:12 +00003645 // Apply the type of the result to the source pattern. This helps us
3646 // resolve cases where the input type is known to be a pointer type (which
3647 // is considered resolved), but the result knows it needs to be 32- or
3648 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003649 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003650 Pattern->getTree(0)->getNumTypes());
3651 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003652 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3653 i, Result.getTree(0)->getExtType(i), Result);
3654 IterateInference |= Result.getTree(0)->UpdateNodeType(
3655 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003656 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003657
Chris Lattnercabe0372010-03-15 06:00:16 +00003658 // If our iteration has converged and the input pattern's types are fully
3659 // resolved but the result pattern is not fully resolved, we may have a
3660 // situation where we have two instructions in the result pattern and
3661 // the instructions require a common register class, but don't care about
3662 // what actual MVT is used. This is actually a bug in our modelling:
3663 // output patterns should have register classes, not MVTs.
3664 //
3665 // In any case, to handle this, we just go through and disambiguate some
3666 // arbitrary types to the result pattern's nodes.
3667 if (!IterateInference && InferredAllPatternTypes &&
3668 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003669 IterateInference =
3670 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003671 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003672
Chris Lattner8cab0212008-01-05 22:25:12 +00003673 // Verify that we inferred enough types that we can do something with the
3674 // pattern and result. If these fire the user has to add type casts.
3675 if (!InferredAllPatternTypes)
3676 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003677 if (!InferredAllResultTypes) {
3678 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003679 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003680 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003681
Chris Lattner8cab0212008-01-05 22:25:12 +00003682 // Validate that the input pattern is correct.
3683 std::map<std::string, TreePatternNode*> InstInputs;
3684 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003685 std::vector<Record*> InstImpResults;
3686 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3687 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3688 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003689 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003690
3691 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003692 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003693 std::vector<TreePatternNode*> ResultNodeOperands;
3694 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3695 TreePatternNode *OpNode = DstPattern->getChild(ii);
3696 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003697 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003698 std::vector<TreePatternNode*> Children;
3699 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003700 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003701 }
3702 ResultNodeOperands.push_back(OpNode);
3703 }
David Blaikiecf195302014-11-17 22:55:41 +00003704 DstPattern = Result.getOnlyTree();
3705 if (!DstPattern->isLeaf())
3706 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3707 ResultNodeOperands,
3708 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003709
David Blaikiecf195302014-11-17 22:55:41 +00003710 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3711 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3712
3713 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003714 Temp.InferAllTypes();
3715
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003716 // A pattern may end up with an "impossible" type, i.e. a situation
3717 // where all types have been eliminated for some node in this pattern.
3718 // This could occur for intrinsics that only make sense for a specific
3719 // value type, and use a specific register class. If, for some mode,
3720 // that register class does not accept that type, the type inference
3721 // will lead to a contradiction, which is not an error however, but
3722 // a sign that this pattern will simply never match.
3723 if (Pattern->getTree(0)->hasPossibleType() &&
3724 Temp.getOnlyTree()->hasPossibleType()) {
3725 ListInit *Preds = CurPattern->getValueAsListInit("Predicates");
3726 int Complexity = CurPattern->getValueAsInt("AddedComplexity");
3727 AddPatternToMatch(
3728 Pattern,
3729 PatternToMatch(
3730 CurPattern, makePredList(Preds), Pattern->getTree(0),
3731 Temp.getOnlyTree(), std::move(InstImpResults), Complexity,
3732 CurPattern->getID()));
3733 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003734 }
3735}
3736
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003737static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
3738 for (const TypeSetByHwMode &VTS : N->getExtTypes())
3739 for (const auto &I : VTS)
3740 Modes.insert(I.first);
3741
3742 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3743 collectModes(Modes, N->getChild(i));
3744}
3745
3746void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
3747 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3748 std::map<unsigned,std::vector<Predicate>> ModeChecks;
3749 std::vector<PatternToMatch> Copy = PatternsToMatch;
3750 PatternsToMatch.clear();
3751
3752 auto AppendPattern = [this,&ModeChecks](PatternToMatch &P, unsigned Mode) {
3753 TreePatternNode *NewSrc = P.SrcPattern->clone();
3754 TreePatternNode *NewDst = P.DstPattern->clone();
3755 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
3756 delete NewSrc;
3757 delete NewDst;
3758 return;
3759 }
3760
3761 std::vector<Predicate> Preds = P.Predicates;
3762 const std::vector<Predicate> &MC = ModeChecks[Mode];
3763 Preds.insert(Preds.end(), MC.begin(), MC.end());
3764 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, NewSrc, NewDst,
3765 P.getDstRegs(), P.getAddedComplexity(),
3766 Record::getNewUID(), Mode);
3767 };
3768
3769 for (PatternToMatch &P : Copy) {
3770 TreePatternNode *SrcP = nullptr, *DstP = nullptr;
3771 if (P.SrcPattern->hasProperTypeByHwMode())
3772 SrcP = P.SrcPattern;
3773 if (P.DstPattern->hasProperTypeByHwMode())
3774 DstP = P.DstPattern;
3775 if (!SrcP && !DstP) {
3776 PatternsToMatch.push_back(P);
3777 continue;
3778 }
3779
3780 std::set<unsigned> Modes;
3781 if (SrcP)
3782 collectModes(Modes, SrcP);
3783 if (DstP)
3784 collectModes(Modes, DstP);
3785
3786 // The predicate for the default mode needs to be constructed for each
3787 // pattern separately.
3788 // Since not all modes must be present in each pattern, if a mode m is
3789 // absent, then there is no point in constructing a check for m. If such
3790 // a check was created, it would be equivalent to checking the default
3791 // mode, except not all modes' predicates would be a part of the checking
3792 // code. The subsequently generated check for the default mode would then
3793 // have the exact same patterns, but a different predicate code. To avoid
3794 // duplicated patterns with different predicate checks, construct the
3795 // default check as a negation of all predicates that are actually present
3796 // in the source/destination patterns.
3797 std::vector<Predicate> DefaultPred;
3798
3799 for (unsigned M : Modes) {
3800 if (M == DefaultMode)
3801 continue;
3802 if (ModeChecks.find(M) != ModeChecks.end())
3803 continue;
3804
3805 // Fill the map entry for this mode.
3806 const HwMode &HM = CGH.getMode(M);
3807 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
3808
3809 // Add negations of the HM's predicates to the default predicate.
3810 DefaultPred.emplace_back(Predicate(HM.Features, false));
3811 }
3812
3813 for (unsigned M : Modes) {
3814 if (M == DefaultMode)
3815 continue;
3816 AppendPattern(P, M);
3817 }
3818
3819 bool HasDefault = Modes.count(DefaultMode);
3820 if (HasDefault)
3821 AppendPattern(P, DefaultMode);
3822 }
3823}
3824
3825/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turner249dc142017-09-20 18:01:40 +00003826typedef StringMap<int> DepVarMap;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003827
3828static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
3829 if (N->isLeaf()) {
Zachary Turner249dc142017-09-20 18:01:40 +00003830 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003831 DepMap[N->getName()]++;
3832 } else {
3833 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
3834 FindDepVarsOf(N->getChild(i), DepMap);
3835 }
3836}
3837
3838/// Find dependent variables within child patterns
3839static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
3840 DepVarMap depcounts;
3841 FindDepVarsOf(N, depcounts);
Zachary Turner249dc142017-09-20 18:01:40 +00003842 for (const auto &Pair : depcounts) {
3843 if (Pair.getValue() > 1)
3844 DepVars.insert(Pair.getKey());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003845 }
3846}
3847
3848#ifndef NDEBUG
3849/// Dump the dependent variable set:
3850static void DumpDepVars(MultipleUseVarSet &DepVars) {
3851 if (DepVars.empty()) {
3852 DEBUG(errs() << "<empty set>");
3853 } else {
3854 DEBUG(errs() << "[ ");
Zachary Turner249dc142017-09-20 18:01:40 +00003855 for (const auto &DepVar : DepVars) {
3856 DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003857 }
3858 DEBUG(errs() << "]");
3859 }
3860}
3861#endif
3862
3863
Chris Lattner8cab0212008-01-05 22:25:12 +00003864/// CombineChildVariants - Given a bunch of permutations of each child of the
3865/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003866static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003867 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3868 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003869 CodeGenDAGPatterns &CDP,
3870 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003871 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00003872 for (const auto &Variants : ChildVariants)
3873 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003874 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003875
Chris Lattner8cab0212008-01-05 22:25:12 +00003876 // The end result is an all-pairs construction of the resultant pattern.
3877 std::vector<unsigned> Idxs;
3878 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003879 bool NotDone;
3880 do {
3881#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003882 DEBUG(if (!Idxs.empty()) {
3883 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00003884 for (unsigned Idx : Idxs) {
3885 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003886 }
3887 errs() << "]\n";
3888 });
Scott Michel94420742008-03-05 17:49:05 +00003889#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003890 // Create the variant and add it to the output list.
3891 std::vector<TreePatternNode*> NewChildren;
3892 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3893 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00003894 auto R = llvm::make_unique<TreePatternNode>(
3895 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003896
Chris Lattner8cab0212008-01-05 22:25:12 +00003897 // Copy over properties.
3898 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003899 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003900 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003901 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3902 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003903
Scott Michel94420742008-03-05 17:49:05 +00003904 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003905 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00003906 // Scan to see if this pattern has already been emitted. We can get
3907 // duplication due to things like commuting:
3908 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3909 // which are the same pattern. Ignore the dups.
3910 if (R->canPatternMatch(ErrString, CDP) &&
David Majnemer0a16c222016-08-11 21:15:00 +00003911 none_of(OutVariants, [&](TreePatternNode *Variant) {
3912 return R->isIsomorphicTo(Variant, DepVars);
3913 }))
David Blaikiefda69dd2015-11-22 20:11:21 +00003914 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003915
Scott Michel94420742008-03-05 17:49:05 +00003916 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003917 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00003918 // [0, 0], [0, 1], [1, 0], [1, 1].
3919 int IdxsIdx;
3920 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3921 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3922 Idxs[IdxsIdx] = 0;
3923 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003924 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003925 }
Scott Michel94420742008-03-05 17:49:05 +00003926 NotDone = (IdxsIdx >= 0);
3927 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003928}
3929
3930/// CombineChildVariants - A helper function for binary operators.
3931///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003932static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003933 const std::vector<TreePatternNode*> &LHS,
3934 const std::vector<TreePatternNode*> &RHS,
3935 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003936 CodeGenDAGPatterns &CDP,
3937 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003938 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3939 ChildVariants.push_back(LHS);
3940 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003941 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003942}
Chris Lattner8cab0212008-01-05 22:25:12 +00003943
3944
3945static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3946 std::vector<TreePatternNode *> &Children) {
3947 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3948 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003949
Chris Lattner8cab0212008-01-05 22:25:12 +00003950 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003951 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003952 N->getTransformFn()) {
3953 Children.push_back(N);
3954 return;
3955 }
3956
3957 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3958 Children.push_back(N->getChild(0));
3959 else
3960 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3961
3962 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3963 Children.push_back(N->getChild(1));
3964 else
3965 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3966}
3967
3968/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3969/// the (potentially recursive) pattern by using algebraic laws.
3970///
3971static void GenerateVariantsOf(TreePatternNode *N,
3972 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003973 CodeGenDAGPatterns &CDP,
3974 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003975 // We cannot permute leaves or ComplexPattern uses.
3976 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003977 OutVariants.push_back(N);
3978 return;
3979 }
3980
3981 // Look up interesting info about the node.
3982 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3983
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003984 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003985 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003986 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003987 std::vector<TreePatternNode*> MaximalChildren;
3988 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3989
3990 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3991 // permutations.
3992 if (MaximalChildren.size() == 3) {
3993 // Find the variants of all of our maximal children.
3994 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003995 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3996 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3997 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003998
Chris Lattner8cab0212008-01-05 22:25:12 +00003999 // There are only two ways we can permute the tree:
4000 // (A op B) op C and A op (B op C)
4001 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004002
Chris Lattner8cab0212008-01-05 22:25:12 +00004003 // Generate legal pair permutations of A/B/C.
4004 std::vector<TreePatternNode*> ABVariants;
4005 std::vector<TreePatternNode*> BAVariants;
4006 std::vector<TreePatternNode*> ACVariants;
4007 std::vector<TreePatternNode*> CAVariants;
4008 std::vector<TreePatternNode*> BCVariants;
4009 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00004010 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4011 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4012 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4013 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4014 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4015 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004016
4017 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00004018 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4019 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4020 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4021 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4022 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4023 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004024
4025 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00004026 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4027 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4028 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4029 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4030 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4031 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004032 return;
4033 }
4034 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004035
Chris Lattner8cab0212008-01-05 22:25:12 +00004036 // Compute permutations of all children.
4037 std::vector<std::vector<TreePatternNode*> > ChildVariants;
4038 ChildVariants.resize(N->getNumChildren());
4039 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00004040 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004041
4042 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00004043 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004044
4045 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004046 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4047 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004048 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004049 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004050 // Don't count children which are actually register references.
4051 unsigned NC = 0;
4052 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4053 TreePatternNode *Child = N->getChild(i);
4054 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00004055 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004056 Record *RR = DI->getDef();
4057 if (RR->isSubClassOf("Register"))
4058 continue;
4059 }
4060 NC++;
4061 }
4062 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004063 if (isCommIntrinsic) {
4064 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4065 // operands are the commutative operands, and there might be more operands
4066 // after those.
4067 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004068 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00004069 std::vector<std::vector<TreePatternNode*> > Variants;
4070 Variants.push_back(ChildVariants[0]); // Intrinsic id.
4071 Variants.push_back(ChildVariants[2]);
4072 Variants.push_back(ChildVariants[1]);
4073 for (unsigned i = 3; i != NC; ++i)
4074 Variants.push_back(ChildVariants[i]);
4075 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004076 } else if (NC == N->getNumChildren()) {
4077 std::vector<std::vector<TreePatternNode*> > Variants;
4078 Variants.push_back(ChildVariants[1]);
4079 Variants.push_back(ChildVariants[0]);
4080 for (unsigned i = 2; i != NC; ++i)
4081 Variants.push_back(ChildVariants[i]);
4082 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4083 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004084 }
4085}
4086
4087
4088// GenerateVariants - Generate variants. For example, commutative patterns can
4089// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004090void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00004091 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004092
Chris Lattner8cab0212008-01-05 22:25:12 +00004093 // Loop over all of the patterns we've collected, checking to see if we can
4094 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004095 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004096 // the .td file having to contain tons of variants of instructions.
4097 //
4098 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4099 // intentionally do not reconsider these. Any variants of added patterns have
4100 // already been added.
4101 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00004102 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00004103 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00004104 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004105 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00004106 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00004107 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00004108 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00004109 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00004110 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004111
4112 assert(!Variants.empty() && "Must create at least original variant!");
Krzysztof Parzyszekf7237762017-06-16 13:44:34 +00004113 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004114 continue;
4115
Chris Lattner34822f62009-08-23 04:44:11 +00004116 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00004117 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00004118 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004119
4120 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4121 TreePatternNode *Variant = Variants[v];
4122
Chris Lattner34822f62009-08-23 04:44:11 +00004123 DEBUG(errs() << " VAR#" << v << ": ";
4124 Variant->dump();
4125 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004126
Chris Lattner8cab0212008-01-05 22:25:12 +00004127 // Scan to see if an instruction or explicit pattern already matches this.
4128 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004129 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004130 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004131 if (PatternsToMatch[i].getPredicates() !=
4132 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00004133 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004134 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004135 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4136 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00004137 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004138 AlreadyExists = true;
4139 break;
4140 }
4141 }
4142 // If we already have it, ignore the variant.
4143 if (AlreadyExists) continue;
4144
4145 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004146 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004147 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4148 Variant, PatternsToMatch[i].getDstPattern(),
4149 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004150 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00004151 }
4152
Chris Lattner34822f62009-08-23 04:44:11 +00004153 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004154 }
4155}