blob: 6476e9436c74491b0e234e536e53e334147c6229 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner8cab0212008-01-05 22:25:12 +00006//
7//===----------------------------------------------------------------------===//
8//
Chris Lattnerab3242f2008-01-06 01:10:31 +00009// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner8cab0212008-01-05 22:25:12 +000010// represent the patterns present in a .td file for instructions.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner78ac0742008-01-05 23:37:52 +000014#include "CodeGenDAGPatterns.h"
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +000015#include "llvm/ADT/BitVector.h"
Zachary Turner249dc142017-09-20 18:01:40 +000016#include "llvm/ADT/DenseSet.h"
Craig Topperbd199f82018-12-05 00:47:59 +000017#include "llvm/ADT/MapVector.h"
Chris Lattnercabe0372010-03-15 06:00:16 +000018#include "llvm/ADT/STLExtras.h"
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000019#include "llvm/ADT/SmallSet.h"
Craig Topper3522ab32015-11-28 08:23:02 +000020#include "llvm/ADT/SmallString.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000021#include "llvm/ADT/StringExtras.h"
Craig Topperddfdd942017-09-21 04:55:03 +000022#include "llvm/ADT/StringMap.h"
Jim Grosbach3ae48a62012-04-18 17:46:41 +000023#include "llvm/ADT/Twine.h"
Chris Lattner8cab0212008-01-05 22:25:12 +000024#include "llvm/Support/Debug.h"
David Blaikieb48ed1a2012-01-17 04:43:56 +000025#include "llvm/Support/ErrorHandling.h"
Chandler Carruth91d19d82012-12-04 10:37:14 +000026#include "llvm/TableGen/Error.h"
27#include "llvm/TableGen/Record.h"
Chuck Rose IIIfe2714f2008-01-15 21:43:17 +000028#include <algorithm>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000029#include <cstdio>
Craig Topperbd199f82018-12-05 00:47:59 +000030#include <iterator>
Benjamin Kramerb0640db2012-03-23 11:35:30 +000031#include <set>
Chris Lattner8cab0212008-01-05 22:25:12 +000032using namespace llvm;
33
Chandler Carruthe96dd892014-04-21 22:55:11 +000034#define DEBUG_TYPE "dag-patterns"
35
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000036static inline bool isIntegerOrPtr(MVT VT) {
37 return VT.isInteger() || VT == MVT::iPTR;
Duncan Sands13237ac2008-06-06 12:08:01 +000038}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000039static inline bool isFloatingPoint(MVT VT) {
40 return VT.isFloatingPoint();
Duncan Sands13237ac2008-06-06 12:08:01 +000041}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000042static inline bool isVector(MVT VT) {
43 return VT.isVector();
Duncan Sands13237ac2008-06-06 12:08:01 +000044}
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000045static inline bool isScalar(MVT VT) {
46 return !VT.isVector();
Chris Lattner6d765eb2010-03-19 17:41:26 +000047}
Duncan Sands13237ac2008-06-06 12:08:01 +000048
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000049template <typename Predicate>
50static bool berase_if(MachineValueTypeSet &S, Predicate P) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000051 bool Erased = false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +000052 // It is ok to iterate over MachineValueTypeSet and remove elements from it
53 // at the same time.
54 for (MVT T : S) {
55 if (!P(T))
56 continue;
57 Erased = true;
58 S.erase(T);
Chris Lattnercabe0372010-03-15 06:00:16 +000059 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000060 return Erased;
Chris Lattner8cab0212008-01-05 22:25:12 +000061}
62
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000063// --- TypeSetByHwMode
Chris Lattnercabe0372010-03-15 06:00:16 +000064
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000065// This is a parameterized type-set class. For each mode there is a list
66// of types that are currently possible for a given tree node. Type
67// inference will apply to each mode separately.
Jim Grosbach65586fe2010-12-21 16:16:00 +000068
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000069TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
70 for (const ValueTypeByHwMode &VVT : VTList)
71 insert(VVT);
Chris Lattner8cab0212008-01-05 22:25:12 +000072}
73
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000074bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
75 for (const auto &I : *this) {
76 if (I.second.size() > 1)
77 return false;
78 if (!AllowEmpty && I.second.empty())
79 return false;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000080 }
Chris Lattnerbe6b17f2010-03-19 04:54:36 +000081 return true;
82}
Chris Lattnercabe0372010-03-15 06:00:16 +000083
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000084ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
85 assert(isValueTypeByHwMode(true) &&
86 "The type set has multiple types for at least one HW mode");
87 ValueTypeByHwMode VVT;
88 for (const auto &I : *this) {
89 MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
90 VVT.getOrCreateTypeForMode(I.first, T);
Chris Lattnercabe0372010-03-15 06:00:16 +000091 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000092 return VVT;
Bob Wilson2cd5da82009-08-11 01:14:02 +000093}
Chris Lattnercabe0372010-03-15 06:00:16 +000094
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +000095bool TypeSetByHwMode::isPossible() const {
96 for (const auto &I : *this)
97 if (!I.second.empty())
98 return true;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +000099 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +0000100}
101
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000102bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
103 bool Changed = false;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000104 bool ContainsDefault = false;
105 MVT DT = MVT::Other;
106
Zachary Turner249dc142017-09-20 18:01:40 +0000107 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000108 for (const auto &P : VVT) {
109 unsigned M = P.first;
110 Modes.insert(M);
111 // Make sure there exists a set for each specific mode from VVT.
112 Changed |= getOrCreate(M).insert(P.second).second;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000113 // Cache VVT's default mode.
114 if (DefaultMode == M) {
115 ContainsDefault = true;
116 DT = P.second;
117 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000118 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000119
120 // If VVT has a default mode, add the corresponding type to all
121 // modes in "this" that do not exist in VVT.
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000122 if (ContainsDefault)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000123 for (auto &I : *this)
124 if (!Modes.count(I.first))
125 Changed |= I.second.insert(DT).second;
Simon Pilgrim16a2f542018-08-17 13:03:17 +0000126
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000127 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000128}
129
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000130// Constrain the type set to be the intersection with VTS.
131bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
132 bool Changed = false;
133 if (hasDefault()) {
134 for (const auto &I : VTS) {
135 unsigned M = I.first;
136 if (M == DefaultMode || hasMode(M))
137 continue;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000138 Map.insert({M, Map.at(DefaultMode)});
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000139 Changed = true;
140 }
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000141 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000142
143 for (auto &I : *this) {
144 unsigned M = I.first;
145 SetType &S = I.second;
146 if (VTS.hasMode(M) || VTS.hasDefault()) {
147 Changed |= intersect(I.second, VTS.get(M));
148 } else if (!S.empty()) {
149 S.clear();
150 Changed = true;
151 }
152 }
153 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000154}
155
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000156template <typename Predicate>
157bool TypeSetByHwMode::constrain(Predicate P) {
158 bool Changed = false;
159 for (auto &I : *this)
Benjamin Kramere57308e2017-09-17 11:19:53 +0000160 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000161 return Changed;
Chris Lattnercabe0372010-03-15 06:00:16 +0000162}
163
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000164template <typename Predicate>
165bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
166 assert(empty());
167 for (const auto &I : VTS) {
168 SetType &S = getOrCreate(I.first);
169 for (auto J : I.second)
170 if (P(J))
171 S.insert(J);
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000172 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000173 return !empty();
Chris Lattnercabe0372010-03-15 06:00:16 +0000174}
175
Zachary Turner249dc142017-09-20 18:01:40 +0000176void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
177 SmallVector<unsigned, 4> Modes;
178 Modes.reserve(Map.size());
Chris Lattnercabe0372010-03-15 06:00:16 +0000179
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000180 for (const auto &I : *this)
181 Modes.push_back(I.first);
Zachary Turner249dc142017-09-20 18:01:40 +0000182 if (Modes.empty()) {
183 OS << "{}";
184 return;
185 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000186 array_pod_sort(Modes.begin(), Modes.end());
Chris Lattnerbe6b17f2010-03-19 04:54:36 +0000187
Zachary Turner249dc142017-09-20 18:01:40 +0000188 OS << '{';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000189 for (unsigned M : Modes) {
Zachary Turner249dc142017-09-20 18:01:40 +0000190 OS << ' ' << getModeName(M) << ':';
191 writeToStream(get(M), OS);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000192 }
Zachary Turner249dc142017-09-20 18:01:40 +0000193 OS << " }";
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000194}
195
Zachary Turner249dc142017-09-20 18:01:40 +0000196void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
197 SmallVector<MVT, 4> Types(S.begin(), S.end());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000198 array_pod_sort(Types.begin(), Types.end());
199
Zachary Turner249dc142017-09-20 18:01:40 +0000200 OS << '[';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000201 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
Zachary Turner249dc142017-09-20 18:01:40 +0000202 OS << ValueTypeByHwMode::getMVTName(Types[i]);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000203 if (i != e-1)
Zachary Turner249dc142017-09-20 18:01:40 +0000204 OS << ' ';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000205 }
Zachary Turner249dc142017-09-20 18:01:40 +0000206 OS << ']';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000207}
208
209bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
Simon Pilgrim0e181332018-08-16 16:16:28 +0000210 // The isSimple call is much quicker than hasDefault - check this first.
211 bool IsSimple = isSimple();
212 bool VTSIsSimple = VTS.isSimple();
213 if (IsSimple && VTSIsSimple)
214 return *begin() == *VTS.begin();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +0000215
Simon Pilgrim0e181332018-08-16 16:16:28 +0000216 // Speedup: We have a default if the set is simple.
217 bool HaveDefault = IsSimple || hasDefault();
218 bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
219 if (HaveDefault != VTSHaveDefault)
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000220 return false;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000221
Zachary Turner249dc142017-09-20 18:01:40 +0000222 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000223 for (auto &I : *this)
224 Modes.insert(I.first);
225 for (const auto &I : VTS)
226 Modes.insert(I.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +0000227
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000228 if (HaveDefault) {
229 // Both sets have default mode.
230 for (unsigned M : Modes) {
231 if (get(M) != VTS.get(M))
David Majnemerc7004902016-08-12 04:32:37 +0000232 return false;
Craig Topper5712d462015-11-24 08:20:47 +0000233 }
Scott Michel94420742008-03-05 17:49:05 +0000234 } else {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000235 // Neither set has default mode.
236 for (unsigned M : Modes) {
237 // If there is no default mode, an empty set is equivalent to not having
238 // the corresponding mode.
239 bool NoModeThis = !hasMode(M) || get(M).empty();
240 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
241 if (NoModeThis != NoModeVTS)
242 return false;
243 if (!NoModeThis)
244 if (get(M) != VTS.get(M))
245 return false;
246 }
Scott Michel94420742008-03-05 17:49:05 +0000247 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000248
249 return true;
Scott Michel94420742008-03-05 17:49:05 +0000250}
251
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000252namespace llvm {
253 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
254 T.writeToStream(OS);
255 return OS;
256 }
257}
258
Krzysztof Parzyszek426bf362017-09-12 15:31:26 +0000259LLVM_DUMP_METHOD
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000260void TypeSetByHwMode::dump() const {
Krzysztof Parzyszek7725e492017-09-22 18:29:37 +0000261 dbgs() << *this << '\n';
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000262}
263
264bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
265 bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
266 auto Int = [&In](MVT T) -> bool { return !In.count(T); };
267
268 if (OutP == InP)
269 return berase_if(Out, Int);
270
271 // Compute the intersection of scalars separately to account for only
272 // one set containing iPTR.
273 // The itersection of iPTR with a set of integer scalar types that does not
274 // include iPTR will result in the most specific scalar type:
275 // - iPTR is more specific than any set with two elements or more
276 // - iPTR is less specific than any single integer scalar type.
277 // For example
278 // { iPTR } * { i32 } -> { i32 }
279 // { iPTR } * { i32 i64 } -> { iPTR }
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000280 // and
281 // { iPTR i32 } * { i32 } -> { i32 }
282 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
283 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000284
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000285 // Compute the difference between the two sets in such a way that the
286 // iPTR is in the set that is being subtracted. This is to see if there
287 // are any extra scalars in the set without iPTR that are not in the
288 // set containing iPTR. Then the iPTR could be considered a "wildcard"
289 // matching these scalars. If there is only one such scalar, it would
290 // replace the iPTR, if there are more, the iPTR would be retained.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000291 SetType Diff;
292 if (InP) {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000293 Diff = Out;
294 berase_if(Diff, [&In](MVT T) { return In.count(T); });
295 // Pre-remove these elements and rely only on InP/OutP to determine
296 // whether a change has been made.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000297 berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
Scott Michel94420742008-03-05 17:49:05 +0000298 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000299 Diff = In;
300 berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000301 Out.erase(MVT::iPTR);
302 }
303
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000304 // The actual intersection.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000305 bool Changed = berase_if(Out, Int);
306 unsigned NumD = Diff.size();
307 if (NumD == 0)
308 return Changed;
309
310 if (NumD == 1) {
311 Out.insert(*Diff.begin());
312 // This is a change only if Out was the one with iPTR (which is now
313 // being replaced).
314 Changed |= OutP;
315 } else {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000316 // Multiple elements from Out are now replaced with iPTR.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000317 Out.insert(MVT::iPTR);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000318 Changed |= !OutP;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000319 }
320 return Changed;
321}
322
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000323bool TypeSetByHwMode::validate() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000324#ifndef NDEBUG
325 if (empty())
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000326 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000327 bool AllEmpty = true;
328 for (const auto &I : *this)
329 AllEmpty &= I.second.empty();
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000330 return !AllEmpty;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000331#endif
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000332 return true;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000333}
334
335// --- TypeInfer
336
337bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
338 const TypeSetByHwMode &In) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000339 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000340 In.validate();
341 if (In.empty() || Out == In || TP.hasError())
342 return false;
343 if (Out.empty()) {
344 Out = In;
345 return true;
346 }
347
348 bool Changed = Out.constrain(In);
349 if (Changed && Out.empty())
350 TP.error("Type contradiction");
351
352 return Changed;
353}
354
355bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000356 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000357 if (TP.hasError())
358 return false;
359 assert(!Out.empty() && "cannot pick from an empty set");
360
361 bool Changed = false;
362 for (auto &I : Out) {
363 TypeSetByHwMode::SetType &S = I.second;
364 if (S.size() <= 1)
365 continue;
366 MVT T = *S.begin(); // Pick the first element.
367 S.clear();
368 S.insert(T);
369 Changed = true;
370 }
371 return Changed;
372}
373
374bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000375 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000376 if (TP.hasError())
377 return false;
378 if (!Out.empty())
379 return Out.constrain(isIntegerOrPtr);
380
381 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
382}
383
384bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000385 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000386 if (TP.hasError())
387 return false;
388 if (!Out.empty())
389 return Out.constrain(isFloatingPoint);
390
391 return Out.assign_if(getLegalTypes(), isFloatingPoint);
392}
393
394bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000395 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000396 if (TP.hasError())
397 return false;
398 if (!Out.empty())
399 return Out.constrain(isScalar);
400
401 return Out.assign_if(getLegalTypes(), isScalar);
402}
403
404bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000405 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000406 if (TP.hasError())
407 return false;
408 if (!Out.empty())
409 return Out.constrain(isVector);
410
411 return Out.assign_if(getLegalTypes(), isVector);
412}
413
414bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000415 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000416 if (TP.hasError() || !Out.empty())
417 return false;
418
419 Out = getLegalTypes();
420 return true;
421}
422
423template <typename Iter, typename Pred, typename Less>
424static Iter min_if(Iter B, Iter E, Pred P, Less L) {
425 if (B == E)
426 return E;
427 Iter Min = E;
428 for (Iter I = B; I != E; ++I) {
429 if (!P(*I))
430 continue;
431 if (Min == E || L(*I, *Min))
432 Min = I;
433 }
434 return Min;
435}
436
437template <typename Iter, typename Pred, typename Less>
438static Iter max_if(Iter B, Iter E, Pred P, Less L) {
439 if (B == E)
440 return E;
441 Iter Max = E;
442 for (Iter I = B; I != E; ++I) {
443 if (!P(*I))
444 continue;
445 if (Max == E || L(*Max, *I))
446 Max = I;
447 }
448 return Max;
449}
450
451/// Make sure that for each type in Small, there exists a larger type in Big.
452bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
453 TypeSetByHwMode &Big) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000454 ValidateOnExit _1(Small, *this), _2(Big, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000455 if (TP.hasError())
456 return false;
457 bool Changed = false;
458
459 if (Small.empty())
460 Changed |= EnforceAny(Small);
461 if (Big.empty())
462 Changed |= EnforceAny(Big);
463
464 assert(Small.hasDefault() && Big.hasDefault());
465
466 std::vector<unsigned> Modes = union_modes(Small, Big);
467
468 // 1. Only allow integer or floating point types and make sure that
469 // both sides are both integer or both floating point.
470 // 2. Make sure that either both sides have vector types, or neither
471 // of them does.
472 for (unsigned M : Modes) {
473 TypeSetByHwMode::SetType &S = Small.get(M);
474 TypeSetByHwMode::SetType &B = Big.get(M);
475
476 if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000477 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000478 Changed |= berase_if(S, NotInt) |
479 berase_if(B, NotInt);
480 } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
Benjamin Kramere57308e2017-09-17 11:19:53 +0000481 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000482 Changed |= berase_if(S, NotFP) |
483 berase_if(B, NotFP);
484 } else if (S.empty() || B.empty()) {
485 Changed = !S.empty() || !B.empty();
486 S.clear();
487 B.clear();
488 } else {
489 TP.error("Incompatible types");
490 return Changed;
Scott Michel94420742008-03-05 17:49:05 +0000491 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000492
493 if (none_of(S, isVector) || none_of(B, isVector)) {
494 Changed |= berase_if(S, isVector) |
495 berase_if(B, isVector);
496 }
497 }
498
499 auto LT = [](MVT A, MVT B) -> bool {
500 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
501 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
502 A.getSizeInBits() < B.getSizeInBits());
503 };
504 auto LE = [](MVT A, MVT B) -> bool {
505 // This function is used when removing elements: when a vector is compared
506 // to a non-vector, it should return false (to avoid removal).
507 if (A.isVector() != B.isVector())
508 return false;
509
510 // Note on the < comparison below:
511 // X86 has patterns like
512 // (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))),
513 // where the truncated vector is given a type v16i8, while the source
514 // vector has type v4i32. They both have the same size in bits.
515 // The minimal type in the result is obviously v16i8, and when we remove
516 // all types from the source that are smaller-or-equal than v8i16, the
517 // only source type would also be removed (since it's equal in size).
518 return A.getScalarSizeInBits() <= B.getScalarSizeInBits() ||
519 A.getSizeInBits() < B.getSizeInBits();
520 };
521
522 for (unsigned M : Modes) {
523 TypeSetByHwMode::SetType &S = Small.get(M);
524 TypeSetByHwMode::SetType &B = Big.get(M);
525 // MinS = min scalar in Small, remove all scalars from Big that are
526 // smaller-or-equal than MinS.
527 auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000528 if (MinS != S.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000529 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000530
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000531 // MaxS = max scalar in Big, remove all scalars from Small that are
532 // larger than MaxS.
533 auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000534 if (MaxS != B.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000535 Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000536
537 // MinV = min vector in Small, remove all vectors from Big that are
538 // smaller-or-equal than MinV.
539 auto MinV = min_if(S.begin(), S.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000540 if (MinV != S.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000541 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000542
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000543 // MaxV = max vector in Big, remove all vectors from Small that are
544 // larger than MaxV.
545 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
Krzysztof Parzyszek4b3876f2017-10-15 15:39:56 +0000546 if (MaxV != B.end())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000547 Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000548 }
549
550 return Changed;
551}
552
553/// 1. Ensure that for each type T in Vec, T is a vector type, and that
554/// for each type U in Elem, U is a scalar type.
555/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
556/// type T in Vec, such that U is the element type of T.
557bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
558 TypeSetByHwMode &Elem) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000559 ValidateOnExit _1(Vec, *this), _2(Elem, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000560 if (TP.hasError())
561 return false;
562 bool Changed = false;
563
564 if (Vec.empty())
565 Changed |= EnforceVector(Vec);
566 if (Elem.empty())
567 Changed |= EnforceScalar(Elem);
568
569 for (unsigned M : union_modes(Vec, Elem)) {
570 TypeSetByHwMode::SetType &V = Vec.get(M);
571 TypeSetByHwMode::SetType &E = Elem.get(M);
572
573 Changed |= berase_if(V, isScalar); // Scalar = !vector
574 Changed |= berase_if(E, isVector); // Vector = !scalar
575 assert(!V.empty() && !E.empty());
576
577 SmallSet<MVT,4> VT, ST;
578 // Collect element types from the "vector" set.
579 for (MVT T : V)
580 VT.insert(T.getVectorElementType());
581 // Collect scalar types from the "element" set.
582 for (MVT T : E)
583 ST.insert(T);
584
585 // Remove from V all (vector) types whose element type is not in S.
586 Changed |= berase_if(V, [&ST](MVT T) -> bool {
587 return !ST.count(T.getVectorElementType());
588 });
589 // Remove from E all (scalar) types, for which there is no corresponding
590 // type in V.
591 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000592 }
593
594 return Changed;
595}
596
597bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
598 const ValueTypeByHwMode &VVT) {
599 TypeSetByHwMode Tmp(VVT);
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000600 ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000601 return EnforceVectorEltTypeIs(Vec, Tmp);
602}
603
604/// Ensure that for each type T in Sub, T is a vector type, and there
605/// exists a type U in Vec such that U is a vector type with the same
606/// element type as T and at least as many elements as T.
607bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
608 TypeSetByHwMode &Sub) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000609 ValidateOnExit _1(Vec, *this), _2(Sub, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000610 if (TP.hasError())
611 return false;
612
613 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
614 auto IsSubVec = [](MVT B, MVT P) -> bool {
615 if (!B.isVector() || !P.isVector())
616 return false;
Florian Hahn603c6452017-11-07 10:43:56 +0000617 // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
618 // but until there are obvious use-cases for this, keep the
619 // types separate.
620 if (B.isScalableVector() != P.isScalableVector())
621 return false;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000622 if (B.getVectorElementType() != P.getVectorElementType())
623 return false;
624 return B.getVectorNumElements() < P.getVectorNumElements();
625 };
626
627 /// Return true if S has no element (vector type) that T is a sub-vector of,
628 /// i.e. has the same element type as T and more elements.
629 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
630 for (const auto &I : S)
631 if (IsSubVec(T, I))
632 return false;
633 return true;
634 };
635
636 /// Return true if S has no element (vector type) that T is a super-vector
637 /// of, i.e. has the same element type as T and fewer elements.
638 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
639 for (const auto &I : S)
640 if (IsSubVec(I, T))
641 return false;
642 return true;
643 };
644
645 bool Changed = false;
646
647 if (Vec.empty())
648 Changed |= EnforceVector(Vec);
649 if (Sub.empty())
650 Changed |= EnforceVector(Sub);
651
652 for (unsigned M : union_modes(Vec, Sub)) {
653 TypeSetByHwMode::SetType &S = Sub.get(M);
654 TypeSetByHwMode::SetType &V = Vec.get(M);
655
656 Changed |= berase_if(S, isScalar);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000657
658 // Erase all types from S that are not sub-vectors of a type in V.
659 Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000660
661 // Erase all types from V that are not super-vectors of a type in S.
662 Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000663 }
664
665 return Changed;
666}
667
668/// 1. Ensure that V has a scalar type iff W has a scalar type.
669/// 2. Ensure that for each vector type T in V, there exists a vector
670/// type U in W, such that T and U have the same number of elements.
671/// 3. Ensure that for each vector type U in W, there exists a vector
672/// type T in V, such that T and U have the same number of elements
673/// (reverse of 2).
674bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000675 ValidateOnExit _1(V, *this), _2(W, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000676 if (TP.hasError())
677 return false;
678
679 bool Changed = false;
680 if (V.empty())
681 Changed |= EnforceAny(V);
682 if (W.empty())
683 Changed |= EnforceAny(W);
684
685 // An actual vector type cannot have 0 elements, so we can treat scalars
686 // as zero-length vectors. This way both vectors and scalars can be
687 // processed identically.
688 auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
689 return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
690 };
691
692 for (unsigned M : union_modes(V, W)) {
693 TypeSetByHwMode::SetType &VS = V.get(M);
694 TypeSetByHwMode::SetType &WS = W.get(M);
695
696 SmallSet<unsigned,2> VN, WN;
697 for (MVT T : VS)
698 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
699 for (MVT T : WS)
700 WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
701
702 Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
703 Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
704 }
705 return Changed;
706}
707
708/// 1. Ensure that for each type T in A, there exists a type U in B,
709/// such that T and U have equal size in bits.
710/// 2. Ensure that for each type U in B, there exists a type T in A
711/// such that T and U have equal size in bits (reverse of 1).
712bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000713 ValidateOnExit _1(A, *this), _2(B, *this);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000714 if (TP.hasError())
715 return false;
716 bool Changed = false;
717 if (A.empty())
718 Changed |= EnforceAny(A);
719 if (B.empty())
720 Changed |= EnforceAny(B);
721
722 auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
723 return !Sizes.count(T.getSizeInBits());
724 };
725
726 for (unsigned M : union_modes(A, B)) {
727 TypeSetByHwMode::SetType &AS = A.get(M);
728 TypeSetByHwMode::SetType &BS = B.get(M);
729 SmallSet<unsigned,2> AN, BN;
730
731 for (MVT T : AS)
732 AN.insert(T.getSizeInBits());
733 for (MVT T : BS)
734 BN.insert(T.getSizeInBits());
735
736 Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
737 Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
738 }
739
740 return Changed;
741}
742
743void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000744 ValidateOnExit _1(VTS, *this);
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000745 const TypeSetByHwMode &Legal = getLegalTypes();
746 assert(Legal.isDefaultOnly() && "Default-mode only expected");
747 const TypeSetByHwMode::SetType &LegalTypes = Legal.get(DefaultMode);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000748
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000749 for (auto &I : VTS)
750 expandOverloads(I.second, LegalTypes);
Scott Michel94420742008-03-05 17:49:05 +0000751}
Daniel Dunbarba66a812010-10-08 02:07:22 +0000752
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000753void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
754 const TypeSetByHwMode::SetType &Legal) {
755 std::set<MVT> Ovs;
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000756 for (MVT T : Out) {
757 if (!T.isOverloaded())
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000758 continue;
Zachary Turner249dc142017-09-20 18:01:40 +0000759
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000760 Ovs.insert(T);
761 // MachineValueTypeSet allows iteration and erasing.
762 Out.erase(T);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000763 }
764
765 for (MVT Ov : Ovs) {
766 switch (Ov.SimpleTy) {
767 case MVT::iPTRAny:
768 Out.insert(MVT::iPTR);
769 return;
770 case MVT::iAny:
771 for (MVT T : MVT::integer_valuetypes())
772 if (Legal.count(T))
773 Out.insert(T);
774 for (MVT T : MVT::integer_vector_valuetypes())
775 if (Legal.count(T))
776 Out.insert(T);
777 return;
778 case MVT::fAny:
779 for (MVT T : MVT::fp_valuetypes())
780 if (Legal.count(T))
781 Out.insert(T);
782 for (MVT T : MVT::fp_vector_valuetypes())
783 if (Legal.count(T))
784 Out.insert(T);
785 return;
786 case MVT::vAny:
787 for (MVT T : MVT::vector_valuetypes())
788 if (Legal.count(T))
789 Out.insert(T);
790 return;
791 case MVT::Any:
792 for (MVT T : MVT::all_valuetypes())
793 if (Legal.count(T))
794 Out.insert(T);
795 return;
796 default:
797 break;
798 }
799 }
800}
801
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000802const TypeSetByHwMode &TypeInfer::getLegalTypes() {
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000803 if (!LegalTypesCached) {
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000804 TypeSetByHwMode::SetType &LegalTypes = LegalCache.getOrCreate(DefaultMode);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000805 // Stuff all types from all modes into the default mode.
806 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
807 for (const auto &I : LTS)
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000808 LegalTypes.insert(I.second);
Krzysztof Parzyszekaffd2012017-09-19 18:42:34 +0000809 LegalTypesCached = true;
810 }
Simon Pilgrim45e61c52018-08-17 15:54:07 +0000811 assert(LegalCache.isDefaultOnly() && "Default-mode only expected");
812 return LegalCache;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +0000813}
Chris Lattner514e2922011-04-17 21:38:24 +0000814
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000815#ifndef NDEBUG
816TypeInfer::ValidateOnExit::~ValidateOnExit() {
Ulrich Weigand22b1af82018-07-13 16:42:15 +0000817 if (Infer.Validate && !VTS.validate()) {
Krzysztof Parzyszek2e0f7bd2017-12-21 17:12:43 +0000818 dbgs() << "Type set is empty for each HW mode:\n"
819 "possible type contradiction in the pattern below "
820 "(use -print-records with llvm-tblgen to see all "
821 "expanded records).\n";
822 Infer.TP.dump();
823 llvm_unreachable(nullptr);
824 }
825}
826#endif
827
Nicolai Haehnle445b0b62018-11-30 14:15:13 +0000828
829//===----------------------------------------------------------------------===//
830// ScopedName Implementation
831//===----------------------------------------------------------------------===//
832
833bool ScopedName::operator==(const ScopedName &o) const {
834 return Scope == o.Scope && Identifier == o.Identifier;
835}
836
837bool ScopedName::operator!=(const ScopedName &o) const {
838 return !(*this == o);
839}
840
841
Chris Lattner514e2922011-04-17 21:38:24 +0000842//===----------------------------------------------------------------------===//
843// TreePredicateFn Implementation
844//===----------------------------------------------------------------------===//
845
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000846/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
847TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000848 assert(
849 (!hasPredCode() || !hasImmCode()) &&
850 ".td file corrupt: can't have a node predicate *and* an imm predicate");
851}
852
853bool TreePredicateFn::hasPredCode() const {
Daniel Sanders87d196c2017-11-13 22:26:13 +0000854 return isLoad() || isStore() || isAtomic() ||
Daniel Sandersadbf58d2017-10-15 19:01:32 +0000855 !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +0000856}
857
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000858std::string TreePredicateFn::getPredCode() const {
859 std::string Code = "";
860
Daniel Sanders87d196c2017-11-13 22:26:13 +0000861 if (!isLoad() && !isStore() && !isAtomic()) {
862 Record *MemoryVT = getMemoryVT();
863
864 if (MemoryVT)
865 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
866 "MemoryVT requires IsLoad or IsStore");
867 }
868
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000869 if (!isLoad() && !isStore()) {
870 if (isUnindexed())
871 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
872 "IsUnindexed requires IsLoad or IsStore");
873
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000874 Record *ScalarMemoryVT = getScalarMemoryVT();
875
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000876 if (ScalarMemoryVT)
877 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
878 "ScalarMemoryVT requires IsLoad or IsStore");
879 }
880
Daniel Sanders87d196c2017-11-13 22:26:13 +0000881 if (isLoad() + isStore() + isAtomic() > 1)
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000882 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
Daniel Sanders87d196c2017-11-13 22:26:13 +0000883 "IsLoad, IsStore, and IsAtomic are mutually exclusive");
Daniel Sanders3f267bf2017-10-15 02:06:44 +0000884
885 if (isLoad()) {
886 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
887 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
888 getScalarMemoryVT() == nullptr)
889 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
890 "IsLoad cannot be used by itself");
891 } else {
892 if (isNonExtLoad())
893 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
894 "IsNonExtLoad requires IsLoad");
895 if (isAnyExtLoad())
896 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
897 "IsAnyExtLoad requires IsLoad");
898 if (isSignExtLoad())
899 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
900 "IsSignExtLoad requires IsLoad");
901 if (isZeroExtLoad())
902 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
903 "IsZeroExtLoad requires IsLoad");
904 }
905
906 if (isStore()) {
907 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
908 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr)
909 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
910 "IsStore cannot be used by itself");
911 } else {
912 if (isNonTruncStore())
913 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
914 "IsNonTruncStore requires IsStore");
915 if (isTruncStore())
916 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
917 "IsTruncStore requires IsStore");
918 }
919
Daniel Sanders87d196c2017-11-13 22:26:13 +0000920 if (isAtomic()) {
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000921 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
922 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
923 !isAtomicOrderingAcquireRelease() &&
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000924 !isAtomicOrderingSequentiallyConsistent() &&
925 !isAtomicOrderingAcquireOrStronger() &&
926 !isAtomicOrderingReleaseOrStronger() &&
927 !isAtomicOrderingWeakerThanAcquire() &&
928 !isAtomicOrderingWeakerThanRelease())
Daniel Sanders87d196c2017-11-13 22:26:13 +0000929 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
930 "IsAtomic cannot be used by itself");
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000931 } else {
932 if (isAtomicOrderingMonotonic())
933 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
934 "IsAtomicOrderingMonotonic requires IsAtomic");
935 if (isAtomicOrderingAcquire())
936 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
937 "IsAtomicOrderingAcquire requires IsAtomic");
938 if (isAtomicOrderingRelease())
939 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
940 "IsAtomicOrderingRelease requires IsAtomic");
941 if (isAtomicOrderingAcquireRelease())
942 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
943 "IsAtomicOrderingAcquireRelease requires IsAtomic");
944 if (isAtomicOrderingSequentiallyConsistent())
945 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
946 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000947 if (isAtomicOrderingAcquireOrStronger())
948 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
949 "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
950 if (isAtomicOrderingReleaseOrStronger())
951 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
952 "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
953 if (isAtomicOrderingWeakerThanAcquire())
954 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
955 "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
Daniel Sanders87d196c2017-11-13 22:26:13 +0000956 }
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000957
Daniel Sanders87d196c2017-11-13 22:26:13 +0000958 if (isLoad() || isStore() || isAtomic()) {
959 StringRef SDNodeName =
960 isLoad() ? "LoadSDNode" : isStore() ? "StoreSDNode" : "AtomicSDNode";
961
962 Record *MemoryVT = getMemoryVT();
963
964 if (MemoryVT)
965 Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT() != MVT::" +
966 MemoryVT->getName() + ") return false;\n")
967 .str();
968 }
969
Daniel Sanders6d9d30a2017-11-13 23:03:47 +0000970 if (isAtomic() && isAtomicOrderingMonotonic())
971 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
972 "AtomicOrdering::Monotonic) return false;\n";
973 if (isAtomic() && isAtomicOrderingAcquire())
974 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
975 "AtomicOrdering::Acquire) return false;\n";
976 if (isAtomic() && isAtomicOrderingRelease())
977 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
978 "AtomicOrdering::Release) return false;\n";
979 if (isAtomic() && isAtomicOrderingAcquireRelease())
980 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
981 "AtomicOrdering::AcquireRelease) return false;\n";
982 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
983 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
984 "AtomicOrdering::SequentiallyConsistent) return false;\n";
985
Daniel Sanders0c43b3a2017-11-30 21:05:59 +0000986 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
987 Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
988 "return false;\n";
989 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
990 Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
991 "return false;\n";
992
993 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
994 Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
995 "return false;\n";
996 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
997 Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
998 "return false;\n";
999
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001000 if (isLoad() || isStore()) {
1001 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
1002
1003 if (isUnindexed())
1004 Code += ("if (cast<" + SDNodeName +
1005 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
1006 "return false;\n")
1007 .str();
1008
1009 if (isLoad()) {
1010 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
1011 isZeroExtLoad()) > 1)
1012 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1013 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
1014 "IsZeroExtLoad are mutually exclusive");
1015 if (isNonExtLoad())
1016 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
1017 "ISD::NON_EXTLOAD) return false;\n";
1018 if (isAnyExtLoad())
1019 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1020 "return false;\n";
1021 if (isSignExtLoad())
1022 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1023 "return false;\n";
1024 if (isZeroExtLoad())
1025 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1026 "return false;\n";
1027 } else {
1028 if ((isNonTruncStore() + isTruncStore()) > 1)
1029 PrintFatalError(
1030 getOrigPatFragRecord()->getRecord()->getLoc(),
1031 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1032 if (isNonTruncStore())
1033 Code +=
1034 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1035 if (isTruncStore())
1036 Code +=
1037 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1038 }
1039
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001040 Record *ScalarMemoryVT = getScalarMemoryVT();
1041
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001042 if (ScalarMemoryVT)
1043 Code += ("if (cast<" + SDNodeName +
1044 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1045 ScalarMemoryVT->getName() + ") return false;\n")
1046 .str();
1047 }
1048
1049 std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
1050
1051 Code += PredicateCode;
1052
1053 if (PredicateCode.empty() && !Code.empty())
1054 Code += "return true;\n";
1055
1056 return Code;
Chris Lattner514e2922011-04-17 21:38:24 +00001057}
1058
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001059bool TreePredicateFn::hasImmCode() const {
1060 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1061}
1062
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001063std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00001064 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001065}
1066
Daniel Sanders649c5852017-10-13 20:42:18 +00001067bool TreePredicateFn::immCodeUsesAPInt() const {
1068 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1069}
1070
1071bool TreePredicateFn::immCodeUsesAPFloat() const {
1072 bool Unset;
1073 // The return value will be false when IsAPFloat is unset.
1074 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1075 Unset);
1076}
1077
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001078bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1079 bool Value) const {
1080 bool Unset;
1081 bool Result =
1082 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1083 if (Unset)
1084 return false;
1085 return Result == Value;
1086}
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001087bool TreePredicateFn::usesOperands() const {
1088 return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
1089}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001090bool TreePredicateFn::isLoad() const {
1091 return isPredefinedPredicateEqualTo("IsLoad", true);
1092}
1093bool TreePredicateFn::isStore() const {
1094 return isPredefinedPredicateEqualTo("IsStore", true);
1095}
Daniel Sanders87d196c2017-11-13 22:26:13 +00001096bool TreePredicateFn::isAtomic() const {
1097 return isPredefinedPredicateEqualTo("IsAtomic", true);
1098}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001099bool TreePredicateFn::isUnindexed() const {
1100 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1101}
1102bool TreePredicateFn::isNonExtLoad() const {
1103 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1104}
1105bool TreePredicateFn::isAnyExtLoad() const {
1106 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1107}
1108bool TreePredicateFn::isSignExtLoad() const {
1109 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1110}
1111bool TreePredicateFn::isZeroExtLoad() const {
1112 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1113}
1114bool TreePredicateFn::isNonTruncStore() const {
1115 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1116}
1117bool TreePredicateFn::isTruncStore() const {
1118 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1119}
Daniel Sanders6d9d30a2017-11-13 23:03:47 +00001120bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1121 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1122}
1123bool TreePredicateFn::isAtomicOrderingAcquire() const {
1124 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1125}
1126bool TreePredicateFn::isAtomicOrderingRelease() const {
1127 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1128}
1129bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1130 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1131}
1132bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1133 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1134 true);
1135}
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001136bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1137 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1138}
1139bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1140 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1141}
1142bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1143 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1144}
1145bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1146 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1147}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001148Record *TreePredicateFn::getMemoryVT() const {
1149 Record *R = getOrigPatFragRecord()->getRecord();
1150 if (R->isValueUnset("MemoryVT"))
1151 return nullptr;
1152 return R->getValueAsDef("MemoryVT");
1153}
1154Record *TreePredicateFn::getScalarMemoryVT() const {
1155 Record *R = getOrigPatFragRecord()->getRecord();
1156 if (R->isValueUnset("ScalarMemoryVT"))
1157 return nullptr;
1158 return R->getValueAsDef("ScalarMemoryVT");
1159}
Daniel Sanders8ead1292018-06-15 23:13:43 +00001160bool TreePredicateFn::hasGISelPredicateCode() const {
1161 return !PatFragRec->getRecord()
1162 ->getValueAsString("GISelPredicateCode")
1163 .empty();
1164}
1165std::string TreePredicateFn::getGISelPredicateCode() const {
1166 return PatFragRec->getRecord()->getValueAsString("GISelPredicateCode");
1167}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001168
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001169StringRef TreePredicateFn::getImmType() const {
Daniel Sanders649c5852017-10-13 20:42:18 +00001170 if (immCodeUsesAPInt())
1171 return "const APInt &";
1172 if (immCodeUsesAPFloat())
1173 return "const APFloat &";
1174 return "int64_t";
1175}
Chris Lattner514e2922011-04-17 21:38:24 +00001176
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001177StringRef TreePredicateFn::getImmTypeIdentifier() const {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001178 if (immCodeUsesAPInt())
1179 return "APInt";
1180 else if (immCodeUsesAPFloat())
1181 return "APFloat";
1182 return "I64";
1183}
1184
Chris Lattner514e2922011-04-17 21:38:24 +00001185/// isAlwaysTrue - Return true if this is a noop predicate.
1186bool TreePredicateFn::isAlwaysTrue() const {
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001187 return !hasPredCode() && !hasImmCode();
Chris Lattner514e2922011-04-17 21:38:24 +00001188}
1189
1190/// Return the name to use in the generated code to reference this, this is
1191/// "Predicate_foo" if from a pattern fragment "foo".
1192std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +00001193 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +00001194}
1195
1196/// getCodeToRunOnSDNode - Return the code for the function body that
1197/// evaluates this predicate. The argument is expected to be in "Node",
1198/// not N. This handles casting and conversion to a concrete node type as
1199/// appropriate.
1200std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001201 // Handle immediate predicates first.
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001202 std::string ImmCode = getImmCode();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001203 if (!ImmCode.empty()) {
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001204 if (isLoad())
1205 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1206 "IsLoad cannot be used with ImmLeaf or its subclasses");
1207 if (isStore())
1208 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1209 "IsStore cannot be used with ImmLeaf or its subclasses");
1210 if (isUnindexed())
1211 PrintFatalError(
1212 getOrigPatFragRecord()->getRecord()->getLoc(),
1213 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1214 if (isNonExtLoad())
1215 PrintFatalError(
1216 getOrigPatFragRecord()->getRecord()->getLoc(),
1217 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1218 if (isAnyExtLoad())
1219 PrintFatalError(
1220 getOrigPatFragRecord()->getRecord()->getLoc(),
1221 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1222 if (isSignExtLoad())
1223 PrintFatalError(
1224 getOrigPatFragRecord()->getRecord()->getLoc(),
1225 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1226 if (isZeroExtLoad())
1227 PrintFatalError(
1228 getOrigPatFragRecord()->getRecord()->getLoc(),
1229 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1230 if (isNonTruncStore())
1231 PrintFatalError(
1232 getOrigPatFragRecord()->getRecord()->getLoc(),
1233 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1234 if (isTruncStore())
1235 PrintFatalError(
1236 getOrigPatFragRecord()->getRecord()->getLoc(),
1237 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1238 if (getMemoryVT())
1239 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1240 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1241 if (getScalarMemoryVT())
1242 PrintFatalError(
1243 getOrigPatFragRecord()->getRecord()->getLoc(),
1244 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1245
1246 std::string Result = (" " + getImmType() + " Imm = ").str();
Daniel Sanders649c5852017-10-13 20:42:18 +00001247 if (immCodeUsesAPFloat())
1248 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1249 else if (immCodeUsesAPInt())
1250 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1251 else
1252 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001253 return Result + ImmCode;
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001254 }
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001255
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001256 // Handle arbitrary node predicates.
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001257 assert(hasPredCode() && "Don't have any predicate code!");
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001258 StringRef ClassName;
Chris Lattner514e2922011-04-17 21:38:24 +00001259 if (PatFragRec->getOnlyTree()->isLeaf())
1260 ClassName = "SDNode";
1261 else {
1262 Record *Op = PatFragRec->getOnlyTree()->getOperator();
1263 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1264 }
1265 std::string Result;
1266 if (ClassName == "SDNode")
1267 Result = " SDNode *N = Node;\n";
1268 else
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001269 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001270
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001271 return (Twine(Result) + " (void)N;\n" + getPredCode()).str();
Scott Michel94420742008-03-05 17:49:05 +00001272}
1273
Chris Lattner8cab0212008-01-05 22:25:12 +00001274//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +00001275// PatternToMatch implementation
1276//
1277
Chris Lattner05925fe2010-03-29 01:40:38 +00001278/// getPatternSize - Return the 'size' of this pattern. We want to match large
1279/// patterns before small ones. This is used to determine the size of a
1280/// pattern.
Florian Hahn6b1db822018-06-14 20:32:58 +00001281static unsigned getPatternSize(const TreePatternNode *P,
Chris Lattner05925fe2010-03-29 01:40:38 +00001282 const CodeGenDAGPatterns &CGP) {
1283 unsigned Size = 3; // The node itself.
1284 // If the root node is a ConstantSDNode, increases its size.
1285 // e.g. (set R32:$dst, 0).
Florian Hahn6b1db822018-06-14 20:32:58 +00001286 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001287 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001288
Florian Hahn6b1db822018-06-14 20:32:58 +00001289 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001290 Size += AM->getComplexity();
Tim Northoverc807a172014-05-20 11:52:46 +00001291 // We don't want to count any children twice, so return early.
1292 return Size;
1293 }
1294
Chris Lattner05925fe2010-03-29 01:40:38 +00001295 // If this node has some predicate function that must match, it adds to the
1296 // complexity of this node.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001297 if (!P->getPredicateCalls().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001298 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001299
Chris Lattner05925fe2010-03-29 01:40:38 +00001300 // Count children in the count if they are also nodes.
Florian Hahn6b1db822018-06-14 20:32:58 +00001301 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1302 const TreePatternNode *Child = P->getChild(i);
1303 if (!Child->isLeaf() && Child->getNumTypes()) {
Simon Pilgrimc3c14412018-08-15 20:41:19 +00001304 const TypeSetByHwMode &T0 = Child->getExtType(0);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001305 // At this point, all variable type sets should be simple, i.e. only
1306 // have a default mode.
1307 if (T0.getMachineValueType() != MVT::Other) {
1308 Size += getPatternSize(Child, CGP);
1309 continue;
1310 }
1311 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001312 if (Child->isLeaf()) {
1313 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001314 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Florian Hahn6b1db822018-06-14 20:32:58 +00001315 else if (Child->getComplexPatternInfo(CGP))
Chris Lattner05925fe2010-03-29 01:40:38 +00001316 Size += getPatternSize(Child, CGP);
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001317 else if (!Child->getPredicateCalls().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001318 ++Size;
1319 }
1320 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001321
Chris Lattner05925fe2010-03-29 01:40:38 +00001322 return Size;
1323}
1324
1325/// Compute the complexity metric for the input pattern. This roughly
1326/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +00001327int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +00001328getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001329 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
Chris Lattner05925fe2010-03-29 01:40:38 +00001330}
1331
Dan Gohman49e19e92008-08-22 00:20:26 +00001332/// getPredicateCheck - Return a single string containing all of this
1333/// pattern's predicates concatenated with "&&" operators.
1334///
1335std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001336 SmallVector<const Predicate*,4> PredList;
1337 for (const Predicate &P : Predicates)
1338 PredList.push_back(&P);
Fangrui Song0cac7262018-09-27 02:13:45 +00001339 llvm::sort(PredList, deref<llvm::less>());
Craig Topper8985efe2015-11-27 05:44:04 +00001340
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001341 std::string Check;
1342 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1343 if (i != 0)
1344 Check += " && ";
1345 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +00001346 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001347 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +00001348}
1349
1350//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00001351// SDTypeConstraint implementation
1352//
1353
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001354SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001355 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001356
Chris Lattner8cab0212008-01-05 22:25:12 +00001357 if (R->isSubClassOf("SDTCisVT")) {
1358 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001359 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1360 for (const auto &P : VVT)
1361 if (P.second == MVT::isVoid)
1362 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +00001363 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1364 ConstraintType = SDTCisPtrTy;
1365 } else if (R->isSubClassOf("SDTCisInt")) {
1366 ConstraintType = SDTCisInt;
1367 } else if (R->isSubClassOf("SDTCisFP")) {
1368 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +00001369 } else if (R->isSubClassOf("SDTCisVec")) {
1370 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001371 } else if (R->isSubClassOf("SDTCisSameAs")) {
1372 ConstraintType = SDTCisSameAs;
1373 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1374 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1375 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001376 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001377 R->getValueAsInt("OtherOperandNum");
1378 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1379 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001380 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001381 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001382 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1383 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001384 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001385 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1386 ConstraintType = SDTCisSubVecOfVec;
1387 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1388 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001389 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1390 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001391 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1392 for (const auto &P : VVT) {
1393 MVT T = P.second;
1394 if (T.isVector())
1395 PrintFatalError(R->getLoc(),
1396 "Cannot use vector type as SDTCVecEltisVT");
1397 if (!T.isInteger() && !T.isFloatingPoint())
1398 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1399 "as SDTCVecEltisVT");
1400 }
Craig Topper0be34582015-03-05 07:11:34 +00001401 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1402 ConstraintType = SDTCisSameNumEltsAs;
1403 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1404 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001405 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1406 ConstraintType = SDTCisSameSizeAs;
1407 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1408 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001409 } else {
James Y Knighte452e272015-05-11 22:17:13 +00001410 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001411 }
1412}
1413
1414/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001415/// N, and the result number in ResNo.
Florian Hahn6b1db822018-06-14 20:32:58 +00001416static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
Chris Lattner2db7aba2010-03-19 21:56:21 +00001417 const SDNodeInfo &NodeInfo,
1418 unsigned &ResNo) {
1419 unsigned NumResults = NodeInfo.getNumResults();
1420 if (OpNo < NumResults) {
1421 ResNo = OpNo;
1422 return N;
1423 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001424
Chris Lattner2db7aba2010-03-19 21:56:21 +00001425 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001426
Florian Hahn6b1db822018-06-14 20:32:58 +00001427 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001428 std::string S;
1429 raw_string_ostream OS(S);
1430 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001431 << (OpNo+NumResults) << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001432 N->print(OS);
James Y Knighte452e272015-05-11 22:17:13 +00001433 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001434 }
1435
Florian Hahn6b1db822018-06-14 20:32:58 +00001436 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001437}
1438
1439/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1440/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001441/// change, false otherwise. If a type contradiction is found, flag an error.
Florian Hahn6b1db822018-06-14 20:32:58 +00001442bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
Chris Lattner8cab0212008-01-05 22:25:12 +00001443 const SDNodeInfo &NodeInfo,
1444 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001445 if (TP.hasError())
1446 return false;
1447
Chris Lattner2db7aba2010-03-19 21:56:21 +00001448 unsigned ResNo = 0; // The result number being referenced.
Florian Hahn6b1db822018-06-14 20:32:58 +00001449 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001450 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001451
Chris Lattner8cab0212008-01-05 22:25:12 +00001452 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001453 case SDTCisVT:
1454 // Operand must be a particular type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001455 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001456 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001457 // Operand must be same as target pointer type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001458 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001459 case SDTCisInt:
1460 // Require it to be one of the legal integer VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001461 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001462 case SDTCisFP:
1463 // Require it to be one of the legal fp VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001464 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001465 case SDTCisVec:
1466 // Require it to be one of the legal vector VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001467 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001468 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001469 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001470 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001471 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001472 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1473 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001474 }
1475 case SDTCisVTSmallerThanOp: {
1476 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1477 // have an integer type that is smaller than the VT.
Florian Hahn6b1db822018-06-14 20:32:58 +00001478 if (!NodeToApply->isLeaf() ||
1479 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1480 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001481 ->isSubClassOf("ValueType")) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001482 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001483 return false;
1484 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001485 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001486 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1487 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1488 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001489
Chris Lattner2db7aba2010-03-19 21:56:21 +00001490 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001491 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001492 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1493 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001494
Florian Hahn6b1db822018-06-14 20:32:58 +00001495 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001496 }
1497 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001498 unsigned BResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001499 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001500 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1501 BResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001502 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1503 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001504 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001505 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001506 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001507 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001508 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1509 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001510 // Filter vector types out of VecOperand that don't have the right element
1511 // type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001512 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1513 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001514 }
David Greene127fd1d2011-01-24 20:53:18 +00001515 case SDTCisSubVecOfVec: {
1516 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001517 TreePatternNode *BigVecOperand =
David Greene127fd1d2011-01-24 20:53:18 +00001518 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1519 VResNo);
1520
1521 // Filter vector types out of BigVecOperand that don't have the
1522 // right subvector type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001523 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1524 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001525 }
Craig Topper0be34582015-03-05 07:11:34 +00001526 case SDTCVecEltisVT: {
Florian Hahn6b1db822018-06-14 20:32:58 +00001527 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001528 }
1529 case SDTCisSameNumEltsAs: {
1530 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001531 TreePatternNode *OtherNode =
Craig Topper0be34582015-03-05 07:11:34 +00001532 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1533 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001534 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1535 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001536 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001537 case SDTCisSameSizeAs: {
1538 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001539 TreePatternNode *OtherNode =
Craig Topper9a44b3f2015-11-26 07:02:18 +00001540 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1541 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001542 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1543 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001544 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001545 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001546 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001547}
1548
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001549// Update the node type to match an instruction operand or result as specified
1550// in the ins or outs lists on the instruction definition. Return true if the
1551// type was actually changed.
1552bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1553 Record *Operand,
1554 TreePattern &TP) {
1555 // The 'unknown' operand indicates that types should be inferred from the
1556 // context.
1557 if (Operand->isSubClassOf("unknown_class"))
1558 return false;
1559
1560 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001561 if (Operand->isSubClassOf("Operand")) {
1562 Record *R = Operand->getValueAsDef("Type");
1563 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1564 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1565 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001566
1567 // PointerLikeRegClass has a type that is determined at runtime.
1568 if (Operand->isSubClassOf("PointerLikeRegClass"))
1569 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1570
1571 // Both RegisterClass and RegisterOperand operands derive their types from a
1572 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001573 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001574 if (Operand->isSubClassOf("RegisterClass"))
1575 RC = Operand;
1576 else if (Operand->isSubClassOf("RegisterOperand"))
1577 RC = Operand->getValueAsDef("RegClass");
1578
1579 assert(RC && "Unknown operand type");
1580 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1581 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1582}
1583
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001584bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1585 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1586 if (!TP.getInfer().isConcrete(Types[i], true))
1587 return true;
1588 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001589 if (getChild(i)->ContainsUnresolvedType(TP))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001590 return true;
1591 return false;
1592}
1593
1594bool TreePatternNode::hasProperTypeByHwMode() const {
1595 for (const TypeSetByHwMode &S : Types)
1596 if (!S.isDefaultOnly())
1597 return true;
Florian Hahn75e87c32018-05-30 21:00:18 +00001598 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001599 if (C->hasProperTypeByHwMode())
1600 return true;
1601 return false;
1602}
1603
1604bool TreePatternNode::hasPossibleType() const {
1605 for (const TypeSetByHwMode &S : Types)
1606 if (!S.isPossible())
1607 return false;
Florian Hahn75e87c32018-05-30 21:00:18 +00001608 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001609 if (!C->hasPossibleType())
1610 return false;
1611 return true;
1612}
1613
1614bool TreePatternNode::setDefaultMode(unsigned Mode) {
1615 for (TypeSetByHwMode &S : Types) {
1616 S.makeSimple(Mode);
1617 // Check if the selected mode had a type conflict.
1618 if (S.get(DefaultMode).empty())
1619 return false;
1620 }
Florian Hahn75e87c32018-05-30 21:00:18 +00001621 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001622 if (!C->setDefaultMode(Mode))
1623 return false;
1624 return true;
1625}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001626
Chris Lattner8cab0212008-01-05 22:25:12 +00001627//===----------------------------------------------------------------------===//
1628// SDNodeInfo implementation
1629//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001630SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001631 EnumName = R->getValueAsString("Opcode");
1632 SDClassName = R->getValueAsString("SDClass");
1633 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1634 NumResults = TypeProfile->getValueAsInt("NumResults");
1635 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001636
Chris Lattner8cab0212008-01-05 22:25:12 +00001637 // Parse the properties.
Matt Arsenault303327d2017-12-20 19:36:28 +00001638 Properties = parseSDPatternOperatorProperties(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001639
Chris Lattner8cab0212008-01-05 22:25:12 +00001640 // Parse the type constraints.
1641 std::vector<Record*> ConstraintList =
1642 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001643 for (Record *R : ConstraintList)
1644 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001645}
1646
Chris Lattner99e53b32010-02-28 00:22:30 +00001647/// getKnownType - If the type constraints on this node imply a fixed type
1648/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001649/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001650MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001651 unsigned NumResults = getNumResults();
1652 assert(NumResults <= 1 &&
1653 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001654 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001655
Craig Topper306cb122015-11-22 20:46:24 +00001656 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001657 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001658 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001659 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001660
Craig Topper306cb122015-11-22 20:46:24 +00001661 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001662 default: break;
1663 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001664 if (Constraint.VVT.isSimple())
1665 return Constraint.VVT.getSimple().SimpleTy;
1666 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001667 case SDTypeConstraint::SDTCisPtrTy:
1668 return MVT::iPTR;
1669 }
1670 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001671 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001672}
1673
Chris Lattner8cab0212008-01-05 22:25:12 +00001674//===----------------------------------------------------------------------===//
1675// TreePatternNode implementation
1676//
1677
Chris Lattnerf1447252010-03-19 21:37:09 +00001678static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1679 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001680 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001681 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001682
Chris Lattner2109cb42010-03-22 20:56:36 +00001683 if (Operator->isSubClassOf("Intrinsic"))
1684 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001685
Chris Lattnerf1447252010-03-19 21:37:09 +00001686 if (Operator->isSubClassOf("SDNode"))
1687 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001688
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001689 if (Operator->isSubClassOf("PatFrags")) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001690 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1691 // the forward reference case where one pattern fragment references another
1692 // before it is processed.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001693 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
1694 // The number of results of a fragment with alternative records is the
1695 // maximum number of results across all alternatives.
1696 unsigned NumResults = 0;
1697 for (auto T : PFRec->getTrees())
1698 NumResults = std::max(NumResults, T->getNumTypes());
1699 return NumResults;
1700 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001701
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001702 ListInit *LI = Operator->getValueAsListInit("Fragments");
1703 assert(LI && "Invalid Fragment");
1704 unsigned NumResults = 0;
1705 for (Init *I : LI->getValues()) {
1706 Record *Op = nullptr;
1707 if (DagInit *Dag = dyn_cast<DagInit>(I))
1708 if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
1709 Op = DI->getDef();
1710 assert(Op && "Invalid Fragment");
1711 NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
1712 }
1713 return NumResults;
Chris Lattnerf1447252010-03-19 21:37:09 +00001714 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001715
Chris Lattnerf1447252010-03-19 21:37:09 +00001716 if (Operator->isSubClassOf("Instruction")) {
1717 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001718
Craig Topper3a8eb892015-03-20 05:09:06 +00001719 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1720
1721 // Subtract any defaulted outputs.
1722 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1723 Record *OperandNode = InstInfo.Operands[i].Rec;
1724
1725 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1726 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1727 --NumDefsToAdd;
1728 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001729
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001730 // Add on one implicit def if it has a resolvable type.
1731 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1732 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001733 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001734 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001735
Chris Lattnerf1447252010-03-19 21:37:09 +00001736 if (Operator->isSubClassOf("SDNodeXForm"))
1737 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001738
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001739 if (Operator->isSubClassOf("ValueType"))
1740 return 1; // A type-cast of one result.
1741
Tim Northoverc807a172014-05-20 11:52:46 +00001742 if (Operator->isSubClassOf("ComplexPattern"))
1743 return 1;
1744
Matthias Braun8c209aa2017-01-28 02:02:38 +00001745 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001746 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001747}
1748
1749void TreePatternNode::print(raw_ostream &OS) const {
1750 if (isLeaf())
1751 OS << *getLeafValue();
1752 else
1753 OS << '(' << getOperator()->getName();
1754
Zachary Turner249dc142017-09-20 18:01:40 +00001755 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1756 OS << ':';
1757 getExtType(i).writeToStream(OS);
1758 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001759
1760 if (!isLeaf()) {
1761 if (getNumChildren() != 0) {
1762 OS << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001763 getChild(0)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001764 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1765 OS << ", ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001766 getChild(i)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001767 }
1768 }
1769 OS << ")";
1770 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001771
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001772 for (const TreePredicateCall &Pred : PredicateCalls) {
1773 OS << "<<P:";
1774 if (Pred.Scope)
1775 OS << Pred.Scope << ":";
1776 OS << Pred.Fn.getFnName() << ">>";
1777 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001778 if (TransformFn)
1779 OS << "<<X:" << TransformFn->getName() << ">>";
1780 if (!getName().empty())
1781 OS << ":$" << getName();
1782
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001783 for (const ScopedName &Name : NamesAsPredicateArg)
1784 OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();
Chris Lattner8cab0212008-01-05 22:25:12 +00001785}
1786void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001787 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001788}
1789
Scott Michel94420742008-03-05 17:49:05 +00001790/// isIsomorphicTo - Return true if this node is recursively
1791/// isomorphic to the specified node. For this comparison, the node's
1792/// entire state is considered. The assigned name is ignored, since
1793/// nodes with differing names are considered isomorphic. However, if
1794/// the assigned name is present in the dependent variable set, then
1795/// the assigned name is considered significant and the node is
1796/// isomorphic if the names match.
Florian Hahn6b1db822018-06-14 20:32:58 +00001797bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
Scott Michel94420742008-03-05 17:49:05 +00001798 const MultipleUseVarSet &DepVars) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001799 if (N == this) return true;
1800 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001801 getPredicateCalls() != N->getPredicateCalls() ||
Florian Hahn6b1db822018-06-14 20:32:58 +00001802 getTransformFn() != N->getTransformFn())
Chris Lattner8cab0212008-01-05 22:25:12 +00001803 return false;
1804
1805 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001806 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001807 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001808 return ((DI->getDef() == NDI->getDef())
1809 && (DepVars.find(getName()) == DepVars.end()
Florian Hahn6b1db822018-06-14 20:32:58 +00001810 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001811 }
1812 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001813 return getLeafValue() == N->getLeafValue();
Chris Lattner8cab0212008-01-05 22:25:12 +00001814 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001815
Florian Hahn6b1db822018-06-14 20:32:58 +00001816 if (N->getOperator() != getOperator() ||
1817 N->getNumChildren() != getNumChildren()) return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001818 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001819 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001820 return false;
1821 return true;
1822}
1823
1824/// clone - Make a copy of this tree and all of its children.
1825///
Florian Hahn75e87c32018-05-30 21:00:18 +00001826TreePatternNodePtr TreePatternNode::clone() const {
1827 TreePatternNodePtr New;
Chris Lattner8cab0212008-01-05 22:25:12 +00001828 if (isLeaf()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001829 New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001830 } else {
Florian Hahn75e87c32018-05-30 21:00:18 +00001831 std::vector<TreePatternNodePtr> CChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00001832 CChildren.reserve(Children.size());
1833 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001834 CChildren.push_back(getChild(i)->clone());
Craig Topper26fc06352018-07-15 06:52:49 +00001835 New = std::make_shared<TreePatternNode>(getOperator(), std::move(CChildren),
Florian Hahn75e87c32018-05-30 21:00:18 +00001836 getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001837 }
1838 New->setName(getName());
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001839 New->setNamesAsPredicateArg(getNamesAsPredicateArg());
Chris Lattnerf1447252010-03-19 21:37:09 +00001840 New->Types = Types;
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001841 New->setPredicateCalls(getPredicateCalls());
Chris Lattner8cab0212008-01-05 22:25:12 +00001842 New->setTransformFn(getTransformFn());
1843 return New;
1844}
1845
Chris Lattner53c39ba2010-02-14 22:22:58 +00001846/// RemoveAllTypes - Recursively strip all the types of this tree.
1847void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001848 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001849 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001850 if (isLeaf()) return;
1851 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001852 getChild(i)->RemoveAllTypes();
Chris Lattner53c39ba2010-02-14 22:22:58 +00001853}
1854
1855
Chris Lattner8cab0212008-01-05 22:25:12 +00001856/// SubstituteFormalArguments - Replace the formal arguments in this tree
1857/// with actual values specified by ArgMap.
Florian Hahn75e87c32018-05-30 21:00:18 +00001858void TreePatternNode::SubstituteFormalArguments(
1859 std::map<std::string, TreePatternNodePtr> &ArgMap) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001860 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001861
Chris Lattner8cab0212008-01-05 22:25:12 +00001862 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001863 TreePatternNode *Child = getChild(i);
1864 if (Child->isLeaf()) {
1865 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001866 // Note that, when substituting into an output pattern, Val might be an
1867 // UnsetInit.
1868 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1869 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001870 // We found a use of a formal argument, replace it with its value.
Florian Hahn6b1db822018-06-14 20:32:58 +00001871 TreePatternNodePtr NewChild = ArgMap[Child->getName()];
Dan Gohman6e979022008-10-15 06:17:21 +00001872 assert(NewChild && "Couldn't find formal argument!");
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001873 assert((Child->getPredicateCalls().empty() ||
1874 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
Dan Gohman6e979022008-10-15 06:17:21 +00001875 "Non-empty child predicate clobbered!");
Florian Hahn0a2e0b62018-06-14 11:56:19 +00001876 setChild(i, std::move(NewChild));
Chris Lattner8cab0212008-01-05 22:25:12 +00001877 }
1878 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00001879 getChild(i)->SubstituteFormalArguments(ArgMap);
Chris Lattner8cab0212008-01-05 22:25:12 +00001880 }
1881 }
1882}
1883
1884
1885/// InlinePatternFragments - If this pattern refers to any pattern
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001886/// fragments, return the set of inlined versions (this can be more than
1887/// one if a PatFrags record has multiple alternatives).
1888void TreePatternNode::InlinePatternFragments(
1889 TreePatternNodePtr T, TreePattern &TP,
1890 std::vector<TreePatternNodePtr> &OutAlternatives) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001891
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001892 if (TP.hasError())
1893 return;
1894
1895 if (isLeaf()) {
1896 OutAlternatives.push_back(T); // nothing to do.
1897 return;
1898 }
1899
Chris Lattner8cab0212008-01-05 22:25:12 +00001900 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001901
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001902 if (!Op->isSubClassOf("PatFrags")) {
1903 if (getNumChildren() == 0) {
1904 OutAlternatives.push_back(T);
1905 return;
1906 }
1907
1908 // Recursively inline children nodes.
1909 std::vector<std::vector<TreePatternNodePtr> > ChildAlternatives;
1910 ChildAlternatives.resize(getNumChildren());
Dan Gohman6e979022008-10-15 06:17:21 +00001911 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001912 TreePatternNodePtr Child = getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001913 Child->InlinePatternFragments(Child, TP, ChildAlternatives[i]);
1914 // If there are no alternatives for any child, there are no
1915 // alternatives for this expression as whole.
1916 if (ChildAlternatives[i].empty())
1917 return;
Dan Gohman6e979022008-10-15 06:17:21 +00001918
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001919 for (auto NewChild : ChildAlternatives[i])
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001920 assert((Child->getPredicateCalls().empty() ||
1921 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001922 "Non-empty child predicate clobbered!");
Dan Gohman6e979022008-10-15 06:17:21 +00001923 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001924
1925 // The end result is an all-pairs construction of the resultant pattern.
1926 std::vector<unsigned> Idxs;
1927 Idxs.resize(ChildAlternatives.size());
1928 bool NotDone;
1929 do {
1930 // Create the variant and add it to the output list.
1931 std::vector<TreePatternNodePtr> NewChildren;
1932 for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
1933 NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
1934 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00001935 getOperator(), std::move(NewChildren), getNumTypes());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001936
1937 // Copy over properties.
1938 R->setName(getName());
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001939 R->setNamesAsPredicateArg(getNamesAsPredicateArg());
1940 R->setPredicateCalls(getPredicateCalls());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001941 R->setTransformFn(getTransformFn());
1942 for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
1943 R->setType(i, getExtType(i));
Craig Topperbd199f82018-12-05 00:47:59 +00001944 for (unsigned i = 0, e = getNumResults(); i != e; ++i)
1945 R->setResultIndex(i, getResultIndex(i));
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001946
1947 // Register alternative.
1948 OutAlternatives.push_back(R);
1949
1950 // Increment indices to the next permutation by incrementing the
1951 // indices from last index backward, e.g., generate the sequence
1952 // [0, 0], [0, 1], [1, 0], [1, 1].
1953 int IdxsIdx;
1954 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
1955 if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
1956 Idxs[IdxsIdx] = 0;
1957 else
1958 break;
1959 }
1960 NotDone = (IdxsIdx >= 0);
1961 } while (NotDone);
1962
1963 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00001964 }
1965
1966 // Otherwise, we found a reference to a fragment. First, look up its
1967 // TreePattern record.
1968 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001969
Chris Lattner8cab0212008-01-05 22:25:12 +00001970 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001971 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001972 TP.error("'" + Op->getName() + "' fragment requires " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001973 Twine(Frag->getNumArgs()) + " operands!");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001974 return;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001975 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001976
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001977 TreePredicateFn PredFn(Frag);
1978 unsigned Scope = 0;
1979 if (TreePredicateFn(Frag).usesOperands())
1980 Scope = TP.getDAGPatterns().allocateScope();
1981
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001982 // Compute the map of formal to actual arguments.
1983 std::map<std::string, TreePatternNodePtr> ArgMap;
1984 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001985 TreePatternNodePtr Child = getChildShared(i);
1986 if (Scope != 0) {
1987 Child = Child->clone();
1988 Child->addNameAsPredicateArg(ScopedName(Scope, Frag->getArgName(i)));
1989 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001990 ArgMap[Frag->getArgName(i)] = Child;
Chris Lattner8cab0212008-01-05 22:25:12 +00001991 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001992
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001993 // Loop over all fragment alternatives.
1994 for (auto Alternative : Frag->getTrees()) {
1995 TreePatternNodePtr FragTree = Alternative->clone();
Dan Gohman6e979022008-10-15 06:17:21 +00001996
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001997 if (!PredFn.isAlwaysTrue())
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001998 FragTree->addPredicateCall(PredFn, Scope);
Dan Gohman6e979022008-10-15 06:17:21 +00001999
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002000 // Resolve formal arguments to their actual value.
2001 if (Frag->getNumArgs())
2002 FragTree->SubstituteFormalArguments(ArgMap);
2003
2004 // Transfer types. Note that the resolved alternative may have fewer
2005 // (but not more) results than the PatFrags node.
2006 FragTree->setName(getName());
2007 for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
2008 FragTree->UpdateNodeType(i, getExtType(i), TP);
2009
2010 // Transfer in the old predicates.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002011 for (const TreePredicateCall &Pred : getPredicateCalls())
2012 FragTree->addPredicateCall(Pred);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002013
2014 // The fragment we inlined could have recursive inlining that is needed. See
2015 // if there are any pattern fragments in it and inline them as needed.
2016 FragTree->InlinePatternFragments(FragTree, TP, OutAlternatives);
2017 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002018}
2019
2020/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00002021/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00002022/// references from the register file information, for example.
2023///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002024/// When Unnamed is set, return the type of a DAG operand with no name, such as
2025/// the F8RC register class argument in:
2026///
2027/// (COPY_TO_REGCLASS GPR:$src, F8RC)
2028///
2029/// When Unnamed is false, return the type of a named DAG operand such as the
2030/// GPR:$src operand above.
2031///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002032static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
2033 bool NotRegisters,
2034 bool Unnamed,
2035 TreePattern &TP) {
2036 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2037
Owen Andersona84be6c2011-06-27 21:06:21 +00002038 // Check to see if this is a register operand.
2039 if (R->isSubClassOf("RegisterOperand")) {
2040 assert(ResNo == 0 && "Regoperand ref only has one result!");
2041 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002042 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00002043 Record *RegClass = R->getValueAsDef("RegClass");
2044 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002045 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00002046 }
2047
Chris Lattnercabe0372010-03-15 06:00:16 +00002048 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00002049 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002050 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002051 // An unnamed register class represents itself as an i32 immediate, for
2052 // example on a COPY_TO_REGCLASS instruction.
2053 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002054 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002055
2056 // In a named operand, the register class provides the possible set of
2057 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002058 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002059 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00002060 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002061 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00002062 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002063
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002064 if (R->isSubClassOf("PatFrags")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002065 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00002066 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002067 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00002068 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002069
Chris Lattner6070ee22010-03-23 23:50:31 +00002070 if (R->isSubClassOf("Register")) {
2071 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002072 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002073 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002074 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002075 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00002076 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002077
2078 if (R->isSubClassOf("SubRegIndex")) {
2079 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002080 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002081 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002082
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002083 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002084 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002085 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2086 //
2087 // (sext_inreg GPR:$src, i16)
2088 // ~~~
2089 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002090 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002091 // With a name, the ValueType simply provides the type of the named
2092 // variable.
2093 //
2094 // (sext_inreg i32:$src, i16)
2095 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002096 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002097 return TypeSetByHwMode(); // Unknown.
2098 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2099 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002100 }
2101
2102 if (R->isSubClassOf("CondCode")) {
2103 assert(ResNo == 0 && "This node only has one result!");
2104 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002105 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00002106 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002107
Chris Lattner6070ee22010-03-23 23:50:31 +00002108 if (R->isSubClassOf("ComplexPattern")) {
2109 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002110 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002111 return TypeSetByHwMode(); // Unknown.
2112 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00002113 }
2114 if (R->isSubClassOf("PointerLikeRegClass")) {
2115 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002116 TypeSetByHwMode VTS(MVT::iPTR);
2117 TP.getInfer().expandOverloads(VTS);
2118 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00002119 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002120
Chris Lattner6070ee22010-03-23 23:50:31 +00002121 if (R->getName() == "node" || R->getName() == "srcvalue" ||
2122 R->getName() == "zero_reg") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002123 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002124 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002125 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002126
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002127 if (R->isSubClassOf("Operand")) {
2128 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2129 Record *T = R->getValueAsDef("Type");
2130 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2131 }
Tim Northoverc807a172014-05-20 11:52:46 +00002132
Chris Lattner8cab0212008-01-05 22:25:12 +00002133 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002134 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00002135}
2136
Chris Lattner89c65662008-01-06 05:36:50 +00002137
2138/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2139/// CodeGenIntrinsic information for it, otherwise return a null pointer.
2140const CodeGenIntrinsic *TreePatternNode::
2141getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2142 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2143 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2144 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00002145 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002146
Florian Hahn6b1db822018-06-14 20:32:58 +00002147 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00002148 return &CDP.getIntrinsicInfo(IID);
2149}
2150
Chris Lattner53c39ba2010-02-14 22:22:58 +00002151/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2152/// return the ComplexPattern information, otherwise return null.
2153const ComplexPattern *
2154TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00002155 Record *Rec;
2156 if (isLeaf()) {
2157 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2158 if (!DI)
2159 return nullptr;
2160 Rec = DI->getDef();
2161 } else
2162 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002163
Tim Northoverc807a172014-05-20 11:52:46 +00002164 if (!Rec->isSubClassOf("ComplexPattern"))
2165 return nullptr;
2166 return &CGP.getComplexPattern(Rec);
2167}
2168
2169unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2170 // A ComplexPattern specifically declares how many results it fills in.
2171 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2172 return CP->getNumOperands();
2173
2174 // If MIOperandInfo is specified, that gives the count.
2175 if (isLeaf()) {
2176 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2177 if (DI && DI->getDef()->isSubClassOf("Operand")) {
2178 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2179 if (MIOps->getNumArgs())
2180 return MIOps->getNumArgs();
2181 }
2182 }
2183
2184 // Otherwise there is just one result.
2185 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00002186}
2187
2188/// NodeHasProperty - Return true if this node has the specified property.
2189bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002190 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002191 if (isLeaf()) {
2192 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2193 return CP->hasProperty(Property);
Matt Arsenault303327d2017-12-20 19:36:28 +00002194
Chris Lattner53c39ba2010-02-14 22:22:58 +00002195 return false;
2196 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002197
Matt Arsenault303327d2017-12-20 19:36:28 +00002198 if (Property != SDNPHasChain) {
2199 // The chain proprety is already present on the different intrinsic node
2200 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2201 // on the intrinsic. Anything else is specific to the individual intrinsic.
2202 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2203 return Int->hasProperty(Property);
2204 }
2205
2206 if (!Operator->isSubClassOf("SDPatternOperator"))
2207 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002208
Chris Lattner53c39ba2010-02-14 22:22:58 +00002209 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2210}
2211
2212
2213
2214
2215/// TreeHasProperty - Return true if any node in this tree has the specified
2216/// property.
2217bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002218 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002219 if (NodeHasProperty(Property, CGP))
2220 return true;
2221 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002222 if (getChild(i)->TreeHasProperty(Property, CGP))
Chris Lattner53c39ba2010-02-14 22:22:58 +00002223 return true;
2224 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002225}
Chris Lattner53c39ba2010-02-14 22:22:58 +00002226
Evan Cheng49bad4c2008-06-16 20:29:38 +00002227/// isCommutativeIntrinsic - Return true if the node corresponds to a
2228/// commutative intrinsic.
2229bool
2230TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2231 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2232 return Int->isCommutative;
2233 return false;
2234}
2235
Florian Hahn6b1db822018-06-14 20:32:58 +00002236static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2237 if (!N->isLeaf())
2238 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00002239
Florian Hahn6b1db822018-06-14 20:32:58 +00002240 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
Matt Arsenaulteb492162014-11-02 23:46:51 +00002241 if (DI && DI->getDef()->isSubClassOf(Class))
2242 return true;
2243
2244 return false;
2245}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002246
2247static void emitTooManyOperandsError(TreePattern &TP,
2248 StringRef InstName,
2249 unsigned Expected,
2250 unsigned Actual) {
2251 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2252 " operands but expected only " + Twine(Expected) + "!");
2253}
2254
2255static void emitTooFewOperandsError(TreePattern &TP,
2256 StringRef InstName,
2257 unsigned Actual) {
2258 TP.error("Instruction '" + InstName +
2259 "' expects more than the provided " + Twine(Actual) + " operands!");
2260}
2261
Bob Wilson1b97f3f2009-01-05 17:23:09 +00002262/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00002263/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002264/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00002265bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002266 if (TP.hasError())
2267 return false;
2268
Chris Lattnerab3242f2008-01-06 01:10:31 +00002269 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00002270 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002271 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002272 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00002273 bool MadeChange = false;
2274 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2275 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002276 NotRegisters,
2277 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002278 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00002279 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002280
Sean Silvafb509ed2012-10-10 20:24:43 +00002281 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002282 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002283
Chris Lattnerf1447252010-03-19 21:37:09 +00002284 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002285 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002286
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002287 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00002288 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002289
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002290 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2291 for (auto &P : VVT) {
2292 MVT::SimpleValueType VT = P.second.SimpleTy;
2293 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2294 continue;
2295 unsigned Size = MVT(VT).getSizeInBits();
2296 // Make sure that the value is representable for this type.
2297 if (Size >= 32)
2298 continue;
2299 // Check that the value doesn't use more bits than we have. It must
2300 // either be a sign- or zero-extended equivalent of the original.
2301 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2302 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2303 SignBitAndAbove == 1)
2304 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002305
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002306 TP.error("Integer value '" + Twine(II->getValue()) +
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002307 "' is out of range for type '" + getEnumName(VT) + "'!");
2308 break;
2309 }
2310 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002311 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002312
Chris Lattner8cab0212008-01-05 22:25:12 +00002313 return false;
2314 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002315
Chris Lattneree820ac2010-02-23 05:51:07 +00002316 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002317 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00002318
Chris Lattner8cab0212008-01-05 22:25:12 +00002319 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00002320 unsigned NumRetVTs = Int->IS.RetVTs.size();
2321 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002322
Bill Wendling91821472008-11-13 09:08:33 +00002323 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00002324 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00002325
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002326 if (getNumChildren() != NumParamVTs + 1) {
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002327 TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2328 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002329 return false;
2330 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002331
2332 // Apply type info to the intrinsic ID.
Florian Hahn6b1db822018-06-14 20:32:58 +00002333 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002334
Chris Lattnerf1447252010-03-19 21:37:09 +00002335 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002336 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002337
Chris Lattnerf1447252010-03-19 21:37:09 +00002338 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
Florian Hahn6b1db822018-06-14 20:32:58 +00002339 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2340 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002341 }
2342 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002343 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002344
Chris Lattneree820ac2010-02-23 05:51:07 +00002345 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002346 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002347
Chris Lattner135091b2010-03-28 08:48:47 +00002348 // Check that the number of operands is sane. Negative operands -> varargs.
2349 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002350 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00002351 TP.error(getOperator()->getName() + " node requires exactly " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002352 Twine(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002353 return false;
2354 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002355
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002356 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00002357 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002358 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2359 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002360 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002361 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002362
Chris Lattneree820ac2010-02-23 05:51:07 +00002363 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002364 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002365 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00002366 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002367
Chris Lattnerd44966f2010-03-27 19:15:02 +00002368 bool MadeChange = false;
2369
2370 // Apply the result types to the node, these come from the things in the
2371 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00002372 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2373 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002374 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2375 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002376
Chris Lattnerd44966f2010-03-27 19:15:02 +00002377 // If the instruction has implicit defs, we apply the first one as a result.
2378 // FIXME: This sucks, it should apply all implicit defs.
2379 if (!InstInfo.ImplicitDefs.empty()) {
2380 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002381
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002382 // FIXME: Generalize to multiple possible types and multiple possible
2383 // ImplicitDefs.
2384 MVT::SimpleValueType VT =
2385 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002386
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002387 if (VT != MVT::Other)
2388 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002389 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002390
Chris Lattnercabe0372010-03-15 06:00:16 +00002391 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2392 // be the same.
2393 if (getOperator()->getName() == "INSERT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00002394 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2395 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2396 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002397 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2398 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2399 // variadic.
2400
2401 unsigned NChild = getNumChildren();
2402 if (NChild < 3) {
2403 TP.error("REG_SEQUENCE requires at least 3 operands!");
2404 return false;
2405 }
2406
2407 if (NChild % 2 == 0) {
2408 TP.error("REG_SEQUENCE requires an odd number of operands!");
2409 return false;
2410 }
2411
2412 if (!isOperandClass(getChild(0), "RegisterClass")) {
2413 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2414 return false;
2415 }
2416
2417 for (unsigned I = 1; I < NChild; I += 2) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002418 TreePatternNode *SubIdxChild = getChild(I + 1);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002419 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2420 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002421 Twine(I + 1) + "!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00002422 return false;
2423 }
2424 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002425 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002426
2427 unsigned ChildNo = 0;
2428 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2429 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002430
Chris Lattner8cab0212008-01-05 22:25:12 +00002431 // If the instruction expects a predicate or optional def operand, we
2432 // codegen this by setting the operand to it's default value if it has a
2433 // non-empty DefaultOps field.
Tom Stellardb7246a72012-09-06 14:15:52 +00002434 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002435 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2436 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002437
Chris Lattner8cab0212008-01-05 22:25:12 +00002438 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002439 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002440 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002441 return false;
2442 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002443
Florian Hahn6b1db822018-06-14 20:32:58 +00002444 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002445 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002446
2447 // If the operand has sub-operands, they may be provided by distinct
2448 // child patterns, so attempt to match each sub-operand separately.
2449 if (OperandNode->isSubClassOf("Operand")) {
2450 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2451 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2452 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002453 // a single ComplexPattern-related Operand.
2454
2455 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002456 // Match first sub-operand against the child we already have.
2457 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2458 MadeChange |=
2459 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2460
2461 // And the remaining sub-operands against subsequent children.
2462 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2463 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002464 emitTooFewOperandsError(TP, getOperator()->getName(),
2465 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002466 return false;
2467 }
Florian Hahn6b1db822018-06-14 20:32:58 +00002468 Child = getChild(ChildNo++);
Ulrich Weigande618abd2013-03-19 19:51:09 +00002469
2470 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2471 MadeChange |=
2472 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2473 }
2474 continue;
2475 }
2476 }
2477 }
2478
2479 // If we didn't match by pieces above, attempt to match the whole
2480 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002481 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002482 }
Christopher Lamba7312392008-03-11 09:33:47 +00002483
Matt Arsenaulteb492162014-11-02 23:46:51 +00002484 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002485 emitTooManyOperandsError(TP, getOperator()->getName(),
2486 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002487 return false;
2488 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002489
Ulrich Weigande618abd2013-03-19 19:51:09 +00002490 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002491 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002492 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002493 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002494
Tim Northoverc807a172014-05-20 11:52:46 +00002495 if (getOperator()->isSubClassOf("ComplexPattern")) {
2496 bool MadeChange = false;
2497
2498 for (unsigned i = 0; i < getNumChildren(); ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002499 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Tim Northoverc807a172014-05-20 11:52:46 +00002500
2501 return MadeChange;
2502 }
2503
Chris Lattneree820ac2010-02-23 05:51:07 +00002504 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002505
Chris Lattneree820ac2010-02-23 05:51:07 +00002506 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002507 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002508 TP.error("Node transform '" + getOperator()->getName() +
2509 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002510 return false;
2511 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002512
Florian Hahn6b1db822018-06-14 20:32:58 +00002513 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002514 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002515}
2516
2517/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2518/// RHS of a commutative operation, not the on LHS.
Florian Hahn6b1db822018-06-14 20:32:58 +00002519static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2520 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
Chris Lattner8cab0212008-01-05 22:25:12 +00002521 return true;
Florian Hahn6b1db822018-06-14 20:32:58 +00002522 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002523 return true;
2524 return false;
2525}
2526
2527
2528/// canPatternMatch - If it is impossible for this pattern to match on this
2529/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002530/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002531/// that can never possibly work), and to prevent the pattern permuter from
2532/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002533bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002534 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002535 if (isLeaf()) return true;
2536
2537 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002538 if (!getChild(i)->canPatternMatch(Reason, CDP))
Chris Lattner8cab0212008-01-05 22:25:12 +00002539 return false;
2540
2541 // If this is an intrinsic, handle cases that would make it not match. For
2542 // example, if an operand is required to be an immediate.
2543 if (getOperator()->isSubClassOf("Intrinsic")) {
2544 // TODO:
2545 return true;
2546 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002547
Tim Northoverc807a172014-05-20 11:52:46 +00002548 if (getOperator()->isSubClassOf("ComplexPattern"))
2549 return true;
2550
Chris Lattner8cab0212008-01-05 22:25:12 +00002551 // If this node is a commutative operator, check that the LHS isn't an
2552 // immediate.
2553 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002554 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2555 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002556 // Scan all of the operands of the node and make sure that only the last one
2557 // is a constant node, unless the RHS also is.
2558 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002559 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002560 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002561 if (OnlyOnRHSOfCommutative(getChild(i))) {
2562 Reason="Immediate value must be on the RHS of commutative operators!";
2563 return false;
2564 }
2565 }
2566 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002567
Chris Lattner8cab0212008-01-05 22:25:12 +00002568 return true;
2569}
2570
2571//===----------------------------------------------------------------------===//
2572// TreePattern implementation
2573//
2574
David Greeneaf8ee2c2011-07-29 22:43:06 +00002575TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002576 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002577 isInputPattern(isInput), HasError(false),
2578 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002579 for (Init *I : RawPat->getValues())
2580 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002581}
2582
David Greeneaf8ee2c2011-07-29 22:43:06 +00002583TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002584 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002585 isInputPattern(isInput), HasError(false),
2586 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002587 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002588}
2589
Florian Hahn75e87c32018-05-30 21:00:18 +00002590TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
2591 CodeGenDAGPatterns &cdp)
2592 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2593 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002594 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002595}
2596
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002597void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002598 if (HasError)
2599 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002600 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002601 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2602 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002603}
2604
Chris Lattnercabe0372010-03-15 06:00:16 +00002605void TreePattern::ComputeNamedNodes() {
Florian Hahn6b1db822018-06-14 20:32:58 +00002606 for (TreePatternNodePtr &Tree : Trees)
2607 ComputeNamedNodes(Tree.get());
Chris Lattnercabe0372010-03-15 06:00:16 +00002608}
2609
Florian Hahn6b1db822018-06-14 20:32:58 +00002610void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002611 if (!N->getName().empty())
Florian Hahn6b1db822018-06-14 20:32:58 +00002612 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002613
Chris Lattnercabe0372010-03-15 06:00:16 +00002614 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002615 ComputeNamedNodes(N->getChild(i));
Chris Lattnercabe0372010-03-15 06:00:16 +00002616}
2617
Florian Hahn75e87c32018-05-30 21:00:18 +00002618TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
2619 StringRef OpName) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002620 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002621 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002622
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002623 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002624 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002625 /// (foo GPR, imm) -> (foo GPR, (imm))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002626 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
David Greenee32ebf22011-07-29 19:07:07 +00002627 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002628 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002629 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002630 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002631
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002632 // Input argument?
Florian Hahn75e87c32018-05-30 21:00:18 +00002633 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002634 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002635 if (OpName.empty())
2636 error("'node' argument requires a name to match with operand list");
2637 Args.push_back(OpName);
2638 }
2639
2640 Res->setName(OpName);
2641 return Res;
2642 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002643
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002644 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002645 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002646 if (OpName.empty())
2647 error("'?' argument requires a name to match with operand list");
Florian Hahn75e87c32018-05-30 21:00:18 +00002648 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002649 Args.push_back(OpName);
2650 Res->setName(OpName);
2651 return Res;
2652 }
2653
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002654 if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002655 if (!OpName.empty())
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002656 error("Constant int or bit argument should not have a name!");
2657 if (isa<BitInit>(TheInit))
2658 TheInit = TheInit->convertInitializerTo(IntRecTy::get());
2659 return std::make_shared<TreePatternNode>(TheInit, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002660 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002661
Sean Silvafb509ed2012-10-10 20:24:43 +00002662 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002663 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002664 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002665 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002666 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002667 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002668 }
2669
Sean Silvafb509ed2012-10-10 20:24:43 +00002670 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002671 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002672 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002673 error("Pattern has unexpected init kind!");
2674 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002675 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002676 if (!OpDef) error("Pattern has unexpected operator type!");
2677 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002678
Chris Lattner8cab0212008-01-05 22:25:12 +00002679 if (Operator->isSubClassOf("ValueType")) {
2680 // If the operator is a ValueType, then this must be "type cast" of a leaf
2681 // node.
2682 if (Dag->getNumArgs() != 1)
2683 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002684
Florian Hahn75e87c32018-05-30 21:00:18 +00002685 TreePatternNodePtr New =
2686 ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002687
Chris Lattner8cab0212008-01-05 22:25:12 +00002688 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002689 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002690 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2691 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002692
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002693 if (!OpName.empty())
2694 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002695 return New;
2696 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002697
Chris Lattner8cab0212008-01-05 22:25:12 +00002698 // Verify that this is something that makes sense for an operator.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002699 if (!Operator->isSubClassOf("PatFrags") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002700 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002701 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002702 !Operator->isSubClassOf("SDNodeXForm") &&
2703 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002704 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002705 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002706 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002707 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002708
Chris Lattner8cab0212008-01-05 22:25:12 +00002709 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002710 if (isInputPattern) {
2711 if (Operator->isSubClassOf("Instruction") ||
2712 Operator->isSubClassOf("SDNodeXForm"))
2713 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2714 } else {
2715 if (Operator->isSubClassOf("Intrinsic"))
2716 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002717
Chris Lattner2e9eae12010-03-28 06:57:56 +00002718 if (Operator->isSubClassOf("SDNode") &&
2719 Operator->getName() != "imm" &&
2720 Operator->getName() != "fpimm" &&
2721 Operator->getName() != "tglobaltlsaddr" &&
2722 Operator->getName() != "tconstpool" &&
2723 Operator->getName() != "tjumptable" &&
2724 Operator->getName() != "tframeindex" &&
2725 Operator->getName() != "texternalsym" &&
2726 Operator->getName() != "tblockaddress" &&
2727 Operator->getName() != "tglobaladdr" &&
2728 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002729 Operator->getName() != "vt" &&
2730 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002731 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2732 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002733
Florian Hahn75e87c32018-05-30 21:00:18 +00002734 std::vector<TreePatternNodePtr> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002735
2736 // Parse all the operands.
2737 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002738 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002739
Hal Finkel8b4bdfdb2018-01-03 11:35:09 +00002740 // Get the actual number of results before Operator is converted to an intrinsic
2741 // node (which is hard-coded to have either zero or one result).
2742 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2743
Fangrui Song956ee792018-03-30 22:22:31 +00002744 // If the operator is an intrinsic, then this is just syntactic sugar for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002745 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002746 // convert the intrinsic name to a number.
2747 if (Operator->isSubClassOf("Intrinsic")) {
2748 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2749 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2750
2751 // If this intrinsic returns void, it must have side-effects and thus a
2752 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002753 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002754 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002755 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner8cab0212008-01-05 22:25:12 +00002756 // Has side-effects, requires chain.
2757 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002758 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002759 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002760
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002761 Children.insert(Children.begin(),
2762 std::make_shared<TreePatternNode>(IntInit::get(IID), 1));
Chris Lattner8cab0212008-01-05 22:25:12 +00002763 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002764
Tim Northoverc807a172014-05-20 11:52:46 +00002765 if (Operator->isSubClassOf("ComplexPattern")) {
2766 for (unsigned i = 0; i < Children.size(); ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002767 TreePatternNodePtr Child = Children[i];
Tim Northoverc807a172014-05-20 11:52:46 +00002768
2769 if (Child->getName().empty())
2770 error("All arguments to a ComplexPattern must be named");
2771
2772 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2773 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2774 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2775 auto OperandId = std::make_pair(Operator, i);
2776 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2777 if (PrevOp != ComplexPatternOperands.end()) {
2778 if (PrevOp->getValue() != OperandId)
2779 error("All ComplexPattern operands must appear consistently: "
2780 "in the same order in just one ComplexPattern instance.");
2781 } else
2782 ComplexPatternOperands[Child->getName()] = OperandId;
2783 }
2784 }
2785
Florian Hahn6b1db822018-06-14 20:32:58 +00002786 TreePatternNodePtr Result =
Craig Topper26fc06352018-07-15 06:52:49 +00002787 std::make_shared<TreePatternNode>(Operator, std::move(Children),
2788 NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002789 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002790
Matthias Braun7cf3b112016-12-05 06:00:41 +00002791 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002792 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002793 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002794 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002795 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002796}
2797
Chris Lattnera787c9e2010-03-28 08:38:32 +00002798/// SimplifyTree - See if we can simplify this tree to eliminate something that
2799/// will never match in favor of something obvious that will. This is here
2800/// strictly as a convenience to target authors because it allows them to write
2801/// more type generic things and have useless type casts fold away.
2802///
2803/// This returns true if any change is made.
Florian Hahn75e87c32018-05-30 21:00:18 +00002804static bool SimplifyTree(TreePatternNodePtr &N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002805 if (N->isLeaf())
2806 return false;
2807
2808 // If we have a bitconvert with a resolved type and if the source and
2809 // destination types are the same, then the bitconvert is useless, remove it.
2810 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002811 N->getExtType(0).isValueTypeByHwMode(false) &&
Florian Hahn6b1db822018-06-14 20:32:58 +00002812 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002813 N->getName().empty()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002814 N = N->getChildShared(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002815 SimplifyTree(N);
2816 return true;
2817 }
2818
2819 // Walk all children.
2820 bool MadeChange = false;
2821 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002822 TreePatternNodePtr Child = N->getChildShared(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002823 MadeChange |= SimplifyTree(Child);
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002824 N->setChild(i, std::move(Child));
Chris Lattnera787c9e2010-03-28 08:38:32 +00002825 }
2826 return MadeChange;
2827}
2828
2829
2830
Chris Lattner8cab0212008-01-05 22:25:12 +00002831/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002832/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002833/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002834bool TreePattern::
2835InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2836 if (NamedNodes.empty())
2837 ComputeNamedNodes();
2838
Chris Lattner8cab0212008-01-05 22:25:12 +00002839 bool MadeChange = true;
2840 while (MadeChange) {
2841 MadeChange = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002842 for (TreePatternNodePtr &Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002843 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2844 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002845 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002846
2847 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002848 for (auto &Entry : NamedNodes) {
2849 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002850
Chris Lattnercabe0372010-03-15 06:00:16 +00002851 // If we have input named node types, propagate their types to the named
2852 // values here.
2853 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002854 if (!InNamedTypes->count(Entry.getKey())) {
2855 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002856 "' in output pattern but not input pattern");
2857 return true;
2858 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002859
2860 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002861 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002862
2863 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002864 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002865 // If this node is a register class, and it is the root of the pattern
2866 // then we're mapping something onto an input register. We allow
2867 // changing the type of the input register in this case. This allows
2868 // us to match things like:
2869 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Florian Hahn75e87c32018-05-30 21:00:18 +00002870 if (Node == Trees[0].get() && Node->isLeaf()) {
Craig Topper306cb122015-11-22 20:46:24 +00002871 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002872 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2873 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002874 continue;
2875 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002876
Craig Topper306cb122015-11-22 20:46:24 +00002877 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002878 InNodes[0]->getNumTypes() == 1 &&
2879 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002880 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2881 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002882 }
2883 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002884
Chris Lattnercabe0372010-03-15 06:00:16 +00002885 // If there are multiple nodes with the same name, they must all have the
2886 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002887 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002888 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002889 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002890 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002891 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002892
Chris Lattnerf1447252010-03-19 21:37:09 +00002893 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2894 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002895 }
2896 }
2897 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002898 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002899
Chris Lattner8cab0212008-01-05 22:25:12 +00002900 bool HasUnresolvedTypes = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002901 for (const TreePatternNodePtr &Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002902 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002903 return !HasUnresolvedTypes;
2904}
2905
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002906void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002907 OS << getRecord()->getName();
2908 if (!Args.empty()) {
2909 OS << "(" << Args[0];
2910 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2911 OS << ", " << Args[i];
2912 OS << ")";
2913 }
2914 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00002915
Chris Lattner8cab0212008-01-05 22:25:12 +00002916 if (Trees.size() > 1)
2917 OS << "[\n";
Florian Hahn75e87c32018-05-30 21:00:18 +00002918 for (const TreePatternNodePtr &Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002919 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00002920 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00002921 OS << "\n";
2922 }
2923
2924 if (Trees.size() > 1)
2925 OS << "]\n";
2926}
2927
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002928void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00002929
2930//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00002931// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00002932//
2933
Daniel Sanders7e523672017-11-11 03:23:44 +00002934CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
2935 PatternRewriterFn PatternRewriter)
2936 : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
2937 PatternRewriter(PatternRewriter) {
Chris Lattner77d369c2010-12-13 00:23:57 +00002938
Justin Bogner92a8c612016-07-15 16:31:37 +00002939 Intrinsics = CodeGenIntrinsicTable(Records, false);
2940 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002941 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00002942 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00002943 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00002944 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00002945 ParseDefaultOperands();
2946 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00002947 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00002948 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002949
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002950 // Break patterns with parameterized types into a series of patterns,
2951 // where each one has a fixed type and is predicated on the conditions
2952 // of the associated HW mode.
2953 ExpandHwModeBasedTypes();
2954
Chris Lattner8cab0212008-01-05 22:25:12 +00002955 // Generate variants. For example, commutative patterns can match
2956 // multiple ways. Add them to PatternsToMatch as well.
2957 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002958
2959 // Infer instruction flags. For example, we can detect loads,
2960 // stores, and side effects in many cases by examining an
2961 // instruction's pattern.
2962 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00002963
2964 // Verify that instruction flags match the patterns.
2965 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00002966}
2967
Daniel Sanders9e0ae7b2017-10-13 19:00:01 +00002968Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002969 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00002970 if (!N || !N->isSubClassOf("SDNode"))
2971 PrintFatalError("Error getting SDNode '" + Name + "'!");
2972
Chris Lattner8cab0212008-01-05 22:25:12 +00002973 return N;
2974}
2975
2976// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002977void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002978 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002979 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2980
Chris Lattner8cab0212008-01-05 22:25:12 +00002981 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002982 Record *R = Nodes.back();
2983 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00002984 Nodes.pop_back();
2985 }
2986
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002987 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00002988 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2989 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2990 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2991}
2992
2993/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2994/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00002995void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00002996 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2997 while (!Xforms.empty()) {
2998 Record *XFormNode = Xforms.back();
2999 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00003000 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00003001 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00003002
3003 Xforms.pop_back();
3004 }
3005}
3006
Chris Lattnerab3242f2008-01-06 01:10:31 +00003007void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003008 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
3009 while (!AMs.empty()) {
3010 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
3011 AMs.pop_back();
3012 }
3013}
3014
3015
3016/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3017/// file, building up the PatternFragments map. After we've collected them all,
3018/// inline fragments together as necessary, so that there are no references left
3019/// inside a pattern fragment to a pattern fragment.
3020///
Hal Finkel2756dc12014-02-28 00:26:56 +00003021void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003022 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrags");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003023
Chris Lattnere7170df2008-01-05 22:43:57 +00003024 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00003025 for (Record *Frag : Fragments) {
3026 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00003027 continue;
3028
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003029 ListInit *LI = Frag->getValueAsListInit("Fragments");
Hal Finkel2756dc12014-02-28 00:26:56 +00003030 TreePattern *P =
Craig Topper306cb122015-11-22 20:46:24 +00003031 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003032 Frag, LI, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00003033 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003034
Chris Lattnere7170df2008-01-05 22:43:57 +00003035 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00003036 std::vector<std::string> &Args = P->getArgList();
Zachary Turner249dc142017-09-20 18:01:40 +00003037 // Copy the args so we can take StringRefs to them.
3038 auto ArgsCopy = Args;
3039 SmallDenseSet<StringRef, 4> OperandsSet;
3040 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003041
Chris Lattnere7170df2008-01-05 22:43:57 +00003042 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00003043 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003044
Chris Lattner8cab0212008-01-05 22:25:12 +00003045 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00003046 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00003047 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00003048 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003049 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00003050 if (!OpsOp ||
3051 (OpsOp->getDef()->getName() != "ops" &&
3052 OpsOp->getDef()->getName() != "outs" &&
3053 OpsOp->getDef()->getName() != "ins"))
3054 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003055
3056 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00003057 Args.clear();
3058 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003059 if (!isa<DefInit>(OpsList->getArg(j)) ||
3060 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00003061 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00003062 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00003063 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00003064 StringRef ArgNameStr = OpsList->getArgNameStr(j);
3065 if (!OperandsSet.count(ArgNameStr))
3066 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00003067 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00003068 OperandsSet.erase(ArgNameStr);
3069 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003070 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003071
Chris Lattnere7170df2008-01-05 22:43:57 +00003072 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003073 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00003074 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003075
Chris Lattner8cab0212008-01-05 22:25:12 +00003076 // If there is a node transformation corresponding to this, keep track of
3077 // it.
Craig Topper306cb122015-11-22 20:46:24 +00003078 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00003079 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003080 for (auto T : P->getTrees())
3081 T->setTransformFn(Transform);
Chris Lattner8cab0212008-01-05 22:25:12 +00003082 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003083
Chris Lattner8cab0212008-01-05 22:25:12 +00003084 // Now that we've parsed all of the tree fragments, do a closure on them so
3085 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00003086 for (Record *Frag : Fragments) {
3087 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00003088 continue;
3089
Craig Topper306cb122015-11-22 20:46:24 +00003090 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00003091 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003092
Chris Lattner8cab0212008-01-05 22:25:12 +00003093 // Infer as many types as possible. Don't worry about it if we don't infer
Ulrich Weigand22b1af82018-07-13 16:42:15 +00003094 // all of them, some may depend on the inputs of the pattern. Also, don't
3095 // validate type sets; validation may cause spurious failures e.g. if a
3096 // fragment needs floating-point types but the current target does not have
3097 // any (this is only an error if that fragment is ever used!).
3098 {
3099 TypeInfer::SuppressValidation SV(ThePat.getInfer());
3100 ThePat.InferAllTypes();
3101 ThePat.resetError();
3102 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003103
Chris Lattner8cab0212008-01-05 22:25:12 +00003104 // If debugging, print out the pattern fragment result.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003105 LLVM_DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003106 }
3107}
3108
Chris Lattnerab3242f2008-01-06 01:10:31 +00003109void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00003110 std::vector<Record*> DefaultOps;
3111 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00003112
3113 // Find some SDNode.
3114 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00003115 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003116
Tom Stellardb7246a72012-09-06 14:15:52 +00003117 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3118 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003119
Tom Stellardb7246a72012-09-06 14:15:52 +00003120 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3121 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00003122 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00003123 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3124 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3125 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00003126 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003127
Tom Stellardb7246a72012-09-06 14:15:52 +00003128 // Create a TreePattern to parse this.
3129 TreePattern P(DefaultOps[i], DI, false, *this);
3130 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003131
Tom Stellardb7246a72012-09-06 14:15:52 +00003132 // Copy the operands over into a DAGDefaultOperand.
3133 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003134
Florian Hahn75e87c32018-05-30 21:00:18 +00003135 const TreePatternNodePtr &T = P.getTree(0);
Tom Stellardb7246a72012-09-06 14:15:52 +00003136 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
Florian Hahn75e87c32018-05-30 21:00:18 +00003137 TreePatternNodePtr TPN = T->getChildShared(op);
Tom Stellardb7246a72012-09-06 14:15:52 +00003138 while (TPN->ApplyTypeConstraints(P, false))
3139 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003140
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003141 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00003142 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3143 DefaultOps[i]->getName() +
3144 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003145 }
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003146 DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
Chris Lattner8cab0212008-01-05 22:25:12 +00003147 }
Tom Stellardb7246a72012-09-06 14:15:52 +00003148
3149 // Insert it into the DefaultOperands map so we can find it later.
3150 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00003151 }
3152}
3153
3154/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3155/// instruction input. Return true if this is a real use.
David Blaikie19b22d42018-06-11 22:14:43 +00003156static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003157 std::map<std::string, TreePatternNodePtr> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003158 // No name -> not interesting.
3159 if (Pat->getName().empty()) {
3160 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003161 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00003162 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3163 DI->getDef()->isSubClassOf("RegisterOperand")))
David Blaikie19b22d42018-06-11 22:14:43 +00003164 I.error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003165 }
3166 return false;
3167 }
3168
3169 Record *Rec;
3170 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003171 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
David Blaikie19b22d42018-06-11 22:14:43 +00003172 if (!DI)
3173 I.error("Input $" + Pat->getName() + " must be an identifier!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003174 Rec = DI->getDef();
3175 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00003176 Rec = Pat->getOperator();
3177 }
3178
3179 // SRCVALUE nodes are ignored.
3180 if (Rec->getName() == "srcvalue")
3181 return false;
3182
Florian Hahn75e87c32018-05-30 21:00:18 +00003183 TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
Chris Lattner8cab0212008-01-05 22:25:12 +00003184 if (!Slot) {
3185 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003186 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00003187 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003188 Record *SlotRec;
3189 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003190 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003191 } else {
3192 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3193 SlotRec = Slot->getOperator();
3194 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003195
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003196 // Ensure that the inputs agree if we've already seen this input.
3197 if (Rec != SlotRec)
David Blaikie19b22d42018-06-11 22:14:43 +00003198 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003199 // Ensure that the types can agree as well.
3200 Slot->UpdateNodeType(0, Pat->getExtType(0), I);
3201 Pat->UpdateNodeType(0, Slot->getExtType(0), I);
Chris Lattnerf1447252010-03-19 21:37:09 +00003202 if (Slot->getExtTypes() != Pat->getExtTypes())
David Blaikie19b22d42018-06-11 22:14:43 +00003203 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00003204 return true;
3205}
3206
3207/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3208/// part of "I", the instruction), computing the set of inputs and outputs of
3209/// the pattern. Report errors if we see anything naughty.
Florian Hahn75e87c32018-05-30 21:00:18 +00003210void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
Florian Hahn6b1db822018-06-14 20:32:58 +00003211 TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003212 std::map<std::string, TreePatternNodePtr> &InstInputs,
Craig Topperbd199f82018-12-05 00:47:59 +00003213 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3214 &InstResults,
Florian Hahn75e87c32018-05-30 21:00:18 +00003215 std::vector<Record *> &InstImpResults) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003216
3217 // The instruction pattern still has unresolved fragments. For *named*
3218 // nodes we must resolve those here. This may not result in multiple
3219 // alternatives.
3220 if (!Pat->getName().empty()) {
3221 TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3222 SrcPattern.InlinePatternFragments();
3223 SrcPattern.InferAllTypes();
3224 Pat = SrcPattern.getOnlyTree();
3225 }
3226
Chris Lattner8cab0212008-01-05 22:25:12 +00003227 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00003228 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00003229 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003230 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003231 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003232 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003233
Chris Lattnerf2d70992010-02-17 06:53:36 +00003234 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003235 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003236 TreePatternNode *Dest = Pat->getChild(i);
3237 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003238 I.error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003239
Florian Hahn6b1db822018-06-14 20:32:58 +00003240 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00003241 if (!Val || !Val->getDef()->isSubClassOf("Register"))
David Blaikie19b22d42018-06-11 22:14:43 +00003242 I.error("implicitly defined value should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003243 InstImpResults.push_back(Val->getDef());
3244 }
3245 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003246 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003247
Chris Lattnerf2d70992010-02-17 06:53:36 +00003248 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003249 // If this is not a set, verify that the children nodes are not void typed,
3250 // and recurse.
3251 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003252 if (Pat->getChild(i)->getNumTypes() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003253 I.error("Cannot have void nodes inside of patterns!");
Florian Hahn75e87c32018-05-30 21:00:18 +00003254 FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3255 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003256 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003257
Chris Lattner8cab0212008-01-05 22:25:12 +00003258 // If this is a non-leaf node with no children, treat it basically as if
3259 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00003260 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003261
Chris Lattner8cab0212008-01-05 22:25:12 +00003262 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003263 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003264 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003265 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003266
Chris Lattner8cab0212008-01-05 22:25:12 +00003267 // Otherwise, this is a set, validate and collect instruction results.
3268 if (Pat->getNumChildren() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003269 I.error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003270
Chris Lattner8cab0212008-01-05 22:25:12 +00003271 if (Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003272 I.error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003273
Chris Lattner8cab0212008-01-05 22:25:12 +00003274 // Check the set destinations.
3275 unsigned NumDests = Pat->getNumChildren()-1;
3276 for (unsigned i = 0; i != NumDests; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003277 TreePatternNodePtr Dest = Pat->getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003278 // For set destinations we also must resolve fragments here.
3279 TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3280 DestPattern.InlinePatternFragments();
3281 DestPattern.InferAllTypes();
3282 Dest = DestPattern.getOnlyTree();
3283
Chris Lattner8cab0212008-01-05 22:25:12 +00003284 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003285 I.error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003286
Sean Silvafb509ed2012-10-10 20:24:43 +00003287 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00003288 if (!Val) {
David Blaikie19b22d42018-06-11 22:14:43 +00003289 I.error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00003290 continue;
3291 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003292
3293 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003294 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00003295 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00003296 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003297 if (Dest->getName().empty())
David Blaikie19b22d42018-06-11 22:14:43 +00003298 I.error("set destination must have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003299 if (InstResults.count(Dest->getName()))
David Blaikie19b22d42018-06-11 22:14:43 +00003300 I.error("cannot set '" + Dest->getName() + "' multiple times");
Chris Lattner8cab0212008-01-05 22:25:12 +00003301 InstResults[Dest->getName()] = Dest;
3302 } else if (Val->getDef()->isSubClassOf("Register")) {
3303 InstImpResults.push_back(Val->getDef());
3304 } else {
David Blaikie19b22d42018-06-11 22:14:43 +00003305 I.error("set destination should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003306 }
3307 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003308
Chris Lattner8cab0212008-01-05 22:25:12 +00003309 // Verify and collect info from the computation.
Florian Hahn75e87c32018-05-30 21:00:18 +00003310 FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3311 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003312}
3313
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003314//===----------------------------------------------------------------------===//
3315// Instruction Analysis
3316//===----------------------------------------------------------------------===//
3317
3318class InstAnalyzer {
3319 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003320public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003321 bool hasSideEffects;
3322 bool mayStore;
3323 bool mayLoad;
3324 bool isBitcast;
3325 bool isVariadic;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003326 bool hasChain;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003327
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003328 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3329 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003330 isBitcast(false), isVariadic(false), hasChain(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003331
Craig Topper2a053a92017-06-20 16:34:37 +00003332 void Analyze(const PatternToMatch &Pat) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003333 const TreePatternNode *N = Pat.getSrcPattern();
3334 AnalyzeNode(N);
3335 // These properties are detected only on the root node.
3336 isBitcast = IsNodeBitcast(N);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003337 }
3338
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003339private:
Florian Hahn6b1db822018-06-14 20:32:58 +00003340 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003341 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00003342 return false;
3343
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003344 if (N->isLeaf())
3345 return false;
3346 if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
Evan Cheng880e299d2011-03-15 05:09:26 +00003347 return false;
3348
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003349 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
Evan Cheng880e299d2011-03-15 05:09:26 +00003350 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3351 return false;
3352 return OpInfo.getEnumName() == "ISD::BITCAST";
3353 }
3354
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003355public:
Florian Hahn6b1db822018-06-14 20:32:58 +00003356 void AnalyzeNode(const TreePatternNode *N) {
3357 if (N->isLeaf()) {
3358 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003359 Record *LeafRec = DI->getDef();
3360 // Handle ComplexPattern leaves.
3361 if (LeafRec->isSubClassOf("ComplexPattern")) {
3362 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3363 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3364 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003365 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003366 }
3367 }
3368 return;
3369 }
3370
3371 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00003372 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3373 AnalyzeNode(N->getChild(i));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003374
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003375 // Notice properties of the node.
Florian Hahn6b1db822018-06-14 20:32:58 +00003376 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3377 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3378 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3379 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003380 if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003381
Florian Hahn6b1db822018-06-14 20:32:58 +00003382 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003383 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003384 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003385 mayLoad = true;// These may load memory.
3386
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003387 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003388 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3389
Matt Arsenault868af922017-04-28 21:01:46 +00003390 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3391 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003392 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003393 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003394 }
3395 }
3396
3397};
3398
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003399static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003400 const InstAnalyzer &PatInfo,
3401 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003402 bool Error = false;
3403
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003404 // Remember where InstInfo got its flags.
3405 if (InstInfo.hasUndefFlags())
3406 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003407
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003408 // Check explicitly set flags for consistency.
3409 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3410 !InstInfo.hasSideEffects_Unset) {
3411 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3412 // the pattern has no side effects. That could be useful for div/rem
3413 // instructions that may trap.
3414 if (!InstInfo.hasSideEffects) {
3415 Error = true;
3416 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3417 Twine(InstInfo.hasSideEffects));
3418 }
3419 }
3420
3421 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3422 Error = true;
3423 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3424 Twine(InstInfo.mayStore));
3425 }
3426
3427 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3428 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003429 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003430 if (!InstInfo.mayLoad) {
3431 Error = true;
3432 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3433 Twine(InstInfo.mayLoad));
3434 }
3435 }
3436
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003437 // Transfer inferred flags.
3438 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3439 InstInfo.mayStore |= PatInfo.mayStore;
3440 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003441
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003442 // These flags are silently added without any verification.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003443 // FIXME: To match historical behavior of TableGen, for now add those flags
3444 // only when we're inferring from the primary instruction pattern.
3445 if (PatDef->isSubClassOf("Instruction")) {
3446 InstInfo.isBitcast |= PatInfo.isBitcast;
3447 InstInfo.hasChain |= PatInfo.hasChain;
3448 InstInfo.hasChain_Inferred = true;
3449 }
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003450
3451 // Don't infer isVariadic. This flag means something different on SDNodes and
3452 // instructions. For example, a CALL SDNode is variadic because it has the
3453 // call arguments as operands, but a CALL instruction is not variadic - it
3454 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003455
3456 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003457}
3458
Jim Grosbach514410b2012-07-17 00:47:06 +00003459/// hasNullFragReference - Return true if the DAG has any reference to the
3460/// null_frag operator.
3461static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003462 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003463 if (!OpDef) return false;
3464 Record *Operator = OpDef->getDef();
3465
3466 // If this is the null fragment, return true.
3467 if (Operator->getName() == "null_frag") return true;
3468 // If any of the arguments reference the null fragment, return true.
3469 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003470 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003471 if (Arg && hasNullFragReference(Arg))
3472 return true;
3473 }
3474
3475 return false;
3476}
3477
3478/// hasNullFragReference - Return true if any DAG in the list references
3479/// the null_frag operator.
3480static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003481 for (Init *I : LI->getValues()) {
3482 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003483 assert(DI && "non-dag in an instruction Pattern list?!");
3484 if (hasNullFragReference(DI))
3485 return true;
3486 }
3487 return false;
3488}
3489
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003490/// Get all the instructions in a tree.
3491static void
Florian Hahn6b1db822018-06-14 20:32:58 +00003492getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3493 if (Tree->isLeaf())
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003494 return;
Florian Hahn6b1db822018-06-14 20:32:58 +00003495 if (Tree->getOperator()->isSubClassOf("Instruction"))
3496 Instrs.push_back(Tree->getOperator());
3497 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3498 getInstructionsInTree(Tree->getChild(i), Instrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003499}
3500
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003501/// Check the class of a pattern leaf node against the instruction operand it
3502/// represents.
3503static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3504 Record *Leaf) {
3505 if (OI.Rec == Leaf)
3506 return true;
3507
3508 // Allow direct value types to be used in instruction set patterns.
3509 // The type will be checked later.
3510 if (Leaf->isSubClassOf("ValueType"))
3511 return true;
3512
3513 // Patterns can also be ComplexPattern instances.
3514 if (Leaf->isSubClassOf("ComplexPattern"))
3515 return true;
3516
3517 return false;
3518}
3519
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003520void CodeGenDAGPatterns::parseInstructionPattern(
Ahmed Bougacha14107512013-10-28 18:07:21 +00003521 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003522
Craig Topper0d1fb902015-03-10 03:25:04 +00003523 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003524
Craig Topper0d1fb902015-03-10 03:25:04 +00003525 // Parse the instruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003526 TreePattern I(CGI.TheDef, Pat, true, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003527
Craig Topper0d1fb902015-03-10 03:25:04 +00003528 // InstInputs - Keep track of all of the inputs of the instruction, along
3529 // with the record they are declared as.
Florian Hahn75e87c32018-05-30 21:00:18 +00003530 std::map<std::string, TreePatternNodePtr> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003531
Craig Topper0d1fb902015-03-10 03:25:04 +00003532 // InstResults - Keep track of all the virtual registers that are 'set'
3533 // in the instruction, including what reg class they are.
Craig Topperbd199f82018-12-05 00:47:59 +00003534 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3535 InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003536
Craig Topper0d1fb902015-03-10 03:25:04 +00003537 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003538
Craig Topper0d1fb902015-03-10 03:25:04 +00003539 // Verify that the top-level forms in the instruction are of void type, and
3540 // fill in the InstResults map.
Zachary Turner249dc142017-09-20 18:01:40 +00003541 SmallString<32> TypesString;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003542 for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
Zachary Turner249dc142017-09-20 18:01:40 +00003543 TypesString.clear();
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003544 TreePatternNodePtr Pat = I.getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003545 if (Pat->getNumTypes() != 0) {
Zachary Turner249dc142017-09-20 18:01:40 +00003546 raw_svector_ostream OS(TypesString);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003547 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3548 if (k > 0)
Zachary Turner249dc142017-09-20 18:01:40 +00003549 OS << ", ";
3550 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003551 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003552 I.error("Top-level forms in instruction pattern should have"
Zachary Turner249dc142017-09-20 18:01:40 +00003553 " void types, has types " +
3554 OS.str());
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003555 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003556
Craig Topper0d1fb902015-03-10 03:25:04 +00003557 // Find inputs and outputs, and verify the structure of the uses/defs.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003558 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Craig Topper0d1fb902015-03-10 03:25:04 +00003559 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003560 }
3561
Craig Topper0d1fb902015-03-10 03:25:04 +00003562 // Now that we have inputs and outputs of the pattern, inspect the operands
3563 // list for the instruction. This determines the order that operands are
3564 // added to the machine instruction the node corresponds to.
3565 unsigned NumResults = InstResults.size();
3566
3567 // Parse the operands list from the (ops) list, validating it.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003568 assert(I.getArgList().empty() && "Args list should still be empty here!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003569
3570 // Check that all of the results occur first in the list.
3571 std::vector<Record*> Results;
Craig Topperbd199f82018-12-05 00:47:59 +00003572 std::vector<unsigned> ResultIndices;
Florian Hahn75e87c32018-05-30 21:00:18 +00003573 SmallVector<TreePatternNodePtr, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003574 for (unsigned i = 0; i != NumResults; ++i) {
Craig Topperbd199f82018-12-05 00:47:59 +00003575 if (i == CGI.Operands.size()) {
3576 const std::string &OpName =
3577 std::find_if(InstResults.begin(), InstResults.end(),
3578 [](const std::pair<std::string, TreePatternNodePtr> &P) {
3579 return P.second;
3580 })
3581 ->first;
3582
3583 I.error("'" + OpName + "' set but does not appear in operand list!");
3584 }
3585
Craig Topper0d1fb902015-03-10 03:25:04 +00003586 const std::string &OpName = CGI.Operands[i].Name;
3587
3588 // Check that it exists in InstResults.
Craig Topperbd199f82018-12-05 00:47:59 +00003589 auto InstResultIter = InstResults.find(OpName);
3590 if (InstResultIter == InstResults.end() || !InstResultIter->second)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003591 I.error("Operand $" + OpName + " does not exist in operand list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003592
Craig Topperbd199f82018-12-05 00:47:59 +00003593 TreePatternNodePtr RNode = InstResultIter->second;
Craig Topper0d1fb902015-03-10 03:25:04 +00003594 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003595 ResNodes.push_back(std::move(RNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003596 if (!R)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003597 I.error("Operand $" + OpName + " should be a set destination: all "
Craig Topper0d1fb902015-03-10 03:25:04 +00003598 "outputs must occur before inputs in operand list!");
3599
3600 if (!checkOperandClass(CGI.Operands[i], R))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003601 I.error("Operand $" + OpName + " class mismatch!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003602
3603 // Remember the return type.
3604 Results.push_back(CGI.Operands[i].Rec);
3605
Craig Topperbd199f82018-12-05 00:47:59 +00003606 // Remember the result index.
3607 ResultIndices.push_back(std::distance(InstResults.begin(), InstResultIter));
3608
Craig Topper0d1fb902015-03-10 03:25:04 +00003609 // Okay, this one checks out.
Craig Topperbd199f82018-12-05 00:47:59 +00003610 InstResultIter->second = nullptr;
Craig Topper0d1fb902015-03-10 03:25:04 +00003611 }
3612
Craig Topper765b9202018-07-15 06:52:48 +00003613 // Loop over the inputs next.
Florian Hahn75e87c32018-05-30 21:00:18 +00003614 std::vector<TreePatternNodePtr> ResultNodeOperands;
Craig Topper0d1fb902015-03-10 03:25:04 +00003615 std::vector<Record*> Operands;
3616 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3617 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3618 const std::string &OpName = Op.Name;
3619 if (OpName.empty())
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003620 I.error("Operand #" + Twine(i) + " in operands list has no name!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003621
Craig Topper765b9202018-07-15 06:52:48 +00003622 if (!InstInputs.count(OpName)) {
Craig Topper0d1fb902015-03-10 03:25:04 +00003623 // If this is an operand with a DefaultOps set filled in, we can ignore
3624 // this. When we codegen it, we will do so as always executed.
3625 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3626 // Does it have a non-empty DefaultOps field? If so, ignore this
3627 // operand.
3628 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3629 continue;
3630 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003631 I.error("Operand $" + OpName +
Craig Topper0d1fb902015-03-10 03:25:04 +00003632 " does not appear in the instruction pattern");
3633 }
Craig Topper765b9202018-07-15 06:52:48 +00003634 TreePatternNodePtr InVal = InstInputs[OpName];
3635 InstInputs.erase(OpName); // It occurred, remove from map.
Craig Topper0d1fb902015-03-10 03:25:04 +00003636
3637 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3638 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3639 if (!checkOperandClass(Op, InRec))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003640 I.error("Operand $" + OpName + "'s register class disagrees"
Craig Topper0d1fb902015-03-10 03:25:04 +00003641 " between the operand and pattern");
3642 }
3643 Operands.push_back(Op.Rec);
3644
3645 // Construct the result for the dest-pattern operand list.
Florian Hahn75e87c32018-05-30 21:00:18 +00003646 TreePatternNodePtr OpNode = InVal->clone();
Craig Topper0d1fb902015-03-10 03:25:04 +00003647
3648 // No predicate is useful on the result.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003649 OpNode->clearPredicateCalls();
Craig Topper0d1fb902015-03-10 03:25:04 +00003650
3651 // Promote the xform function to be an explicit node if set.
3652 if (Record *Xform = OpNode->getTransformFn()) {
3653 OpNode->setTransformFn(nullptr);
Florian Hahn75e87c32018-05-30 21:00:18 +00003654 std::vector<TreePatternNodePtr> Children;
Craig Topper0d1fb902015-03-10 03:25:04 +00003655 Children.push_back(OpNode);
Craig Topper26fc06352018-07-15 06:52:49 +00003656 OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
Florian Hahn6b1db822018-06-14 20:32:58 +00003657 OpNode->getNumTypes());
Craig Topper0d1fb902015-03-10 03:25:04 +00003658 }
3659
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003660 ResultNodeOperands.push_back(std::move(OpNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003661 }
3662
Craig Topper765b9202018-07-15 06:52:48 +00003663 if (!InstInputs.empty())
3664 I.error("Input operand $" + InstInputs.begin()->first +
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003665 " occurs in pattern but not in operands list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003666
Florian Hahn6b1db822018-06-14 20:32:58 +00003667 TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00003668 I.getRecord(), std::move(ResultNodeOperands),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003669 GetNumNodeResults(I.getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003670 // Copy fully inferred output node types to instruction result pattern.
3671 for (unsigned i = 0; i != NumResults; ++i) {
3672 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3673 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
Craig Topperbd199f82018-12-05 00:47:59 +00003674 ResultPattern->setResultIndex(i, ResultIndices[i]);
Craig Topper3a8eb892015-03-20 05:09:06 +00003675 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003676
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003677 // FIXME: Assume only the first tree is the pattern. The others are clobber
3678 // nodes.
3679 TreePatternNodePtr Pattern = I.getTree(0);
3680 TreePatternNodePtr SrcPattern;
3681 if (Pattern->getOperator()->getName() == "set") {
3682 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3683 } else{
3684 // Not a set (store or something?)
3685 SrcPattern = Pattern;
3686 }
3687
Craig Topper0d1fb902015-03-10 03:25:04 +00003688 // Create and insert the instruction.
3689 // FIXME: InstImpResults should not be part of DAGInstruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003690 Record *R = I.getRecord();
3691 DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
3692 std::forward_as_tuple(Results, Operands, InstImpResults,
3693 SrcPattern, ResultPattern));
Craig Topper0d1fb902015-03-10 03:25:04 +00003694
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003695 LLVM_DEBUG(I.dump());
Craig Topper0d1fb902015-03-10 03:25:04 +00003696}
3697
Ahmed Bougacha14107512013-10-28 18:07:21 +00003698/// ParseInstructions - Parse all of the instructions, inlining and resolving
3699/// any fragments involved. This populates the Instructions list with fully
3700/// resolved instructions.
3701void CodeGenDAGPatterns::ParseInstructions() {
3702 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3703
Craig Topper306cb122015-11-22 20:46:24 +00003704 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003705 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003706
Craig Topper306cb122015-11-22 20:46:24 +00003707 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3708 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003709
3710 // If there is no pattern, only collect minimal information about the
3711 // instruction for its operand list. We have to assume that there is one
3712 // result, as we have no detailed info. A pattern which references the
3713 // null_frag operator is as-if no pattern were specified. Normally this
3714 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3715 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003716 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003717 std::vector<Record*> Results;
3718 std::vector<Record*> Operands;
3719
Craig Topper306cb122015-11-22 20:46:24 +00003720 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003721
3722 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003723 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3724 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003725
Craig Topper3a8eb892015-03-20 05:09:06 +00003726 // The rest are inputs.
3727 for (unsigned j = InstInfo.Operands.NumDefs,
3728 e = InstInfo.Operands.size(); j < e; ++j)
3729 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003730 }
3731
3732 // Create and insert the instruction.
3733 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003734 Instructions.insert(std::make_pair(Instr,
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003735 DAGInstruction(Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003736 continue; // no pattern.
3737 }
3738
Craig Topper306cb122015-11-22 20:46:24 +00003739 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003740 parseInstructionPattern(CGI, LI, Instructions);
Chris Lattner8cab0212008-01-05 22:25:12 +00003741 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003742
Chris Lattner8cab0212008-01-05 22:25:12 +00003743 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003744 for (auto &Entry : Instructions) {
Craig Topper306cb122015-11-22 20:46:24 +00003745 Record *Instr = Entry.first;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003746 DAGInstruction &TheInst = Entry.second;
3747 TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
3748 TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
3749
3750 if (SrcPattern && ResultPattern) {
3751 TreePattern Pattern(Instr, SrcPattern, true, *this);
3752 TreePattern Result(Instr, ResultPattern, false, *this);
3753 ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
3754 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003755 }
3756}
3757
Florian Hahn6b1db822018-06-14 20:32:58 +00003758typedef std::pair<TreePatternNode *, unsigned> NameRecord;
Chris Lattnera7722b62010-02-23 06:55:24 +00003759
Florian Hahn6b1db822018-06-14 20:32:58 +00003760static void FindNames(TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003761 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003762 TreePattern *PatternTop) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003763 if (!P->getName().empty()) {
3764 NameRecord &Rec = Names[P->getName()];
Chris Lattnera7722b62010-02-23 06:55:24 +00003765 // If this is the first instance of the name, remember the node.
3766 if (Rec.second++ == 0)
Florian Hahn6b1db822018-06-14 20:32:58 +00003767 Rec.first = P;
3768 else if (Rec.first->getExtTypes() != P->getExtTypes())
3769 PatternTop->error("repetition of value: $" + P->getName() +
Chris Lattner5b0e2492010-02-23 07:22:28 +00003770 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003771 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003772
Florian Hahn6b1db822018-06-14 20:32:58 +00003773 if (!P->isLeaf()) {
3774 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3775 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003776 }
3777}
3778
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003779std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3780 std::vector<Predicate> Preds;
3781 for (Init *I : L->getValues()) {
3782 if (DefInit *Pred = dyn_cast<DefInit>(I))
3783 Preds.push_back(Pred->getDef());
3784 else
3785 llvm_unreachable("Non-def on the list");
3786 }
3787
3788 // Sort so that different orders get canonicalized to the same string.
Fangrui Song0cac7262018-09-27 02:13:45 +00003789 llvm::sort(Preds);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003790 return Preds;
3791}
3792
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003793void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003794 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003795 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003796 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003797 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3798 PrintWarning(Pattern->getRecord()->getLoc(),
3799 Twine("Pattern can never match: ") + Reason);
3800 return;
3801 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003802
Chris Lattner1e634e32010-03-01 22:29:19 +00003803 // If the source pattern's root is a complex pattern, that complex pattern
3804 // must specify the nodes it can potentially match.
3805 if (const ComplexPattern *CP =
3806 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3807 if (CP->getRootNodes().empty())
3808 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3809 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003810
3811
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003812 // Find all of the named values in the input and output, ensure they have the
3813 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003814 std::map<std::string, NameRecord> SrcNames, DstNames;
Florian Hahn6b1db822018-06-14 20:32:58 +00003815 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3816 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003817
3818 // Scan all of the named values in the destination pattern, rejecting them if
3819 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003820 for (const auto &Entry : DstNames) {
3821 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003822 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003823 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003824 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003825
Chris Lattnera7722b62010-02-23 06:55:24 +00003826 // Scan all of the named values in the source pattern, rejecting them if the
3827 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003828 for (const auto &Entry : SrcNames)
3829 if (DstNames[Entry.first].first == nullptr &&
3830 SrcNames[Entry.first].second == 1)
3831 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003832
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003833 PatternsToMatch.push_back(PTM);
Chris Lattner0c0baa92010-02-23 06:16:51 +00003834}
3835
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003836void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003837 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003838 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003839
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003840 unsigned Errors = 0;
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003841
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003842 // Try to infer flags from all patterns in PatternToMatch. These include
3843 // both the primary instruction patterns (which always come first) and
3844 // patterns defined outside the instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003845 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003846 // We can only infer from single-instruction patterns, otherwise we won't
3847 // know which instruction should get the flags.
3848 SmallVector<Record*, 8> PatInstrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003849 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003850 if (PatInstrs.size() != 1)
3851 continue;
3852
3853 // Get the single instruction.
3854 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3855
3856 // Only infer properties from the first pattern. We'll verify the others.
3857 if (InstInfo.InferredFrom)
3858 continue;
3859
3860 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003861 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003862 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3863 }
3864
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003865 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003866 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003867
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003868 // If requested by the target, guess any undefined properties.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003869 if (Target.guessInstructionProperties()) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003870 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3871 CodeGenInstruction *InstInfo =
3872 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003873 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003874 continue;
3875 // The mayLoad and mayStore flags default to false.
3876 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003877 if (InstInfo->hasSideEffects_Unset)
3878 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003879 }
3880 return;
3881 }
3882
3883 // Complain about any flags that are still undefined.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003884 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3885 CodeGenInstruction *InstInfo =
3886 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003887 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003888 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003889 if (InstInfo->hasSideEffects_Unset)
3890 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003891 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003892 if (InstInfo->mayStore_Unset)
3893 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003894 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003895 if (InstInfo->mayLoad_Unset)
3896 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003897 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003898 }
3899}
3900
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003901
3902/// Verify instruction flags against pattern node properties.
3903void CodeGenDAGPatterns::VerifyInstructionFlags() {
3904 unsigned Errors = 0;
3905 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3906 const PatternToMatch &PTM = *I;
3907 SmallVector<Record*, 8> Instrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003908 getInstructionsInTree(PTM.getDstPattern(), Instrs);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003909 if (Instrs.empty())
3910 continue;
3911
3912 // Count the number of instructions with each flag set.
3913 unsigned NumSideEffects = 0;
3914 unsigned NumStores = 0;
3915 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00003916 for (const Record *Instr : Instrs) {
3917 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003918 NumSideEffects += InstInfo.hasSideEffects;
3919 NumStores += InstInfo.mayStore;
3920 NumLoads += InstInfo.mayLoad;
3921 }
3922
3923 // Analyze the source pattern.
3924 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003925 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003926
3927 // Collect error messages.
3928 SmallVector<std::string, 4> Msgs;
3929
3930 // Check for missing flags in the output.
3931 // Permit extra flags for now at least.
3932 if (PatInfo.hasSideEffects && !NumSideEffects)
3933 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3934
3935 // Don't verify store flags on instructions with side effects. At least for
3936 // intrinsics, side effects implies mayStore.
3937 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3938 Msgs.push_back("pattern may store, but mayStore isn't set");
3939
3940 // Similarly, mayStore implies mayLoad on intrinsics.
3941 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3942 Msgs.push_back("pattern may load, but mayLoad isn't set");
3943
3944 // Print error messages.
3945 if (Msgs.empty())
3946 continue;
3947 ++Errors;
3948
Craig Topper306cb122015-11-22 20:46:24 +00003949 for (const std::string &Msg : Msgs)
3950 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003951 (Instrs.size() == 1 ?
3952 "instruction" : "output instructions"));
3953 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00003954 for (const Record *Instr : Instrs) {
3955 if (Instr != PTM.getSrcRecord())
3956 PrintError(Instr->getLoc(), "defined here");
3957 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003958 if (InstInfo.InferredFrom &&
3959 InstInfo.InferredFrom != InstInfo.TheDef &&
3960 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003961 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003962 }
3963 }
3964 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003965 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003966}
3967
Chris Lattnercabe0372010-03-15 06:00:16 +00003968/// Given a pattern result with an unresolved type, see if we can find one
3969/// instruction with an unresolved result type. Force this result type to an
3970/// arbitrary element if it's possible types to converge results.
Florian Hahn6b1db822018-06-14 20:32:58 +00003971static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3972 if (N->isLeaf())
Chris Lattnercabe0372010-03-15 06:00:16 +00003973 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003974
Chris Lattnercabe0372010-03-15 06:00:16 +00003975 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00003976 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3977 if (ForceArbitraryInstResultType(N->getChild(i), TP))
Chris Lattnercabe0372010-03-15 06:00:16 +00003978 return true;
3979
Florian Hahn6b1db822018-06-14 20:32:58 +00003980 if (!N->getOperator()->isSubClassOf("Instruction"))
Chris Lattnercabe0372010-03-15 06:00:16 +00003981 return false;
3982
3983 // If this type is already concrete or completely unknown we can't do
3984 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003985 TypeInfer &TI = TP.getInfer();
Florian Hahn6b1db822018-06-14 20:32:58 +00003986 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3987 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00003988 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003989
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003990 // Otherwise, force its type to an arbitrary choice.
Florian Hahn6b1db822018-06-14 20:32:58 +00003991 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00003992 return true;
3993 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003994
Chris Lattnerf1447252010-03-19 21:37:09 +00003995 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00003996}
3997
Ulrich Weigand58a97862018-08-01 11:57:58 +00003998// Promote xform function to be an explicit node wherever set.
3999static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
4000 if (Record *Xform = N->getTransformFn()) {
4001 N->setTransformFn(nullptr);
4002 std::vector<TreePatternNodePtr> Children;
4003 Children.push_back(PromoteXForms(N));
4004 return std::make_shared<TreePatternNode>(Xform, std::move(Children),
4005 N->getNumTypes());
4006 }
4007
4008 if (!N->isLeaf())
4009 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4010 TreePatternNodePtr Child = N->getChildShared(i);
Ulrich Weigandf989cd72018-08-01 12:07:32 +00004011 N->setChild(i, PromoteXForms(Child));
Ulrich Weigand58a97862018-08-01 11:57:58 +00004012 }
4013 return N;
4014}
4015
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004016void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
4017 TreePattern &Pattern, TreePattern &Result,
4018 const std::vector<Record *> &InstImpResults) {
4019
4020 // Inline pattern fragments and expand multiple alternatives.
4021 Pattern.InlinePatternFragments();
4022 Result.InlinePatternFragments();
4023
4024 if (Result.getNumTrees() != 1)
4025 Result.error("Cannot use multi-alternative fragments in result pattern!");
4026
4027 // Infer types.
4028 bool IterateInference;
4029 bool InferredAllPatternTypes, InferredAllResultTypes;
4030 do {
4031 // Infer as many types as possible. If we cannot infer all of them, we
4032 // can never do anything with this pattern: report it to the user.
4033 InferredAllPatternTypes =
4034 Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
4035
4036 // Infer as many types as possible. If we cannot infer all of them, we
4037 // can never do anything with this pattern: report it to the user.
4038 InferredAllResultTypes =
4039 Result.InferAllTypes(&Pattern.getNamedNodesMap());
4040
4041 IterateInference = false;
4042
4043 // Apply the type of the result to the source pattern. This helps us
4044 // resolve cases where the input type is known to be a pointer type (which
4045 // is considered resolved), but the result knows it needs to be 32- or
4046 // 64-bits. Infer the other way for good measure.
4047 for (auto T : Pattern.getTrees())
4048 for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
4049 T->getNumTypes());
4050 i != e; ++i) {
4051 IterateInference |= T->UpdateNodeType(
4052 i, Result.getOnlyTree()->getExtType(i), Result);
4053 IterateInference |= Result.getOnlyTree()->UpdateNodeType(
4054 i, T->getExtType(i), Result);
4055 }
4056
4057 // If our iteration has converged and the input pattern's types are fully
4058 // resolved but the result pattern is not fully resolved, we may have a
4059 // situation where we have two instructions in the result pattern and
4060 // the instructions require a common register class, but don't care about
4061 // what actual MVT is used. This is actually a bug in our modelling:
4062 // output patterns should have register classes, not MVTs.
4063 //
4064 // In any case, to handle this, we just go through and disambiguate some
4065 // arbitrary types to the result pattern's nodes.
4066 if (!IterateInference && InferredAllPatternTypes &&
4067 !InferredAllResultTypes)
4068 IterateInference =
4069 ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
4070 } while (IterateInference);
4071
4072 // Verify that we inferred enough types that we can do something with the
4073 // pattern and result. If these fire the user has to add type casts.
4074 if (!InferredAllPatternTypes)
4075 Pattern.error("Could not infer all types in pattern!");
4076 if (!InferredAllResultTypes) {
4077 Pattern.dump();
4078 Result.error("Could not infer all types in pattern result!");
4079 }
4080
Ulrich Weigand58a97862018-08-01 11:57:58 +00004081 // Promote xform function to be an explicit node wherever set.
4082 TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004083
4084 TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4085 Temp.InferAllTypes();
4086
4087 ListInit *Preds = TheDef->getValueAsListInit("Predicates");
4088 int Complexity = TheDef->getValueAsInt("AddedComplexity");
4089
4090 if (PatternRewriter)
4091 PatternRewriter(&Pattern);
4092
4093 // A pattern may end up with an "impossible" type, i.e. a situation
4094 // where all types have been eliminated for some node in this pattern.
4095 // This could occur for intrinsics that only make sense for a specific
4096 // value type, and use a specific register class. If, for some mode,
4097 // that register class does not accept that type, the type inference
4098 // will lead to a contradiction, which is not an error however, but
4099 // a sign that this pattern will simply never match.
4100 if (Temp.getOnlyTree()->hasPossibleType())
4101 for (auto T : Pattern.getTrees())
4102 if (T->hasPossibleType())
4103 AddPatternToMatch(&Pattern,
4104 PatternToMatch(TheDef, makePredList(Preds),
4105 T, Temp.getOnlyTree(),
4106 InstImpResults, Complexity,
4107 TheDef->getID()));
4108}
4109
Chris Lattnerab3242f2008-01-06 01:10:31 +00004110void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00004111 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
4112
Craig Topper306cb122015-11-22 20:46:24 +00004113 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00004114 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00004115
4116 // If the pattern references the null_frag, there's nothing to do.
4117 if (hasNullFragReference(Tree))
4118 continue;
4119
Florian Hahn75e87c32018-05-30 21:00:18 +00004120 TreePattern Pattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00004121
David Greeneaf8ee2c2011-07-29 22:43:06 +00004122 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00004123 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004124
Chris Lattner8cab0212008-01-05 22:25:12 +00004125 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004126 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004127
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004128 if (Result.getNumTrees() != 1)
4129 Result.error("Cannot handle instructions producing instructions "
4130 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004131
Chris Lattner8cab0212008-01-05 22:25:12 +00004132 // Validate that the input pattern is correct.
Florian Hahn75e87c32018-05-30 21:00:18 +00004133 std::map<std::string, TreePatternNodePtr> InstInputs;
Craig Topperbd199f82018-12-05 00:47:59 +00004134 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
4135 InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00004136 std::vector<Record*> InstImpResults;
Florian Hahn75e87c32018-05-30 21:00:18 +00004137 for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
David Blaikie19b22d42018-06-11 22:14:43 +00004138 FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
Florian Hahn75e87c32018-05-30 21:00:18 +00004139 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004140
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004141 ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004142 }
4143}
4144
Florian Hahn6b1db822018-06-14 20:32:58 +00004145static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004146 for (const TypeSetByHwMode &VTS : N->getExtTypes())
4147 for (const auto &I : VTS)
4148 Modes.insert(I.first);
4149
4150 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00004151 collectModes(Modes, N->getChild(i));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004152}
4153
4154void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4155 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4156 std::map<unsigned,std::vector<Predicate>> ModeChecks;
4157 std::vector<PatternToMatch> Copy = PatternsToMatch;
4158 PatternsToMatch.clear();
4159
Florian Hahn75e87c32018-05-30 21:00:18 +00004160 auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) {
4161 TreePatternNodePtr NewSrc = P.SrcPattern->clone();
4162 TreePatternNodePtr NewDst = P.DstPattern->clone();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004163 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004164 return;
4165 }
4166
4167 std::vector<Predicate> Preds = P.Predicates;
4168 const std::vector<Predicate> &MC = ModeChecks[Mode];
4169 Preds.insert(Preds.end(), MC.begin(), MC.end());
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004170 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, std::move(NewSrc),
4171 std::move(NewDst), P.getDstRegs(),
4172 P.getAddedComplexity(), Record::getNewUID(),
4173 Mode);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004174 };
4175
4176 for (PatternToMatch &P : Copy) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004177 TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
Florian Hahn6b1db822018-06-14 20:32:58 +00004178 if (P.SrcPattern->hasProperTypeByHwMode())
4179 SrcP = P.SrcPattern;
4180 if (P.DstPattern->hasProperTypeByHwMode())
4181 DstP = P.DstPattern;
4182 if (!SrcP && !DstP) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004183 PatternsToMatch.push_back(P);
4184 continue;
4185 }
4186
4187 std::set<unsigned> Modes;
Florian Hahn6b1db822018-06-14 20:32:58 +00004188 if (SrcP)
4189 collectModes(Modes, SrcP.get());
4190 if (DstP)
4191 collectModes(Modes, DstP.get());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004192
4193 // The predicate for the default mode needs to be constructed for each
4194 // pattern separately.
4195 // Since not all modes must be present in each pattern, if a mode m is
4196 // absent, then there is no point in constructing a check for m. If such
4197 // a check was created, it would be equivalent to checking the default
4198 // mode, except not all modes' predicates would be a part of the checking
4199 // code. The subsequently generated check for the default mode would then
4200 // have the exact same patterns, but a different predicate code. To avoid
4201 // duplicated patterns with different predicate checks, construct the
4202 // default check as a negation of all predicates that are actually present
4203 // in the source/destination patterns.
4204 std::vector<Predicate> DefaultPred;
4205
4206 for (unsigned M : Modes) {
4207 if (M == DefaultMode)
4208 continue;
4209 if (ModeChecks.find(M) != ModeChecks.end())
4210 continue;
4211
4212 // Fill the map entry for this mode.
4213 const HwMode &HM = CGH.getMode(M);
4214 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4215
4216 // Add negations of the HM's predicates to the default predicate.
4217 DefaultPred.emplace_back(Predicate(HM.Features, false));
4218 }
4219
4220 for (unsigned M : Modes) {
4221 if (M == DefaultMode)
4222 continue;
4223 AppendPattern(P, M);
4224 }
4225
4226 bool HasDefault = Modes.count(DefaultMode);
4227 if (HasDefault)
4228 AppendPattern(P, DefaultMode);
4229 }
4230}
4231
4232/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turner249dc142017-09-20 18:01:40 +00004233typedef StringMap<int> DepVarMap;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004234
Florian Hahn6b1db822018-06-14 20:32:58 +00004235static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4236 if (N->isLeaf()) {
4237 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
4238 DepMap[N->getName()]++;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004239 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00004240 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4241 FindDepVarsOf(N->getChild(i), DepMap);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004242 }
4243}
4244
4245/// Find dependent variables within child patterns
Florian Hahn6b1db822018-06-14 20:32:58 +00004246static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004247 DepVarMap depcounts;
4248 FindDepVarsOf(N, depcounts);
Zachary Turner249dc142017-09-20 18:01:40 +00004249 for (const auto &Pair : depcounts) {
4250 if (Pair.getValue() > 1)
4251 DepVars.insert(Pair.getKey());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004252 }
4253}
4254
4255#ifndef NDEBUG
4256/// Dump the dependent variable set:
4257static void DumpDepVars(MultipleUseVarSet &DepVars) {
4258 if (DepVars.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004259 LLVM_DEBUG(errs() << "<empty set>");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004260 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004261 LLVM_DEBUG(errs() << "[ ");
Zachary Turner249dc142017-09-20 18:01:40 +00004262 for (const auto &DepVar : DepVars) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004263 LLVM_DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004264 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004265 LLVM_DEBUG(errs() << "]");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004266 }
4267}
4268#endif
4269
4270
Chris Lattner8cab0212008-01-05 22:25:12 +00004271/// CombineChildVariants - Given a bunch of permutations of each child of the
4272/// 'operator' node, put them together in all possible ways.
Florian Hahn75e87c32018-05-30 21:00:18 +00004273static void CombineChildVariants(
Florian Hahn6b1db822018-06-14 20:32:58 +00004274 TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004275 const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4276 std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4277 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004278 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00004279 for (const auto &Variants : ChildVariants)
4280 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00004281 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004282
Chris Lattner8cab0212008-01-05 22:25:12 +00004283 // The end result is an all-pairs construction of the resultant pattern.
4284 std::vector<unsigned> Idxs;
4285 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00004286 bool NotDone;
4287 do {
4288#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004289 LLVM_DEBUG(if (!Idxs.empty()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004290 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004291 for (unsigned Idx : Idxs) {
4292 errs() << Idx << " ";
4293 }
4294 errs() << "]\n";
4295 });
Scott Michel94420742008-03-05 17:49:05 +00004296#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00004297 // Create the variant and add it to the output list.
Florian Hahn75e87c32018-05-30 21:00:18 +00004298 std::vector<TreePatternNodePtr> NewChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004299 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4300 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Florian Hahn75e87c32018-05-30 21:00:18 +00004301 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00004302 Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004303
Chris Lattner8cab0212008-01-05 22:25:12 +00004304 // Copy over properties.
Florian Hahn6b1db822018-06-14 20:32:58 +00004305 R->setName(Orig->getName());
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00004306 R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
4307 R->setPredicateCalls(Orig->getPredicateCalls());
Florian Hahn6b1db822018-06-14 20:32:58 +00004308 R->setTransformFn(Orig->getTransformFn());
4309 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4310 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00004311
Scott Michel94420742008-03-05 17:49:05 +00004312 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00004313 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00004314 // Scan to see if this pattern has already been emitted. We can get
4315 // duplication due to things like commuting:
4316 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4317 // which are the same pattern. Ignore the dups.
4318 if (R->canPatternMatch(ErrString, CDP) &&
Florian Hahn75e87c32018-05-30 21:00:18 +00004319 none_of(OutVariants, [&](TreePatternNodePtr Variant) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004320 return R->isIsomorphicTo(Variant.get(), DepVars);
David Majnemer0a16c222016-08-11 21:15:00 +00004321 }))
Florian Hahn75e87c32018-05-30 21:00:18 +00004322 OutVariants.push_back(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004323
Scott Michel94420742008-03-05 17:49:05 +00004324 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004325 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00004326 // [0, 0], [0, 1], [1, 0], [1, 1].
4327 int IdxsIdx;
4328 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4329 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4330 Idxs[IdxsIdx] = 0;
4331 else
Chris Lattner8cab0212008-01-05 22:25:12 +00004332 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00004333 }
Scott Michel94420742008-03-05 17:49:05 +00004334 NotDone = (IdxsIdx >= 0);
4335 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00004336}
4337
4338/// CombineChildVariants - A helper function for binary operators.
4339///
Florian Hahn6b1db822018-06-14 20:32:58 +00004340static void CombineChildVariants(TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004341 const std::vector<TreePatternNodePtr> &LHS,
4342 const std::vector<TreePatternNodePtr> &RHS,
4343 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004344 CodeGenDAGPatterns &CDP,
4345 const MultipleUseVarSet &DepVars) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004346 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004347 ChildVariants.push_back(LHS);
4348 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00004349 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004350}
Chris Lattner8cab0212008-01-05 22:25:12 +00004351
Florian Hahn75e87c32018-05-30 21:00:18 +00004352static void
Florian Hahn6b1db822018-06-14 20:32:58 +00004353GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004354 std::vector<TreePatternNodePtr> &Children) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004355 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4356 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00004357
Chris Lattner8cab0212008-01-05 22:25:12 +00004358 // Only permit raw nodes.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00004359 if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00004360 N->getTransformFn()) {
4361 Children.push_back(N);
4362 return;
4363 }
4364
Florian Hahn6b1db822018-06-14 20:32:58 +00004365 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004366 Children.push_back(N->getChildShared(0));
Chris Lattner8cab0212008-01-05 22:25:12 +00004367 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004368 GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004369
Florian Hahn6b1db822018-06-14 20:32:58 +00004370 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004371 Children.push_back(N->getChildShared(1));
Chris Lattner8cab0212008-01-05 22:25:12 +00004372 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004373 GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004374}
4375
4376/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4377/// the (potentially recursive) pattern by using algebraic laws.
4378///
Florian Hahn6b1db822018-06-14 20:32:58 +00004379static void GenerateVariantsOf(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004380 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004381 CodeGenDAGPatterns &CDP,
4382 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00004383 // We cannot permute leaves or ComplexPattern uses.
4384 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004385 OutVariants.push_back(N);
4386 return;
4387 }
4388
4389 // Look up interesting info about the node.
4390 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4391
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004392 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00004393 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00004394 // Re-associate by pulling together all of the linked operators
Florian Hahn75e87c32018-05-30 21:00:18 +00004395 std::vector<TreePatternNodePtr> MaximalChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004396 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4397
4398 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4399 // permutations.
4400 if (MaximalChildren.size() == 3) {
4401 // Find the variants of all of our maximal children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004402 std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00004403 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4404 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4405 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004406
Chris Lattner8cab0212008-01-05 22:25:12 +00004407 // There are only two ways we can permute the tree:
4408 // (A op B) op C and A op (B op C)
4409 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004410
Chris Lattner8cab0212008-01-05 22:25:12 +00004411 // Generate legal pair permutations of A/B/C.
Florian Hahn75e87c32018-05-30 21:00:18 +00004412 std::vector<TreePatternNodePtr> ABVariants;
4413 std::vector<TreePatternNodePtr> BAVariants;
4414 std::vector<TreePatternNodePtr> ACVariants;
4415 std::vector<TreePatternNodePtr> CAVariants;
4416 std::vector<TreePatternNodePtr> BCVariants;
4417 std::vector<TreePatternNodePtr> CBVariants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004418 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4419 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4420 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4421 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4422 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4423 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004424
4425 // Combine those into the result: (x op x) op x
Florian Hahn6b1db822018-06-14 20:32:58 +00004426 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4427 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4428 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4429 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4430 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4431 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004432
4433 // Combine those into the result: x op (x op x)
Florian Hahn6b1db822018-06-14 20:32:58 +00004434 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4435 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4436 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4437 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4438 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4439 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004440 return;
4441 }
4442 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004443
Chris Lattner8cab0212008-01-05 22:25:12 +00004444 // Compute permutations of all children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004445 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004446 ChildVariants.resize(N->getNumChildren());
4447 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn75e87c32018-05-30 21:00:18 +00004448 GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004449
4450 // Build all permutations based on how the children were formed.
Florian Hahn6b1db822018-06-14 20:32:58 +00004451 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004452
4453 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004454 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4455 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004456 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004457 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004458 // Don't count children which are actually register references.
4459 unsigned NC = 0;
4460 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004461 TreePatternNode *Child = N->getChild(i);
4462 if (Child->isLeaf())
4463 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004464 Record *RR = DI->getDef();
4465 if (RR->isSubClassOf("Register"))
4466 continue;
4467 }
4468 NC++;
4469 }
4470 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004471 if (isCommIntrinsic) {
4472 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4473 // operands are the commutative operands, and there might be more operands
4474 // after those.
4475 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004476 "Commutative intrinsic should have at least 3 children!");
Florian Hahn75e87c32018-05-30 21:00:18 +00004477 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004478 Variants.push_back(std::move(ChildVariants[0])); // Intrinsic id.
4479 Variants.push_back(std::move(ChildVariants[2]));
4480 Variants.push_back(std::move(ChildVariants[1]));
Evan Cheng49bad4c2008-06-16 20:29:38 +00004481 for (unsigned i = 3; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004482 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004483 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004484 } else if (NC == N->getNumChildren()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004485 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004486 Variants.push_back(std::move(ChildVariants[1]));
4487 Variants.push_back(std::move(ChildVariants[0]));
Craig Topper98a96282017-09-04 03:44:33 +00004488 for (unsigned i = 2; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004489 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004490 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004491 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004492 }
4493}
4494
4495
4496// GenerateVariants - Generate variants. For example, commutative patterns can
4497// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004498void CodeGenDAGPatterns::GenerateVariants() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004499 LLVM_DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004500
Chris Lattner8cab0212008-01-05 22:25:12 +00004501 // Loop over all of the patterns we've collected, checking to see if we can
4502 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004503 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004504 // the .td file having to contain tons of variants of instructions.
4505 //
4506 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4507 // intentionally do not reconsider these. Any variants of added patterns have
4508 // already been added.
4509 //
Simon Pilgrim0621f562018-09-18 11:30:30 +00004510 const unsigned NumOriginalPatterns = PatternsToMatch.size();
4511 BitVector MatchedPatterns(NumOriginalPatterns);
4512 std::vector<BitVector> MatchedPredicates(NumOriginalPatterns,
4513 BitVector(NumOriginalPatterns));
4514
4515 typedef std::pair<MultipleUseVarSet, std::vector<TreePatternNodePtr>>
4516 DepsAndVariants;
4517 std::map<unsigned, DepsAndVariants> PatternsWithVariants;
4518
4519 // Collect patterns with more than one variant.
4520 for (unsigned i = 0; i != NumOriginalPatterns; ++i) {
4521 MultipleUseVarSet DepVars;
Florian Hahn75e87c32018-05-30 21:00:18 +00004522 std::vector<TreePatternNodePtr> Variants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004523 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004524 LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4525 LLVM_DEBUG(DumpDepVars(DepVars));
4526 LLVM_DEBUG(errs() << "\n");
Florian Hahn75e87c32018-05-30 21:00:18 +00004527 GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4528 *this, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004529
4530 assert(!Variants.empty() && "Must create at least original variant!");
Simon Pilgrim0621f562018-09-18 11:30:30 +00004531 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004532 continue;
4533
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004534 LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4535 PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004536
Simon Pilgrim0621f562018-09-18 11:30:30 +00004537 PatternsWithVariants[i] = std::make_pair(DepVars, Variants);
4538
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +00004539 // Cache matching predicates.
Simon Pilgrim0621f562018-09-18 11:30:30 +00004540 if (MatchedPatterns[i])
4541 continue;
4542
4543 const std::vector<Predicate> &Predicates =
4544 PatternsToMatch[i].getPredicates();
4545
4546 BitVector &Matches = MatchedPredicates[i];
Simon Pilgrim6d706772018-09-19 12:23:50 +00004547 MatchedPatterns.set(i);
4548 Matches.set(i);
Simon Pilgrim0621f562018-09-18 11:30:30 +00004549
4550 // Don't test patterns that have already been cached - it won't match.
4551 for (unsigned p = 0; p != NumOriginalPatterns; ++p)
4552 if (!MatchedPatterns[p])
4553 Matches[p] = (Predicates == PatternsToMatch[p].getPredicates());
4554
4555 // Copy this to all the matching patterns.
4556 for (int p = Matches.find_first(); p != -1; p = Matches.find_next(p))
Simon Pilgrime3c6f8d2018-09-18 12:01:25 +00004557 if (p != (int)i) {
Simon Pilgrim6d706772018-09-19 12:23:50 +00004558 MatchedPatterns.set(p);
Simon Pilgrim0621f562018-09-18 11:30:30 +00004559 MatchedPredicates[p] = Matches;
4560 }
4561 }
4562
4563 for (auto it : PatternsWithVariants) {
4564 unsigned i = it.first;
4565 const MultipleUseVarSet &DepVars = it.second.first;
4566 const std::vector<TreePatternNodePtr> &Variants = it.second.second;
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +00004567
Chris Lattner8cab0212008-01-05 22:25:12 +00004568 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004569 TreePatternNodePtr Variant = Variants[v];
Simon Pilgrim0621f562018-09-18 11:30:30 +00004570 BitVector &Matches = MatchedPredicates[i];
Chris Lattner8cab0212008-01-05 22:25:12 +00004571
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004572 LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump();
4573 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004574
Chris Lattner8cab0212008-01-05 22:25:12 +00004575 // Scan to see if an instruction or explicit pattern already matches this.
4576 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004577 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004578 // Skip if the top level predicates do not match.
Simon Pilgrim0621f562018-09-18 11:30:30 +00004579 if (!Matches[p])
Evan Cheng34c8c742009-06-26 05:59:16 +00004580 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004581 // Check to see if this variant already exists.
Florian Hahn6b1db822018-06-14 20:32:58 +00004582 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004583 DepVars)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004584 LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004585 AlreadyExists = true;
4586 break;
4587 }
4588 }
4589 // If we already have it, ignore the variant.
4590 if (AlreadyExists) continue;
4591
4592 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004593 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004594 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
Florian Hahn75e87c32018-05-30 21:00:18 +00004595 Variant, PatternsToMatch[i].getDstPatternShared(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004596 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004597 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Simon Pilgrim0621f562018-09-18 11:30:30 +00004598 MatchedPredicates.push_back(Matches);
4599
Simon Pilgrimb2444352018-09-18 14:05:07 +00004600 // Add a new match the same as this pattern.
Simon Pilgrimb2444352018-09-18 14:05:07 +00004601 for (auto &P : MatchedPredicates)
Simon Pilgrim429df292018-09-19 11:18:49 +00004602 P.push_back(P[i]);
Chris Lattner8cab0212008-01-05 22:25:12 +00004603 }
4604
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004605 LLVM_DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004606 }
4607}