blob: 8987091a16244d396c6087458b876739134a1b7d [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
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +0000857StringRef 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
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +0000861StringRef 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
Daniel Sanders649c5852017-10-13 20:42:18 +0000865bool TreePredicateFn::immCodeUsesAPInt() const {
866 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
867}
868
869bool TreePredicateFn::immCodeUsesAPFloat() const {
870 bool Unset;
871 // The return value will be false when IsAPFloat is unset.
872 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
873 Unset);
874}
875
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +0000876StringRef TreePredicateFn::getImmType() const {
Daniel Sanders649c5852017-10-13 20:42:18 +0000877 if (immCodeUsesAPInt())
878 return "const APInt &";
879 if (immCodeUsesAPFloat())
880 return "const APFloat &";
881 return "int64_t";
882}
Chris Lattner514e2922011-04-17 21:38:24 +0000883
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +0000884StringRef TreePredicateFn::getImmTypeIdentifier() const {
Daniel Sanders11300ce2017-10-13 21:28:03 +0000885 if (immCodeUsesAPInt())
886 return "APInt";
887 else if (immCodeUsesAPFloat())
888 return "APFloat";
889 return "I64";
890}
891
Chris Lattner514e2922011-04-17 21:38:24 +0000892/// isAlwaysTrue - Return true if this is a noop predicate.
893bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000894 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000895}
896
897/// Return the name to use in the generated code to reference this, this is
898/// "Predicate_foo" if from a pattern fragment "foo".
899std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +0000900 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +0000901}
902
903/// getCodeToRunOnSDNode - Return the code for the function body that
904/// evaluates this predicate. The argument is expected to be in "Node",
905/// not N. This handles casting and conversion to a concrete node type as
906/// appropriate.
907std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000908 // Handle immediate predicates first.
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +0000909 StringRef ImmCode = getImmCode();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000910 if (!ImmCode.empty()) {
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +0000911 std::string Result = " " + getImmType().str() + " Imm = ";
Daniel Sanders649c5852017-10-13 20:42:18 +0000912 if (immCodeUsesAPFloat())
913 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
914 else if (immCodeUsesAPInt())
915 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
916 else
917 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +0000918 return Result + ImmCode.str();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000919 }
Simon Pilgrim8c4d0612017-09-22 16:57:28 +0000920
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000921 // Handle arbitrary node predicates.
922 assert(!getPredCode().empty() && "Don't have any predicate code!");
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +0000923 StringRef ClassName;
Chris Lattner514e2922011-04-17 21:38:24 +0000924 if (PatFragRec->getOnlyTree()->isLeaf())
925 ClassName = "SDNode";
926 else {
927 Record *Op = PatFragRec->getOnlyTree()->getOperator();
928 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
929 }
930 std::string Result;
931 if (ClassName == "SDNode")
932 Result = " SDNode *N = Node;\n";
933 else
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +0000934 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
Simon Pilgrim8c4d0612017-09-22 16:57:28 +0000935
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +0000936 return Result + getPredCode().str();
Scott Michel94420742008-03-05 17:49:05 +0000937}
938
Chris Lattner8cab0212008-01-05 22:25:12 +0000939//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000940// PatternToMatch implementation
941//
942
Chris Lattner05925fe2010-03-29 01:40:38 +0000943/// getPatternSize - Return the 'size' of this pattern. We want to match large
944/// patterns before small ones. This is used to determine the size of a
945/// pattern.
946static unsigned getPatternSize(const TreePatternNode *P,
947 const CodeGenDAGPatterns &CGP) {
948 unsigned Size = 3; // The node itself.
949 // If the root node is a ConstantSDNode, increases its size.
950 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000951 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000952 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000953
Simon Pilgrim40687012017-09-26 12:59:01 +0000954 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +0000955 Size += AM->getComplexity();
Tim Northoverc807a172014-05-20 11:52:46 +0000956 // We don't want to count any children twice, so return early.
957 return Size;
958 }
959
Chris Lattner05925fe2010-03-29 01:40:38 +0000960 // If this node has some predicate function that must match, it adds to the
961 // complexity of this node.
962 if (!P->getPredicateFns().empty())
963 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000964
Chris Lattner05925fe2010-03-29 01:40:38 +0000965 // Count children in the count if they are also nodes.
966 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
Simon Pilgrima932bfc2017-09-27 10:03:17 +0000967 const TreePatternNode *Child = P->getChild(i);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000968 if (!Child->isLeaf() && Child->getNumTypes()) {
969 const TypeSetByHwMode &T0 = Child->getType(0);
970 // At this point, all variable type sets should be simple, i.e. only
971 // have a default mode.
972 if (T0.getMachineValueType() != MVT::Other) {
973 Size += getPatternSize(Child, CGP);
974 continue;
975 }
976 }
977 if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000978 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000979 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
980 else if (Child->getComplexPatternInfo(CGP))
981 Size += getPatternSize(Child, CGP);
982 else if (!Child->getPredicateFns().empty())
983 ++Size;
984 }
985 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000986
Chris Lattner05925fe2010-03-29 01:40:38 +0000987 return Size;
988}
989
990/// Compute the complexity metric for the input pattern. This roughly
991/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000992int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000993getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
994 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
995}
996
Dan Gohman49e19e92008-08-22 00:20:26 +0000997/// getPredicateCheck - Return a single string containing all of this
998/// pattern's predicates concatenated with "&&" operators.
999///
1000std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001001 SmallVector<const Predicate*,4> PredList;
1002 for (const Predicate &P : Predicates)
1003 PredList.push_back(&P);
1004 std::sort(PredList.begin(), PredList.end(), deref<llvm::less>());
Craig Topper8985efe2015-11-27 05:44:04 +00001005
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001006 std::string Check;
1007 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1008 if (i != 0)
1009 Check += " && ";
1010 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +00001011 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001012 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +00001013}
1014
1015//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00001016// SDTypeConstraint implementation
1017//
1018
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001019SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001020 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001021
Chris Lattner8cab0212008-01-05 22:25:12 +00001022 if (R->isSubClassOf("SDTCisVT")) {
1023 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001024 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1025 for (const auto &P : VVT)
1026 if (P.second == MVT::isVoid)
1027 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +00001028 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1029 ConstraintType = SDTCisPtrTy;
1030 } else if (R->isSubClassOf("SDTCisInt")) {
1031 ConstraintType = SDTCisInt;
1032 } else if (R->isSubClassOf("SDTCisFP")) {
1033 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +00001034 } else if (R->isSubClassOf("SDTCisVec")) {
1035 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001036 } else if (R->isSubClassOf("SDTCisSameAs")) {
1037 ConstraintType = SDTCisSameAs;
1038 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1039 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1040 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001041 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001042 R->getValueAsInt("OtherOperandNum");
1043 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1044 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001045 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001046 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001047 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1048 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001049 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001050 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1051 ConstraintType = SDTCisSubVecOfVec;
1052 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1053 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001054 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1055 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001056 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1057 for (const auto &P : VVT) {
1058 MVT T = P.second;
1059 if (T.isVector())
1060 PrintFatalError(R->getLoc(),
1061 "Cannot use vector type as SDTCVecEltisVT");
1062 if (!T.isInteger() && !T.isFloatingPoint())
1063 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1064 "as SDTCVecEltisVT");
1065 }
Craig Topper0be34582015-03-05 07:11:34 +00001066 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1067 ConstraintType = SDTCisSameNumEltsAs;
1068 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1069 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001070 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1071 ConstraintType = SDTCisSameSizeAs;
1072 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1073 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001074 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001075 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001076 }
1077}
1078
1079/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001080/// N, and the result number in ResNo.
1081static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
1082 const SDNodeInfo &NodeInfo,
1083 unsigned &ResNo) {
1084 unsigned NumResults = NodeInfo.getNumResults();
1085 if (OpNo < NumResults) {
1086 ResNo = OpNo;
1087 return N;
1088 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001089
Chris Lattner2db7aba2010-03-19 21:56:21 +00001090 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001091
Chris Lattner2db7aba2010-03-19 21:56:21 +00001092 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001093 std::string S;
1094 raw_string_ostream OS(S);
1095 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001096 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +00001097 N->print(OS);
1098 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001099 }
1100
Chris Lattner2db7aba2010-03-19 21:56:21 +00001101 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001102}
1103
1104/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1105/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001106/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001107bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
1108 const SDNodeInfo &NodeInfo,
1109 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001110 if (TP.hasError())
1111 return false;
1112
Chris Lattner2db7aba2010-03-19 21:56:21 +00001113 unsigned ResNo = 0; // The result number being referenced.
1114 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001115 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001116
Chris Lattner8cab0212008-01-05 22:25:12 +00001117 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001118 case SDTCisVT:
1119 // Operand must be a particular type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001120 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001121 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001122 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001123 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001124 case SDTCisInt:
1125 // Require it to be one of the legal integer VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001126 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001127 case SDTCisFP:
1128 // Require it to be one of the legal fp VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001129 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001130 case SDTCisVec:
1131 // Require it to be one of the legal vector VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001132 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001133 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001134 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001135 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001136 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +00001137 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1138 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001139 }
1140 case SDTCisVTSmallerThanOp: {
1141 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1142 // have an integer type that is smaller than the VT.
1143 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +00001144 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +00001145 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001146 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001147 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001148 return false;
1149 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001150 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
1151 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1152 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1153 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001154
Chris Lattner2db7aba2010-03-19 21:56:21 +00001155 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001156 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001157 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1158 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001159
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001160 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001161 }
1162 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001163 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001164 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001165 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1166 BResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001167 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1168 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001169 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001170 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001171 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +00001172 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001173 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1174 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001175 // Filter vector types out of VecOperand that don't have the right element
1176 // type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001177 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1178 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001179 }
David Greene127fd1d2011-01-24 20:53:18 +00001180 case SDTCisSubVecOfVec: {
1181 unsigned VResNo = 0;
1182 TreePatternNode *BigVecOperand =
1183 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1184 VResNo);
1185
1186 // Filter vector types out of BigVecOperand that don't have the
1187 // right subvector type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001188 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1189 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001190 }
Craig Topper0be34582015-03-05 07:11:34 +00001191 case SDTCVecEltisVT: {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001192 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001193 }
1194 case SDTCisSameNumEltsAs: {
1195 unsigned OResNo = 0;
1196 TreePatternNode *OtherNode =
1197 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1198 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001199 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1200 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001201 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001202 case SDTCisSameSizeAs: {
1203 unsigned OResNo = 0;
1204 TreePatternNode *OtherNode =
1205 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1206 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001207 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1208 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001209 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001210 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001211 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001212}
1213
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001214// Update the node type to match an instruction operand or result as specified
1215// in the ins or outs lists on the instruction definition. Return true if the
1216// type was actually changed.
1217bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1218 Record *Operand,
1219 TreePattern &TP) {
1220 // The 'unknown' operand indicates that types should be inferred from the
1221 // context.
1222 if (Operand->isSubClassOf("unknown_class"))
1223 return false;
1224
1225 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001226 if (Operand->isSubClassOf("Operand")) {
1227 Record *R = Operand->getValueAsDef("Type");
1228 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1229 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1230 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001231
1232 // PointerLikeRegClass has a type that is determined at runtime.
1233 if (Operand->isSubClassOf("PointerLikeRegClass"))
1234 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1235
1236 // Both RegisterClass and RegisterOperand operands derive their types from a
1237 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001238 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001239 if (Operand->isSubClassOf("RegisterClass"))
1240 RC = Operand;
1241 else if (Operand->isSubClassOf("RegisterOperand"))
1242 RC = Operand->getValueAsDef("RegClass");
1243
1244 assert(RC && "Unknown operand type");
1245 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1246 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1247}
1248
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001249bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1250 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1251 if (!TP.getInfer().isConcrete(Types[i], true))
1252 return true;
1253 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1254 if (getChild(i)->ContainsUnresolvedType(TP))
1255 return true;
1256 return false;
1257}
1258
1259bool TreePatternNode::hasProperTypeByHwMode() const {
1260 for (const TypeSetByHwMode &S : Types)
1261 if (!S.isDefaultOnly())
1262 return true;
1263 for (TreePatternNode *C : Children)
1264 if (C->hasProperTypeByHwMode())
1265 return true;
1266 return false;
1267}
1268
1269bool TreePatternNode::hasPossibleType() const {
1270 for (const TypeSetByHwMode &S : Types)
1271 if (!S.isPossible())
1272 return false;
1273 for (TreePatternNode *C : Children)
1274 if (!C->hasPossibleType())
1275 return false;
1276 return true;
1277}
1278
1279bool TreePatternNode::setDefaultMode(unsigned Mode) {
1280 for (TypeSetByHwMode &S : Types) {
1281 S.makeSimple(Mode);
1282 // Check if the selected mode had a type conflict.
1283 if (S.get(DefaultMode).empty())
1284 return false;
1285 }
1286 for (TreePatternNode *C : Children)
1287 if (!C->setDefaultMode(Mode))
1288 return false;
1289 return true;
1290}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001291
Chris Lattner8cab0212008-01-05 22:25:12 +00001292//===----------------------------------------------------------------------===//
1293// SDNodeInfo implementation
1294//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001295SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001296 EnumName = R->getValueAsString("Opcode");
1297 SDClassName = R->getValueAsString("SDClass");
1298 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1299 NumResults = TypeProfile->getValueAsInt("NumResults");
1300 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001301
Chris Lattner8cab0212008-01-05 22:25:12 +00001302 // Parse the properties.
1303 Properties = 0;
Craig Topper306cb122015-11-22 20:46:24 +00001304 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1305 if (Property->getName() == "SDNPCommutative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001306 Properties |= 1 << SDNPCommutative;
Craig Topper306cb122015-11-22 20:46:24 +00001307 } else if (Property->getName() == "SDNPAssociative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001308 Properties |= 1 << SDNPAssociative;
Craig Topper306cb122015-11-22 20:46:24 +00001309 } else if (Property->getName() == "SDNPHasChain") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001310 Properties |= 1 << SDNPHasChain;
Craig Topper306cb122015-11-22 20:46:24 +00001311 } else if (Property->getName() == "SDNPOutGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001312 Properties |= 1 << SDNPOutGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001313 } else if (Property->getName() == "SDNPInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001314 Properties |= 1 << SDNPInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001315 } else if (Property->getName() == "SDNPOptInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001316 Properties |= 1 << SDNPOptInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001317 } else if (Property->getName() == "SDNPMayStore") {
Chris Lattnera348f552008-01-06 06:44:58 +00001318 Properties |= 1 << SDNPMayStore;
Craig Topper306cb122015-11-22 20:46:24 +00001319 } else if (Property->getName() == "SDNPMayLoad") {
Chris Lattner1ca20682008-01-10 04:38:57 +00001320 Properties |= 1 << SDNPMayLoad;
Craig Topper306cb122015-11-22 20:46:24 +00001321 } else if (Property->getName() == "SDNPSideEffect") {
Chris Lattner42c63ef2008-01-10 05:39:30 +00001322 Properties |= 1 << SDNPSideEffect;
Craig Topper306cb122015-11-22 20:46:24 +00001323 } else if (Property->getName() == "SDNPMemOperand") {
Mon P Wang6a490372008-06-25 08:15:39 +00001324 Properties |= 1 << SDNPMemOperand;
Craig Topper306cb122015-11-22 20:46:24 +00001325 } else if (Property->getName() == "SDNPVariadic") {
Chris Lattner83aeaab2010-03-19 05:07:09 +00001326 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001327 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001328 PrintFatalError("Unknown SD Node property '" +
Craig Topper306cb122015-11-22 20:46:24 +00001329 Property->getName() + "' on node '" +
James Y Knighte452e272015-05-11 22:17:13 +00001330 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001331 }
1332 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001333
1334
Chris Lattner8cab0212008-01-05 22:25:12 +00001335 // Parse the type constraints.
1336 std::vector<Record*> ConstraintList =
1337 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001338 for (Record *R : ConstraintList)
1339 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001340}
1341
Chris Lattner99e53b32010-02-28 00:22:30 +00001342/// getKnownType - If the type constraints on this node imply a fixed type
1343/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001344/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001345MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001346 unsigned NumResults = getNumResults();
1347 assert(NumResults <= 1 &&
1348 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001349 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001350
Craig Topper306cb122015-11-22 20:46:24 +00001351 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001352 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001353 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001354 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001355
Craig Topper306cb122015-11-22 20:46:24 +00001356 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001357 default: break;
1358 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001359 if (Constraint.VVT.isSimple())
1360 return Constraint.VVT.getSimple().SimpleTy;
1361 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001362 case SDTypeConstraint::SDTCisPtrTy:
1363 return MVT::iPTR;
1364 }
1365 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001366 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001367}
1368
Chris Lattner8cab0212008-01-05 22:25:12 +00001369//===----------------------------------------------------------------------===//
1370// TreePatternNode implementation
1371//
1372
1373TreePatternNode::~TreePatternNode() {
1374#if 0 // FIXME: implement refcounted tree nodes!
1375 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1376 delete getChild(i);
1377#endif
1378}
1379
Chris Lattnerf1447252010-03-19 21:37:09 +00001380static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1381 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001382 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001383 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001384
Chris Lattner2109cb42010-03-22 20:56:36 +00001385 if (Operator->isSubClassOf("Intrinsic"))
1386 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001387
Chris Lattnerf1447252010-03-19 21:37:09 +00001388 if (Operator->isSubClassOf("SDNode"))
1389 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001390
Chris Lattnerf1447252010-03-19 21:37:09 +00001391 if (Operator->isSubClassOf("PatFrag")) {
1392 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1393 // the forward reference case where one pattern fragment references another
1394 // before it is processed.
1395 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1396 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001397
Chris Lattnerf1447252010-03-19 21:37:09 +00001398 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001399 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001400 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001401 if (Tree)
1402 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1403 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001404 assert(Op && "Invalid Fragment");
1405 return GetNumNodeResults(Op, CDP);
1406 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001407
Chris Lattnerf1447252010-03-19 21:37:09 +00001408 if (Operator->isSubClassOf("Instruction")) {
1409 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001410
Craig Topper3a8eb892015-03-20 05:09:06 +00001411 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1412
1413 // Subtract any defaulted outputs.
1414 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1415 Record *OperandNode = InstInfo.Operands[i].Rec;
1416
1417 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1418 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1419 --NumDefsToAdd;
1420 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001421
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001422 // Add on one implicit def if it has a resolvable type.
1423 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1424 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001425 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001426 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001427
Chris Lattnerf1447252010-03-19 21:37:09 +00001428 if (Operator->isSubClassOf("SDNodeXForm"))
1429 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001430
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001431 if (Operator->isSubClassOf("ValueType"))
1432 return 1; // A type-cast of one result.
1433
Tim Northoverc807a172014-05-20 11:52:46 +00001434 if (Operator->isSubClassOf("ComplexPattern"))
1435 return 1;
1436
Matthias Braun8c209aa2017-01-28 02:02:38 +00001437 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001438 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001439}
1440
1441void TreePatternNode::print(raw_ostream &OS) const {
1442 if (isLeaf())
1443 OS << *getLeafValue();
1444 else
1445 OS << '(' << getOperator()->getName();
1446
Zachary Turner249dc142017-09-20 18:01:40 +00001447 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1448 OS << ':';
1449 getExtType(i).writeToStream(OS);
1450 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001451
1452 if (!isLeaf()) {
1453 if (getNumChildren() != 0) {
1454 OS << " ";
1455 getChild(0)->print(OS);
1456 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1457 OS << ", ";
1458 getChild(i)->print(OS);
1459 }
1460 }
1461 OS << ")";
1462 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001463
Craig Topper306cb122015-11-22 20:46:24 +00001464 for (const TreePredicateFn &Pred : PredicateFns)
1465 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001466 if (TransformFn)
1467 OS << "<<X:" << TransformFn->getName() << ">>";
1468 if (!getName().empty())
1469 OS << ":$" << getName();
1470
1471}
1472void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001473 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001474}
1475
Scott Michel94420742008-03-05 17:49:05 +00001476/// isIsomorphicTo - Return true if this node is recursively
1477/// isomorphic to the specified node. For this comparison, the node's
1478/// entire state is considered. The assigned name is ignored, since
1479/// nodes with differing names are considered isomorphic. However, if
1480/// the assigned name is present in the dependent variable set, then
1481/// the assigned name is considered significant and the node is
1482/// isomorphic if the names match.
1483bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1484 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001485 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001486 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001487 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001488 getTransformFn() != N->getTransformFn())
1489 return false;
1490
1491 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001492 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1493 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001494 return ((DI->getDef() == NDI->getDef())
1495 && (DepVars.find(getName()) == DepVars.end()
1496 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001497 }
1498 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001499 return getLeafValue() == N->getLeafValue();
1500 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001501
Chris Lattner8cab0212008-01-05 22:25:12 +00001502 if (N->getOperator() != getOperator() ||
1503 N->getNumChildren() != getNumChildren()) return false;
1504 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001505 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001506 return false;
1507 return true;
1508}
1509
1510/// clone - Make a copy of this tree and all of its children.
1511///
1512TreePatternNode *TreePatternNode::clone() const {
1513 TreePatternNode *New;
1514 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001515 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001516 } else {
1517 std::vector<TreePatternNode*> CChildren;
1518 CChildren.reserve(Children.size());
1519 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1520 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001521 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001522 }
1523 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001524 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001525 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001526 New->setTransformFn(getTransformFn());
1527 return New;
1528}
1529
Chris Lattner53c39ba2010-02-14 22:22:58 +00001530/// RemoveAllTypes - Recursively strip all the types of this tree.
1531void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001532 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001533 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001534 if (isLeaf()) return;
1535 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1536 getChild(i)->RemoveAllTypes();
1537}
1538
1539
Chris Lattner8cab0212008-01-05 22:25:12 +00001540/// SubstituteFormalArguments - Replace the formal arguments in this tree
1541/// with actual values specified by ArgMap.
1542void TreePatternNode::
1543SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1544 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001545
Chris Lattner8cab0212008-01-05 22:25:12 +00001546 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1547 TreePatternNode *Child = getChild(i);
1548 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001549 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001550 // Note that, when substituting into an output pattern, Val might be an
1551 // UnsetInit.
1552 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1553 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001554 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001555 TreePatternNode *NewChild = ArgMap[Child->getName()];
1556 assert(NewChild && "Couldn't find formal argument!");
1557 assert((Child->getPredicateFns().empty() ||
1558 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1559 "Non-empty child predicate clobbered!");
1560 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001561 }
1562 } else {
1563 getChild(i)->SubstituteFormalArguments(ArgMap);
1564 }
1565 }
1566}
1567
1568
1569/// InlinePatternFragments - If this pattern refers to any pattern
1570/// fragments, inline them into place, giving us a pattern without any
1571/// PatFrag references.
1572TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001573 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001574 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001575
1576 if (isLeaf())
1577 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001578 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001579
Chris Lattner8cab0212008-01-05 22:25:12 +00001580 if (!Op->isSubClassOf("PatFrag")) {
1581 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001582 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1583 TreePatternNode *Child = getChild(i);
1584 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1585
1586 assert((Child->getPredicateFns().empty() ||
1587 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1588 "Non-empty child predicate clobbered!");
1589
1590 setChild(i, NewChild);
1591 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001592 return this;
1593 }
1594
1595 // Otherwise, we found a reference to a fragment. First, look up its
1596 // TreePattern record.
1597 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001598
Chris Lattner8cab0212008-01-05 22:25:12 +00001599 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001600 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001601 TP.error("'" + Op->getName() + "' fragment requires " +
1602 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001603 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001604 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001605
1606 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1607
Chris Lattner514e2922011-04-17 21:38:24 +00001608 TreePredicateFn PredFn(Frag);
1609 if (!PredFn.isAlwaysTrue())
1610 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001611
Chris Lattner8cab0212008-01-05 22:25:12 +00001612 // Resolve formal arguments to their actual value.
1613 if (Frag->getNumArgs()) {
1614 // Compute the map of formal to actual arguments.
1615 std::map<std::string, TreePatternNode*> ArgMap;
1616 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1617 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001618
Chris Lattner8cab0212008-01-05 22:25:12 +00001619 FragTree->SubstituteFormalArguments(ArgMap);
1620 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001621
Chris Lattner8cab0212008-01-05 22:25:12 +00001622 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001623 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1624 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001625
1626 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001627 for (const TreePredicateFn &Pred : getPredicateFns())
1628 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001629
Chris Lattner8cab0212008-01-05 22:25:12 +00001630 // Get a new copy of this fragment to stitch into here.
1631 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001632
Chris Lattner2e253b42008-06-30 03:02:03 +00001633 // The fragment we inlined could have recursive inlining that is needed. See
1634 // if there are any pattern fragments in it and inline them as needed.
1635 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001636}
1637
1638/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001639/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001640/// references from the register file information, for example.
1641///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001642/// When Unnamed is set, return the type of a DAG operand with no name, such as
1643/// the F8RC register class argument in:
1644///
1645/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1646///
1647/// When Unnamed is false, return the type of a named DAG operand such as the
1648/// GPR:$src operand above.
1649///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001650static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
1651 bool NotRegisters,
1652 bool Unnamed,
1653 TreePattern &TP) {
1654 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1655
Owen Andersona84be6c2011-06-27 21:06:21 +00001656 // Check to see if this is a register operand.
1657 if (R->isSubClassOf("RegisterOperand")) {
1658 assert(ResNo == 0 && "Regoperand ref only has one result!");
1659 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001660 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00001661 Record *RegClass = R->getValueAsDef("RegClass");
1662 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001663 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00001664 }
1665
Chris Lattnercabe0372010-03-15 06:00:16 +00001666 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001667 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001668 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001669 // An unnamed register class represents itself as an i32 immediate, for
1670 // example on a COPY_TO_REGCLASS instruction.
1671 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001672 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001673
1674 // In a named operand, the register class provides the possible set of
1675 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001676 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001677 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00001678 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001679 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001680 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001681
Chris Lattner6070ee22010-03-23 23:50:31 +00001682 if (R->isSubClassOf("PatFrag")) {
1683 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001684 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001685 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001686 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001687
Chris Lattner6070ee22010-03-23 23:50:31 +00001688 if (R->isSubClassOf("Register")) {
1689 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001690 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001691 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001692 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001693 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001694 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001695
1696 if (R->isSubClassOf("SubRegIndex")) {
1697 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001698 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001699 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001700
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001701 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001702 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001703 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1704 //
1705 // (sext_inreg GPR:$src, i16)
1706 // ~~~
1707 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001708 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001709 // With a name, the ValueType simply provides the type of the named
1710 // variable.
1711 //
1712 // (sext_inreg i32:$src, i16)
1713 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001714 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001715 return TypeSetByHwMode(); // Unknown.
1716 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1717 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001718 }
1719
1720 if (R->isSubClassOf("CondCode")) {
1721 assert(ResNo == 0 && "This node only has one result!");
1722 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001723 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00001724 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001725
Chris Lattner6070ee22010-03-23 23:50:31 +00001726 if (R->isSubClassOf("ComplexPattern")) {
1727 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001728 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001729 return TypeSetByHwMode(); // Unknown.
1730 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00001731 }
1732 if (R->isSubClassOf("PointerLikeRegClass")) {
1733 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001734 TypeSetByHwMode VTS(MVT::iPTR);
1735 TP.getInfer().expandOverloads(VTS);
1736 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00001737 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001738
Chris Lattner6070ee22010-03-23 23:50:31 +00001739 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1740 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001741 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001742 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001743 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001744
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001745 if (R->isSubClassOf("Operand")) {
1746 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1747 Record *T = R->getValueAsDef("Type");
1748 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
1749 }
Tim Northoverc807a172014-05-20 11:52:46 +00001750
Chris Lattner8cab0212008-01-05 22:25:12 +00001751 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001752 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00001753}
1754
Chris Lattner89c65662008-01-06 05:36:50 +00001755
1756/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1757/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1758const CodeGenIntrinsic *TreePatternNode::
1759getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1760 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1761 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1762 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001763 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001764
Sean Silva88eb8dd2012-10-10 20:24:47 +00001765 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001766 return &CDP.getIntrinsicInfo(IID);
1767}
1768
Chris Lattner53c39ba2010-02-14 22:22:58 +00001769/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1770/// return the ComplexPattern information, otherwise return null.
1771const ComplexPattern *
1772TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001773 Record *Rec;
1774 if (isLeaf()) {
1775 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1776 if (!DI)
1777 return nullptr;
1778 Rec = DI->getDef();
1779 } else
1780 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001781
Tim Northoverc807a172014-05-20 11:52:46 +00001782 if (!Rec->isSubClassOf("ComplexPattern"))
1783 return nullptr;
1784 return &CGP.getComplexPattern(Rec);
1785}
1786
1787unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1788 // A ComplexPattern specifically declares how many results it fills in.
1789 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1790 return CP->getNumOperands();
1791
1792 // If MIOperandInfo is specified, that gives the count.
1793 if (isLeaf()) {
1794 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1795 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1796 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1797 if (MIOps->getNumArgs())
1798 return MIOps->getNumArgs();
1799 }
1800 }
1801
1802 // Otherwise there is just one result.
1803 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001804}
1805
1806/// NodeHasProperty - Return true if this node has the specified property.
1807bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001808 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001809 if (isLeaf()) {
1810 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1811 return CP->hasProperty(Property);
1812 return false;
1813 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001814
Chris Lattner53c39ba2010-02-14 22:22:58 +00001815 Record *Operator = getOperator();
1816 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001817
Chris Lattner53c39ba2010-02-14 22:22:58 +00001818 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1819}
1820
1821
1822
1823
1824/// TreeHasProperty - Return true if any node in this tree has the specified
1825/// property.
1826bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001827 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001828 if (NodeHasProperty(Property, CGP))
1829 return true;
1830 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1831 if (getChild(i)->TreeHasProperty(Property, CGP))
1832 return true;
1833 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001834}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001835
Evan Cheng49bad4c2008-06-16 20:29:38 +00001836/// isCommutativeIntrinsic - Return true if the node corresponds to a
1837/// commutative intrinsic.
1838bool
1839TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1840 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1841 return Int->isCommutative;
1842 return false;
1843}
1844
Matt Arsenaulteb492162014-11-02 23:46:51 +00001845static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1846 if (!N->isLeaf())
1847 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001848
Matt Arsenaulteb492162014-11-02 23:46:51 +00001849 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1850 if (DI && DI->getDef()->isSubClassOf(Class))
1851 return true;
1852
1853 return false;
1854}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001855
1856static void emitTooManyOperandsError(TreePattern &TP,
1857 StringRef InstName,
1858 unsigned Expected,
1859 unsigned Actual) {
1860 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1861 " operands but expected only " + Twine(Expected) + "!");
1862}
1863
1864static void emitTooFewOperandsError(TreePattern &TP,
1865 StringRef InstName,
1866 unsigned Actual) {
1867 TP.error("Instruction '" + InstName +
1868 "' expects more than the provided " + Twine(Actual) + " operands!");
1869}
1870
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001871/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001872/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001873/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001874bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001875 if (TP.hasError())
1876 return false;
1877
Chris Lattnerab3242f2008-01-06 01:10:31 +00001878 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001879 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001880 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001881 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001882 bool MadeChange = false;
1883 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1884 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001885 NotRegisters,
1886 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001887 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001888 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001889
Sean Silvafb509ed2012-10-10 20:24:43 +00001890 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001891 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001892
Chris Lattnerf1447252010-03-19 21:37:09 +00001893 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001894 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001895
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001896 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00001897 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001898
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001899 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
1900 for (auto &P : VVT) {
1901 MVT::SimpleValueType VT = P.second.SimpleTy;
1902 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1903 continue;
1904 unsigned Size = MVT(VT).getSizeInBits();
1905 // Make sure that the value is representable for this type.
1906 if (Size >= 32)
1907 continue;
1908 // Check that the value doesn't use more bits than we have. It must
1909 // either be a sign- or zero-extended equivalent of the original.
1910 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1911 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
1912 SignBitAndAbove == 1)
1913 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001914
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001915 TP.error("Integer value '" + itostr(II->getValue()) +
1916 "' is out of range for type '" + getEnumName(VT) + "'!");
1917 break;
1918 }
1919 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001920 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001921
Chris Lattner8cab0212008-01-05 22:25:12 +00001922 return false;
1923 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001924
Chris Lattner8cab0212008-01-05 22:25:12 +00001925 // special handling for set, which isn't really an SDNode.
1926 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001927 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1928 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001929 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001930
Chris Lattnerf1447252010-03-19 21:37:09 +00001931 TreePatternNode *SetVal = getChild(NC-1);
1932 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1933
Elena Demikhovsky09954792015-03-01 08:23:41 +00001934 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001935 TreePatternNode *Child = getChild(i);
1936 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001937
Chris Lattner8cab0212008-01-05 22:25:12 +00001938 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001939 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1940 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001941 }
1942 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001943 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001944
Chris Lattner5c2182e2010-03-27 02:53:27 +00001945 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001946 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1947
Chris Lattner8cab0212008-01-05 22:25:12 +00001948 bool MadeChange = false;
1949 for (unsigned i = 0; i < getNumChildren(); ++i)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001950 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001951 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001952 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001953
Chris Lattneree820ac2010-02-23 05:51:07 +00001954 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001955 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001956
Chris Lattner8cab0212008-01-05 22:25:12 +00001957 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001958 unsigned NumRetVTs = Int->IS.RetVTs.size();
1959 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001960
Bill Wendling91821472008-11-13 09:08:33 +00001961 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001962 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001963
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001964 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001965 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001966 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001967 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001968 return false;
1969 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001970
1971 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001972 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001973
Chris Lattnerf1447252010-03-19 21:37:09 +00001974 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1975 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001976
Chris Lattnerf1447252010-03-19 21:37:09 +00001977 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1978 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1979 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001980 }
1981 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001982 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001983
Chris Lattneree820ac2010-02-23 05:51:07 +00001984 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001985 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001986
Chris Lattner135091b2010-03-28 08:48:47 +00001987 // Check that the number of operands is sane. Negative operands -> varargs.
1988 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001989 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001990 TP.error(getOperator()->getName() + " node requires exactly " +
1991 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001992 return false;
1993 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001994
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001995 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001996 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1997 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001998 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001999 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002000 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002001
Chris Lattneree820ac2010-02-23 05:51:07 +00002002 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002003 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002004 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00002005 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002006
Chris Lattnerd44966f2010-03-27 19:15:02 +00002007 bool MadeChange = false;
2008
2009 // Apply the result types to the node, these come from the things in the
2010 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00002011 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2012 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002013 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2014 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002015
Chris Lattnerd44966f2010-03-27 19:15:02 +00002016 // If the instruction has implicit defs, we apply the first one as a result.
2017 // FIXME: This sucks, it should apply all implicit defs.
2018 if (!InstInfo.ImplicitDefs.empty()) {
2019 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002020
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002021 // FIXME: Generalize to multiple possible types and multiple possible
2022 // ImplicitDefs.
2023 MVT::SimpleValueType VT =
2024 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002025
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002026 if (VT != MVT::Other)
2027 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002028 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002029
Chris Lattnercabe0372010-03-15 06:00:16 +00002030 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2031 // be the same.
2032 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00002033 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2034 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2035 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002036 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2037 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2038 // variadic.
2039
2040 unsigned NChild = getNumChildren();
2041 if (NChild < 3) {
2042 TP.error("REG_SEQUENCE requires at least 3 operands!");
2043 return false;
2044 }
2045
2046 if (NChild % 2 == 0) {
2047 TP.error("REG_SEQUENCE requires an odd number of operands!");
2048 return false;
2049 }
2050
2051 if (!isOperandClass(getChild(0), "RegisterClass")) {
2052 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2053 return false;
2054 }
2055
2056 for (unsigned I = 1; I < NChild; I += 2) {
2057 TreePatternNode *SubIdxChild = getChild(I + 1);
2058 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2059 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2060 itostr(I + 1) + "!");
2061 return false;
2062 }
2063 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002064 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002065
2066 unsigned ChildNo = 0;
2067 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2068 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002069
Chris Lattner8cab0212008-01-05 22:25:12 +00002070 // If the instruction expects a predicate or optional def operand, we
2071 // codegen this by setting the operand to it's default value if it has a
2072 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00002073 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002074 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2075 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002076
Chris Lattner8cab0212008-01-05 22:25:12 +00002077 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002078 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002079 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002080 return false;
2081 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002082
Chris Lattner8cab0212008-01-05 22:25:12 +00002083 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002084 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002085
2086 // If the operand has sub-operands, they may be provided by distinct
2087 // child patterns, so attempt to match each sub-operand separately.
2088 if (OperandNode->isSubClassOf("Operand")) {
2089 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2090 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2091 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002092 // a single ComplexPattern-related Operand.
2093
2094 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002095 // Match first sub-operand against the child we already have.
2096 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2097 MadeChange |=
2098 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2099
2100 // And the remaining sub-operands against subsequent children.
2101 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2102 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002103 emitTooFewOperandsError(TP, getOperator()->getName(),
2104 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002105 return false;
2106 }
2107 Child = getChild(ChildNo++);
2108
2109 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2110 MadeChange |=
2111 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2112 }
2113 continue;
2114 }
2115 }
2116 }
2117
2118 // If we didn't match by pieces above, attempt to match the whole
2119 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002120 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002121 }
Christopher Lamba7312392008-03-11 09:33:47 +00002122
Matt Arsenaulteb492162014-11-02 23:46:51 +00002123 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002124 emitTooManyOperandsError(TP, getOperator()->getName(),
2125 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002126 return false;
2127 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002128
Ulrich Weigande618abd2013-03-19 19:51:09 +00002129 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2130 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002131 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002132 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002133
Tim Northoverc807a172014-05-20 11:52:46 +00002134 if (getOperator()->isSubClassOf("ComplexPattern")) {
2135 bool MadeChange = false;
2136
2137 for (unsigned i = 0; i < getNumChildren(); ++i)
2138 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2139
2140 return MadeChange;
2141 }
2142
Chris Lattneree820ac2010-02-23 05:51:07 +00002143 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002144
Chris Lattneree820ac2010-02-23 05:51:07 +00002145 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002146 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002147 TP.error("Node transform '" + getOperator()->getName() +
2148 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002149 return false;
2150 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002151
Chris Lattnercabe0372010-03-15 06:00:16 +00002152 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002153 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002154}
2155
2156/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2157/// RHS of a commutative operation, not the on LHS.
2158static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2159 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
2160 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00002161 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002162 return true;
2163 return false;
2164}
2165
2166
2167/// canPatternMatch - If it is impossible for this pattern to match on this
2168/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002169/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002170/// that can never possibly work), and to prevent the pattern permuter from
2171/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002172bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002173 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002174 if (isLeaf()) return true;
2175
2176 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2177 if (!getChild(i)->canPatternMatch(Reason, CDP))
2178 return false;
2179
2180 // If this is an intrinsic, handle cases that would make it not match. For
2181 // example, if an operand is required to be an immediate.
2182 if (getOperator()->isSubClassOf("Intrinsic")) {
2183 // TODO:
2184 return true;
2185 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002186
Tim Northoverc807a172014-05-20 11:52:46 +00002187 if (getOperator()->isSubClassOf("ComplexPattern"))
2188 return true;
2189
Chris Lattner8cab0212008-01-05 22:25:12 +00002190 // If this node is a commutative operator, check that the LHS isn't an
2191 // immediate.
2192 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002193 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2194 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002195 // Scan all of the operands of the node and make sure that only the last one
2196 // is a constant node, unless the RHS also is.
2197 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002198 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002199 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002200 if (OnlyOnRHSOfCommutative(getChild(i))) {
2201 Reason="Immediate value must be on the RHS of commutative operators!";
2202 return false;
2203 }
2204 }
2205 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002206
Chris Lattner8cab0212008-01-05 22:25:12 +00002207 return true;
2208}
2209
2210//===----------------------------------------------------------------------===//
2211// TreePattern implementation
2212//
2213
David Greeneaf8ee2c2011-07-29 22:43:06 +00002214TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002215 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002216 isInputPattern(isInput), HasError(false),
2217 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002218 for (Init *I : RawPat->getValues())
2219 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002220}
2221
David Greeneaf8ee2c2011-07-29 22:43:06 +00002222TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002223 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002224 isInputPattern(isInput), HasError(false),
2225 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002226 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002227}
2228
David Blaikiecf195302014-11-17 22:55:41 +00002229TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002230 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002231 isInputPattern(isInput), HasError(false),
2232 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002233 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002234}
2235
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002236void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002237 if (HasError)
2238 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002239 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002240 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2241 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002242}
2243
Chris Lattnercabe0372010-03-15 06:00:16 +00002244void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00002245 for (TreePatternNode *Tree : Trees)
2246 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00002247}
2248
2249void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2250 if (!N->getName().empty())
2251 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002252
Chris Lattnercabe0372010-03-15 06:00:16 +00002253 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2254 ComputeNamedNodes(N->getChild(i));
2255}
2256
David Blaikiecf195302014-11-17 22:55:41 +00002257
2258TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002259 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002260 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002261
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002262 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002263 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002264 /// (foo GPR, imm) -> (foo GPR, (imm))
2265 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002266 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002267 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002268 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002269 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002270
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002271 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002272 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002273 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002274 if (OpName.empty())
2275 error("'node' argument requires a name to match with operand list");
2276 Args.push_back(OpName);
2277 }
2278
2279 Res->setName(OpName);
2280 return Res;
2281 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002282
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002283 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002284 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002285 if (OpName.empty())
2286 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002287 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002288 Args.push_back(OpName);
2289 Res->setName(OpName);
2290 return Res;
2291 }
2292
Sean Silvafb509ed2012-10-10 20:24:43 +00002293 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002294 if (!OpName.empty())
2295 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002296 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002297 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002298
Sean Silvafb509ed2012-10-10 20:24:43 +00002299 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002300 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002301 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002302 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002303 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002304 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002305 }
2306
Sean Silvafb509ed2012-10-10 20:24:43 +00002307 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002308 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002309 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002310 error("Pattern has unexpected init kind!");
2311 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002312 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002313 if (!OpDef) error("Pattern has unexpected operator type!");
2314 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002315
Chris Lattner8cab0212008-01-05 22:25:12 +00002316 if (Operator->isSubClassOf("ValueType")) {
2317 // If the operator is a ValueType, then this must be "type cast" of a leaf
2318 // node.
2319 if (Dag->getNumArgs() != 1)
2320 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002321
Matthias Braunbb053162016-12-05 06:00:46 +00002322 TreePatternNode *New = ParseTreePattern(Dag->getArg(0),
2323 Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002324
Chris Lattner8cab0212008-01-05 22:25:12 +00002325 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002326 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002327 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2328 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002329
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002330 if (!OpName.empty())
2331 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002332 return New;
2333 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002334
Chris Lattner8cab0212008-01-05 22:25:12 +00002335 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002336 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002337 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002338 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002339 !Operator->isSubClassOf("SDNodeXForm") &&
2340 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002341 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002342 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002343 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002344 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002345
Chris Lattner8cab0212008-01-05 22:25:12 +00002346 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002347 if (isInputPattern) {
2348 if (Operator->isSubClassOf("Instruction") ||
2349 Operator->isSubClassOf("SDNodeXForm"))
2350 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2351 } else {
2352 if (Operator->isSubClassOf("Intrinsic"))
2353 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002354
Chris Lattner2e9eae12010-03-28 06:57:56 +00002355 if (Operator->isSubClassOf("SDNode") &&
2356 Operator->getName() != "imm" &&
2357 Operator->getName() != "fpimm" &&
2358 Operator->getName() != "tglobaltlsaddr" &&
2359 Operator->getName() != "tconstpool" &&
2360 Operator->getName() != "tjumptable" &&
2361 Operator->getName() != "tframeindex" &&
2362 Operator->getName() != "texternalsym" &&
2363 Operator->getName() != "tblockaddress" &&
2364 Operator->getName() != "tglobaladdr" &&
2365 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002366 Operator->getName() != "vt" &&
2367 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002368 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2369 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002370
Chris Lattner8cab0212008-01-05 22:25:12 +00002371 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002372
2373 // Parse all the operands.
2374 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002375 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002376
Chris Lattner8cab0212008-01-05 22:25:12 +00002377 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002378 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002379 // convert the intrinsic name to a number.
2380 if (Operator->isSubClassOf("Intrinsic")) {
2381 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2382 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2383
2384 // If this intrinsic returns void, it must have side-effects and thus a
2385 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002386 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002387 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002388 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002389 // Has side-effects, requires chain.
2390 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002391 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002392 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002393
David Greenee32ebf22011-07-29 19:07:07 +00002394 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002395 Children.insert(Children.begin(), IIDNode);
2396 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002397
Tim Northoverc807a172014-05-20 11:52:46 +00002398 if (Operator->isSubClassOf("ComplexPattern")) {
2399 for (unsigned i = 0; i < Children.size(); ++i) {
2400 TreePatternNode *Child = Children[i];
2401
2402 if (Child->getName().empty())
2403 error("All arguments to a ComplexPattern must be named");
2404
2405 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2406 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2407 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2408 auto OperandId = std::make_pair(Operator, i);
2409 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2410 if (PrevOp != ComplexPatternOperands.end()) {
2411 if (PrevOp->getValue() != OperandId)
2412 error("All ComplexPattern operands must appear consistently: "
2413 "in the same order in just one ComplexPattern instance.");
2414 } else
2415 ComplexPatternOperands[Child->getName()] = OperandId;
2416 }
2417 }
2418
Chris Lattnerf1447252010-03-19 21:37:09 +00002419 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002420 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002421 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002422
Matthias Braun7cf3b112016-12-05 06:00:41 +00002423 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002424 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002425 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002426 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002427 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002428}
2429
Chris Lattnera787c9e2010-03-28 08:38:32 +00002430/// SimplifyTree - See if we can simplify this tree to eliminate something that
2431/// will never match in favor of something obvious that will. This is here
2432/// strictly as a convenience to target authors because it allows them to write
2433/// more type generic things and have useless type casts fold away.
2434///
2435/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002436static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002437 if (N->isLeaf())
2438 return false;
2439
2440 // If we have a bitconvert with a resolved type and if the source and
2441 // destination types are the same, then the bitconvert is useless, remove it.
2442 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002443 N->getExtType(0).isValueTypeByHwMode(false) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002444 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2445 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002446 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002447 SimplifyTree(N);
2448 return true;
2449 }
2450
2451 // Walk all children.
2452 bool MadeChange = false;
2453 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002454 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002455 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002456 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002457 }
2458 return MadeChange;
2459}
2460
2461
2462
Chris Lattner8cab0212008-01-05 22:25:12 +00002463/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002464/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002465/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002466bool TreePattern::
2467InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2468 if (NamedNodes.empty())
2469 ComputeNamedNodes();
2470
Chris Lattner8cab0212008-01-05 22:25:12 +00002471 bool MadeChange = true;
2472 while (MadeChange) {
2473 MadeChange = false;
Craig Topper3f7864e2017-08-30 02:05:03 +00002474 for (TreePatternNode *&Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002475 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2476 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002477 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002478
2479 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002480 for (auto &Entry : NamedNodes) {
2481 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002482
Chris Lattnercabe0372010-03-15 06:00:16 +00002483 // If we have input named node types, propagate their types to the named
2484 // values here.
2485 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002486 if (!InNamedTypes->count(Entry.getKey())) {
2487 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002488 "' in output pattern but not input pattern");
2489 return true;
2490 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002491
2492 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002493 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002494
2495 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002496 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002497 // If this node is a register class, and it is the root of the pattern
2498 // then we're mapping something onto an input register. We allow
2499 // changing the type of the input register in this case. This allows
2500 // us to match things like:
2501 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002502 if (Node == Trees[0] && Node->isLeaf()) {
2503 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002504 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2505 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002506 continue;
2507 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002508
Craig Topper306cb122015-11-22 20:46:24 +00002509 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002510 InNodes[0]->getNumTypes() == 1 &&
2511 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002512 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2513 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002514 }
2515 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002516
Chris Lattnercabe0372010-03-15 06:00:16 +00002517 // If there are multiple nodes with the same name, they must all have the
2518 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002519 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002520 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002521 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002522 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002523 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002524
Chris Lattnerf1447252010-03-19 21:37:09 +00002525 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2526 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002527 }
2528 }
2529 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002530 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002531
Chris Lattner8cab0212008-01-05 22:25:12 +00002532 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002533 for (const TreePatternNode *Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002534 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002535 return !HasUnresolvedTypes;
2536}
2537
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002538void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002539 OS << getRecord()->getName();
2540 if (!Args.empty()) {
2541 OS << "(" << Args[0];
2542 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2543 OS << ", " << Args[i];
2544 OS << ")";
2545 }
2546 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002547
Chris Lattner8cab0212008-01-05 22:25:12 +00002548 if (Trees.size() > 1)
2549 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002550 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002551 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002552 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002553 OS << "\n";
2554 }
2555
2556 if (Trees.size() > 1)
2557 OS << "]\n";
2558}
2559
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002560void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002561
2562//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002563// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002564//
2565
Jim Grosbach65586fe2010-12-21 16:16:00 +00002566CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002567 Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002568
Justin Bogner92a8c612016-07-15 16:31:37 +00002569 Intrinsics = CodeGenIntrinsicTable(Records, false);
2570 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002571 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002572 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002573 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002574 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002575 ParseDefaultOperands();
2576 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002577 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002578 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002579
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002580 // Break patterns with parameterized types into a series of patterns,
2581 // where each one has a fixed type and is predicated on the conditions
2582 // of the associated HW mode.
2583 ExpandHwModeBasedTypes();
2584
Chris Lattner8cab0212008-01-05 22:25:12 +00002585 // Generate variants. For example, commutative patterns can match
2586 // multiple ways. Add them to PatternsToMatch as well.
2587 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002588
2589 // Infer instruction flags. For example, we can detect loads,
2590 // stores, and side effects in many cases by examining an
2591 // instruction's pattern.
2592 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002593
2594 // Verify that instruction flags match the patterns.
2595 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002596}
2597
Daniel Sanders9e0ae7b2017-10-13 19:00:01 +00002598Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002599 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002600 if (!N || !N->isSubClassOf("SDNode"))
2601 PrintFatalError("Error getting SDNode '" + Name + "'!");
2602
Chris Lattner8cab0212008-01-05 22:25:12 +00002603 return N;
2604}
2605
2606// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002607void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002608 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002609 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2610
Chris Lattner8cab0212008-01-05 22:25:12 +00002611 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002612 Record *R = Nodes.back();
2613 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002614 Nodes.pop_back();
2615 }
2616
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002617 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002618 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2619 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2620 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2621}
2622
2623/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2624/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002625void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002626 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2627 while (!Xforms.empty()) {
2628 Record *XFormNode = Xforms.back();
2629 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00002630 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002631 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002632
2633 Xforms.pop_back();
2634 }
2635}
2636
Chris Lattnerab3242f2008-01-06 01:10:31 +00002637void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002638 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2639 while (!AMs.empty()) {
2640 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2641 AMs.pop_back();
2642 }
2643}
2644
2645
2646/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2647/// file, building up the PatternFragments map. After we've collected them all,
2648/// inline fragments together as necessary, so that there are no references left
2649/// inside a pattern fragment to a pattern fragment.
2650///
Hal Finkel2756dc12014-02-28 00:26:56 +00002651void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002652 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002653
Chris Lattnere7170df2008-01-05 22:43:57 +00002654 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002655 for (Record *Frag : Fragments) {
2656 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002657 continue;
2658
Craig Topper306cb122015-11-22 20:46:24 +00002659 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002660 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002661 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2662 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002663 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002664
Chris Lattnere7170df2008-01-05 22:43:57 +00002665 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002666 std::vector<std::string> &Args = P->getArgList();
Zachary Turner249dc142017-09-20 18:01:40 +00002667 // Copy the args so we can take StringRefs to them.
2668 auto ArgsCopy = Args;
2669 SmallDenseSet<StringRef, 4> OperandsSet;
2670 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002671
Chris Lattnere7170df2008-01-05 22:43:57 +00002672 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002673 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002674
Chris Lattner8cab0212008-01-05 22:25:12 +00002675 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002676 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002677 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002678 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002679 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002680 if (!OpsOp ||
2681 (OpsOp->getDef()->getName() != "ops" &&
2682 OpsOp->getDef()->getName() != "outs" &&
2683 OpsOp->getDef()->getName() != "ins"))
2684 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002685
2686 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002687 Args.clear();
2688 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002689 if (!isa<DefInit>(OpsList->getArg(j)) ||
2690 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002691 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00002692 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00002693 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00002694 StringRef ArgNameStr = OpsList->getArgNameStr(j);
2695 if (!OperandsSet.count(ArgNameStr))
2696 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00002697 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00002698 OperandsSet.erase(ArgNameStr);
2699 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00002700 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002701
Chris Lattnere7170df2008-01-05 22:43:57 +00002702 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002703 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002704 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002705
Chris Lattnere7170df2008-01-05 22:43:57 +00002706 // If there is a code init for this fragment, keep track of the fact that
2707 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002708 TreePredicateFn PredFn(P);
2709 if (!PredFn.isAlwaysTrue())
2710 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002711
Chris Lattner8cab0212008-01-05 22:25:12 +00002712 // If there is a node transformation corresponding to this, keep track of
2713 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002714 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002715 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2716 P->getOnlyTree()->setTransformFn(Transform);
2717 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002718
Chris Lattner8cab0212008-01-05 22:25:12 +00002719 // Now that we've parsed all of the tree fragments, do a closure on them so
2720 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002721 for (Record *Frag : Fragments) {
2722 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002723 continue;
2724
Craig Topper306cb122015-11-22 20:46:24 +00002725 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002726 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002727
Chris Lattner8cab0212008-01-05 22:25:12 +00002728 // Infer as many types as possible. Don't worry about it if we don't infer
2729 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002730 ThePat.InferAllTypes();
2731 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002732
Chris Lattner8cab0212008-01-05 22:25:12 +00002733 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002734 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002735 }
2736}
2737
Chris Lattnerab3242f2008-01-06 01:10:31 +00002738void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002739 std::vector<Record*> DefaultOps;
2740 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002741
2742 // Find some SDNode.
2743 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002744 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002745
Tom Stellardb7246a72012-09-06 14:15:52 +00002746 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2747 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002748
Tom Stellardb7246a72012-09-06 14:15:52 +00002749 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2750 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00002751 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00002752 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2753 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2754 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00002755 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002756
Tom Stellardb7246a72012-09-06 14:15:52 +00002757 // Create a TreePattern to parse this.
2758 TreePattern P(DefaultOps[i], DI, false, *this);
2759 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002760
Tom Stellardb7246a72012-09-06 14:15:52 +00002761 // Copy the operands over into a DAGDefaultOperand.
2762 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002763
Tom Stellardb7246a72012-09-06 14:15:52 +00002764 TreePatternNode *T = P.getTree(0);
2765 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2766 TreePatternNode *TPN = T->getChild(op);
2767 while (TPN->ApplyTypeConstraints(P, false))
2768 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002769
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002770 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002771 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2772 DefaultOps[i]->getName() +
2773 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002774 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002775 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002776 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002777
2778 // Insert it into the DefaultOperands map so we can find it later.
2779 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002780 }
2781}
2782
2783/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2784/// instruction input. Return true if this is a real use.
2785static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002786 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002787 // No name -> not interesting.
2788 if (Pat->getName().empty()) {
2789 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002790 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002791 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2792 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002793 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002794 }
2795 return false;
2796 }
2797
2798 Record *Rec;
2799 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002800 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002801 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2802 Rec = DI->getDef();
2803 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002804 Rec = Pat->getOperator();
2805 }
2806
2807 // SRCVALUE nodes are ignored.
2808 if (Rec->getName() == "srcvalue")
2809 return false;
2810
2811 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2812 if (!Slot) {
2813 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002814 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002815 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002816 Record *SlotRec;
2817 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002818 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002819 } else {
2820 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2821 SlotRec = Slot->getOperator();
2822 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002823
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002824 // Ensure that the inputs agree if we've already seen this input.
2825 if (Rec != SlotRec)
2826 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002827 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002828 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002829 return true;
2830}
2831
2832/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2833/// part of "I", the instruction), computing the set of inputs and outputs of
2834/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002835void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002836FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2837 std::map<std::string, TreePatternNode*> &InstInputs,
2838 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002839 std::vector<Record*> &InstImpResults) {
2840 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002841 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002842 if (!isUse && Pat->getTransformFn())
2843 I->error("Cannot specify a transform function for a non-input value!");
2844 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002845 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002846
Chris Lattnerf2d70992010-02-17 06:53:36 +00002847 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002848 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2849 TreePatternNode *Dest = Pat->getChild(i);
2850 if (!Dest->isLeaf())
2851 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002852
Sean Silvafb509ed2012-10-10 20:24:43 +00002853 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002854 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2855 I->error("implicitly defined value should be a register!");
2856 InstImpResults.push_back(Val->getDef());
2857 }
2858 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002859 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002860
Chris Lattnerf2d70992010-02-17 06:53:36 +00002861 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002862 // If this is not a set, verify that the children nodes are not void typed,
2863 // and recurse.
2864 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002865 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002866 I->error("Cannot have void nodes inside of patterns!");
2867 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002868 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002869 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002870
Chris Lattner8cab0212008-01-05 22:25:12 +00002871 // If this is a non-leaf node with no children, treat it basically as if
2872 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002873 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002874
Chris Lattner8cab0212008-01-05 22:25:12 +00002875 if (!isUse && Pat->getTransformFn())
2876 I->error("Cannot specify a transform function for a non-input value!");
2877 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002878 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002879
Chris Lattner8cab0212008-01-05 22:25:12 +00002880 // Otherwise, this is a set, validate and collect instruction results.
2881 if (Pat->getNumChildren() == 0)
2882 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002883
Chris Lattner8cab0212008-01-05 22:25:12 +00002884 if (Pat->getTransformFn())
2885 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002886
Chris Lattner8cab0212008-01-05 22:25:12 +00002887 // Check the set destinations.
2888 unsigned NumDests = Pat->getNumChildren()-1;
2889 for (unsigned i = 0; i != NumDests; ++i) {
2890 TreePatternNode *Dest = Pat->getChild(i);
2891 if (!Dest->isLeaf())
2892 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002893
Sean Silvafb509ed2012-10-10 20:24:43 +00002894 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002895 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002896 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002897 continue;
2898 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002899
2900 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002901 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002902 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002903 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002904 if (Dest->getName().empty())
2905 I->error("set destination must have a name!");
2906 if (InstResults.count(Dest->getName()))
2907 I->error("cannot set '" + Dest->getName() +"' multiple times");
2908 InstResults[Dest->getName()] = Dest;
2909 } else if (Val->getDef()->isSubClassOf("Register")) {
2910 InstImpResults.push_back(Val->getDef());
2911 } else {
2912 I->error("set destination should be a register!");
2913 }
2914 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002915
Chris Lattner8cab0212008-01-05 22:25:12 +00002916 // Verify and collect info from the computation.
2917 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002918 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002919}
2920
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002921//===----------------------------------------------------------------------===//
2922// Instruction Analysis
2923//===----------------------------------------------------------------------===//
2924
2925class InstAnalyzer {
2926 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002927public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002928 bool hasSideEffects;
2929 bool mayStore;
2930 bool mayLoad;
2931 bool isBitcast;
2932 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002933
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002934 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2935 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2936 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002937
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002938 void Analyze(const TreePattern *Pat) {
2939 // Assume only the first tree is the pattern. The others are clobber nodes.
2940 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002941 }
2942
Craig Topper2a053a92017-06-20 16:34:37 +00002943 void Analyze(const PatternToMatch &Pat) {
2944 AnalyzeNode(Pat.getSrcPattern());
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002945 }
2946
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002947private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002948 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002949 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002950 return false;
2951
2952 if (N->getNumChildren() != 2)
2953 return false;
2954
2955 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002956 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002957 return false;
2958
2959 const TreePatternNode *N1 = N->getChild(1);
2960 if (N1->isLeaf())
2961 return false;
2962 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2963 return false;
2964
2965 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2966 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2967 return false;
2968 return OpInfo.getEnumName() == "ISD::BITCAST";
2969 }
2970
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002971public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002972 void AnalyzeNode(const TreePatternNode *N) {
2973 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002974 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002975 Record *LeafRec = DI->getDef();
2976 // Handle ComplexPattern leaves.
2977 if (LeafRec->isSubClassOf("ComplexPattern")) {
2978 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2979 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2980 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002981 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002982 }
2983 }
2984 return;
2985 }
2986
2987 // Analyze children.
2988 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2989 AnalyzeNode(N->getChild(i));
2990
2991 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002992 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002993 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002994 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002995 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002996
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002997 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002998 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2999 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3000 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3001 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003002
3003 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
3004 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003005 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003006 mayLoad = true;// These may load memory.
3007
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003008 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003009 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3010
Matt Arsenault868af922017-04-28 21:01:46 +00003011 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3012 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003013 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003014 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003015 }
3016 }
3017
3018};
3019
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003020static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003021 const InstAnalyzer &PatInfo,
3022 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003023 bool Error = false;
3024
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003025 // Remember where InstInfo got its flags.
3026 if (InstInfo.hasUndefFlags())
3027 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003028
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003029 // Check explicitly set flags for consistency.
3030 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3031 !InstInfo.hasSideEffects_Unset) {
3032 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3033 // the pattern has no side effects. That could be useful for div/rem
3034 // instructions that may trap.
3035 if (!InstInfo.hasSideEffects) {
3036 Error = true;
3037 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3038 Twine(InstInfo.hasSideEffects));
3039 }
3040 }
3041
3042 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3043 Error = true;
3044 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3045 Twine(InstInfo.mayStore));
3046 }
3047
3048 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3049 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003050 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003051 if (!InstInfo.mayLoad) {
3052 Error = true;
3053 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3054 Twine(InstInfo.mayLoad));
3055 }
3056 }
3057
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003058 // Transfer inferred flags.
3059 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3060 InstInfo.mayStore |= PatInfo.mayStore;
3061 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003062
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003063 // These flags are silently added without any verification.
3064 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003065
3066 // Don't infer isVariadic. This flag means something different on SDNodes and
3067 // instructions. For example, a CALL SDNode is variadic because it has the
3068 // call arguments as operands, but a CALL instruction is not variadic - it
3069 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003070
3071 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003072}
3073
Jim Grosbach514410b2012-07-17 00:47:06 +00003074/// hasNullFragReference - Return true if the DAG has any reference to the
3075/// null_frag operator.
3076static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003077 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003078 if (!OpDef) return false;
3079 Record *Operator = OpDef->getDef();
3080
3081 // If this is the null fragment, return true.
3082 if (Operator->getName() == "null_frag") return true;
3083 // If any of the arguments reference the null fragment, return true.
3084 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003085 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003086 if (Arg && hasNullFragReference(Arg))
3087 return true;
3088 }
3089
3090 return false;
3091}
3092
3093/// hasNullFragReference - Return true if any DAG in the list references
3094/// the null_frag operator.
3095static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003096 for (Init *I : LI->getValues()) {
3097 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003098 assert(DI && "non-dag in an instruction Pattern list?!");
3099 if (hasNullFragReference(DI))
3100 return true;
3101 }
3102 return false;
3103}
3104
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003105/// Get all the instructions in a tree.
3106static void
3107getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3108 if (Tree->isLeaf())
3109 return;
3110 if (Tree->getOperator()->isSubClassOf("Instruction"))
3111 Instrs.push_back(Tree->getOperator());
3112 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3113 getInstructionsInTree(Tree->getChild(i), Instrs);
3114}
3115
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003116/// Check the class of a pattern leaf node against the instruction operand it
3117/// represents.
3118static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3119 Record *Leaf) {
3120 if (OI.Rec == Leaf)
3121 return true;
3122
3123 // Allow direct value types to be used in instruction set patterns.
3124 // The type will be checked later.
3125 if (Leaf->isSubClassOf("ValueType"))
3126 return true;
3127
3128 // Patterns can also be ComplexPattern instances.
3129 if (Leaf->isSubClassOf("ComplexPattern"))
3130 return true;
3131
3132 return false;
3133}
3134
Ahmed Bougacha14107512013-10-28 18:07:21 +00003135const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
3136 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003137
Craig Topper0d1fb902015-03-10 03:25:04 +00003138 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003139
Craig Topper0d1fb902015-03-10 03:25:04 +00003140 // Parse the instruction.
3141 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
3142 // Inline pattern fragments into it.
3143 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003144
Craig Topper0d1fb902015-03-10 03:25:04 +00003145 // Infer as many types as possible. If we cannot infer all of them, we can
3146 // never do anything with this instruction pattern: report it to the user.
3147 if (!I->InferAllTypes())
3148 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003149
Craig Topper0d1fb902015-03-10 03:25:04 +00003150 // InstInputs - Keep track of all of the inputs of the instruction, along
3151 // with the record they are declared as.
3152 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003153
Craig Topper0d1fb902015-03-10 03:25:04 +00003154 // InstResults - Keep track of all the virtual registers that are 'set'
3155 // in the instruction, including what reg class they are.
3156 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003157
Craig Topper0d1fb902015-03-10 03:25:04 +00003158 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003159
Craig Topper0d1fb902015-03-10 03:25:04 +00003160 // Verify that the top-level forms in the instruction are of void type, and
3161 // fill in the InstResults map.
Zachary Turner249dc142017-09-20 18:01:40 +00003162 SmallString<32> TypesString;
Craig Topper0d1fb902015-03-10 03:25:04 +00003163 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
Zachary Turner249dc142017-09-20 18:01:40 +00003164 TypesString.clear();
Craig Topper0d1fb902015-03-10 03:25:04 +00003165 TreePatternNode *Pat = I->getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003166 if (Pat->getNumTypes() != 0) {
Zachary Turner249dc142017-09-20 18:01:40 +00003167 raw_svector_ostream OS(TypesString);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003168 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3169 if (k > 0)
Zachary Turner249dc142017-09-20 18:01:40 +00003170 OS << ", ";
3171 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003172 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003173 I->error("Top-level forms in instruction pattern should have"
Zachary Turner249dc142017-09-20 18:01:40 +00003174 " void types, has types " +
3175 OS.str());
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003176 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003177
Craig Topper0d1fb902015-03-10 03:25:04 +00003178 // Find inputs and outputs, and verify the structure of the uses/defs.
3179 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3180 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003181 }
3182
Craig Topper0d1fb902015-03-10 03:25:04 +00003183 // Now that we have inputs and outputs of the pattern, inspect the operands
3184 // list for the instruction. This determines the order that operands are
3185 // added to the machine instruction the node corresponds to.
3186 unsigned NumResults = InstResults.size();
3187
3188 // Parse the operands list from the (ops) list, validating it.
3189 assert(I->getArgList().empty() && "Args list should still be empty here!");
3190
3191 // Check that all of the results occur first in the list.
3192 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00003193 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003194 for (unsigned i = 0; i != NumResults; ++i) {
3195 if (i == CGI.Operands.size())
3196 I->error("'" + InstResults.begin()->first +
3197 "' set but does not appear in operand list!");
3198 const std::string &OpName = CGI.Operands[i].Name;
3199
3200 // Check that it exists in InstResults.
3201 TreePatternNode *RNode = InstResults[OpName];
3202 if (!RNode)
3203 I->error("Operand $" + OpName + " does not exist in operand list!");
3204
Craig Topper3a8eb892015-03-20 05:09:06 +00003205 ResNodes.push_back(RNode);
3206
Craig Topper0d1fb902015-03-10 03:25:04 +00003207 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3208 if (!R)
3209 I->error("Operand $" + OpName + " should be a set destination: all "
3210 "outputs must occur before inputs in operand list!");
3211
3212 if (!checkOperandClass(CGI.Operands[i], R))
3213 I->error("Operand $" + OpName + " class mismatch!");
3214
3215 // Remember the return type.
3216 Results.push_back(CGI.Operands[i].Rec);
3217
3218 // Okay, this one checks out.
3219 InstResults.erase(OpName);
3220 }
3221
3222 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3223 // the copy while we're checking the inputs.
3224 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3225
3226 std::vector<TreePatternNode*> ResultNodeOperands;
3227 std::vector<Record*> Operands;
3228 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3229 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3230 const std::string &OpName = Op.Name;
3231 if (OpName.empty())
3232 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3233
3234 if (!InstInputsCheck.count(OpName)) {
3235 // If this is an operand with a DefaultOps set filled in, we can ignore
3236 // this. When we codegen it, we will do so as always executed.
3237 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3238 // Does it have a non-empty DefaultOps field? If so, ignore this
3239 // operand.
3240 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3241 continue;
3242 }
3243 I->error("Operand $" + OpName +
3244 " does not appear in the instruction pattern");
3245 }
3246 TreePatternNode *InVal = InstInputsCheck[OpName];
3247 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3248
3249 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3250 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3251 if (!checkOperandClass(Op, InRec))
3252 I->error("Operand $" + OpName + "'s register class disagrees"
3253 " between the operand and pattern");
3254 }
3255 Operands.push_back(Op.Rec);
3256
3257 // Construct the result for the dest-pattern operand list.
3258 TreePatternNode *OpNode = InVal->clone();
3259
3260 // No predicate is useful on the result.
3261 OpNode->clearPredicateFns();
3262
3263 // Promote the xform function to be an explicit node if set.
3264 if (Record *Xform = OpNode->getTransformFn()) {
3265 OpNode->setTransformFn(nullptr);
3266 std::vector<TreePatternNode*> Children;
3267 Children.push_back(OpNode);
3268 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3269 }
3270
3271 ResultNodeOperands.push_back(OpNode);
3272 }
3273
3274 if (!InstInputsCheck.empty())
3275 I->error("Input operand $" + InstInputsCheck.begin()->first +
3276 " occurs in pattern but not in operands list!");
3277
3278 TreePatternNode *ResultPattern =
3279 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3280 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003281 // Copy fully inferred output node types to instruction result pattern.
3282 for (unsigned i = 0; i != NumResults; ++i) {
3283 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3284 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3285 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003286
3287 // Create and insert the instruction.
3288 // FIXME: InstImpResults should not be part of DAGInstruction.
3289 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3290 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3291
3292 // Use a temporary tree pattern to infer all types and make sure that the
3293 // constructed result is correct. This depends on the instruction already
3294 // being inserted into the DAGInsts map.
3295 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3296 Temp.InferAllTypes(&I->getNamedNodesMap());
3297
3298 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3299 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3300
3301 return TheInsertedInst;
3302}
3303
Ahmed Bougacha14107512013-10-28 18:07:21 +00003304/// ParseInstructions - Parse all of the instructions, inlining and resolving
3305/// any fragments involved. This populates the Instructions list with fully
3306/// resolved instructions.
3307void CodeGenDAGPatterns::ParseInstructions() {
3308 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3309
Craig Topper306cb122015-11-22 20:46:24 +00003310 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003311 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003312
Craig Topper306cb122015-11-22 20:46:24 +00003313 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3314 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003315
3316 // If there is no pattern, only collect minimal information about the
3317 // instruction for its operand list. We have to assume that there is one
3318 // result, as we have no detailed info. A pattern which references the
3319 // null_frag operator is as-if no pattern were specified. Normally this
3320 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3321 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003322 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003323 std::vector<Record*> Results;
3324 std::vector<Record*> Operands;
3325
Craig Topper306cb122015-11-22 20:46:24 +00003326 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003327
3328 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003329 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3330 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003331
Craig Topper3a8eb892015-03-20 05:09:06 +00003332 // The rest are inputs.
3333 for (unsigned j = InstInfo.Operands.NumDefs,
3334 e = InstInfo.Operands.size(); j < e; ++j)
3335 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003336 }
3337
3338 // Create and insert the instruction.
3339 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003340 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003341 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003342 continue; // no pattern.
3343 }
3344
Craig Topper306cb122015-11-22 20:46:24 +00003345 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003346 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3347
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003348 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003349 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003350 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003351
Chris Lattner8cab0212008-01-05 22:25:12 +00003352 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003353 for (auto &Entry : Instructions) {
3354 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003355 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003356 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003357
3358 // FIXME: Assume only the first tree is the pattern. The others are clobber
3359 // nodes.
3360 TreePatternNode *Pattern = I->getTree(0);
3361 TreePatternNode *SrcPattern;
3362 if (Pattern->getOperator()->getName() == "set") {
3363 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3364 } else{
3365 // Not a set (store or something?)
3366 SrcPattern = Pattern;
3367 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003368
Craig Topper306cb122015-11-22 20:46:24 +00003369 Record *Instr = Entry.first;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003370 ListInit *Preds = Instr->getValueAsListInit("Predicates");
3371 int Complexity = Instr->getValueAsInt("AddedComplexity");
3372 AddPatternToMatch(
3373 I,
3374 PatternToMatch(Instr, makePredList(Preds), SrcPattern,
3375 TheInst.getResultPattern(), TheInst.getImpResults(),
3376 Complexity, Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003377 }
3378}
3379
Chris Lattnera7722b62010-02-23 06:55:24 +00003380
3381typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3382
Jim Grosbach65586fe2010-12-21 16:16:00 +00003383static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003384 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003385 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003386 if (!P->getName().empty()) {
3387 NameRecord &Rec = Names[P->getName()];
3388 // If this is the first instance of the name, remember the node.
3389 if (Rec.second++ == 0)
3390 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003391 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003392 PatternTop->error("repetition of value: $" + P->getName() +
3393 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003394 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003395
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003396 if (!P->isLeaf()) {
3397 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003398 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003399 }
3400}
3401
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003402std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3403 std::vector<Predicate> Preds;
3404 for (Init *I : L->getValues()) {
3405 if (DefInit *Pred = dyn_cast<DefInit>(I))
3406 Preds.push_back(Pred->getDef());
3407 else
3408 llvm_unreachable("Non-def on the list");
3409 }
3410
3411 // Sort so that different orders get canonicalized to the same string.
3412 std::sort(Preds.begin(), Preds.end());
3413 return Preds;
3414}
3415
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003416void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003417 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003418 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003419 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003420 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3421 PrintWarning(Pattern->getRecord()->getLoc(),
3422 Twine("Pattern can never match: ") + Reason);
3423 return;
3424 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003425
Chris Lattner1e634e32010-03-01 22:29:19 +00003426 // If the source pattern's root is a complex pattern, that complex pattern
3427 // must specify the nodes it can potentially match.
3428 if (const ComplexPattern *CP =
3429 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3430 if (CP->getRootNodes().empty())
3431 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3432 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003433
3434
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003435 // Find all of the named values in the input and output, ensure they have the
3436 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003437 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003438 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3439 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003440
3441 // Scan all of the named values in the destination pattern, rejecting them if
3442 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003443 for (const auto &Entry : DstNames) {
3444 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003445 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003446 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003447 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003448
Chris Lattnera7722b62010-02-23 06:55:24 +00003449 // Scan all of the named values in the source pattern, rejecting them if the
3450 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003451 for (const auto &Entry : SrcNames)
3452 if (DstNames[Entry.first].first == nullptr &&
3453 SrcNames[Entry.first].second == 1)
3454 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003455
Craig Topper18e6b572017-06-25 17:33:49 +00003456 PatternsToMatch.push_back(std::move(PTM));
Chris Lattner0c0baa92010-02-23 06:16:51 +00003457}
3458
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003459void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003460 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003461 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003462
3463 // First try to infer flags from the primary instruction pattern, if any.
3464 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003465 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003466 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3467 CodeGenInstruction &InstInfo =
3468 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003469
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003470 // Get the primary instruction pattern.
3471 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3472 if (!Pattern) {
3473 if (InstInfo.hasUndefFlags())
3474 Revisit.push_back(&InstInfo);
3475 continue;
3476 }
3477 InstAnalyzer PatInfo(*this);
3478 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003479 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003480 }
3481
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003482 // Second, look for single-instruction patterns defined outside the
3483 // instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003484 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003485 // We can only infer from single-instruction patterns, otherwise we won't
3486 // know which instruction should get the flags.
3487 SmallVector<Record*, 8> PatInstrs;
3488 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3489 if (PatInstrs.size() != 1)
3490 continue;
3491
3492 // Get the single instruction.
3493 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3494
3495 // Only infer properties from the first pattern. We'll verify the others.
3496 if (InstInfo.InferredFrom)
3497 continue;
3498
3499 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003500 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003501 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3502 }
3503
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003504 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003505 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003506
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003507 // Revisit instructions with undefined flags and no pattern.
3508 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003509 for (CodeGenInstruction *InstInfo : Revisit) {
3510 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003511 continue;
3512 // The mayLoad and mayStore flags default to false.
3513 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003514 if (InstInfo->hasSideEffects_Unset)
3515 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003516 }
3517 return;
3518 }
3519
3520 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003521 for (CodeGenInstruction *InstInfo : Revisit) {
3522 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003523 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003524 if (InstInfo->hasSideEffects_Unset)
3525 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003526 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003527 if (InstInfo->mayStore_Unset)
3528 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003529 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003530 if (InstInfo->mayLoad_Unset)
3531 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003532 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003533 }
3534}
3535
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003536
3537/// Verify instruction flags against pattern node properties.
3538void CodeGenDAGPatterns::VerifyInstructionFlags() {
3539 unsigned Errors = 0;
3540 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3541 const PatternToMatch &PTM = *I;
3542 SmallVector<Record*, 8> Instrs;
3543 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3544 if (Instrs.empty())
3545 continue;
3546
3547 // Count the number of instructions with each flag set.
3548 unsigned NumSideEffects = 0;
3549 unsigned NumStores = 0;
3550 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003551 for (const Record *Instr : Instrs) {
3552 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003553 NumSideEffects += InstInfo.hasSideEffects;
3554 NumStores += InstInfo.mayStore;
3555 NumLoads += InstInfo.mayLoad;
3556 }
3557
3558 // Analyze the source pattern.
3559 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003560 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003561
3562 // Collect error messages.
3563 SmallVector<std::string, 4> Msgs;
3564
3565 // Check for missing flags in the output.
3566 // Permit extra flags for now at least.
3567 if (PatInfo.hasSideEffects && !NumSideEffects)
3568 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3569
3570 // Don't verify store flags on instructions with side effects. At least for
3571 // intrinsics, side effects implies mayStore.
3572 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3573 Msgs.push_back("pattern may store, but mayStore isn't set");
3574
3575 // Similarly, mayStore implies mayLoad on intrinsics.
3576 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3577 Msgs.push_back("pattern may load, but mayLoad isn't set");
3578
3579 // Print error messages.
3580 if (Msgs.empty())
3581 continue;
3582 ++Errors;
3583
Craig Topper306cb122015-11-22 20:46:24 +00003584 for (const std::string &Msg : Msgs)
3585 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003586 (Instrs.size() == 1 ?
3587 "instruction" : "output instructions"));
3588 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003589 for (const Record *Instr : Instrs) {
3590 if (Instr != PTM.getSrcRecord())
3591 PrintError(Instr->getLoc(), "defined here");
3592 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003593 if (InstInfo.InferredFrom &&
3594 InstInfo.InferredFrom != InstInfo.TheDef &&
3595 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003596 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003597 }
3598 }
3599 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003600 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003601}
3602
Chris Lattnercabe0372010-03-15 06:00:16 +00003603/// Given a pattern result with an unresolved type, see if we can find one
3604/// instruction with an unresolved result type. Force this result type to an
3605/// arbitrary element if it's possible types to converge results.
3606static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3607 if (N->isLeaf())
3608 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003609
Chris Lattnercabe0372010-03-15 06:00:16 +00003610 // Analyze children.
3611 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3612 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3613 return true;
3614
3615 if (!N->getOperator()->isSubClassOf("Instruction"))
3616 return false;
3617
3618 // If this type is already concrete or completely unknown we can't do
3619 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003620 TypeInfer &TI = TP.getInfer();
Chris Lattnerf1447252010-03-19 21:37:09 +00003621 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003622 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00003623 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003624
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003625 // Otherwise, force its type to an arbitrary choice.
3626 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00003627 return true;
3628 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003629
Chris Lattnerf1447252010-03-19 21:37:09 +00003630 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003631}
3632
Chris Lattnerab3242f2008-01-06 01:10:31 +00003633void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003634 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3635
Craig Topper306cb122015-11-22 20:46:24 +00003636 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003637 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003638
3639 // If the pattern references the null_frag, there's nothing to do.
3640 if (hasNullFragReference(Tree))
3641 continue;
3642
Chris Lattner5c2182e2010-03-27 02:53:27 +00003643 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003644
3645 // Inline pattern fragments into it.
3646 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003647
David Greeneaf8ee2c2011-07-29 22:43:06 +00003648 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003649 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003650
Chris Lattner8cab0212008-01-05 22:25:12 +00003651 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003652 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003653
Chris Lattner8cab0212008-01-05 22:25:12 +00003654 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003655 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003656
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003657 if (Result.getNumTrees() != 1)
3658 Result.error("Cannot handle instructions producing instructions "
3659 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003660
Chris Lattner8cab0212008-01-05 22:25:12 +00003661 bool IterateInference;
3662 bool InferredAllPatternTypes, InferredAllResultTypes;
3663 do {
3664 // Infer as many types as possible. If we cannot infer all of them, we
3665 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003666 InferredAllPatternTypes =
3667 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003668
Chris Lattner8cab0212008-01-05 22:25:12 +00003669 // Infer as many types as possible. If we cannot infer all of them, we
3670 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003671 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003672 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003673
Chris Lattnerfdc20712010-03-18 23:15:10 +00003674 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003675
Chris Lattner8cab0212008-01-05 22:25:12 +00003676 // Apply the type of the result to the source pattern. This helps us
3677 // resolve cases where the input type is known to be a pointer type (which
3678 // is considered resolved), but the result knows it needs to be 32- or
3679 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003680 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003681 Pattern->getTree(0)->getNumTypes());
3682 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003683 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3684 i, Result.getTree(0)->getExtType(i), Result);
3685 IterateInference |= Result.getTree(0)->UpdateNodeType(
3686 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003687 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003688
Chris Lattnercabe0372010-03-15 06:00:16 +00003689 // If our iteration has converged and the input pattern's types are fully
3690 // resolved but the result pattern is not fully resolved, we may have a
3691 // situation where we have two instructions in the result pattern and
3692 // the instructions require a common register class, but don't care about
3693 // what actual MVT is used. This is actually a bug in our modelling:
3694 // output patterns should have register classes, not MVTs.
3695 //
3696 // In any case, to handle this, we just go through and disambiguate some
3697 // arbitrary types to the result pattern's nodes.
3698 if (!IterateInference && InferredAllPatternTypes &&
3699 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003700 IterateInference =
3701 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003702 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003703
Chris Lattner8cab0212008-01-05 22:25:12 +00003704 // Verify that we inferred enough types that we can do something with the
3705 // pattern and result. If these fire the user has to add type casts.
3706 if (!InferredAllPatternTypes)
3707 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003708 if (!InferredAllResultTypes) {
3709 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003710 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003711 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003712
Chris Lattner8cab0212008-01-05 22:25:12 +00003713 // Validate that the input pattern is correct.
3714 std::map<std::string, TreePatternNode*> InstInputs;
3715 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003716 std::vector<Record*> InstImpResults;
3717 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3718 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3719 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003720 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003721
3722 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003723 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003724 std::vector<TreePatternNode*> ResultNodeOperands;
3725 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3726 TreePatternNode *OpNode = DstPattern->getChild(ii);
3727 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003728 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003729 std::vector<TreePatternNode*> Children;
3730 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003731 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003732 }
3733 ResultNodeOperands.push_back(OpNode);
3734 }
David Blaikiecf195302014-11-17 22:55:41 +00003735 DstPattern = Result.getOnlyTree();
3736 if (!DstPattern->isLeaf())
3737 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3738 ResultNodeOperands,
3739 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003740
David Blaikiecf195302014-11-17 22:55:41 +00003741 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3742 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3743
3744 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003745 Temp.InferAllTypes();
3746
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003747 // A pattern may end up with an "impossible" type, i.e. a situation
3748 // where all types have been eliminated for some node in this pattern.
3749 // This could occur for intrinsics that only make sense for a specific
3750 // value type, and use a specific register class. If, for some mode,
3751 // that register class does not accept that type, the type inference
3752 // will lead to a contradiction, which is not an error however, but
3753 // a sign that this pattern will simply never match.
3754 if (Pattern->getTree(0)->hasPossibleType() &&
3755 Temp.getOnlyTree()->hasPossibleType()) {
3756 ListInit *Preds = CurPattern->getValueAsListInit("Predicates");
3757 int Complexity = CurPattern->getValueAsInt("AddedComplexity");
3758 AddPatternToMatch(
3759 Pattern,
3760 PatternToMatch(
3761 CurPattern, makePredList(Preds), Pattern->getTree(0),
3762 Temp.getOnlyTree(), std::move(InstImpResults), Complexity,
3763 CurPattern->getID()));
3764 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003765 }
3766}
3767
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003768static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
3769 for (const TypeSetByHwMode &VTS : N->getExtTypes())
3770 for (const auto &I : VTS)
3771 Modes.insert(I.first);
3772
3773 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3774 collectModes(Modes, N->getChild(i));
3775}
3776
3777void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
3778 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3779 std::map<unsigned,std::vector<Predicate>> ModeChecks;
3780 std::vector<PatternToMatch> Copy = PatternsToMatch;
3781 PatternsToMatch.clear();
3782
3783 auto AppendPattern = [this,&ModeChecks](PatternToMatch &P, unsigned Mode) {
3784 TreePatternNode *NewSrc = P.SrcPattern->clone();
3785 TreePatternNode *NewDst = P.DstPattern->clone();
3786 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
3787 delete NewSrc;
3788 delete NewDst;
3789 return;
3790 }
3791
3792 std::vector<Predicate> Preds = P.Predicates;
3793 const std::vector<Predicate> &MC = ModeChecks[Mode];
3794 Preds.insert(Preds.end(), MC.begin(), MC.end());
3795 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, NewSrc, NewDst,
3796 P.getDstRegs(), P.getAddedComplexity(),
3797 Record::getNewUID(), Mode);
3798 };
3799
3800 for (PatternToMatch &P : Copy) {
3801 TreePatternNode *SrcP = nullptr, *DstP = nullptr;
3802 if (P.SrcPattern->hasProperTypeByHwMode())
3803 SrcP = P.SrcPattern;
3804 if (P.DstPattern->hasProperTypeByHwMode())
3805 DstP = P.DstPattern;
3806 if (!SrcP && !DstP) {
3807 PatternsToMatch.push_back(P);
3808 continue;
3809 }
3810
3811 std::set<unsigned> Modes;
3812 if (SrcP)
3813 collectModes(Modes, SrcP);
3814 if (DstP)
3815 collectModes(Modes, DstP);
3816
3817 // The predicate for the default mode needs to be constructed for each
3818 // pattern separately.
3819 // Since not all modes must be present in each pattern, if a mode m is
3820 // absent, then there is no point in constructing a check for m. If such
3821 // a check was created, it would be equivalent to checking the default
3822 // mode, except not all modes' predicates would be a part of the checking
3823 // code. The subsequently generated check for the default mode would then
3824 // have the exact same patterns, but a different predicate code. To avoid
3825 // duplicated patterns with different predicate checks, construct the
3826 // default check as a negation of all predicates that are actually present
3827 // in the source/destination patterns.
3828 std::vector<Predicate> DefaultPred;
3829
3830 for (unsigned M : Modes) {
3831 if (M == DefaultMode)
3832 continue;
3833 if (ModeChecks.find(M) != ModeChecks.end())
3834 continue;
3835
3836 // Fill the map entry for this mode.
3837 const HwMode &HM = CGH.getMode(M);
3838 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
3839
3840 // Add negations of the HM's predicates to the default predicate.
3841 DefaultPred.emplace_back(Predicate(HM.Features, false));
3842 }
3843
3844 for (unsigned M : Modes) {
3845 if (M == DefaultMode)
3846 continue;
3847 AppendPattern(P, M);
3848 }
3849
3850 bool HasDefault = Modes.count(DefaultMode);
3851 if (HasDefault)
3852 AppendPattern(P, DefaultMode);
3853 }
3854}
3855
3856/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turner249dc142017-09-20 18:01:40 +00003857typedef StringMap<int> DepVarMap;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003858
3859static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
3860 if (N->isLeaf()) {
Zachary Turner249dc142017-09-20 18:01:40 +00003861 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003862 DepMap[N->getName()]++;
3863 } else {
3864 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
3865 FindDepVarsOf(N->getChild(i), DepMap);
3866 }
3867}
3868
3869/// Find dependent variables within child patterns
3870static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
3871 DepVarMap depcounts;
3872 FindDepVarsOf(N, depcounts);
Zachary Turner249dc142017-09-20 18:01:40 +00003873 for (const auto &Pair : depcounts) {
3874 if (Pair.getValue() > 1)
3875 DepVars.insert(Pair.getKey());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003876 }
3877}
3878
3879#ifndef NDEBUG
3880/// Dump the dependent variable set:
3881static void DumpDepVars(MultipleUseVarSet &DepVars) {
3882 if (DepVars.empty()) {
3883 DEBUG(errs() << "<empty set>");
3884 } else {
3885 DEBUG(errs() << "[ ");
Zachary Turner249dc142017-09-20 18:01:40 +00003886 for (const auto &DepVar : DepVars) {
3887 DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003888 }
3889 DEBUG(errs() << "]");
3890 }
3891}
3892#endif
3893
3894
Chris Lattner8cab0212008-01-05 22:25:12 +00003895/// CombineChildVariants - Given a bunch of permutations of each child of the
3896/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003897static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003898 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3899 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003900 CodeGenDAGPatterns &CDP,
3901 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003902 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00003903 for (const auto &Variants : ChildVariants)
3904 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003905 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003906
Chris Lattner8cab0212008-01-05 22:25:12 +00003907 // The end result is an all-pairs construction of the resultant pattern.
3908 std::vector<unsigned> Idxs;
3909 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003910 bool NotDone;
3911 do {
3912#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003913 DEBUG(if (!Idxs.empty()) {
3914 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00003915 for (unsigned Idx : Idxs) {
3916 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003917 }
3918 errs() << "]\n";
3919 });
Scott Michel94420742008-03-05 17:49:05 +00003920#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003921 // Create the variant and add it to the output list.
3922 std::vector<TreePatternNode*> NewChildren;
3923 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3924 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00003925 auto R = llvm::make_unique<TreePatternNode>(
3926 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003927
Chris Lattner8cab0212008-01-05 22:25:12 +00003928 // Copy over properties.
3929 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003930 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003931 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003932 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3933 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003934
Scott Michel94420742008-03-05 17:49:05 +00003935 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003936 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00003937 // Scan to see if this pattern has already been emitted. We can get
3938 // duplication due to things like commuting:
3939 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3940 // which are the same pattern. Ignore the dups.
3941 if (R->canPatternMatch(ErrString, CDP) &&
David Majnemer0a16c222016-08-11 21:15:00 +00003942 none_of(OutVariants, [&](TreePatternNode *Variant) {
3943 return R->isIsomorphicTo(Variant, DepVars);
3944 }))
David Blaikiefda69dd2015-11-22 20:11:21 +00003945 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003946
Scott Michel94420742008-03-05 17:49:05 +00003947 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003948 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00003949 // [0, 0], [0, 1], [1, 0], [1, 1].
3950 int IdxsIdx;
3951 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3952 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3953 Idxs[IdxsIdx] = 0;
3954 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003955 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003956 }
Scott Michel94420742008-03-05 17:49:05 +00003957 NotDone = (IdxsIdx >= 0);
3958 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003959}
3960
3961/// CombineChildVariants - A helper function for binary operators.
3962///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003963static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003964 const std::vector<TreePatternNode*> &LHS,
3965 const std::vector<TreePatternNode*> &RHS,
3966 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003967 CodeGenDAGPatterns &CDP,
3968 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003969 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3970 ChildVariants.push_back(LHS);
3971 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003972 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003973}
Chris Lattner8cab0212008-01-05 22:25:12 +00003974
3975
3976static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3977 std::vector<TreePatternNode *> &Children) {
3978 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3979 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003980
Chris Lattner8cab0212008-01-05 22:25:12 +00003981 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003982 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003983 N->getTransformFn()) {
3984 Children.push_back(N);
3985 return;
3986 }
3987
3988 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3989 Children.push_back(N->getChild(0));
3990 else
3991 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3992
3993 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3994 Children.push_back(N->getChild(1));
3995 else
3996 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3997}
3998
3999/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4000/// the (potentially recursive) pattern by using algebraic laws.
4001///
4002static void GenerateVariantsOf(TreePatternNode *N,
4003 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004004 CodeGenDAGPatterns &CDP,
4005 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00004006 // We cannot permute leaves or ComplexPattern uses.
4007 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004008 OutVariants.push_back(N);
4009 return;
4010 }
4011
4012 // Look up interesting info about the node.
4013 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4014
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004015 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00004016 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00004017 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00004018 std::vector<TreePatternNode*> MaximalChildren;
4019 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4020
4021 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4022 // permutations.
4023 if (MaximalChildren.size() == 3) {
4024 // Find the variants of all of our maximal children.
4025 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00004026 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4027 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4028 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004029
Chris Lattner8cab0212008-01-05 22:25:12 +00004030 // There are only two ways we can permute the tree:
4031 // (A op B) op C and A op (B op C)
4032 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004033
Chris Lattner8cab0212008-01-05 22:25:12 +00004034 // Generate legal pair permutations of A/B/C.
4035 std::vector<TreePatternNode*> ABVariants;
4036 std::vector<TreePatternNode*> BAVariants;
4037 std::vector<TreePatternNode*> ACVariants;
4038 std::vector<TreePatternNode*> CAVariants;
4039 std::vector<TreePatternNode*> BCVariants;
4040 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00004041 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4042 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4043 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4044 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4045 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4046 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004047
4048 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00004049 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4050 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4051 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4052 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4053 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4054 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004055
4056 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00004057 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4058 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4059 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4060 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4061 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4062 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004063 return;
4064 }
4065 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004066
Chris Lattner8cab0212008-01-05 22:25:12 +00004067 // Compute permutations of all children.
4068 std::vector<std::vector<TreePatternNode*> > ChildVariants;
4069 ChildVariants.resize(N->getNumChildren());
4070 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00004071 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004072
4073 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00004074 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004075
4076 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004077 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4078 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004079 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004080 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004081 // Don't count children which are actually register references.
4082 unsigned NC = 0;
4083 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4084 TreePatternNode *Child = N->getChild(i);
4085 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00004086 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004087 Record *RR = DI->getDef();
4088 if (RR->isSubClassOf("Register"))
4089 continue;
4090 }
4091 NC++;
4092 }
4093 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004094 if (isCommIntrinsic) {
4095 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4096 // operands are the commutative operands, and there might be more operands
4097 // after those.
4098 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004099 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00004100 std::vector<std::vector<TreePatternNode*> > Variants;
4101 Variants.push_back(ChildVariants[0]); // Intrinsic id.
4102 Variants.push_back(ChildVariants[2]);
4103 Variants.push_back(ChildVariants[1]);
4104 for (unsigned i = 3; i != NC; ++i)
4105 Variants.push_back(ChildVariants[i]);
4106 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004107 } else if (NC == N->getNumChildren()) {
4108 std::vector<std::vector<TreePatternNode*> > Variants;
4109 Variants.push_back(ChildVariants[1]);
4110 Variants.push_back(ChildVariants[0]);
4111 for (unsigned i = 2; i != NC; ++i)
4112 Variants.push_back(ChildVariants[i]);
4113 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4114 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004115 }
4116}
4117
4118
4119// GenerateVariants - Generate variants. For example, commutative patterns can
4120// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004121void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00004122 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004123
Chris Lattner8cab0212008-01-05 22:25:12 +00004124 // Loop over all of the patterns we've collected, checking to see if we can
4125 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004126 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004127 // the .td file having to contain tons of variants of instructions.
4128 //
4129 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4130 // intentionally do not reconsider these. Any variants of added patterns have
4131 // already been added.
4132 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00004133 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00004134 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00004135 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004136 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00004137 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00004138 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00004139 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00004140 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00004141 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004142
4143 assert(!Variants.empty() && "Must create at least original variant!");
Krzysztof Parzyszekf7237762017-06-16 13:44:34 +00004144 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004145 continue;
4146
Chris Lattner34822f62009-08-23 04:44:11 +00004147 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00004148 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00004149 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004150
4151 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4152 TreePatternNode *Variant = Variants[v];
4153
Chris Lattner34822f62009-08-23 04:44:11 +00004154 DEBUG(errs() << " VAR#" << v << ": ";
4155 Variant->dump();
4156 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004157
Chris Lattner8cab0212008-01-05 22:25:12 +00004158 // Scan to see if an instruction or explicit pattern already matches this.
4159 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004160 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004161 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004162 if (PatternsToMatch[i].getPredicates() !=
4163 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00004164 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004165 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004166 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4167 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00004168 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004169 AlreadyExists = true;
4170 break;
4171 }
4172 }
4173 // If we already have it, ignore the variant.
4174 if (AlreadyExists) continue;
4175
4176 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004177 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004178 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4179 Variant, PatternsToMatch[i].getDstPattern(),
4180 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004181 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00004182 }
4183
Chris Lattner34822f62009-08-23 04:44:11 +00004184 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004185 }
4186}