blob: d4c81c327abbda2983518d3c722f2c6a5c17619e [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 Parzyszek426bf362017-09-12 15:31:26 +0000241LLVM_DUMP_METHOD
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000242void TypeSetByHwMode::dump() const {
Zachary Turner249dc142017-09-20 18:01:40 +0000243 writeToStream(dbgs());
244 dbgs() << '\n';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000245}
246
247bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
248 bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
249 auto Int = [&In](MVT T) -> bool { return !In.count(T); };
250
251 if (OutP == InP)
252 return berase_if(Out, Int);
253
254 // Compute the intersection of scalars separately to account for only
255 // one set containing iPTR.
256 // The itersection of iPTR with a set of integer scalar types that does not
257 // include iPTR will result in the most specific scalar type:
258 // - iPTR is more specific than any set with two elements or more
259 // - iPTR is less specific than any single integer scalar type.
260 // For example
261 // { iPTR } * { i32 } -> { i32 }
262 // { iPTR } * { i32 i64 } -> { iPTR }
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000263 // and
264 // { iPTR i32 } * { i32 } -> { i32 }
265 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
266 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000267
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000268 // Compute the difference between the two sets in such a way that the
269 // iPTR is in the set that is being subtracted. This is to see if there
270 // are any extra scalars in the set without iPTR that are not in the
271 // set containing iPTR. Then the iPTR could be considered a "wildcard"
272 // matching these scalars. If there is only one such scalar, it would
273 // replace the iPTR, if there are more, the iPTR would be retained.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000274 SetType Diff;
275 if (InP) {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000276 Diff = Out;
277 berase_if(Diff, [&In](MVT T) { return In.count(T); });
278 // Pre-remove these elements and rely only on InP/OutP to determine
279 // whether a change has been made.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000280 berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
Scott Michel94420742008-03-05 17:49:05 +0000281 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000282 Diff = In;
283 berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000284 Out.erase(MVT::iPTR);
285 }
286
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000287 // The actual intersection.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000288 bool Changed = berase_if(Out, Int);
289 unsigned NumD = Diff.size();
290 if (NumD == 0)
291 return Changed;
292
293 if (NumD == 1) {
294 Out.insert(*Diff.begin());
295 // This is a change only if Out was the one with iPTR (which is now
296 // being replaced).
297 Changed |= OutP;
298 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000299 // Multiple elements from Out are now replaced with iPTR.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000300 Out.insert(MVT::iPTR);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000301 Changed |= !OutP;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000302 }
303 return Changed;
304}
305
306void TypeSetByHwMode::validate() const {
307#ifndef NDEBUG
308 if (empty())
309 return;
310 bool AllEmpty = true;
311 for (const auto &I : *this)
312 AllEmpty &= I.second.empty();
313 assert(!AllEmpty &&
314 "type set is empty for each HW mode: type contradiction?");
315#endif
316}
317
318// --- TypeInfer
319
320bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
321 const TypeSetByHwMode &In) {
322 ValidateOnExit _1(Out);
323 In.validate();
324 if (In.empty() || Out == In || TP.hasError())
325 return false;
326 if (Out.empty()) {
327 Out = In;
328 return true;
329 }
330
331 bool Changed = Out.constrain(In);
332 if (Changed && Out.empty())
333 TP.error("Type contradiction");
334
335 return Changed;
336}
337
338bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
339 ValidateOnExit _1(Out);
340 if (TP.hasError())
341 return false;
342 assert(!Out.empty() && "cannot pick from an empty set");
343
344 bool Changed = false;
345 for (auto &I : Out) {
346 TypeSetByHwMode::SetType &S = I.second;
347 if (S.size() <= 1)
348 continue;
349 MVT T = *S.begin(); // Pick the first element.
350 S.clear();
351 S.insert(T);
352 Changed = true;
353 }
354 return Changed;
355}
356
357bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
358 ValidateOnExit _1(Out);
359 if (TP.hasError())
360 return false;
361 if (!Out.empty())
362 return Out.constrain(isIntegerOrPtr);
363
364 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
365}
366
367bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
368 ValidateOnExit _1(Out);
369 if (TP.hasError())
370 return false;
371 if (!Out.empty())
372 return Out.constrain(isFloatingPoint);
373
374 return Out.assign_if(getLegalTypes(), isFloatingPoint);
375}
376
377bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
378 ValidateOnExit _1(Out);
379 if (TP.hasError())
380 return false;
381 if (!Out.empty())
382 return Out.constrain(isScalar);
383
384 return Out.assign_if(getLegalTypes(), isScalar);
385}
386
387bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
388 ValidateOnExit _1(Out);
389 if (TP.hasError())
390 return false;
391 if (!Out.empty())
392 return Out.constrain(isVector);
393
394 return Out.assign_if(getLegalTypes(), isVector);
395}
396
397bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
398 ValidateOnExit _1(Out);
399 if (TP.hasError() || !Out.empty())
400 return false;
401
402 Out = getLegalTypes();
403 return true;
404}
405
406template <typename Iter, typename Pred, typename Less>
407static Iter min_if(Iter B, Iter E, Pred P, Less L) {
408 if (B == E)
409 return E;
410 Iter Min = E;
411 for (Iter I = B; I != E; ++I) {
412 if (!P(*I))
413 continue;
414 if (Min == E || L(*I, *Min))
415 Min = I;
416 }
417 return Min;
418}
419
420template <typename Iter, typename Pred, typename Less>
421static Iter max_if(Iter B, Iter E, Pred P, Less L) {
422 if (B == E)
423 return E;
424 Iter Max = E;
425 for (Iter I = B; I != E; ++I) {
426 if (!P(*I))
427 continue;
428 if (Max == E || L(*Max, *I))
429 Max = I;
430 }
431 return Max;
432}
433
434/// Make sure that for each type in Small, there exists a larger type in Big.
435bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
436 TypeSetByHwMode &Big) {
437 ValidateOnExit _1(Small), _2(Big);
438 if (TP.hasError())
439 return false;
440 bool Changed = false;
441
442 if (Small.empty())
443 Changed |= EnforceAny(Small);
444 if (Big.empty())
445 Changed |= EnforceAny(Big);
446
447 assert(Small.hasDefault() && Big.hasDefault());
448
449 std::vector<unsigned> Modes = union_modes(Small, Big);
450
451 // 1. Only allow integer or floating point types and make sure that
452 // both sides are both integer or both floating point.
453 // 2. Make sure that either both sides have vector types, or neither
454 // of them does.
455 for (unsigned M : Modes) {
456 TypeSetByHwMode::SetType &S = Small.get(M);
457 TypeSetByHwMode::SetType &B = Big.get(M);
458
459 if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000460 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000461 Changed |= berase_if(S, NotInt) |
462 berase_if(B, NotInt);
463 } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000464 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000465 Changed |= berase_if(S, NotFP) |
466 berase_if(B, NotFP);
467 } else if (S.empty() || B.empty()) {
468 Changed = !S.empty() || !B.empty();
469 S.clear();
470 B.clear();
471 } else {
472 TP.error("Incompatible types");
473 return Changed;
Scott Michel94420742008-03-05 17:49:05 +0000474 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000475
476 if (none_of(S, isVector) || none_of(B, isVector)) {
477 Changed |= berase_if(S, isVector) |
478 berase_if(B, isVector);
479 }
480 }
481
482 auto LT = [](MVT A, MVT B) -> bool {
483 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
484 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
485 A.getSizeInBits() < B.getSizeInBits());
486 };
487 auto LE = [](MVT A, MVT B) -> bool {
488 // This function is used when removing elements: when a vector is compared
489 // to a non-vector, it should return false (to avoid removal).
490 if (A.isVector() != B.isVector())
491 return false;
492
493 // Note on the < comparison below:
494 // X86 has patterns like
495 // (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))),
496 // where the truncated vector is given a type v16i8, while the source
497 // vector has type v4i32. They both have the same size in bits.
498 // The minimal type in the result is obviously v16i8, and when we remove
499 // all types from the source that are smaller-or-equal than v8i16, the
500 // only source type would also be removed (since it's equal in size).
501 return A.getScalarSizeInBits() <= B.getScalarSizeInBits() ||
502 A.getSizeInBits() < B.getSizeInBits();
503 };
504
505 for (unsigned M : Modes) {
506 TypeSetByHwMode::SetType &S = Small.get(M);
507 TypeSetByHwMode::SetType &B = Big.get(M);
508 // MinS = min scalar in Small, remove all scalars from Big that are
509 // smaller-or-equal than MinS.
510 auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
511 if (MinS != S.end()) {
512 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
513 if (B.empty()) {
514 TP.error("Type contradiction in " +
515 Twine(__func__) + ":" + Twine(__LINE__));
516 return Changed;
517 }
518 }
519 // MaxS = max scalar in Big, remove all scalars from Small that are
520 // larger than MaxS.
521 auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
522 if (MaxS != B.end()) {
523 Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
524 if (B.empty()) {
525 TP.error("Type contradiction in " +
526 Twine(__func__) + ":" + Twine(__LINE__));
527 return Changed;
528 }
529 }
530
531 // MinV = min vector in Small, remove all vectors from Big that are
532 // smaller-or-equal than MinV.
533 auto MinV = min_if(S.begin(), S.end(), isVector, LT);
534 if (MinV != S.end()) {
535 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
536 if (B.empty()) {
537 TP.error("Type contradiction in " +
538 Twine(__func__) + ":" + Twine(__LINE__));
539 return Changed;
540 }
541 }
542 // MaxV = max vector in Big, remove all vectors from Small that are
543 // larger than MaxV.
544 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
545 if (MaxV != B.end()) {
546 Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
547 if (B.empty()) {
548 TP.error("Type contradiction in " +
549 Twine(__func__) + ":" + Twine(__LINE__));
550 return Changed;
551 }
552 }
553 }
554
555 return Changed;
556}
557
558/// 1. Ensure that for each type T in Vec, T is a vector type, and that
559/// for each type U in Elem, U is a scalar type.
560/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
561/// type T in Vec, such that U is the element type of T.
562bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
563 TypeSetByHwMode &Elem) {
564 ValidateOnExit _1(Vec), _2(Elem);
565 if (TP.hasError())
566 return false;
567 bool Changed = false;
568
569 if (Vec.empty())
570 Changed |= EnforceVector(Vec);
571 if (Elem.empty())
572 Changed |= EnforceScalar(Elem);
573
574 for (unsigned M : union_modes(Vec, Elem)) {
575 TypeSetByHwMode::SetType &V = Vec.get(M);
576 TypeSetByHwMode::SetType &E = Elem.get(M);
577
578 Changed |= berase_if(V, isScalar); // Scalar = !vector
579 Changed |= berase_if(E, isVector); // Vector = !scalar
580 assert(!V.empty() && !E.empty());
581
582 SmallSet<MVT,4> VT, ST;
583 // Collect element types from the "vector" set.
584 for (MVT T : V)
585 VT.insert(T.getVectorElementType());
586 // Collect scalar types from the "element" set.
587 for (MVT T : E)
588 ST.insert(T);
589
590 // Remove from V all (vector) types whose element type is not in S.
591 Changed |= berase_if(V, [&ST](MVT T) -> bool {
592 return !ST.count(T.getVectorElementType());
593 });
594 // Remove from E all (scalar) types, for which there is no corresponding
595 // type in V.
596 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
597
598 if (V.empty() || E.empty()) {
599 TP.error("Type contradiction in " +
600 Twine(__func__) + ":" + Twine(__LINE__));
601 return Changed;
602 }
603 }
604
605 return Changed;
606}
607
608bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
609 const ValueTypeByHwMode &VVT) {
610 TypeSetByHwMode Tmp(VVT);
611 ValidateOnExit _1(Vec), _2(Tmp);
612 return EnforceVectorEltTypeIs(Vec, Tmp);
613}
614
615/// Ensure that for each type T in Sub, T is a vector type, and there
616/// exists a type U in Vec such that U is a vector type with the same
617/// element type as T and at least as many elements as T.
618bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
619 TypeSetByHwMode &Sub) {
620 ValidateOnExit _1(Vec), _2(Sub);
621 if (TP.hasError())
622 return false;
623
624 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
625 auto IsSubVec = [](MVT B, MVT P) -> bool {
626 if (!B.isVector() || !P.isVector())
627 return false;
628 if (B.getVectorElementType() != P.getVectorElementType())
629 return false;
630 return B.getVectorNumElements() < P.getVectorNumElements();
631 };
632
633 /// Return true if S has no element (vector type) that T is a sub-vector of,
634 /// i.e. has the same element type as T and more elements.
635 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
636 for (const auto &I : S)
637 if (IsSubVec(T, I))
638 return false;
639 return true;
640 };
641
642 /// Return true if S has no element (vector type) that T is a super-vector
643 /// of, i.e. has the same element type as T and fewer elements.
644 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
645 for (const auto &I : S)
646 if (IsSubVec(I, T))
647 return false;
648 return true;
649 };
650
651 bool Changed = false;
652
653 if (Vec.empty())
654 Changed |= EnforceVector(Vec);
655 if (Sub.empty())
656 Changed |= EnforceVector(Sub);
657
658 for (unsigned M : union_modes(Vec, Sub)) {
659 TypeSetByHwMode::SetType &S = Sub.get(M);
660 TypeSetByHwMode::SetType &V = Vec.get(M);
661
662 Changed |= berase_if(S, isScalar);
663 if (S.empty()) {
664 TP.error("Type contradiction in " +
665 Twine(__func__) + ":" + Twine(__LINE__));
666 return Changed;
667 }
668
669 // Erase all types from S that are not sub-vectors of a type in V.
670 Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
671 if (S.empty()) {
672 TP.error("Type contradiction in " +
673 Twine(__func__) + ":" + Twine(__LINE__));
674 return Changed;
675 }
676
677 // Erase all types from V that are not super-vectors of a type in S.
678 Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
679 if (V.empty()) {
680 TP.error("Type contradiction in " +
681 Twine(__func__) + ":" + Twine(__LINE__));
682 return Changed;
683 }
684 }
685
686 return Changed;
687}
688
689/// 1. Ensure that V has a scalar type iff W has a scalar type.
690/// 2. Ensure that for each vector type T in V, there exists a vector
691/// type U in W, such that T and U have the same number of elements.
692/// 3. Ensure that for each vector type U in W, there exists a vector
693/// type T in V, such that T and U have the same number of elements
694/// (reverse of 2).
695bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
696 ValidateOnExit _1(V), _2(W);
697 if (TP.hasError())
698 return false;
699
700 bool Changed = false;
701 if (V.empty())
702 Changed |= EnforceAny(V);
703 if (W.empty())
704 Changed |= EnforceAny(W);
705
706 // An actual vector type cannot have 0 elements, so we can treat scalars
707 // as zero-length vectors. This way both vectors and scalars can be
708 // processed identically.
709 auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
710 return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
711 };
712
713 for (unsigned M : union_modes(V, W)) {
714 TypeSetByHwMode::SetType &VS = V.get(M);
715 TypeSetByHwMode::SetType &WS = W.get(M);
716
717 SmallSet<unsigned,2> VN, WN;
718 for (MVT T : VS)
719 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
720 for (MVT T : WS)
721 WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
722
723 Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
724 Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
725 }
726 return Changed;
727}
728
729/// 1. Ensure that for each type T in A, there exists a type U in B,
730/// such that T and U have equal size in bits.
731/// 2. Ensure that for each type U in B, there exists a type T in A
732/// such that T and U have equal size in bits (reverse of 1).
733bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
734 ValidateOnExit _1(A), _2(B);
735 if (TP.hasError())
736 return false;
737 bool Changed = false;
738 if (A.empty())
739 Changed |= EnforceAny(A);
740 if (B.empty())
741 Changed |= EnforceAny(B);
742
743 auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
744 return !Sizes.count(T.getSizeInBits());
745 };
746
747 for (unsigned M : union_modes(A, B)) {
748 TypeSetByHwMode::SetType &AS = A.get(M);
749 TypeSetByHwMode::SetType &BS = B.get(M);
750 SmallSet<unsigned,2> AN, BN;
751
752 for (MVT T : AS)
753 AN.insert(T.getSizeInBits());
754 for (MVT T : BS)
755 BN.insert(T.getSizeInBits());
756
757 Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
758 Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
759 }
760
761 return Changed;
762}
763
764void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
765 ValidateOnExit _1(VTS);
766 TypeSetByHwMode Legal = getLegalTypes();
767 bool HaveLegalDef = Legal.hasDefault();
768
769 for (auto &I : VTS) {
770 unsigned M = I.first;
771 if (!Legal.hasMode(M) && !HaveLegalDef) {
772 TP.error("Invalid mode " + Twine(M));
773 return;
774 }
775 expandOverloads(I.second, Legal.get(M));
Scott Michel94420742008-03-05 17:49:05 +0000776 }
777}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000778
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000779void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
780 const TypeSetByHwMode::SetType &Legal) {
781 std::set<MVT> Ovs;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000782 for (MVT T : Out) {
783 if (!T.isOverloaded())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000784 continue;
Zachary Turner249dc142017-09-20 18:01:40 +0000785
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000786 Ovs.insert(T);
787 // MachineValueTypeSet allows iteration and erasing.
788 Out.erase(T);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000789 }
790
791 for (MVT Ov : Ovs) {
792 switch (Ov.SimpleTy) {
793 case MVT::iPTRAny:
794 Out.insert(MVT::iPTR);
795 return;
796 case MVT::iAny:
797 for (MVT T : MVT::integer_valuetypes())
798 if (Legal.count(T))
799 Out.insert(T);
800 for (MVT T : MVT::integer_vector_valuetypes())
801 if (Legal.count(T))
802 Out.insert(T);
803 return;
804 case MVT::fAny:
805 for (MVT T : MVT::fp_valuetypes())
806 if (Legal.count(T))
807 Out.insert(T);
808 for (MVT T : MVT::fp_vector_valuetypes())
809 if (Legal.count(T))
810 Out.insert(T);
811 return;
812 case MVT::vAny:
813 for (MVT T : MVT::vector_valuetypes())
814 if (Legal.count(T))
815 Out.insert(T);
816 return;
817 case MVT::Any:
818 for (MVT T : MVT::all_valuetypes())
819 if (Legal.count(T))
820 Out.insert(T);
821 return;
822 default:
823 break;
824 }
825 }
826}
827
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000828TypeSetByHwMode TypeInfer::getLegalTypes() {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000829 if (!LegalTypesCached) {
830 // Stuff all types from all modes into the default mode.
831 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
832 for (const auto &I : LTS)
833 LegalCache.insert(I.second);
834 LegalTypesCached = true;
835 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000836 TypeSetByHwMode VTS;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000837 VTS.getOrCreate(DefaultMode) = LegalCache;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000838 return VTS;
839}
Chris Lattner514e2922011-04-17 21:38:24 +0000840
841//===----------------------------------------------------------------------===//
842// TreePredicateFn Implementation
843//===----------------------------------------------------------------------===//
844
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000845/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
846TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
847 assert((getPredCode().empty() || getImmCode().empty()) &&
848 ".td file corrupt: can't have a node predicate *and* an imm predicate");
849}
850
Chris Lattner514e2922011-04-17 21:38:24 +0000851std::string TreePredicateFn::getPredCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000852 return PatFragRec->getRecord()->getValueAsString("PredicateCode");
Chris Lattner514e2922011-04-17 21:38:24 +0000853}
854
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000855std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +0000856 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000857}
858
Chris Lattner514e2922011-04-17 21:38:24 +0000859
860/// isAlwaysTrue - Return true if this is a noop predicate.
861bool TreePredicateFn::isAlwaysTrue() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000862 return getPredCode().empty() && getImmCode().empty();
Chris Lattner514e2922011-04-17 21:38:24 +0000863}
864
865/// Return the name to use in the generated code to reference this, this is
866/// "Predicate_foo" if from a pattern fragment "foo".
867std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +0000868 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +0000869}
870
871/// getCodeToRunOnSDNode - Return the code for the function body that
872/// evaluates this predicate. The argument is expected to be in "Node",
873/// not N. This handles casting and conversion to a concrete node type as
874/// appropriate.
875std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000876 // Handle immediate predicates first.
877 std::string ImmCode = getImmCode();
878 if (!ImmCode.empty()) {
879 std::string Result =
880 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000881 return Result + ImmCode;
882 }
883
884 // Handle arbitrary node predicates.
885 assert(!getPredCode().empty() && "Don't have any predicate code!");
Chris Lattner514e2922011-04-17 21:38:24 +0000886 std::string ClassName;
887 if (PatFragRec->getOnlyTree()->isLeaf())
888 ClassName = "SDNode";
889 else {
890 Record *Op = PatFragRec->getOnlyTree()->getOperator();
891 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
892 }
893 std::string Result;
894 if (ClassName == "SDNode")
895 Result = " SDNode *N = Node;\n";
896 else
Craig Topper5b0f57d2015-10-11 16:59:29 +0000897 Result = " auto *N = cast<" + ClassName + ">(Node);\n";
Chris Lattner514e2922011-04-17 21:38:24 +0000898
899 return Result + getPredCode();
Scott Michel94420742008-03-05 17:49:05 +0000900}
901
Chris Lattner8cab0212008-01-05 22:25:12 +0000902//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +0000903// PatternToMatch implementation
904//
905
Chris Lattner05925fe2010-03-29 01:40:38 +0000906/// getPatternSize - Return the 'size' of this pattern. We want to match large
907/// patterns before small ones. This is used to determine the size of a
908/// pattern.
909static unsigned getPatternSize(const TreePatternNode *P,
910 const CodeGenDAGPatterns &CGP) {
911 unsigned Size = 3; // The node itself.
912 // If the root node is a ConstantSDNode, increases its size.
913 // e.g. (set R32:$dst, 0).
Sean Silva88eb8dd2012-10-10 20:24:47 +0000914 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000915 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000916
Chris Lattner05925fe2010-03-29 01:40:38 +0000917 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Tim Northoverc807a172014-05-20 11:52:46 +0000918 if (AM) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +0000919 Size += AM->getComplexity();
Jim Grosbach65586fe2010-12-21 16:16:00 +0000920
Tim Northoverc807a172014-05-20 11:52:46 +0000921 // We don't want to count any children twice, so return early.
922 return Size;
923 }
924
Chris Lattner05925fe2010-03-29 01:40:38 +0000925 // If this node has some predicate function that must match, it adds to the
926 // complexity of this node.
927 if (!P->getPredicateFns().empty())
928 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +0000929
Chris Lattner05925fe2010-03-29 01:40:38 +0000930 // Count children in the count if they are also nodes.
931 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
932 TreePatternNode *Child = P->getChild(i);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000933 if (!Child->isLeaf() && Child->getNumTypes()) {
934 const TypeSetByHwMode &T0 = Child->getType(0);
935 // At this point, all variable type sets should be simple, i.e. only
936 // have a default mode.
937 if (T0.getMachineValueType() != MVT::Other) {
938 Size += getPatternSize(Child, CGP);
939 continue;
940 }
941 }
942 if (Child->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +0000943 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +0000944 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
945 else if (Child->getComplexPatternInfo(CGP))
946 Size += getPatternSize(Child, CGP);
947 else if (!Child->getPredicateFns().empty())
948 ++Size;
949 }
950 }
Jim Grosbach65586fe2010-12-21 16:16:00 +0000951
Chris Lattner05925fe2010-03-29 01:40:38 +0000952 return Size;
953}
954
955/// Compute the complexity metric for the input pattern. This roughly
956/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +0000957int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +0000958getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
959 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
960}
961
Dan Gohman49e19e92008-08-22 00:20:26 +0000962/// getPredicateCheck - Return a single string containing all of this
963/// pattern's predicates concatenated with "&&" operators.
964///
965std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000966 SmallVector<const Predicate*,4> PredList;
967 for (const Predicate &P : Predicates)
968 PredList.push_back(&P);
969 std::sort(PredList.begin(), PredList.end(), deref<llvm::less>());
Craig Topper8985efe2015-11-27 05:44:04 +0000970
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000971 std::string Check;
972 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
973 if (i != 0)
974 Check += " && ";
975 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +0000976 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000977 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +0000978}
979
980//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +0000981// SDTypeConstraint implementation
982//
983
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000984SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +0000985 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +0000986
Chris Lattner8cab0212008-01-05 22:25:12 +0000987 if (R->isSubClassOf("SDTCisVT")) {
988 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000989 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
990 for (const auto &P : VVT)
991 if (P.second == MVT::isVoid)
992 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +0000993 } else if (R->isSubClassOf("SDTCisPtrTy")) {
994 ConstraintType = SDTCisPtrTy;
995 } else if (R->isSubClassOf("SDTCisInt")) {
996 ConstraintType = SDTCisInt;
997 } else if (R->isSubClassOf("SDTCisFP")) {
998 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +0000999 } else if (R->isSubClassOf("SDTCisVec")) {
1000 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001001 } else if (R->isSubClassOf("SDTCisSameAs")) {
1002 ConstraintType = SDTCisSameAs;
1003 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1004 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1005 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001006 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001007 R->getValueAsInt("OtherOperandNum");
1008 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1009 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001010 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001011 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001012 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1013 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001014 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001015 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1016 ConstraintType = SDTCisSubVecOfVec;
1017 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1018 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001019 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1020 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001021 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1022 for (const auto &P : VVT) {
1023 MVT T = P.second;
1024 if (T.isVector())
1025 PrintFatalError(R->getLoc(),
1026 "Cannot use vector type as SDTCVecEltisVT");
1027 if (!T.isInteger() && !T.isFloatingPoint())
1028 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1029 "as SDTCVecEltisVT");
1030 }
Craig Topper0be34582015-03-05 07:11:34 +00001031 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1032 ConstraintType = SDTCisSameNumEltsAs;
1033 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1034 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001035 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1036 ConstraintType = SDTCisSameSizeAs;
1037 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1038 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001039 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001040 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001041 }
1042}
1043
1044/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001045/// N, and the result number in ResNo.
1046static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
1047 const SDNodeInfo &NodeInfo,
1048 unsigned &ResNo) {
1049 unsigned NumResults = NodeInfo.getNumResults();
1050 if (OpNo < NumResults) {
1051 ResNo = OpNo;
1052 return N;
1053 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001054
Chris Lattner2db7aba2010-03-19 21:56:21 +00001055 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001056
Chris Lattner2db7aba2010-03-19 21:56:21 +00001057 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001058 std::string S;
1059 raw_string_ostream OS(S);
1060 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001061 << (OpNo+NumResults) << " ";
James Y Knighte452e272015-05-11 22:17:13 +00001062 N->print(OS);
1063 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001064 }
1065
Chris Lattner2db7aba2010-03-19 21:56:21 +00001066 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001067}
1068
1069/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1070/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001071/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001072bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
1073 const SDNodeInfo &NodeInfo,
1074 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001075 if (TP.hasError())
1076 return false;
1077
Chris Lattner2db7aba2010-03-19 21:56:21 +00001078 unsigned ResNo = 0; // The result number being referenced.
1079 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001080 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001081
Chris Lattner8cab0212008-01-05 22:25:12 +00001082 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001083 case SDTCisVT:
1084 // Operand must be a particular type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001085 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001086 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001087 // Operand must be same as target pointer type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001088 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001089 case SDTCisInt:
1090 // Require it to be one of the legal integer VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001091 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001092 case SDTCisFP:
1093 // Require it to be one of the legal fp VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001094 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001095 case SDTCisVec:
1096 // Require it to be one of the legal vector VTs.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001097 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001098 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001099 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001100 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001101 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Craig Topper483a3002015-03-04 09:04:54 +00001102 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1103 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001104 }
1105 case SDTCisVTSmallerThanOp: {
1106 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1107 // have an integer type that is smaller than the VT.
1108 if (!NodeToApply->isLeaf() ||
Sean Silva88eb8dd2012-10-10 20:24:47 +00001109 !isa<DefInit>(NodeToApply->getLeafValue()) ||
David Greeneaf8ee2c2011-07-29 22:43:06 +00001110 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001111 ->isSubClassOf("ValueType")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001112 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001113 return false;
1114 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001115 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
1116 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1117 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1118 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001119
Chris Lattner2db7aba2010-03-19 21:56:21 +00001120 unsigned OResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001121 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001122 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1123 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001124
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001125 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001126 }
1127 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001128 unsigned BResNo = 0;
Chris Lattner8cab0212008-01-05 22:25:12 +00001129 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001130 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1131 BResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001132 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1133 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001134 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001135 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001136 unsigned VResNo = 0;
Chris Lattnercabe0372010-03-15 06:00:16 +00001137 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001138 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1139 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001140 // Filter vector types out of VecOperand that don't have the right element
1141 // type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001142 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1143 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001144 }
David Greene127fd1d2011-01-24 20:53:18 +00001145 case SDTCisSubVecOfVec: {
1146 unsigned VResNo = 0;
1147 TreePatternNode *BigVecOperand =
1148 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1149 VResNo);
1150
1151 // Filter vector types out of BigVecOperand that don't have the
1152 // right subvector type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001153 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1154 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001155 }
Craig Topper0be34582015-03-05 07:11:34 +00001156 case SDTCVecEltisVT: {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001157 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001158 }
1159 case SDTCisSameNumEltsAs: {
1160 unsigned OResNo = 0;
1161 TreePatternNode *OtherNode =
1162 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1163 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001164 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1165 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001166 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001167 case SDTCisSameSizeAs: {
1168 unsigned OResNo = 0;
1169 TreePatternNode *OtherNode =
1170 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1171 N, NodeInfo, OResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001172 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1173 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001174 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001175 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001176 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001177}
1178
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001179// Update the node type to match an instruction operand or result as specified
1180// in the ins or outs lists on the instruction definition. Return true if the
1181// type was actually changed.
1182bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1183 Record *Operand,
1184 TreePattern &TP) {
1185 // The 'unknown' operand indicates that types should be inferred from the
1186 // context.
1187 if (Operand->isSubClassOf("unknown_class"))
1188 return false;
1189
1190 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001191 if (Operand->isSubClassOf("Operand")) {
1192 Record *R = Operand->getValueAsDef("Type");
1193 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1194 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1195 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001196
1197 // PointerLikeRegClass has a type that is determined at runtime.
1198 if (Operand->isSubClassOf("PointerLikeRegClass"))
1199 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1200
1201 // Both RegisterClass and RegisterOperand operands derive their types from a
1202 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001203 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001204 if (Operand->isSubClassOf("RegisterClass"))
1205 RC = Operand;
1206 else if (Operand->isSubClassOf("RegisterOperand"))
1207 RC = Operand->getValueAsDef("RegClass");
1208
1209 assert(RC && "Unknown operand type");
1210 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1211 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1212}
1213
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001214bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1215 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1216 if (!TP.getInfer().isConcrete(Types[i], true))
1217 return true;
1218 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1219 if (getChild(i)->ContainsUnresolvedType(TP))
1220 return true;
1221 return false;
1222}
1223
1224bool TreePatternNode::hasProperTypeByHwMode() const {
1225 for (const TypeSetByHwMode &S : Types)
1226 if (!S.isDefaultOnly())
1227 return true;
1228 for (TreePatternNode *C : Children)
1229 if (C->hasProperTypeByHwMode())
1230 return true;
1231 return false;
1232}
1233
1234bool TreePatternNode::hasPossibleType() const {
1235 for (const TypeSetByHwMode &S : Types)
1236 if (!S.isPossible())
1237 return false;
1238 for (TreePatternNode *C : Children)
1239 if (!C->hasPossibleType())
1240 return false;
1241 return true;
1242}
1243
1244bool TreePatternNode::setDefaultMode(unsigned Mode) {
1245 for (TypeSetByHwMode &S : Types) {
1246 S.makeSimple(Mode);
1247 // Check if the selected mode had a type conflict.
1248 if (S.get(DefaultMode).empty())
1249 return false;
1250 }
1251 for (TreePatternNode *C : Children)
1252 if (!C->setDefaultMode(Mode))
1253 return false;
1254 return true;
1255}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001256
Chris Lattner8cab0212008-01-05 22:25:12 +00001257//===----------------------------------------------------------------------===//
1258// SDNodeInfo implementation
1259//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001260SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001261 EnumName = R->getValueAsString("Opcode");
1262 SDClassName = R->getValueAsString("SDClass");
1263 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1264 NumResults = TypeProfile->getValueAsInt("NumResults");
1265 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001266
Chris Lattner8cab0212008-01-05 22:25:12 +00001267 // Parse the properties.
1268 Properties = 0;
Craig Topper306cb122015-11-22 20:46:24 +00001269 for (Record *Property : R->getValueAsListOfDefs("Properties")) {
1270 if (Property->getName() == "SDNPCommutative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001271 Properties |= 1 << SDNPCommutative;
Craig Topper306cb122015-11-22 20:46:24 +00001272 } else if (Property->getName() == "SDNPAssociative") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001273 Properties |= 1 << SDNPAssociative;
Craig Topper306cb122015-11-22 20:46:24 +00001274 } else if (Property->getName() == "SDNPHasChain") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001275 Properties |= 1 << SDNPHasChain;
Craig Topper306cb122015-11-22 20:46:24 +00001276 } else if (Property->getName() == "SDNPOutGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001277 Properties |= 1 << SDNPOutGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001278 } else if (Property->getName() == "SDNPInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001279 Properties |= 1 << SDNPInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001280 } else if (Property->getName() == "SDNPOptInGlue") {
Chris Lattner2a0a3b42010-12-23 18:28:41 +00001281 Properties |= 1 << SDNPOptInGlue;
Craig Topper306cb122015-11-22 20:46:24 +00001282 } else if (Property->getName() == "SDNPMayStore") {
Chris Lattnera348f552008-01-06 06:44:58 +00001283 Properties |= 1 << SDNPMayStore;
Craig Topper306cb122015-11-22 20:46:24 +00001284 } else if (Property->getName() == "SDNPMayLoad") {
Chris Lattner1ca20682008-01-10 04:38:57 +00001285 Properties |= 1 << SDNPMayLoad;
Craig Topper306cb122015-11-22 20:46:24 +00001286 } else if (Property->getName() == "SDNPSideEffect") {
Chris Lattner42c63ef2008-01-10 05:39:30 +00001287 Properties |= 1 << SDNPSideEffect;
Craig Topper306cb122015-11-22 20:46:24 +00001288 } else if (Property->getName() == "SDNPMemOperand") {
Mon P Wang6a490372008-06-25 08:15:39 +00001289 Properties |= 1 << SDNPMemOperand;
Craig Topper306cb122015-11-22 20:46:24 +00001290 } else if (Property->getName() == "SDNPVariadic") {
Chris Lattner83aeaab2010-03-19 05:07:09 +00001291 Properties |= 1 << SDNPVariadic;
Chris Lattner8cab0212008-01-05 22:25:12 +00001292 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001293 PrintFatalError("Unknown SD Node property '" +
Craig Topper306cb122015-11-22 20:46:24 +00001294 Property->getName() + "' on node '" +
James Y Knighte452e272015-05-11 22:17:13 +00001295 R->getName() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001296 }
1297 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001298
1299
Chris Lattner8cab0212008-01-05 22:25:12 +00001300 // Parse the type constraints.
1301 std::vector<Record*> ConstraintList =
1302 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001303 for (Record *R : ConstraintList)
1304 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001305}
1306
Chris Lattner99e53b32010-02-28 00:22:30 +00001307/// getKnownType - If the type constraints on this node imply a fixed type
1308/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001309/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001310MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001311 unsigned NumResults = getNumResults();
1312 assert(NumResults <= 1 &&
1313 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001314 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001315
Craig Topper306cb122015-11-22 20:46:24 +00001316 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001317 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001318 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001319 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001320
Craig Topper306cb122015-11-22 20:46:24 +00001321 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001322 default: break;
1323 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001324 if (Constraint.VVT.isSimple())
1325 return Constraint.VVT.getSimple().SimpleTy;
1326 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001327 case SDTypeConstraint::SDTCisPtrTy:
1328 return MVT::iPTR;
1329 }
1330 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001331 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001332}
1333
Chris Lattner8cab0212008-01-05 22:25:12 +00001334//===----------------------------------------------------------------------===//
1335// TreePatternNode implementation
1336//
1337
1338TreePatternNode::~TreePatternNode() {
1339#if 0 // FIXME: implement refcounted tree nodes!
1340 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1341 delete getChild(i);
1342#endif
1343}
1344
Chris Lattnerf1447252010-03-19 21:37:09 +00001345static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1346 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001347 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001348 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001349
Chris Lattner2109cb42010-03-22 20:56:36 +00001350 if (Operator->isSubClassOf("Intrinsic"))
1351 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001352
Chris Lattnerf1447252010-03-19 21:37:09 +00001353 if (Operator->isSubClassOf("SDNode"))
1354 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001355
Chris Lattnerf1447252010-03-19 21:37:09 +00001356 if (Operator->isSubClassOf("PatFrag")) {
1357 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1358 // the forward reference case where one pattern fragment references another
1359 // before it is processed.
1360 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
1361 return PFRec->getOnlyTree()->getNumTypes();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001362
Chris Lattnerf1447252010-03-19 21:37:09 +00001363 // Get the result tree.
David Greeneaf8ee2c2011-07-29 22:43:06 +00001364 DagInit *Tree = Operator->getValueAsDag("Fragment");
Craig Topper24064772014-04-15 07:20:03 +00001365 Record *Op = nullptr;
Sean Silva88eb8dd2012-10-10 20:24:47 +00001366 if (Tree)
1367 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
1368 Op = DI->getDef();
Chris Lattnerf1447252010-03-19 21:37:09 +00001369 assert(Op && "Invalid Fragment");
1370 return GetNumNodeResults(Op, CDP);
1371 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001372
Chris Lattnerf1447252010-03-19 21:37:09 +00001373 if (Operator->isSubClassOf("Instruction")) {
1374 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001375
Craig Topper3a8eb892015-03-20 05:09:06 +00001376 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1377
1378 // Subtract any defaulted outputs.
1379 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1380 Record *OperandNode = InstInfo.Operands[i].Rec;
1381
1382 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1383 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1384 --NumDefsToAdd;
1385 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001386
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001387 // Add on one implicit def if it has a resolvable type.
1388 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1389 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001390 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001391 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001392
Chris Lattnerf1447252010-03-19 21:37:09 +00001393 if (Operator->isSubClassOf("SDNodeXForm"))
1394 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001395
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001396 if (Operator->isSubClassOf("ValueType"))
1397 return 1; // A type-cast of one result.
1398
Tim Northoverc807a172014-05-20 11:52:46 +00001399 if (Operator->isSubClassOf("ComplexPattern"))
1400 return 1;
1401
Matthias Braun8c209aa2017-01-28 02:02:38 +00001402 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001403 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001404}
1405
1406void TreePatternNode::print(raw_ostream &OS) const {
1407 if (isLeaf())
1408 OS << *getLeafValue();
1409 else
1410 OS << '(' << getOperator()->getName();
1411
Zachary Turner249dc142017-09-20 18:01:40 +00001412 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1413 OS << ':';
1414 getExtType(i).writeToStream(OS);
1415 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001416
1417 if (!isLeaf()) {
1418 if (getNumChildren() != 0) {
1419 OS << " ";
1420 getChild(0)->print(OS);
1421 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1422 OS << ", ";
1423 getChild(i)->print(OS);
1424 }
1425 }
1426 OS << ")";
1427 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001428
Craig Topper306cb122015-11-22 20:46:24 +00001429 for (const TreePredicateFn &Pred : PredicateFns)
1430 OS << "<<P:" << Pred.getFnName() << ">>";
Chris Lattner8cab0212008-01-05 22:25:12 +00001431 if (TransformFn)
1432 OS << "<<X:" << TransformFn->getName() << ">>";
1433 if (!getName().empty())
1434 OS << ":$" << getName();
1435
1436}
1437void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001438 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001439}
1440
Scott Michel94420742008-03-05 17:49:05 +00001441/// isIsomorphicTo - Return true if this node is recursively
1442/// isomorphic to the specified node. For this comparison, the node's
1443/// entire state is considered. The assigned name is ignored, since
1444/// nodes with differing names are considered isomorphic. However, if
1445/// the assigned name is present in the dependent variable set, then
1446/// the assigned name is considered significant and the node is
1447/// isomorphic if the names match.
1448bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
1449 const MultipleUseVarSet &DepVars) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00001450 if (N == this) return true;
Chris Lattnerf1447252010-03-19 21:37:09 +00001451 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Dan Gohman6e979022008-10-15 06:17:21 +00001452 getPredicateFns() != N->getPredicateFns() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00001453 getTransformFn() != N->getTransformFn())
1454 return false;
1455
1456 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001457 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1458 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001459 return ((DI->getDef() == NDI->getDef())
1460 && (DepVars.find(getName()) == DepVars.end()
1461 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001462 }
1463 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001464 return getLeafValue() == N->getLeafValue();
1465 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001466
Chris Lattner8cab0212008-01-05 22:25:12 +00001467 if (N->getOperator() != getOperator() ||
1468 N->getNumChildren() != getNumChildren()) return false;
1469 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00001470 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001471 return false;
1472 return true;
1473}
1474
1475/// clone - Make a copy of this tree and all of its children.
1476///
1477TreePatternNode *TreePatternNode::clone() const {
1478 TreePatternNode *New;
1479 if (isLeaf()) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001480 New = new TreePatternNode(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001481 } else {
1482 std::vector<TreePatternNode*> CChildren;
1483 CChildren.reserve(Children.size());
1484 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1485 CChildren.push_back(getChild(i)->clone());
Chris Lattnerf1447252010-03-19 21:37:09 +00001486 New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001487 }
1488 New->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001489 New->Types = Types;
Dan Gohman6e979022008-10-15 06:17:21 +00001490 New->setPredicateFns(getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00001491 New->setTransformFn(getTransformFn());
1492 return New;
1493}
1494
Chris Lattner53c39ba2010-02-14 22:22:58 +00001495/// RemoveAllTypes - Recursively strip all the types of this tree.
1496void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001497 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001498 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001499 if (isLeaf()) return;
1500 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1501 getChild(i)->RemoveAllTypes();
1502}
1503
1504
Chris Lattner8cab0212008-01-05 22:25:12 +00001505/// SubstituteFormalArguments - Replace the formal arguments in this tree
1506/// with actual values specified by ArgMap.
1507void TreePatternNode::
1508SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
1509 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001510
Chris Lattner8cab0212008-01-05 22:25:12 +00001511 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1512 TreePatternNode *Child = getChild(i);
1513 if (Child->isLeaf()) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00001514 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001515 // Note that, when substituting into an output pattern, Val might be an
1516 // UnsetInit.
1517 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1518 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001519 // We found a use of a formal argument, replace it with its value.
Dan Gohman6e979022008-10-15 06:17:21 +00001520 TreePatternNode *NewChild = ArgMap[Child->getName()];
1521 assert(NewChild && "Couldn't find formal argument!");
1522 assert((Child->getPredicateFns().empty() ||
1523 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1524 "Non-empty child predicate clobbered!");
1525 setChild(i, NewChild);
Chris Lattner8cab0212008-01-05 22:25:12 +00001526 }
1527 } else {
1528 getChild(i)->SubstituteFormalArguments(ArgMap);
1529 }
1530 }
1531}
1532
1533
1534/// InlinePatternFragments - If this pattern refers to any pattern
1535/// fragments, inline them into place, giving us a pattern without any
1536/// PatFrag references.
1537TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001538 if (TP.hasError())
Craig Topper24064772014-04-15 07:20:03 +00001539 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001540
1541 if (isLeaf())
1542 return this; // nothing to do.
Chris Lattner8cab0212008-01-05 22:25:12 +00001543 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001544
Chris Lattner8cab0212008-01-05 22:25:12 +00001545 if (!Op->isSubClassOf("PatFrag")) {
1546 // Just recursively inline children nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00001547 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1548 TreePatternNode *Child = getChild(i);
1549 TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
1550
1551 assert((Child->getPredicateFns().empty() ||
1552 NewChild->getPredicateFns() == Child->getPredicateFns()) &&
1553 "Non-empty child predicate clobbered!");
1554
1555 setChild(i, NewChild);
1556 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001557 return this;
1558 }
1559
1560 // Otherwise, we found a reference to a fragment. First, look up its
1561 // TreePattern record.
1562 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001563
Chris Lattner8cab0212008-01-05 22:25:12 +00001564 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001565 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001566 TP.error("'" + Op->getName() + "' fragment requires " +
1567 utostr(Frag->getNumArgs()) + " operands!");
Craig Topper24064772014-04-15 07:20:03 +00001568 return nullptr;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001569 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001570
1571 TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
1572
Chris Lattner514e2922011-04-17 21:38:24 +00001573 TreePredicateFn PredFn(Frag);
1574 if (!PredFn.isAlwaysTrue())
1575 FragTree->addPredicateFn(PredFn);
Dan Gohman6e979022008-10-15 06:17:21 +00001576
Chris Lattner8cab0212008-01-05 22:25:12 +00001577 // Resolve formal arguments to their actual value.
1578 if (Frag->getNumArgs()) {
1579 // Compute the map of formal to actual arguments.
1580 std::map<std::string, TreePatternNode*> ArgMap;
1581 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
1582 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001583
Chris Lattner8cab0212008-01-05 22:25:12 +00001584 FragTree->SubstituteFormalArguments(ArgMap);
1585 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001586
Chris Lattner8cab0212008-01-05 22:25:12 +00001587 FragTree->setName(getName());
Chris Lattnerf1447252010-03-19 21:37:09 +00001588 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1589 FragTree->UpdateNodeType(i, getExtType(i), TP);
Dan Gohman6e979022008-10-15 06:17:21 +00001590
1591 // Transfer in the old predicates.
Craig Topper306cb122015-11-22 20:46:24 +00001592 for (const TreePredicateFn &Pred : getPredicateFns())
1593 FragTree->addPredicateFn(Pred);
Dan Gohman6e979022008-10-15 06:17:21 +00001594
Chris Lattner8cab0212008-01-05 22:25:12 +00001595 // Get a new copy of this fragment to stitch into here.
1596 //delete this; // FIXME: implement refcounting!
Jim Grosbach65586fe2010-12-21 16:16:00 +00001597
Chris Lattner2e253b42008-06-30 03:02:03 +00001598 // The fragment we inlined could have recursive inlining that is needed. See
1599 // if there are any pattern fragments in it and inline them as needed.
1600 return FragTree->InlinePatternFragments(TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001601}
1602
1603/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00001604/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00001605/// references from the register file information, for example.
1606///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001607/// When Unnamed is set, return the type of a DAG operand with no name, such as
1608/// the F8RC register class argument in:
1609///
1610/// (COPY_TO_REGCLASS GPR:$src, F8RC)
1611///
1612/// When Unnamed is false, return the type of a named DAG operand such as the
1613/// GPR:$src operand above.
1614///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001615static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
1616 bool NotRegisters,
1617 bool Unnamed,
1618 TreePattern &TP) {
1619 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
1620
Owen Andersona84be6c2011-06-27 21:06:21 +00001621 // Check to see if this is a register operand.
1622 if (R->isSubClassOf("RegisterOperand")) {
1623 assert(ResNo == 0 && "Regoperand ref only has one result!");
1624 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001625 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00001626 Record *RegClass = R->getValueAsDef("RegClass");
1627 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001628 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00001629 }
1630
Chris Lattnercabe0372010-03-15 06:00:16 +00001631 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00001632 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001633 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001634 // An unnamed register class represents itself as an i32 immediate, for
1635 // example on a COPY_TO_REGCLASS instruction.
1636 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001637 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001638
1639 // In a named operand, the register class provides the possible set of
1640 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001641 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001642 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00001643 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001644 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00001645 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001646
Chris Lattner6070ee22010-03-23 23:50:31 +00001647 if (R->isSubClassOf("PatFrag")) {
1648 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001649 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001650 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00001651 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001652
Chris Lattner6070ee22010-03-23 23:50:31 +00001653 if (R->isSubClassOf("Register")) {
1654 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001655 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001656 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001657 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001658 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00001659 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001660
1661 if (R->isSubClassOf("SubRegIndex")) {
1662 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001663 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00001664 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001665
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001666 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00001667 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001668 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
1669 //
1670 // (sext_inreg GPR:$src, i16)
1671 // ~~~
1672 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001673 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001674 // With a name, the ValueType simply provides the type of the named
1675 // variable.
1676 //
1677 // (sext_inreg i32:$src, i16)
1678 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00001679 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001680 return TypeSetByHwMode(); // Unknown.
1681 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1682 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00001683 }
1684
1685 if (R->isSubClassOf("CondCode")) {
1686 assert(ResNo == 0 && "This node only has one result!");
1687 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001688 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00001689 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001690
Chris Lattner6070ee22010-03-23 23:50:31 +00001691 if (R->isSubClassOf("ComplexPattern")) {
1692 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001693 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001694 return TypeSetByHwMode(); // Unknown.
1695 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00001696 }
1697 if (R->isSubClassOf("PointerLikeRegClass")) {
1698 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001699 TypeSetByHwMode VTS(MVT::iPTR);
1700 TP.getInfer().expandOverloads(VTS);
1701 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00001702 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001703
Chris Lattner6070ee22010-03-23 23:50:31 +00001704 if (R->getName() == "node" || R->getName() == "srcvalue" ||
1705 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00001706 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001707 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00001708 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001709
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001710 if (R->isSubClassOf("Operand")) {
1711 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
1712 Record *T = R->getValueAsDef("Type");
1713 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
1714 }
Tim Northoverc807a172014-05-20 11:52:46 +00001715
Chris Lattner8cab0212008-01-05 22:25:12 +00001716 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001717 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00001718}
1719
Chris Lattner89c65662008-01-06 05:36:50 +00001720
1721/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
1722/// CodeGenIntrinsic information for it, otherwise return a null pointer.
1723const CodeGenIntrinsic *TreePatternNode::
1724getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
1725 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
1726 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
1727 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00001728 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001729
Sean Silva88eb8dd2012-10-10 20:24:47 +00001730 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00001731 return &CDP.getIntrinsicInfo(IID);
1732}
1733
Chris Lattner53c39ba2010-02-14 22:22:58 +00001734/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
1735/// return the ComplexPattern information, otherwise return null.
1736const ComplexPattern *
1737TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00001738 Record *Rec;
1739 if (isLeaf()) {
1740 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1741 if (!DI)
1742 return nullptr;
1743 Rec = DI->getDef();
1744 } else
1745 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001746
Tim Northoverc807a172014-05-20 11:52:46 +00001747 if (!Rec->isSubClassOf("ComplexPattern"))
1748 return nullptr;
1749 return &CGP.getComplexPattern(Rec);
1750}
1751
1752unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
1753 // A ComplexPattern specifically declares how many results it fills in.
1754 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1755 return CP->getNumOperands();
1756
1757 // If MIOperandInfo is specified, that gives the count.
1758 if (isLeaf()) {
1759 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
1760 if (DI && DI->getDef()->isSubClassOf("Operand")) {
1761 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
1762 if (MIOps->getNumArgs())
1763 return MIOps->getNumArgs();
1764 }
1765 }
1766
1767 // Otherwise there is just one result.
1768 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00001769}
1770
1771/// NodeHasProperty - Return true if this node has the specified property.
1772bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001773 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001774 if (isLeaf()) {
1775 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
1776 return CP->hasProperty(Property);
1777 return false;
1778 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001779
Chris Lattner53c39ba2010-02-14 22:22:58 +00001780 Record *Operator = getOperator();
1781 if (!Operator->isSubClassOf("SDNode")) return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001782
Chris Lattner53c39ba2010-02-14 22:22:58 +00001783 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
1784}
1785
1786
1787
1788
1789/// TreeHasProperty - Return true if any node in this tree has the specified
1790/// property.
1791bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00001792 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00001793 if (NodeHasProperty(Property, CGP))
1794 return true;
1795 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1796 if (getChild(i)->TreeHasProperty(Property, CGP))
1797 return true;
1798 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001799}
Chris Lattner53c39ba2010-02-14 22:22:58 +00001800
Evan Cheng49bad4c2008-06-16 20:29:38 +00001801/// isCommutativeIntrinsic - Return true if the node corresponds to a
1802/// commutative intrinsic.
1803bool
1804TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
1805 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
1806 return Int->isCommutative;
1807 return false;
1808}
1809
Matt Arsenaulteb492162014-11-02 23:46:51 +00001810static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
1811 if (!N->isLeaf())
1812 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00001813
Matt Arsenaulteb492162014-11-02 23:46:51 +00001814 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
1815 if (DI && DI->getDef()->isSubClassOf(Class))
1816 return true;
1817
1818 return false;
1819}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00001820
1821static void emitTooManyOperandsError(TreePattern &TP,
1822 StringRef InstName,
1823 unsigned Expected,
1824 unsigned Actual) {
1825 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
1826 " operands but expected only " + Twine(Expected) + "!");
1827}
1828
1829static void emitTooFewOperandsError(TreePattern &TP,
1830 StringRef InstName,
1831 unsigned Actual) {
1832 TP.error("Instruction '" + InstName +
1833 "' expects more than the provided " + Twine(Actual) + " operands!");
1834}
1835
Bob Wilson1b97f3f2009-01-05 17:23:09 +00001836/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00001837/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001838/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00001839bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001840 if (TP.hasError())
1841 return false;
1842
Chris Lattnerab3242f2008-01-06 01:10:31 +00001843 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00001844 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001845 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001846 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00001847 bool MadeChange = false;
1848 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1849 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00001850 NotRegisters,
1851 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001852 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00001853 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001854
Sean Silvafb509ed2012-10-10 20:24:43 +00001855 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001856 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001857
Chris Lattnerf1447252010-03-19 21:37:09 +00001858 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001859 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001860
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001861 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00001862 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001863
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001864 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
1865 for (auto &P : VVT) {
1866 MVT::SimpleValueType VT = P.second.SimpleTy;
1867 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
1868 continue;
1869 unsigned Size = MVT(VT).getSizeInBits();
1870 // Make sure that the value is representable for this type.
1871 if (Size >= 32)
1872 continue;
1873 // Check that the value doesn't use more bits than we have. It must
1874 // either be a sign- or zero-extended equivalent of the original.
1875 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
1876 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
1877 SignBitAndAbove == 1)
1878 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001879
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001880 TP.error("Integer value '" + itostr(II->getValue()) +
1881 "' is out of range for type '" + getEnumName(VT) + "'!");
1882 break;
1883 }
1884 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00001885 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001886
Chris Lattner8cab0212008-01-05 22:25:12 +00001887 return false;
1888 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001889
Chris Lattner8cab0212008-01-05 22:25:12 +00001890 // special handling for set, which isn't really an SDNode.
1891 if (getOperator()->getName() == "set") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001892 assert(getNumTypes() == 0 && "Set doesn't produce a value");
1893 assert(getNumChildren() >= 2 && "Missing RHS of a set?");
Chris Lattner8cab0212008-01-05 22:25:12 +00001894 unsigned NC = getNumChildren();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001895
Chris Lattnerf1447252010-03-19 21:37:09 +00001896 TreePatternNode *SetVal = getChild(NC-1);
1897 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
1898
Elena Demikhovsky09954792015-03-01 08:23:41 +00001899 for (unsigned i = 0; i < NC-1; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001900 TreePatternNode *Child = getChild(i);
1901 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001902
Chris Lattner8cab0212008-01-05 22:25:12 +00001903 // Types of operands must match.
Chris Lattnerf1447252010-03-19 21:37:09 +00001904 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
1905 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001906 }
1907 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001908 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001909
Chris Lattner5c2182e2010-03-27 02:53:27 +00001910 if (getOperator()->getName() == "implicit") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001911 assert(getNumTypes() == 0 && "Node doesn't produce a value");
1912
Chris Lattner8cab0212008-01-05 22:25:12 +00001913 bool MadeChange = false;
1914 for (unsigned i = 0; i < getNumChildren(); ++i)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001915 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00001916 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001917 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001918
Chris Lattneree820ac2010-02-23 05:51:07 +00001919 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001920 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00001921
Chris Lattner8cab0212008-01-05 22:25:12 +00001922 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00001923 unsigned NumRetVTs = Int->IS.RetVTs.size();
1924 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001925
Bill Wendling91821472008-11-13 09:08:33 +00001926 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00001927 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00001928
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001929 if (getNumChildren() != NumParamVTs + 1) {
Chris Lattner89c65662008-01-06 05:36:50 +00001930 TP.error("Intrinsic '" + Int->Name + "' expects " +
Chris Lattnerf1447252010-03-19 21:37:09 +00001931 utostr(NumParamVTs) + " operands, not " +
Bill Wendling91821472008-11-13 09:08:33 +00001932 utostr(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001933 return false;
1934 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001935
1936 // Apply type info to the intrinsic ID.
Chris Lattnerf1447252010-03-19 21:37:09 +00001937 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001938
Chris Lattnerf1447252010-03-19 21:37:09 +00001939 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
1940 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001941
Chris Lattnerf1447252010-03-19 21:37:09 +00001942 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
1943 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
1944 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001945 }
1946 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001947 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001948
Chris Lattneree820ac2010-02-23 05:51:07 +00001949 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001950 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001951
Chris Lattner135091b2010-03-28 08:48:47 +00001952 // Check that the number of operands is sane. Negative operands -> varargs.
1953 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001954 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00001955 TP.error(getOperator()->getName() + " node requires exactly " +
1956 itostr(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001957 return false;
1958 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001959
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001960 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001961 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1962 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001963 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00001964 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00001965 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001966
Chris Lattneree820ac2010-02-23 05:51:07 +00001967 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001968 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00001969 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00001970 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001971
Chris Lattnerd44966f2010-03-27 19:15:02 +00001972 bool MadeChange = false;
1973
1974 // Apply the result types to the node, these come from the things in the
1975 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00001976 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
1977 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001978 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
1979 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001980
Chris Lattnerd44966f2010-03-27 19:15:02 +00001981 // If the instruction has implicit defs, we apply the first one as a result.
1982 // FIXME: This sucks, it should apply all implicit defs.
1983 if (!InstInfo.ImplicitDefs.empty()) {
1984 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001985
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001986 // FIXME: Generalize to multiple possible types and multiple possible
1987 // ImplicitDefs.
1988 MVT::SimpleValueType VT =
1989 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00001990
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001991 if (VT != MVT::Other)
1992 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001993 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001994
Chris Lattnercabe0372010-03-15 06:00:16 +00001995 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
1996 // be the same.
1997 if (getOperator()->getName() == "INSERT_SUBREG") {
Chris Lattnerf1447252010-03-19 21:37:09 +00001998 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
1999 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2000 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002001 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2002 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2003 // variadic.
2004
2005 unsigned NChild = getNumChildren();
2006 if (NChild < 3) {
2007 TP.error("REG_SEQUENCE requires at least 3 operands!");
2008 return false;
2009 }
2010
2011 if (NChild % 2 == 0) {
2012 TP.error("REG_SEQUENCE requires an odd number of operands!");
2013 return false;
2014 }
2015
2016 if (!isOperandClass(getChild(0), "RegisterClass")) {
2017 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2018 return false;
2019 }
2020
2021 for (unsigned I = 1; I < NChild; I += 2) {
2022 TreePatternNode *SubIdxChild = getChild(I + 1);
2023 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2024 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2025 itostr(I + 1) + "!");
2026 return false;
2027 }
2028 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002029 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002030
2031 unsigned ChildNo = 0;
2032 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2033 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002034
Chris Lattner8cab0212008-01-05 22:25:12 +00002035 // If the instruction expects a predicate or optional def operand, we
2036 // codegen this by setting the operand to it's default value if it has a
2037 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00002038 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002039 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2040 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002041
Chris Lattner8cab0212008-01-05 22:25:12 +00002042 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002043 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002044 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002045 return false;
2046 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002047
Chris Lattner8cab0212008-01-05 22:25:12 +00002048 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002049 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002050
2051 // If the operand has sub-operands, they may be provided by distinct
2052 // child patterns, so attempt to match each sub-operand separately.
2053 if (OperandNode->isSubClassOf("Operand")) {
2054 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2055 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2056 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002057 // a single ComplexPattern-related Operand.
2058
2059 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002060 // Match first sub-operand against the child we already have.
2061 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2062 MadeChange |=
2063 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2064
2065 // And the remaining sub-operands against subsequent children.
2066 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2067 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002068 emitTooFewOperandsError(TP, getOperator()->getName(),
2069 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002070 return false;
2071 }
2072 Child = getChild(ChildNo++);
2073
2074 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2075 MadeChange |=
2076 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2077 }
2078 continue;
2079 }
2080 }
2081 }
2082
2083 // If we didn't match by pieces above, attempt to match the whole
2084 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002085 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002086 }
Christopher Lamba7312392008-03-11 09:33:47 +00002087
Matt Arsenaulteb492162014-11-02 23:46:51 +00002088 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002089 emitTooManyOperandsError(TP, getOperator()->getName(),
2090 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002091 return false;
2092 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002093
Ulrich Weigande618abd2013-03-19 19:51:09 +00002094 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2095 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002096 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002097 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002098
Tim Northoverc807a172014-05-20 11:52:46 +00002099 if (getOperator()->isSubClassOf("ComplexPattern")) {
2100 bool MadeChange = false;
2101
2102 for (unsigned i = 0; i < getNumChildren(); ++i)
2103 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2104
2105 return MadeChange;
2106 }
2107
Chris Lattneree820ac2010-02-23 05:51:07 +00002108 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002109
Chris Lattneree820ac2010-02-23 05:51:07 +00002110 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002111 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002112 TP.error("Node transform '" + getOperator()->getName() +
2113 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002114 return false;
2115 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002116
Chris Lattnercabe0372010-03-15 06:00:16 +00002117 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002118 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002119}
2120
2121/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2122/// RHS of a commutative operation, not the on LHS.
2123static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2124 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
2125 return true;
Sean Silva88eb8dd2012-10-10 20:24:47 +00002126 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002127 return true;
2128 return false;
2129}
2130
2131
2132/// canPatternMatch - If it is impossible for this pattern to match on this
2133/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002134/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002135/// that can never possibly work), and to prevent the pattern permuter from
2136/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002137bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002138 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002139 if (isLeaf()) return true;
2140
2141 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2142 if (!getChild(i)->canPatternMatch(Reason, CDP))
2143 return false;
2144
2145 // If this is an intrinsic, handle cases that would make it not match. For
2146 // example, if an operand is required to be an immediate.
2147 if (getOperator()->isSubClassOf("Intrinsic")) {
2148 // TODO:
2149 return true;
2150 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002151
Tim Northoverc807a172014-05-20 11:52:46 +00002152 if (getOperator()->isSubClassOf("ComplexPattern"))
2153 return true;
2154
Chris Lattner8cab0212008-01-05 22:25:12 +00002155 // If this node is a commutative operator, check that the LHS isn't an
2156 // immediate.
2157 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002158 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2159 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002160 // Scan all of the operands of the node and make sure that only the last one
2161 // is a constant node, unless the RHS also is.
2162 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002163 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002164 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002165 if (OnlyOnRHSOfCommutative(getChild(i))) {
2166 Reason="Immediate value must be on the RHS of commutative operators!";
2167 return false;
2168 }
2169 }
2170 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002171
Chris Lattner8cab0212008-01-05 22:25:12 +00002172 return true;
2173}
2174
2175//===----------------------------------------------------------------------===//
2176// TreePattern implementation
2177//
2178
David Greeneaf8ee2c2011-07-29 22:43:06 +00002179TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002180 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002181 isInputPattern(isInput), HasError(false),
2182 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002183 for (Init *I : RawPat->getValues())
2184 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002185}
2186
David Greeneaf8ee2c2011-07-29 22:43:06 +00002187TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002188 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002189 isInputPattern(isInput), HasError(false),
2190 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002191 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002192}
2193
David Blaikiecf195302014-11-17 22:55:41 +00002194TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002195 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002196 isInputPattern(isInput), HasError(false),
2197 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002198 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002199}
2200
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002201void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002202 if (HasError)
2203 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002204 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002205 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2206 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002207}
2208
Chris Lattnercabe0372010-03-15 06:00:16 +00002209void TreePattern::ComputeNamedNodes() {
Craig Topper306cb122015-11-22 20:46:24 +00002210 for (TreePatternNode *Tree : Trees)
2211 ComputeNamedNodes(Tree);
Chris Lattnercabe0372010-03-15 06:00:16 +00002212}
2213
2214void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
2215 if (!N->getName().empty())
2216 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002217
Chris Lattnercabe0372010-03-15 06:00:16 +00002218 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2219 ComputeNamedNodes(N->getChild(i));
2220}
2221
David Blaikiecf195302014-11-17 22:55:41 +00002222
2223TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
Sean Silvafb509ed2012-10-10 20:24:43 +00002224 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002225 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002226
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002227 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002228 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002229 /// (foo GPR, imm) -> (foo GPR, (imm))
2230 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
David Greenee32ebf22011-07-29 19:07:07 +00002231 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002232 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002233 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002234 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002235
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002236 // Input argument?
David Blaikiecf195302014-11-17 22:55:41 +00002237 TreePatternNode *Res = new TreePatternNode(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002238 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002239 if (OpName.empty())
2240 error("'node' argument requires a name to match with operand list");
2241 Args.push_back(OpName);
2242 }
2243
2244 Res->setName(OpName);
2245 return Res;
2246 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002247
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002248 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002249 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002250 if (OpName.empty())
2251 error("'?' argument requires a name to match with operand list");
David Blaikiecf195302014-11-17 22:55:41 +00002252 TreePatternNode *Res = new TreePatternNode(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002253 Args.push_back(OpName);
2254 Res->setName(OpName);
2255 return Res;
2256 }
2257
Sean Silvafb509ed2012-10-10 20:24:43 +00002258 if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002259 if (!OpName.empty())
2260 error("Constant int argument should not have a name!");
David Blaikiecf195302014-11-17 22:55:41 +00002261 return new TreePatternNode(II, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002262 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002263
Sean Silvafb509ed2012-10-10 20:24:43 +00002264 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002265 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002266 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002267 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002268 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002269 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002270 }
2271
Sean Silvafb509ed2012-10-10 20:24:43 +00002272 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002273 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002274 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002275 error("Pattern has unexpected init kind!");
2276 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002277 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002278 if (!OpDef) error("Pattern has unexpected operator type!");
2279 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002280
Chris Lattner8cab0212008-01-05 22:25:12 +00002281 if (Operator->isSubClassOf("ValueType")) {
2282 // If the operator is a ValueType, then this must be "type cast" of a leaf
2283 // node.
2284 if (Dag->getNumArgs() != 1)
2285 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002286
Matthias Braunbb053162016-12-05 06:00:46 +00002287 TreePatternNode *New = ParseTreePattern(Dag->getArg(0),
2288 Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002289
Chris Lattner8cab0212008-01-05 22:25:12 +00002290 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002291 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002292 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2293 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002294
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002295 if (!OpName.empty())
2296 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002297 return New;
2298 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002299
Chris Lattner8cab0212008-01-05 22:25:12 +00002300 // Verify that this is something that makes sense for an operator.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002301 if (!Operator->isSubClassOf("PatFrag") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002302 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002303 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002304 !Operator->isSubClassOf("SDNodeXForm") &&
2305 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002306 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002307 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002308 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002309 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002310
Chris Lattner8cab0212008-01-05 22:25:12 +00002311 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002312 if (isInputPattern) {
2313 if (Operator->isSubClassOf("Instruction") ||
2314 Operator->isSubClassOf("SDNodeXForm"))
2315 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2316 } else {
2317 if (Operator->isSubClassOf("Intrinsic"))
2318 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002319
Chris Lattner2e9eae12010-03-28 06:57:56 +00002320 if (Operator->isSubClassOf("SDNode") &&
2321 Operator->getName() != "imm" &&
2322 Operator->getName() != "fpimm" &&
2323 Operator->getName() != "tglobaltlsaddr" &&
2324 Operator->getName() != "tconstpool" &&
2325 Operator->getName() != "tjumptable" &&
2326 Operator->getName() != "tframeindex" &&
2327 Operator->getName() != "texternalsym" &&
2328 Operator->getName() != "tblockaddress" &&
2329 Operator->getName() != "tglobaladdr" &&
2330 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002331 Operator->getName() != "vt" &&
2332 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002333 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2334 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002335
Chris Lattner8cab0212008-01-05 22:25:12 +00002336 std::vector<TreePatternNode*> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002337
2338 // Parse all the operands.
2339 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002340 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002341
Chris Lattner8cab0212008-01-05 22:25:12 +00002342 // If the operator is an intrinsic, then this is just syntactic sugar for for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002343 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002344 // convert the intrinsic name to a number.
2345 if (Operator->isSubClassOf("Intrinsic")) {
2346 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2347 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2348
2349 // If this intrinsic returns void, it must have side-effects and thus a
2350 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002351 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002352 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002353 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002354 // Has side-effects, requires chain.
2355 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002356 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002357 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002358
David Greenee32ebf22011-07-29 19:07:07 +00002359 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
Chris Lattner8cab0212008-01-05 22:25:12 +00002360 Children.insert(Children.begin(), IIDNode);
2361 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002362
Tim Northoverc807a172014-05-20 11:52:46 +00002363 if (Operator->isSubClassOf("ComplexPattern")) {
2364 for (unsigned i = 0; i < Children.size(); ++i) {
2365 TreePatternNode *Child = Children[i];
2366
2367 if (Child->getName().empty())
2368 error("All arguments to a ComplexPattern must be named");
2369
2370 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2371 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2372 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2373 auto OperandId = std::make_pair(Operator, i);
2374 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2375 if (PrevOp != ComplexPatternOperands.end()) {
2376 if (PrevOp->getValue() != OperandId)
2377 error("All ComplexPattern operands must appear consistently: "
2378 "in the same order in just one ComplexPattern instance.");
2379 } else
2380 ComplexPatternOperands[Child->getName()] = OperandId;
2381 }
2382 }
2383
Chris Lattnerf1447252010-03-19 21:37:09 +00002384 unsigned NumResults = GetNumNodeResults(Operator, CDP);
David Blaikiecf195302014-11-17 22:55:41 +00002385 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002386 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002387
Matthias Braun7cf3b112016-12-05 06:00:41 +00002388 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002389 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002390 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002391 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002392 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002393}
2394
Chris Lattnera787c9e2010-03-28 08:38:32 +00002395/// SimplifyTree - See if we can simplify this tree to eliminate something that
2396/// will never match in favor of something obvious that will. This is here
2397/// strictly as a convenience to target authors because it allows them to write
2398/// more type generic things and have useless type casts fold away.
2399///
2400/// This returns true if any change is made.
David Blaikiecf195302014-11-17 22:55:41 +00002401static bool SimplifyTree(TreePatternNode *&N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002402 if (N->isLeaf())
2403 return false;
2404
2405 // If we have a bitconvert with a resolved type and if the source and
2406 // destination types are the same, then the bitconvert is useless, remove it.
2407 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002408 N->getExtType(0).isValueTypeByHwMode(false) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002409 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
2410 N->getName().empty()) {
David Blaikiecf195302014-11-17 22:55:41 +00002411 N = N->getChild(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002412 SimplifyTree(N);
2413 return true;
2414 }
2415
2416 // Walk all children.
2417 bool MadeChange = false;
2418 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
David Blaikiecf195302014-11-17 22:55:41 +00002419 TreePatternNode *Child = N->getChild(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002420 MadeChange |= SimplifyTree(Child);
David Blaikiecf195302014-11-17 22:55:41 +00002421 N->setChild(i, Child);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002422 }
2423 return MadeChange;
2424}
2425
2426
2427
Chris Lattner8cab0212008-01-05 22:25:12 +00002428/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002429/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002430/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002431bool TreePattern::
2432InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2433 if (NamedNodes.empty())
2434 ComputeNamedNodes();
2435
Chris Lattner8cab0212008-01-05 22:25:12 +00002436 bool MadeChange = true;
2437 while (MadeChange) {
2438 MadeChange = false;
Craig Topper3f7864e2017-08-30 02:05:03 +00002439 for (TreePatternNode *&Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002440 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2441 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002442 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002443
2444 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002445 for (auto &Entry : NamedNodes) {
2446 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002447
Chris Lattnercabe0372010-03-15 06:00:16 +00002448 // If we have input named node types, propagate their types to the named
2449 // values here.
2450 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002451 if (!InNamedTypes->count(Entry.getKey())) {
2452 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002453 "' in output pattern but not input pattern");
2454 return true;
2455 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002456
2457 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002458 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002459
2460 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002461 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002462 // If this node is a register class, and it is the root of the pattern
2463 // then we're mapping something onto an input register. We allow
2464 // changing the type of the input register in this case. This allows
2465 // us to match things like:
2466 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Craig Topper306cb122015-11-22 20:46:24 +00002467 if (Node == Trees[0] && Node->isLeaf()) {
2468 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002469 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2470 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002471 continue;
2472 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002473
Craig Topper306cb122015-11-22 20:46:24 +00002474 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002475 InNodes[0]->getNumTypes() == 1 &&
2476 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002477 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2478 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002479 }
2480 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002481
Chris Lattnercabe0372010-03-15 06:00:16 +00002482 // If there are multiple nodes with the same name, they must all have the
2483 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002484 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002485 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002486 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002487 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002488 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002489
Chris Lattnerf1447252010-03-19 21:37:09 +00002490 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2491 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002492 }
2493 }
2494 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002495 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002496
Chris Lattner8cab0212008-01-05 22:25:12 +00002497 bool HasUnresolvedTypes = false;
Craig Topper306cb122015-11-22 20:46:24 +00002498 for (const TreePatternNode *Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002499 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002500 return !HasUnresolvedTypes;
2501}
2502
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002503void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002504 OS << getRecord()->getName();
2505 if (!Args.empty()) {
2506 OS << "(" << Args[0];
2507 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2508 OS << ", " << Args[i];
2509 OS << ")";
2510 }
2511 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002512
Chris Lattner8cab0212008-01-05 22:25:12 +00002513 if (Trees.size() > 1)
2514 OS << "[\n";
Craig Topper306cb122015-11-22 20:46:24 +00002515 for (const TreePatternNode *Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002516 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002517 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002518 OS << "\n";
2519 }
2520
2521 if (Trees.size() > 1)
2522 OS << "]\n";
2523}
2524
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002525void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002526
2527//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002528// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002529//
2530
Jim Grosbach65586fe2010-12-21 16:16:00 +00002531CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002532 Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002533
Justin Bogner92a8c612016-07-15 16:31:37 +00002534 Intrinsics = CodeGenIntrinsicTable(Records, false);
2535 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002536 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002537 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002538 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002539 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002540 ParseDefaultOperands();
2541 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002542 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002543 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002544
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002545 // Break patterns with parameterized types into a series of patterns,
2546 // where each one has a fixed type and is predicated on the conditions
2547 // of the associated HW mode.
2548 ExpandHwModeBasedTypes();
2549
Chris Lattner8cab0212008-01-05 22:25:12 +00002550 // Generate variants. For example, commutative patterns can match
2551 // multiple ways. Add them to PatternsToMatch as well.
2552 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002553
2554 // Infer instruction flags. For example, we can detect loads,
2555 // stores, and side effects in many cases by examining an
2556 // instruction's pattern.
2557 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002558
2559 // Verify that instruction flags match the patterns.
2560 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002561}
2562
Chris Lattnerab3242f2008-01-06 01:10:31 +00002563Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002564 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002565 if (!N || !N->isSubClassOf("SDNode"))
2566 PrintFatalError("Error getting SDNode '" + Name + "'!");
2567
Chris Lattner8cab0212008-01-05 22:25:12 +00002568 return N;
2569}
2570
2571// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002572void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002573 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002574 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2575
Chris Lattner8cab0212008-01-05 22:25:12 +00002576 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002577 Record *R = Nodes.back();
2578 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002579 Nodes.pop_back();
2580 }
2581
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002582 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002583 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2584 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2585 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2586}
2587
2588/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2589/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002590void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002591 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2592 while (!Xforms.empty()) {
2593 Record *XFormNode = Xforms.back();
2594 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00002595 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00002596 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002597
2598 Xforms.pop_back();
2599 }
2600}
2601
Chris Lattnerab3242f2008-01-06 01:10:31 +00002602void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002603 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
2604 while (!AMs.empty()) {
2605 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
2606 AMs.pop_back();
2607 }
2608}
2609
2610
2611/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
2612/// file, building up the PatternFragments map. After we've collected them all,
2613/// inline fragments together as necessary, so that there are no references left
2614/// inside a pattern fragment to a pattern fragment.
2615///
Hal Finkel2756dc12014-02-28 00:26:56 +00002616void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002617 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002618
Chris Lattnere7170df2008-01-05 22:43:57 +00002619 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00002620 for (Record *Frag : Fragments) {
2621 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002622 continue;
2623
Craig Topper306cb122015-11-22 20:46:24 +00002624 DagInit *Tree = Frag->getValueAsDag("Fragment");
Hal Finkel2756dc12014-02-28 00:26:56 +00002625 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00002626 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
2627 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00002628 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002629
Chris Lattnere7170df2008-01-05 22:43:57 +00002630 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00002631 std::vector<std::string> &Args = P->getArgList();
Zachary Turner249dc142017-09-20 18:01:40 +00002632 // Copy the args so we can take StringRefs to them.
2633 auto ArgsCopy = Args;
2634 SmallDenseSet<StringRef, 4> OperandsSet;
2635 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002636
Chris Lattnere7170df2008-01-05 22:43:57 +00002637 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00002638 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002639
Chris Lattner8cab0212008-01-05 22:25:12 +00002640 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00002641 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00002642 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002643 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002644 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00002645 if (!OpsOp ||
2646 (OpsOp->getDef()->getName() != "ops" &&
2647 OpsOp->getDef()->getName() != "outs" &&
2648 OpsOp->getDef()->getName() != "ins"))
2649 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002650
2651 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00002652 Args.clear();
2653 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002654 if (!isa<DefInit>(OpsList->getArg(j)) ||
2655 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00002656 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00002657 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00002658 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00002659 StringRef ArgNameStr = OpsList->getArgNameStr(j);
2660 if (!OperandsSet.count(ArgNameStr))
2661 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00002662 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00002663 OperandsSet.erase(ArgNameStr);
2664 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00002665 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002666
Chris Lattnere7170df2008-01-05 22:43:57 +00002667 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002668 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00002669 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002670
Chris Lattnere7170df2008-01-05 22:43:57 +00002671 // If there is a code init for this fragment, keep track of the fact that
2672 // this fragment uses it.
Chris Lattner514e2922011-04-17 21:38:24 +00002673 TreePredicateFn PredFn(P);
2674 if (!PredFn.isAlwaysTrue())
2675 P->getOnlyTree()->addPredicateFn(PredFn);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002676
Chris Lattner8cab0212008-01-05 22:25:12 +00002677 // If there is a node transformation corresponding to this, keep track of
2678 // it.
Craig Topper306cb122015-11-22 20:46:24 +00002679 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00002680 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
2681 P->getOnlyTree()->setTransformFn(Transform);
2682 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002683
Chris Lattner8cab0212008-01-05 22:25:12 +00002684 // Now that we've parsed all of the tree fragments, do a closure on them so
2685 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00002686 for (Record *Frag : Fragments) {
2687 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00002688 continue;
2689
Craig Topper306cb122015-11-22 20:46:24 +00002690 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00002691 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002692
Chris Lattner8cab0212008-01-05 22:25:12 +00002693 // Infer as many types as possible. Don't worry about it if we don't infer
2694 // all of them, some may depend on the inputs of the pattern.
David Blaikie3c6ca232014-11-13 21:40:02 +00002695 ThePat.InferAllTypes();
2696 ThePat.resetError();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002697
Chris Lattner8cab0212008-01-05 22:25:12 +00002698 // If debugging, print out the pattern fragment result.
David Blaikie3c6ca232014-11-13 21:40:02 +00002699 DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00002700 }
2701}
2702
Chris Lattnerab3242f2008-01-06 01:10:31 +00002703void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00002704 std::vector<Record*> DefaultOps;
2705 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00002706
2707 // Find some SDNode.
2708 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00002709 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002710
Tom Stellardb7246a72012-09-06 14:15:52 +00002711 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
2712 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002713
Tom Stellardb7246a72012-09-06 14:15:52 +00002714 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
2715 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00002716 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00002717 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
2718 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
2719 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00002720 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002721
Tom Stellardb7246a72012-09-06 14:15:52 +00002722 // Create a TreePattern to parse this.
2723 TreePattern P(DefaultOps[i], DI, false, *this);
2724 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002725
Tom Stellardb7246a72012-09-06 14:15:52 +00002726 // Copy the operands over into a DAGDefaultOperand.
2727 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002728
Tom Stellardb7246a72012-09-06 14:15:52 +00002729 TreePatternNode *T = P.getTree(0);
2730 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
2731 TreePatternNode *TPN = T->getChild(op);
2732 while (TPN->ApplyTypeConstraints(P, false))
2733 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002734
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002735 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00002736 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
2737 DefaultOps[i]->getName() +
2738 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002739 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002740 DefaultOpInfo.DefaultOps.push_back(TPN);
Chris Lattner8cab0212008-01-05 22:25:12 +00002741 }
Tom Stellardb7246a72012-09-06 14:15:52 +00002742
2743 // Insert it into the DefaultOperands map so we can find it later.
2744 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00002745 }
2746}
2747
2748/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
2749/// instruction input. Return true if this is a real use.
2750static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
Chris Lattner5debc332010-04-20 06:30:25 +00002751 std::map<std::string, TreePatternNode*> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002752 // No name -> not interesting.
2753 if (Pat->getName().empty()) {
2754 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002755 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002756 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2757 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner8cab0212008-01-05 22:25:12 +00002758 I->error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002759 }
2760 return false;
2761 }
2762
2763 Record *Rec;
2764 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002765 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002766 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
2767 Rec = DI->getDef();
2768 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00002769 Rec = Pat->getOperator();
2770 }
2771
2772 // SRCVALUE nodes are ignored.
2773 if (Rec->getName() == "srcvalue")
2774 return false;
2775
2776 TreePatternNode *&Slot = InstInputs[Pat->getName()];
2777 if (!Slot) {
2778 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002779 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002780 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002781 Record *SlotRec;
2782 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00002783 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002784 } else {
2785 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
2786 SlotRec = Slot->getOperator();
2787 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002788
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002789 // Ensure that the inputs agree if we've already seen this input.
2790 if (Rec != SlotRec)
2791 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattnerf1447252010-03-19 21:37:09 +00002792 if (Slot->getExtTypes() != Pat->getExtTypes())
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00002793 I->error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00002794 return true;
2795}
2796
2797/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
2798/// part of "I", the instruction), computing the set of inputs and outputs of
2799/// the pattern. Report errors if we see anything naughty.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002800void CodeGenDAGPatterns::
Chris Lattner8cab0212008-01-05 22:25:12 +00002801FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
2802 std::map<std::string, TreePatternNode*> &InstInputs,
2803 std::map<std::string, TreePatternNode*>&InstResults,
Chris Lattner8cab0212008-01-05 22:25:12 +00002804 std::vector<Record*> &InstImpResults) {
2805 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00002806 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00002807 if (!isUse && Pat->getTransformFn())
2808 I->error("Cannot specify a transform function for a non-input value!");
2809 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002810 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002811
Chris Lattnerf2d70992010-02-17 06:53:36 +00002812 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002813 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
2814 TreePatternNode *Dest = Pat->getChild(i);
2815 if (!Dest->isLeaf())
2816 I->error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002817
Sean Silvafb509ed2012-10-10 20:24:43 +00002818 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00002819 if (!Val || !Val->getDef()->isSubClassOf("Register"))
2820 I->error("implicitly defined value should be a register!");
2821 InstImpResults.push_back(Val->getDef());
2822 }
2823 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002824 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002825
Chris Lattnerf2d70992010-02-17 06:53:36 +00002826 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002827 // If this is not a set, verify that the children nodes are not void typed,
2828 // and recurse.
2829 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002830 if (Pat->getChild(i)->getNumTypes() == 0)
Chris Lattner8cab0212008-01-05 22:25:12 +00002831 I->error("Cannot have void nodes inside of patterns!");
2832 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00002833 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002834 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002835
Chris Lattner8cab0212008-01-05 22:25:12 +00002836 // If this is a non-leaf node with no children, treat it basically as if
2837 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00002838 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002839
Chris Lattner8cab0212008-01-05 22:25:12 +00002840 if (!isUse && Pat->getTransformFn())
2841 I->error("Cannot specify a transform function for a non-input value!");
2842 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00002843 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002844
Chris Lattner8cab0212008-01-05 22:25:12 +00002845 // Otherwise, this is a set, validate and collect instruction results.
2846 if (Pat->getNumChildren() == 0)
2847 I->error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002848
Chris Lattner8cab0212008-01-05 22:25:12 +00002849 if (Pat->getTransformFn())
2850 I->error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002851
Chris Lattner8cab0212008-01-05 22:25:12 +00002852 // Check the set destinations.
2853 unsigned NumDests = Pat->getNumChildren()-1;
2854 for (unsigned i = 0; i != NumDests; ++i) {
2855 TreePatternNode *Dest = Pat->getChild(i);
2856 if (!Dest->isLeaf())
2857 I->error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002858
Sean Silvafb509ed2012-10-10 20:24:43 +00002859 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00002860 if (!Val) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002861 I->error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00002862 continue;
2863 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002864
2865 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002866 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00002867 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00002868 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002869 if (Dest->getName().empty())
2870 I->error("set destination must have a name!");
2871 if (InstResults.count(Dest->getName()))
2872 I->error("cannot set '" + Dest->getName() +"' multiple times");
2873 InstResults[Dest->getName()] = Dest;
2874 } else if (Val->getDef()->isSubClassOf("Register")) {
2875 InstImpResults.push_back(Val->getDef());
2876 } else {
2877 I->error("set destination should be a register!");
2878 }
2879 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002880
Chris Lattner8cab0212008-01-05 22:25:12 +00002881 // Verify and collect info from the computation.
2882 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
Chris Lattner5debc332010-04-20 06:30:25 +00002883 InstInputs, InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00002884}
2885
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002886//===----------------------------------------------------------------------===//
2887// Instruction Analysis
2888//===----------------------------------------------------------------------===//
2889
2890class InstAnalyzer {
2891 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002892public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002893 bool hasSideEffects;
2894 bool mayStore;
2895 bool mayLoad;
2896 bool isBitcast;
2897 bool isVariadic;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002898
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002899 InstAnalyzer(const CodeGenDAGPatterns &cdp)
2900 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
2901 isBitcast(false), isVariadic(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002902
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002903 void Analyze(const TreePattern *Pat) {
2904 // Assume only the first tree is the pattern. The others are clobber nodes.
2905 AnalyzeNode(Pat->getTree(0));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002906 }
2907
Craig Topper2a053a92017-06-20 16:34:37 +00002908 void Analyze(const PatternToMatch &Pat) {
2909 AnalyzeNode(Pat.getSrcPattern());
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00002910 }
2911
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002912private:
Evan Cheng880e299d2011-03-15 05:09:26 +00002913 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002914 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00002915 return false;
2916
2917 if (N->getNumChildren() != 2)
2918 return false;
2919
2920 const TreePatternNode *N0 = N->getChild(0);
Sean Silva88eb8dd2012-10-10 20:24:47 +00002921 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
Evan Cheng880e299d2011-03-15 05:09:26 +00002922 return false;
2923
2924 const TreePatternNode *N1 = N->getChild(1);
2925 if (N1->isLeaf())
2926 return false;
2927 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
2928 return false;
2929
2930 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
2931 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
2932 return false;
2933 return OpInfo.getEnumName() == "ISD::BITCAST";
2934 }
2935
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002936public:
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002937 void AnalyzeNode(const TreePatternNode *N) {
2938 if (N->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002939 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002940 Record *LeafRec = DI->getDef();
2941 // Handle ComplexPattern leaves.
2942 if (LeafRec->isSubClassOf("ComplexPattern")) {
2943 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
2944 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
2945 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002946 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002947 }
2948 }
2949 return;
2950 }
2951
2952 // Analyze children.
2953 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
2954 AnalyzeNode(N->getChild(i));
2955
2956 // Ignore set nodes, which are not SDNodes.
Evan Cheng880e299d2011-03-15 05:09:26 +00002957 if (N->getOperator()->getName() == "set") {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002958 isBitcast = IsNodeBitcast(N);
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002959 return;
Evan Cheng880e299d2011-03-15 05:09:26 +00002960 }
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002961
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002962 // Notice properties of the node.
Tim Northoverc807a172014-05-20 11:52:46 +00002963 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
2964 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
2965 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
2966 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002967
2968 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
2969 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002970 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002971 mayLoad = true;// These may load memory.
2972
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002973 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002974 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
2975
Matt Arsenault868af922017-04-28 21:01:46 +00002976 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
2977 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00002978 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002979 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002980 }
2981 }
2982
2983};
2984
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002985static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002986 const InstAnalyzer &PatInfo,
2987 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002988 bool Error = false;
2989
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00002990 // Remember where InstInfo got its flags.
2991 if (InstInfo.hasUndefFlags())
2992 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002993
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00002994 // Check explicitly set flags for consistency.
2995 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
2996 !InstInfo.hasSideEffects_Unset) {
2997 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
2998 // the pattern has no side effects. That could be useful for div/rem
2999 // instructions that may trap.
3000 if (!InstInfo.hasSideEffects) {
3001 Error = true;
3002 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3003 Twine(InstInfo.hasSideEffects));
3004 }
3005 }
3006
3007 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3008 Error = true;
3009 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3010 Twine(InstInfo.mayStore));
3011 }
3012
3013 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3014 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003015 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003016 if (!InstInfo.mayLoad) {
3017 Error = true;
3018 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3019 Twine(InstInfo.mayLoad));
3020 }
3021 }
3022
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003023 // Transfer inferred flags.
3024 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3025 InstInfo.mayStore |= PatInfo.mayStore;
3026 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003027
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003028 // These flags are silently added without any verification.
3029 InstInfo.isBitcast |= PatInfo.isBitcast;
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003030
3031 // Don't infer isVariadic. This flag means something different on SDNodes and
3032 // instructions. For example, a CALL SDNode is variadic because it has the
3033 // call arguments as operands, but a CALL instruction is not variadic - it
3034 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003035
3036 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003037}
3038
Jim Grosbach514410b2012-07-17 00:47:06 +00003039/// hasNullFragReference - Return true if the DAG has any reference to the
3040/// null_frag operator.
3041static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003042 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003043 if (!OpDef) return false;
3044 Record *Operator = OpDef->getDef();
3045
3046 // If this is the null fragment, return true.
3047 if (Operator->getName() == "null_frag") return true;
3048 // If any of the arguments reference the null fragment, return true.
3049 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003050 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003051 if (Arg && hasNullFragReference(Arg))
3052 return true;
3053 }
3054
3055 return false;
3056}
3057
3058/// hasNullFragReference - Return true if any DAG in the list references
3059/// the null_frag operator.
3060static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003061 for (Init *I : LI->getValues()) {
3062 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003063 assert(DI && "non-dag in an instruction Pattern list?!");
3064 if (hasNullFragReference(DI))
3065 return true;
3066 }
3067 return false;
3068}
3069
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003070/// Get all the instructions in a tree.
3071static void
3072getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3073 if (Tree->isLeaf())
3074 return;
3075 if (Tree->getOperator()->isSubClassOf("Instruction"))
3076 Instrs.push_back(Tree->getOperator());
3077 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3078 getInstructionsInTree(Tree->getChild(i), Instrs);
3079}
3080
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003081/// Check the class of a pattern leaf node against the instruction operand it
3082/// represents.
3083static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3084 Record *Leaf) {
3085 if (OI.Rec == Leaf)
3086 return true;
3087
3088 // Allow direct value types to be used in instruction set patterns.
3089 // The type will be checked later.
3090 if (Leaf->isSubClassOf("ValueType"))
3091 return true;
3092
3093 // Patterns can also be ComplexPattern instances.
3094 if (Leaf->isSubClassOf("ComplexPattern"))
3095 return true;
3096
3097 return false;
3098}
3099
Ahmed Bougacha14107512013-10-28 18:07:21 +00003100const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern(
3101 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003102
Craig Topper0d1fb902015-03-10 03:25:04 +00003103 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003104
Craig Topper0d1fb902015-03-10 03:25:04 +00003105 // Parse the instruction.
3106 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this);
3107 // Inline pattern fragments into it.
3108 I->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003109
Craig Topper0d1fb902015-03-10 03:25:04 +00003110 // Infer as many types as possible. If we cannot infer all of them, we can
3111 // never do anything with this instruction pattern: report it to the user.
3112 if (!I->InferAllTypes())
3113 I->error("Could not infer all types in pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003114
Craig Topper0d1fb902015-03-10 03:25:04 +00003115 // InstInputs - Keep track of all of the inputs of the instruction, along
3116 // with the record they are declared as.
3117 std::map<std::string, TreePatternNode*> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003118
Craig Topper0d1fb902015-03-10 03:25:04 +00003119 // InstResults - Keep track of all the virtual registers that are 'set'
3120 // in the instruction, including what reg class they are.
3121 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003122
Craig Topper0d1fb902015-03-10 03:25:04 +00003123 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003124
Craig Topper0d1fb902015-03-10 03:25:04 +00003125 // Verify that the top-level forms in the instruction are of void type, and
3126 // fill in the InstResults map.
Zachary Turner249dc142017-09-20 18:01:40 +00003127 SmallString<32> TypesString;
Craig Topper0d1fb902015-03-10 03:25:04 +00003128 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
Zachary Turner249dc142017-09-20 18:01:40 +00003129 TypesString.clear();
Craig Topper0d1fb902015-03-10 03:25:04 +00003130 TreePatternNode *Pat = I->getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003131 if (Pat->getNumTypes() != 0) {
Zachary Turner249dc142017-09-20 18:01:40 +00003132 raw_svector_ostream OS(TypesString);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003133 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3134 if (k > 0)
Zachary Turner249dc142017-09-20 18:01:40 +00003135 OS << ", ";
3136 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003137 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003138 I->error("Top-level forms in instruction pattern should have"
Zachary Turner249dc142017-09-20 18:01:40 +00003139 " void types, has types " +
3140 OS.str());
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003141 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003142
Craig Topper0d1fb902015-03-10 03:25:04 +00003143 // Find inputs and outputs, and verify the structure of the uses/defs.
3144 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3145 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003146 }
3147
Craig Topper0d1fb902015-03-10 03:25:04 +00003148 // Now that we have inputs and outputs of the pattern, inspect the operands
3149 // list for the instruction. This determines the order that operands are
3150 // added to the machine instruction the node corresponds to.
3151 unsigned NumResults = InstResults.size();
3152
3153 // Parse the operands list from the (ops) list, validating it.
3154 assert(I->getArgList().empty() && "Args list should still be empty here!");
3155
3156 // Check that all of the results occur first in the list.
3157 std::vector<Record*> Results;
Craig Topper3a8eb892015-03-20 05:09:06 +00003158 SmallVector<TreePatternNode *, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003159 for (unsigned i = 0; i != NumResults; ++i) {
3160 if (i == CGI.Operands.size())
3161 I->error("'" + InstResults.begin()->first +
3162 "' set but does not appear in operand list!");
3163 const std::string &OpName = CGI.Operands[i].Name;
3164
3165 // Check that it exists in InstResults.
3166 TreePatternNode *RNode = InstResults[OpName];
3167 if (!RNode)
3168 I->error("Operand $" + OpName + " does not exist in operand list!");
3169
Craig Topper3a8eb892015-03-20 05:09:06 +00003170 ResNodes.push_back(RNode);
3171
Craig Topper0d1fb902015-03-10 03:25:04 +00003172 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3173 if (!R)
3174 I->error("Operand $" + OpName + " should be a set destination: all "
3175 "outputs must occur before inputs in operand list!");
3176
3177 if (!checkOperandClass(CGI.Operands[i], R))
3178 I->error("Operand $" + OpName + " class mismatch!");
3179
3180 // Remember the return type.
3181 Results.push_back(CGI.Operands[i].Rec);
3182
3183 // Okay, this one checks out.
3184 InstResults.erase(OpName);
3185 }
3186
3187 // Loop over the inputs next. Make a copy of InstInputs so we can destroy
3188 // the copy while we're checking the inputs.
3189 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
3190
3191 std::vector<TreePatternNode*> ResultNodeOperands;
3192 std::vector<Record*> Operands;
3193 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3194 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3195 const std::string &OpName = Op.Name;
3196 if (OpName.empty())
3197 I->error("Operand #" + utostr(i) + " in operands list has no name!");
3198
3199 if (!InstInputsCheck.count(OpName)) {
3200 // If this is an operand with a DefaultOps set filled in, we can ignore
3201 // this. When we codegen it, we will do so as always executed.
3202 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3203 // Does it have a non-empty DefaultOps field? If so, ignore this
3204 // operand.
3205 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3206 continue;
3207 }
3208 I->error("Operand $" + OpName +
3209 " does not appear in the instruction pattern");
3210 }
3211 TreePatternNode *InVal = InstInputsCheck[OpName];
3212 InstInputsCheck.erase(OpName); // It occurred, remove from map.
3213
3214 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3215 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3216 if (!checkOperandClass(Op, InRec))
3217 I->error("Operand $" + OpName + "'s register class disagrees"
3218 " between the operand and pattern");
3219 }
3220 Operands.push_back(Op.Rec);
3221
3222 // Construct the result for the dest-pattern operand list.
3223 TreePatternNode *OpNode = InVal->clone();
3224
3225 // No predicate is useful on the result.
3226 OpNode->clearPredicateFns();
3227
3228 // Promote the xform function to be an explicit node if set.
3229 if (Record *Xform = OpNode->getTransformFn()) {
3230 OpNode->setTransformFn(nullptr);
3231 std::vector<TreePatternNode*> Children;
3232 Children.push_back(OpNode);
3233 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
3234 }
3235
3236 ResultNodeOperands.push_back(OpNode);
3237 }
3238
3239 if (!InstInputsCheck.empty())
3240 I->error("Input operand $" + InstInputsCheck.begin()->first +
3241 " occurs in pattern but not in operands list!");
3242
3243 TreePatternNode *ResultPattern =
3244 new TreePatternNode(I->getRecord(), ResultNodeOperands,
3245 GetNumNodeResults(I->getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003246 // Copy fully inferred output node types to instruction result pattern.
3247 for (unsigned i = 0; i != NumResults; ++i) {
3248 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3249 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3250 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003251
3252 // Create and insert the instruction.
3253 // FIXME: InstImpResults should not be part of DAGInstruction.
3254 DAGInstruction TheInst(I, Results, Operands, InstImpResults);
3255 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst));
3256
3257 // Use a temporary tree pattern to infer all types and make sure that the
3258 // constructed result is correct. This depends on the instruction already
3259 // being inserted into the DAGInsts map.
3260 TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
3261 Temp.InferAllTypes(&I->getNamedNodesMap());
3262
3263 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second;
3264 TheInsertedInst.setResultPattern(Temp.getOnlyTree());
3265
3266 return TheInsertedInst;
3267}
3268
Ahmed Bougacha14107512013-10-28 18:07:21 +00003269/// ParseInstructions - Parse all of the instructions, inlining and resolving
3270/// any fragments involved. This populates the Instructions list with fully
3271/// resolved instructions.
3272void CodeGenDAGPatterns::ParseInstructions() {
3273 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3274
Craig Topper306cb122015-11-22 20:46:24 +00003275 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003276 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003277
Craig Topper306cb122015-11-22 20:46:24 +00003278 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3279 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003280
3281 // If there is no pattern, only collect minimal information about the
3282 // instruction for its operand list. We have to assume that there is one
3283 // result, as we have no detailed info. A pattern which references the
3284 // null_frag operator is as-if no pattern were specified. Normally this
3285 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3286 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003287 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003288 std::vector<Record*> Results;
3289 std::vector<Record*> Operands;
3290
Craig Topper306cb122015-11-22 20:46:24 +00003291 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003292
3293 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003294 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3295 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003296
Craig Topper3a8eb892015-03-20 05:09:06 +00003297 // The rest are inputs.
3298 for (unsigned j = InstInfo.Operands.NumDefs,
3299 e = InstInfo.Operands.size(); j < e; ++j)
3300 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003301 }
3302
3303 // Create and insert the instruction.
3304 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003305 Instructions.insert(std::make_pair(Instr,
Craig Topper24064772014-04-15 07:20:03 +00003306 DAGInstruction(nullptr, Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003307 continue; // no pattern.
3308 }
3309
Craig Topper306cb122015-11-22 20:46:24 +00003310 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003311 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions);
3312
Ahmed Bougachaa70ecdc2013-10-28 18:19:04 +00003313 (void)DI;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003314 DEBUG(DI.getPattern()->dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003315 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003316
Chris Lattner8cab0212008-01-05 22:25:12 +00003317 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003318 for (auto &Entry : Instructions) {
3319 DAGInstruction &TheInst = Entry.second;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003320 TreePattern *I = TheInst.getPattern();
Craig Topper24064772014-04-15 07:20:03 +00003321 if (!I) continue; // No pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00003322
3323 // FIXME: Assume only the first tree is the pattern. The others are clobber
3324 // nodes.
3325 TreePatternNode *Pattern = I->getTree(0);
3326 TreePatternNode *SrcPattern;
3327 if (Pattern->getOperator()->getName() == "set") {
3328 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3329 } else{
3330 // Not a set (store or something?)
3331 SrcPattern = Pattern;
3332 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003333
Craig Topper306cb122015-11-22 20:46:24 +00003334 Record *Instr = Entry.first;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003335 ListInit *Preds = Instr->getValueAsListInit("Predicates");
3336 int Complexity = Instr->getValueAsInt("AddedComplexity");
3337 AddPatternToMatch(
3338 I,
3339 PatternToMatch(Instr, makePredList(Preds), SrcPattern,
3340 TheInst.getResultPattern(), TheInst.getImpResults(),
3341 Complexity, Instr->getID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00003342 }
3343}
3344
Chris Lattnera7722b62010-02-23 06:55:24 +00003345
3346typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
3347
Jim Grosbach65586fe2010-12-21 16:16:00 +00003348static void FindNames(const TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003349 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003350 TreePattern *PatternTop) {
Chris Lattnera7722b62010-02-23 06:55:24 +00003351 if (!P->getName().empty()) {
3352 NameRecord &Rec = Names[P->getName()];
3353 // If this is the first instance of the name, remember the node.
3354 if (Rec.second++ == 0)
3355 Rec.first = P;
Chris Lattnerf1447252010-03-19 21:37:09 +00003356 else if (Rec.first->getExtTypes() != P->getExtTypes())
Chris Lattner5b0e2492010-02-23 07:22:28 +00003357 PatternTop->error("repetition of value: $" + P->getName() +
3358 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003359 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003360
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003361 if (!P->isLeaf()) {
3362 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner5b0e2492010-02-23 07:22:28 +00003363 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003364 }
3365}
3366
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003367std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3368 std::vector<Predicate> Preds;
3369 for (Init *I : L->getValues()) {
3370 if (DefInit *Pred = dyn_cast<DefInit>(I))
3371 Preds.push_back(Pred->getDef());
3372 else
3373 llvm_unreachable("Non-def on the list");
3374 }
3375
3376 // Sort so that different orders get canonicalized to the same string.
3377 std::sort(Preds.begin(), Preds.end());
3378 return Preds;
3379}
3380
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003381void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003382 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003383 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003384 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003385 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3386 PrintWarning(Pattern->getRecord()->getLoc(),
3387 Twine("Pattern can never match: ") + Reason);
3388 return;
3389 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003390
Chris Lattner1e634e32010-03-01 22:29:19 +00003391 // If the source pattern's root is a complex pattern, that complex pattern
3392 // must specify the nodes it can potentially match.
3393 if (const ComplexPattern *CP =
3394 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3395 if (CP->getRootNodes().empty())
3396 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3397 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003398
3399
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003400 // Find all of the named values in the input and output, ensure they have the
3401 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003402 std::map<std::string, NameRecord> SrcNames, DstNames;
Chris Lattner5b0e2492010-02-23 07:22:28 +00003403 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3404 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003405
3406 // Scan all of the named values in the destination pattern, rejecting them if
3407 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003408 for (const auto &Entry : DstNames) {
3409 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003410 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003411 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003412 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003413
Chris Lattnera7722b62010-02-23 06:55:24 +00003414 // Scan all of the named values in the source pattern, rejecting them if the
3415 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003416 for (const auto &Entry : SrcNames)
3417 if (DstNames[Entry.first].first == nullptr &&
3418 SrcNames[Entry.first].second == 1)
3419 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003420
Craig Topper18e6b572017-06-25 17:33:49 +00003421 PatternsToMatch.push_back(std::move(PTM));
Chris Lattner0c0baa92010-02-23 06:16:51 +00003422}
3423
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003424void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003425 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003426 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003427
3428 // First try to infer flags from the primary instruction pattern, if any.
3429 SmallVector<CodeGenInstruction*, 8> Revisit;
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003430 unsigned Errors = 0;
Chris Lattner70eb8972010-03-19 00:18:23 +00003431 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3432 CodeGenInstruction &InstInfo =
3433 const_cast<CodeGenInstruction &>(*Instructions[i]);
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003434
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003435 // Get the primary instruction pattern.
3436 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
3437 if (!Pattern) {
3438 if (InstInfo.hasUndefFlags())
3439 Revisit.push_back(&InstInfo);
3440 continue;
3441 }
3442 InstAnalyzer PatInfo(*this);
3443 PatInfo.Analyze(Pattern);
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003444 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003445 }
3446
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003447 // Second, look for single-instruction patterns defined outside the
3448 // instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003449 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003450 // We can only infer from single-instruction patterns, otherwise we won't
3451 // know which instruction should get the flags.
3452 SmallVector<Record*, 8> PatInstrs;
3453 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
3454 if (PatInstrs.size() != 1)
3455 continue;
3456
3457 // Get the single instruction.
3458 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3459
3460 // Only infer properties from the first pattern. We'll verify the others.
3461 if (InstInfo.InferredFrom)
3462 continue;
3463
3464 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003465 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003466 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3467 }
3468
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003469 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003470 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003471
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003472 // Revisit instructions with undefined flags and no pattern.
3473 if (Target.guessInstructionProperties()) {
Craig Topper306cb122015-11-22 20:46:24 +00003474 for (CodeGenInstruction *InstInfo : Revisit) {
3475 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003476 continue;
3477 // The mayLoad and mayStore flags default to false.
3478 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003479 if (InstInfo->hasSideEffects_Unset)
3480 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003481 }
3482 return;
3483 }
3484
3485 // Complain about any flags that are still undefined.
Craig Topper306cb122015-11-22 20:46:24 +00003486 for (CodeGenInstruction *InstInfo : Revisit) {
3487 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003488 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003489 if (InstInfo->hasSideEffects_Unset)
3490 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003491 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003492 if (InstInfo->mayStore_Unset)
3493 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003494 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003495 if (InstInfo->mayLoad_Unset)
3496 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003497 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003498 }
3499}
3500
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003501
3502/// Verify instruction flags against pattern node properties.
3503void CodeGenDAGPatterns::VerifyInstructionFlags() {
3504 unsigned Errors = 0;
3505 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3506 const PatternToMatch &PTM = *I;
3507 SmallVector<Record*, 8> Instrs;
3508 getInstructionsInTree(PTM.getDstPattern(), Instrs);
3509 if (Instrs.empty())
3510 continue;
3511
3512 // Count the number of instructions with each flag set.
3513 unsigned NumSideEffects = 0;
3514 unsigned NumStores = 0;
3515 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003516 for (const Record *Instr : Instrs) {
3517 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003518 NumSideEffects += InstInfo.hasSideEffects;
3519 NumStores += InstInfo.mayStore;
3520 NumLoads += InstInfo.mayLoad;
3521 }
3522
3523 // Analyze the source pattern.
3524 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003525 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003526
3527 // Collect error messages.
3528 SmallVector<std::string, 4> Msgs;
3529
3530 // Check for missing flags in the output.
3531 // Permit extra flags for now at least.
3532 if (PatInfo.hasSideEffects && !NumSideEffects)
3533 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3534
3535 // Don't verify store flags on instructions with side effects. At least for
3536 // intrinsics, side effects implies mayStore.
3537 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3538 Msgs.push_back("pattern may store, but mayStore isn't set");
3539
3540 // Similarly, mayStore implies mayLoad on intrinsics.
3541 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3542 Msgs.push_back("pattern may load, but mayLoad isn't set");
3543
3544 // Print error messages.
3545 if (Msgs.empty())
3546 continue;
3547 ++Errors;
3548
Craig Topper306cb122015-11-22 20:46:24 +00003549 for (const std::string &Msg : Msgs)
3550 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003551 (Instrs.size() == 1 ?
3552 "instruction" : "output instructions"));
3553 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003554 for (const Record *Instr : Instrs) {
3555 if (Instr != PTM.getSrcRecord())
3556 PrintError(Instr->getLoc(), "defined here");
3557 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003558 if (InstInfo.InferredFrom &&
3559 InstInfo.InferredFrom != InstInfo.TheDef &&
3560 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003561 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003562 }
3563 }
3564 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003565 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003566}
3567
Chris Lattnercabe0372010-03-15 06:00:16 +00003568/// Given a pattern result with an unresolved type, see if we can find one
3569/// instruction with an unresolved result type. Force this result type to an
3570/// arbitrary element if it's possible types to converge results.
3571static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3572 if (N->isLeaf())
3573 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003574
Chris Lattnercabe0372010-03-15 06:00:16 +00003575 // Analyze children.
3576 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3577 if (ForceArbitraryInstResultType(N->getChild(i), TP))
3578 return true;
3579
3580 if (!N->getOperator()->isSubClassOf("Instruction"))
3581 return false;
3582
3583 // If this type is already concrete or completely unknown we can't do
3584 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003585 TypeInfer &TI = TP.getInfer();
Chris Lattnerf1447252010-03-19 21:37:09 +00003586 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003587 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00003588 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003589
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003590 // Otherwise, force its type to an arbitrary choice.
3591 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00003592 return true;
3593 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003594
Chris Lattnerf1447252010-03-19 21:37:09 +00003595 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003596}
3597
Chris Lattnerab3242f2008-01-06 01:10:31 +00003598void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003599 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
3600
Craig Topper306cb122015-11-22 20:46:24 +00003601 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00003602 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00003603
3604 // If the pattern references the null_frag, there's nothing to do.
3605 if (hasNullFragReference(Tree))
3606 continue;
3607
Chris Lattner5c2182e2010-03-27 02:53:27 +00003608 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003609
3610 // Inline pattern fragments into it.
3611 Pattern->InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003612
David Greeneaf8ee2c2011-07-29 22:43:06 +00003613 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00003614 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003615
Chris Lattner8cab0212008-01-05 22:25:12 +00003616 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003617 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003618
Chris Lattner8cab0212008-01-05 22:25:12 +00003619 // Inline pattern fragments into it.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003620 Result.InlinePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003621
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003622 if (Result.getNumTrees() != 1)
3623 Result.error("Cannot handle instructions producing instructions "
3624 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003625
Chris Lattner8cab0212008-01-05 22:25:12 +00003626 bool IterateInference;
3627 bool InferredAllPatternTypes, InferredAllResultTypes;
3628 do {
3629 // Infer as many types as possible. If we cannot infer all of them, we
3630 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003631 InferredAllPatternTypes =
3632 Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003633
Chris Lattner8cab0212008-01-05 22:25:12 +00003634 // Infer as many types as possible. If we cannot infer all of them, we
3635 // can never do anything with this pattern: report it to the user.
Chris Lattnercabe0372010-03-15 06:00:16 +00003636 InferredAllResultTypes =
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003637 Result.InferAllTypes(&Pattern->getNamedNodesMap());
Chris Lattner8cab0212008-01-05 22:25:12 +00003638
Chris Lattnerfdc20712010-03-18 23:15:10 +00003639 IterateInference = false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003640
Chris Lattner8cab0212008-01-05 22:25:12 +00003641 // Apply the type of the result to the source pattern. This helps us
3642 // resolve cases where the input type is known to be a pointer type (which
3643 // is considered resolved), but the result knows it needs to be 32- or
3644 // 64-bits. Infer the other way for good measure.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003645 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(),
Chris Lattnerf1447252010-03-19 21:37:09 +00003646 Pattern->getTree(0)->getNumTypes());
3647 i != e; ++i) {
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003648 IterateInference = Pattern->getTree(0)->UpdateNodeType(
3649 i, Result.getTree(0)->getExtType(i), Result);
3650 IterateInference |= Result.getTree(0)->UpdateNodeType(
3651 i, Pattern->getTree(0)->getExtType(i), Result);
Chris Lattnerfdc20712010-03-18 23:15:10 +00003652 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003653
Chris Lattnercabe0372010-03-15 06:00:16 +00003654 // If our iteration has converged and the input pattern's types are fully
3655 // resolved but the result pattern is not fully resolved, we may have a
3656 // situation where we have two instructions in the result pattern and
3657 // the instructions require a common register class, but don't care about
3658 // what actual MVT is used. This is actually a bug in our modelling:
3659 // output patterns should have register classes, not MVTs.
3660 //
3661 // In any case, to handle this, we just go through and disambiguate some
3662 // arbitrary types to the result pattern's nodes.
3663 if (!IterateInference && InferredAllPatternTypes &&
3664 !InferredAllResultTypes)
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003665 IterateInference =
3666 ForceArbitraryInstResultType(Result.getTree(0), Result);
Chris Lattner8cab0212008-01-05 22:25:12 +00003667 } while (IterateInference);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003668
Chris Lattner8cab0212008-01-05 22:25:12 +00003669 // Verify that we inferred enough types that we can do something with the
3670 // pattern and result. If these fire the user has to add type casts.
3671 if (!InferredAllPatternTypes)
3672 Pattern->error("Could not infer all types in pattern!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003673 if (!InferredAllResultTypes) {
3674 Pattern->dump();
David Blaikie4ac0c0c2014-11-14 21:53:50 +00003675 Result.error("Could not infer all types in pattern result!");
Chris Lattnercabe0372010-03-15 06:00:16 +00003676 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003677
Chris Lattner8cab0212008-01-05 22:25:12 +00003678 // Validate that the input pattern is correct.
3679 std::map<std::string, TreePatternNode*> InstInputs;
3680 std::map<std::string, TreePatternNode*> InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003681 std::vector<Record*> InstImpResults;
3682 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
3683 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
3684 InstInputs, InstResults,
Chris Lattner5debc332010-04-20 06:30:25 +00003685 InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003686
3687 // Promote the xform function to be an explicit node if set.
David Blaikiecf195302014-11-17 22:55:41 +00003688 TreePatternNode *DstPattern = Result.getOnlyTree();
Chris Lattner8cab0212008-01-05 22:25:12 +00003689 std::vector<TreePatternNode*> ResultNodeOperands;
3690 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
3691 TreePatternNode *OpNode = DstPattern->getChild(ii);
3692 if (Record *Xform = OpNode->getTransformFn()) {
Craig Topper24064772014-04-15 07:20:03 +00003693 OpNode->setTransformFn(nullptr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003694 std::vector<TreePatternNode*> Children;
3695 Children.push_back(OpNode);
Chris Lattnerf1447252010-03-19 21:37:09 +00003696 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00003697 }
3698 ResultNodeOperands.push_back(OpNode);
3699 }
David Blaikiecf195302014-11-17 22:55:41 +00003700 DstPattern = Result.getOnlyTree();
3701 if (!DstPattern->isLeaf())
3702 DstPattern = new TreePatternNode(DstPattern->getOperator(),
3703 ResultNodeOperands,
3704 DstPattern->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003705
David Blaikiecf195302014-11-17 22:55:41 +00003706 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i)
3707 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i));
3708
3709 TreePattern Temp(Result.getRecord(), DstPattern, false, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00003710 Temp.InferAllTypes();
3711
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003712 // A pattern may end up with an "impossible" type, i.e. a situation
3713 // where all types have been eliminated for some node in this pattern.
3714 // This could occur for intrinsics that only make sense for a specific
3715 // value type, and use a specific register class. If, for some mode,
3716 // that register class does not accept that type, the type inference
3717 // will lead to a contradiction, which is not an error however, but
3718 // a sign that this pattern will simply never match.
3719 if (Pattern->getTree(0)->hasPossibleType() &&
3720 Temp.getOnlyTree()->hasPossibleType()) {
3721 ListInit *Preds = CurPattern->getValueAsListInit("Predicates");
3722 int Complexity = CurPattern->getValueAsInt("AddedComplexity");
3723 AddPatternToMatch(
3724 Pattern,
3725 PatternToMatch(
3726 CurPattern, makePredList(Preds), Pattern->getTree(0),
3727 Temp.getOnlyTree(), std::move(InstImpResults), Complexity,
3728 CurPattern->getID()));
3729 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003730 }
3731}
3732
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003733static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
3734 for (const TypeSetByHwMode &VTS : N->getExtTypes())
3735 for (const auto &I : VTS)
3736 Modes.insert(I.first);
3737
3738 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3739 collectModes(Modes, N->getChild(i));
3740}
3741
3742void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
3743 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3744 std::map<unsigned,std::vector<Predicate>> ModeChecks;
3745 std::vector<PatternToMatch> Copy = PatternsToMatch;
3746 PatternsToMatch.clear();
3747
3748 auto AppendPattern = [this,&ModeChecks](PatternToMatch &P, unsigned Mode) {
3749 TreePatternNode *NewSrc = P.SrcPattern->clone();
3750 TreePatternNode *NewDst = P.DstPattern->clone();
3751 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
3752 delete NewSrc;
3753 delete NewDst;
3754 return;
3755 }
3756
3757 std::vector<Predicate> Preds = P.Predicates;
3758 const std::vector<Predicate> &MC = ModeChecks[Mode];
3759 Preds.insert(Preds.end(), MC.begin(), MC.end());
3760 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, NewSrc, NewDst,
3761 P.getDstRegs(), P.getAddedComplexity(),
3762 Record::getNewUID(), Mode);
3763 };
3764
3765 for (PatternToMatch &P : Copy) {
3766 TreePatternNode *SrcP = nullptr, *DstP = nullptr;
3767 if (P.SrcPattern->hasProperTypeByHwMode())
3768 SrcP = P.SrcPattern;
3769 if (P.DstPattern->hasProperTypeByHwMode())
3770 DstP = P.DstPattern;
3771 if (!SrcP && !DstP) {
3772 PatternsToMatch.push_back(P);
3773 continue;
3774 }
3775
3776 std::set<unsigned> Modes;
3777 if (SrcP)
3778 collectModes(Modes, SrcP);
3779 if (DstP)
3780 collectModes(Modes, DstP);
3781
3782 // The predicate for the default mode needs to be constructed for each
3783 // pattern separately.
3784 // Since not all modes must be present in each pattern, if a mode m is
3785 // absent, then there is no point in constructing a check for m. If such
3786 // a check was created, it would be equivalent to checking the default
3787 // mode, except not all modes' predicates would be a part of the checking
3788 // code. The subsequently generated check for the default mode would then
3789 // have the exact same patterns, but a different predicate code. To avoid
3790 // duplicated patterns with different predicate checks, construct the
3791 // default check as a negation of all predicates that are actually present
3792 // in the source/destination patterns.
3793 std::vector<Predicate> DefaultPred;
3794
3795 for (unsigned M : Modes) {
3796 if (M == DefaultMode)
3797 continue;
3798 if (ModeChecks.find(M) != ModeChecks.end())
3799 continue;
3800
3801 // Fill the map entry for this mode.
3802 const HwMode &HM = CGH.getMode(M);
3803 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
3804
3805 // Add negations of the HM's predicates to the default predicate.
3806 DefaultPred.emplace_back(Predicate(HM.Features, false));
3807 }
3808
3809 for (unsigned M : Modes) {
3810 if (M == DefaultMode)
3811 continue;
3812 AppendPattern(P, M);
3813 }
3814
3815 bool HasDefault = Modes.count(DefaultMode);
3816 if (HasDefault)
3817 AppendPattern(P, DefaultMode);
3818 }
3819}
3820
3821/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turner249dc142017-09-20 18:01:40 +00003822typedef StringMap<int> DepVarMap;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003823
3824static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
3825 if (N->isLeaf()) {
Zachary Turner249dc142017-09-20 18:01:40 +00003826 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003827 DepMap[N->getName()]++;
3828 } else {
3829 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
3830 FindDepVarsOf(N->getChild(i), DepMap);
3831 }
3832}
3833
3834/// Find dependent variables within child patterns
3835static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
3836 DepVarMap depcounts;
3837 FindDepVarsOf(N, depcounts);
Zachary Turner249dc142017-09-20 18:01:40 +00003838 for (const auto &Pair : depcounts) {
3839 if (Pair.getValue() > 1)
3840 DepVars.insert(Pair.getKey());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003841 }
3842}
3843
3844#ifndef NDEBUG
3845/// Dump the dependent variable set:
3846static void DumpDepVars(MultipleUseVarSet &DepVars) {
3847 if (DepVars.empty()) {
3848 DEBUG(errs() << "<empty set>");
3849 } else {
3850 DEBUG(errs() << "[ ");
Zachary Turner249dc142017-09-20 18:01:40 +00003851 for (const auto &DepVar : DepVars) {
3852 DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003853 }
3854 DEBUG(errs() << "]");
3855 }
3856}
3857#endif
3858
3859
Chris Lattner8cab0212008-01-05 22:25:12 +00003860/// CombineChildVariants - Given a bunch of permutations of each child of the
3861/// 'operator' node, put them together in all possible ways.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003862static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003863 const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
3864 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003865 CodeGenDAGPatterns &CDP,
3866 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003867 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00003868 for (const auto &Variants : ChildVariants)
3869 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003870 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003871
Chris Lattner8cab0212008-01-05 22:25:12 +00003872 // The end result is an all-pairs construction of the resultant pattern.
3873 std::vector<unsigned> Idxs;
3874 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00003875 bool NotDone;
3876 do {
3877#ifndef NDEBUG
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003878 DEBUG(if (!Idxs.empty()) {
3879 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Craig Topper306cb122015-11-22 20:46:24 +00003880 for (unsigned Idx : Idxs) {
3881 errs() << Idx << " ";
Chris Lattner7f28b8e2010-02-27 06:51:44 +00003882 }
3883 errs() << "]\n";
3884 });
Scott Michel94420742008-03-05 17:49:05 +00003885#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00003886 // Create the variant and add it to the output list.
3887 std::vector<TreePatternNode*> NewChildren;
3888 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
3889 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
David Blaikiefda69dd2015-11-22 20:11:21 +00003890 auto R = llvm::make_unique<TreePatternNode>(
3891 Orig->getOperator(), NewChildren, Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003892
Chris Lattner8cab0212008-01-05 22:25:12 +00003893 // Copy over properties.
3894 R->setName(Orig->getName());
Dan Gohman6e979022008-10-15 06:17:21 +00003895 R->setPredicateFns(Orig->getPredicateFns());
Chris Lattner8cab0212008-01-05 22:25:12 +00003896 R->setTransformFn(Orig->getTransformFn());
Chris Lattnerf1447252010-03-19 21:37:09 +00003897 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
3898 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00003899
Scott Michel94420742008-03-05 17:49:05 +00003900 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00003901 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00003902 // Scan to see if this pattern has already been emitted. We can get
3903 // duplication due to things like commuting:
3904 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
3905 // which are the same pattern. Ignore the dups.
3906 if (R->canPatternMatch(ErrString, CDP) &&
David Majnemer0a16c222016-08-11 21:15:00 +00003907 none_of(OutVariants, [&](TreePatternNode *Variant) {
3908 return R->isIsomorphicTo(Variant, DepVars);
3909 }))
David Blaikiefda69dd2015-11-22 20:11:21 +00003910 OutVariants.push_back(R.release());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003911
Scott Michel94420742008-03-05 17:49:05 +00003912 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003913 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00003914 // [0, 0], [0, 1], [1, 0], [1, 1].
3915 int IdxsIdx;
3916 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
3917 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
3918 Idxs[IdxsIdx] = 0;
3919 else
Chris Lattner8cab0212008-01-05 22:25:12 +00003920 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00003921 }
Scott Michel94420742008-03-05 17:49:05 +00003922 NotDone = (IdxsIdx >= 0);
3923 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00003924}
3925
3926/// CombineChildVariants - A helper function for binary operators.
3927///
Jim Grosbach65586fe2010-12-21 16:16:00 +00003928static void CombineChildVariants(TreePatternNode *Orig,
Chris Lattner8cab0212008-01-05 22:25:12 +00003929 const std::vector<TreePatternNode*> &LHS,
3930 const std::vector<TreePatternNode*> &RHS,
3931 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003932 CodeGenDAGPatterns &CDP,
3933 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003934 std::vector<std::vector<TreePatternNode*> > ChildVariants;
3935 ChildVariants.push_back(LHS);
3936 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00003937 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003938}
Chris Lattner8cab0212008-01-05 22:25:12 +00003939
3940
3941static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
3942 std::vector<TreePatternNode *> &Children) {
3943 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
3944 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003945
Chris Lattner8cab0212008-01-05 22:25:12 +00003946 // Only permit raw nodes.
Dan Gohman6e979022008-10-15 06:17:21 +00003947 if (!N->getName().empty() || !N->getPredicateFns().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00003948 N->getTransformFn()) {
3949 Children.push_back(N);
3950 return;
3951 }
3952
3953 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
3954 Children.push_back(N->getChild(0));
3955 else
3956 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
3957
3958 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
3959 Children.push_back(N->getChild(1));
3960 else
3961 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
3962}
3963
3964/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
3965/// the (potentially recursive) pattern by using algebraic laws.
3966///
3967static void GenerateVariantsOf(TreePatternNode *N,
3968 std::vector<TreePatternNode*> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00003969 CodeGenDAGPatterns &CDP,
3970 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00003971 // We cannot permute leaves or ComplexPattern uses.
3972 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003973 OutVariants.push_back(N);
3974 return;
3975 }
3976
3977 // Look up interesting info about the node.
3978 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
3979
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003980 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00003981 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003982 // Re-associate by pulling together all of the linked operators
Chris Lattner8cab0212008-01-05 22:25:12 +00003983 std::vector<TreePatternNode*> MaximalChildren;
3984 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
3985
3986 // Only handle child sizes of 3. Otherwise we'll end up trying too many
3987 // permutations.
3988 if (MaximalChildren.size() == 3) {
3989 // Find the variants of all of our maximal children.
3990 std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00003991 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
3992 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
3993 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003994
Chris Lattner8cab0212008-01-05 22:25:12 +00003995 // There are only two ways we can permute the tree:
3996 // (A op B) op C and A op (B op C)
3997 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00003998
Chris Lattner8cab0212008-01-05 22:25:12 +00003999 // Generate legal pair permutations of A/B/C.
4000 std::vector<TreePatternNode*> ABVariants;
4001 std::vector<TreePatternNode*> BAVariants;
4002 std::vector<TreePatternNode*> ACVariants;
4003 std::vector<TreePatternNode*> CAVariants;
4004 std::vector<TreePatternNode*> BCVariants;
4005 std::vector<TreePatternNode*> CBVariants;
Scott Michel94420742008-03-05 17:49:05 +00004006 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4007 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4008 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4009 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4010 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4011 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004012
4013 // Combine those into the result: (x op x) op x
Scott Michel94420742008-03-05 17:49:05 +00004014 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4015 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4016 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4017 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4018 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4019 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004020
4021 // Combine those into the result: x op (x op x)
Scott Michel94420742008-03-05 17:49:05 +00004022 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4023 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4024 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4025 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4026 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4027 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004028 return;
4029 }
4030 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004031
Chris Lattner8cab0212008-01-05 22:25:12 +00004032 // Compute permutations of all children.
4033 std::vector<std::vector<TreePatternNode*> > ChildVariants;
4034 ChildVariants.resize(N->getNumChildren());
4035 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Scott Michel94420742008-03-05 17:49:05 +00004036 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004037
4038 // Build all permutations based on how the children were formed.
Scott Michel94420742008-03-05 17:49:05 +00004039 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004040
4041 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004042 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4043 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004044 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004045 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004046 // Don't count children which are actually register references.
4047 unsigned NC = 0;
4048 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4049 TreePatternNode *Child = N->getChild(i);
4050 if (Child->isLeaf())
Sean Silvafb509ed2012-10-10 20:24:43 +00004051 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004052 Record *RR = DI->getDef();
4053 if (RR->isSubClassOf("Register"))
4054 continue;
4055 }
4056 NC++;
4057 }
4058 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004059 if (isCommIntrinsic) {
4060 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4061 // operands are the commutative operands, and there might be more operands
4062 // after those.
4063 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004064 "Commutative intrinsic should have at least 3 children!");
Evan Cheng49bad4c2008-06-16 20:29:38 +00004065 std::vector<std::vector<TreePatternNode*> > Variants;
4066 Variants.push_back(ChildVariants[0]); // Intrinsic id.
4067 Variants.push_back(ChildVariants[2]);
4068 Variants.push_back(ChildVariants[1]);
4069 for (unsigned i = 3; i != NC; ++i)
4070 Variants.push_back(ChildVariants[i]);
4071 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004072 } else if (NC == N->getNumChildren()) {
4073 std::vector<std::vector<TreePatternNode*> > Variants;
4074 Variants.push_back(ChildVariants[1]);
4075 Variants.push_back(ChildVariants[0]);
4076 for (unsigned i = 2; i != NC; ++i)
4077 Variants.push_back(ChildVariants[i]);
4078 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
4079 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004080 }
4081}
4082
4083
4084// GenerateVariants - Generate variants. For example, commutative patterns can
4085// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004086void CodeGenDAGPatterns::GenerateVariants() {
Chris Lattner34822f62009-08-23 04:44:11 +00004087 DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004088
Chris Lattner8cab0212008-01-05 22:25:12 +00004089 // Loop over all of the patterns we've collected, checking to see if we can
4090 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004091 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004092 // the .td file having to contain tons of variants of instructions.
4093 //
4094 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4095 // intentionally do not reconsider these. Any variants of added patterns have
4096 // already been added.
4097 //
Craig Topper2f70a7e2015-11-22 22:43:40 +00004098 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
Scott Michel94420742008-03-05 17:49:05 +00004099 MultipleUseVarSet DepVars;
Chris Lattner8cab0212008-01-05 22:25:12 +00004100 std::vector<TreePatternNode*> Variants;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004101 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Chris Lattner34822f62009-08-23 04:44:11 +00004102 DEBUG(errs() << "Dependent/multiply used variables: ");
Scott Michel94420742008-03-05 17:49:05 +00004103 DEBUG(DumpDepVars(DepVars));
Chris Lattner34822f62009-08-23 04:44:11 +00004104 DEBUG(errs() << "\n");
Craig Topper2f70a7e2015-11-22 22:43:40 +00004105 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
Jim Grosbachb75d0ca2010-10-08 18:13:57 +00004106 DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004107
4108 assert(!Variants.empty() && "Must create at least original variant!");
Krzysztof Parzyszekf7237762017-06-16 13:44:34 +00004109 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004110 continue;
4111
Chris Lattner34822f62009-08-23 04:44:11 +00004112 DEBUG(errs() << "FOUND VARIANTS OF: ";
Craig Topper2f70a7e2015-11-22 22:43:40 +00004113 PatternsToMatch[i].getSrcPattern()->dump();
Chris Lattner34822f62009-08-23 04:44:11 +00004114 errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004115
4116 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4117 TreePatternNode *Variant = Variants[v];
4118
Chris Lattner34822f62009-08-23 04:44:11 +00004119 DEBUG(errs() << " VAR#" << v << ": ";
4120 Variant->dump();
4121 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004122
Chris Lattner8cab0212008-01-05 22:25:12 +00004123 // Scan to see if an instruction or explicit pattern already matches this.
4124 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004125 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004126 // Skip if the top level predicates do not match.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004127 if (PatternsToMatch[i].getPredicates() !=
4128 PatternsToMatch[p].getPredicates())
Evan Cheng34c8c742009-06-26 05:59:16 +00004129 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004130 // Check to see if this variant already exists.
Craig Topper2f70a7e2015-11-22 22:43:40 +00004131 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4132 DepVars)) {
Chris Lattner34822f62009-08-23 04:44:11 +00004133 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004134 AlreadyExists = true;
4135 break;
4136 }
4137 }
4138 // If we already have it, ignore the variant.
4139 if (AlreadyExists) continue;
4140
4141 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004142 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004143 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4144 Variant, PatternsToMatch[i].getDstPattern(),
4145 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004146 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Chris Lattner8cab0212008-01-05 22:25:12 +00004147 }
4148
Chris Lattner34822f62009-08-23 04:44:11 +00004149 DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004150 }
4151}