xref: /src/contrib/llvm-project/llvm/utils/TableGen/Common/CodeGenDAGPatterns.cpp (revision 71ac745d76c3ba442e753daff1870893f272b29d)
1009b1c42SEd Schouten //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file implements the CodeGenDAGPatterns class, which is used to read and
10009b1c42SEd Schouten // represent the patterns present in a .td file for instructions.
11009b1c42SEd Schouten //
12009b1c42SEd Schouten //===----------------------------------------------------------------------===//
13009b1c42SEd Schouten 
14009b1c42SEd Schouten #include "CodeGenDAGPatterns.h"
15145449b1SDimitry Andric #include "CodeGenInstruction.h"
167fa27ce4SDimitry Andric #include "CodeGenRegisters.h"
17044eb2f6SDimitry Andric #include "llvm/ADT/DenseSet.h"
18d8e91e46SDimitry Andric #include "llvm/ADT/MapVector.h"
19c6910277SRoman Divacky #include "llvm/ADT/STLExtras.h"
20044eb2f6SDimitry Andric #include "llvm/ADT/SmallSet.h"
21dd58ef01SDimitry Andric #include "llvm/ADT/SmallString.h"
224a16efa3SDimitry Andric #include "llvm/ADT/StringExtras.h"
23044eb2f6SDimitry Andric #include "llvm/ADT/StringMap.h"
24b61ab53cSDimitry Andric #include "llvm/ADT/Twine.h"
25009b1c42SEd Schouten #include "llvm/Support/Debug.h"
2663faed5bSDimitry Andric #include "llvm/Support/ErrorHandling.h"
27706b4fc4SDimitry Andric #include "llvm/Support/TypeSize.h"
284a16efa3SDimitry Andric #include "llvm/TableGen/Error.h"
294a16efa3SDimitry Andric #include "llvm/TableGen/Record.h"
30009b1c42SEd Schouten #include <algorithm>
3163faed5bSDimitry Andric #include <cstdio>
32d8e91e46SDimitry Andric #include <iterator>
3363faed5bSDimitry Andric #include <set>
34009b1c42SEd Schouten using namespace llvm;
35009b1c42SEd Schouten 
365ca98fd9SDimitry Andric #define DEBUG_TYPE "dag-patterns"
375ca98fd9SDimitry Andric 
isIntegerOrPtr(MVT VT)38044eb2f6SDimitry Andric static inline bool isIntegerOrPtr(MVT VT) {
39044eb2f6SDimitry Andric   return VT.isInteger() || VT == MVT::iPTR;
40009b1c42SEd Schouten }
isFloatingPoint(MVT VT)41ac9a064cSDimitry Andric static inline bool isFloatingPoint(MVT VT) { return VT.isFloatingPoint(); }
isVector(MVT VT)42ac9a064cSDimitry Andric static inline bool isVector(MVT VT) { return VT.isVector(); }
isScalar(MVT VT)43ac9a064cSDimitry Andric static inline bool isScalar(MVT VT) { return !VT.isVector(); }
44009b1c42SEd Schouten 
45044eb2f6SDimitry Andric template <typename Predicate>
berase_if(MachineValueTypeSet & S,Predicate P)46044eb2f6SDimitry Andric static bool berase_if(MachineValueTypeSet &S, Predicate P) {
47044eb2f6SDimitry Andric   bool Erased = false;
48044eb2f6SDimitry Andric   // It is ok to iterate over MachineValueTypeSet and remove elements from it
49044eb2f6SDimitry Andric   // at the same time.
50044eb2f6SDimitry Andric   for (MVT T : S) {
51044eb2f6SDimitry Andric     if (!P(T))
52044eb2f6SDimitry Andric       continue;
53044eb2f6SDimitry Andric     Erased = true;
54044eb2f6SDimitry Andric     S.erase(T);
55044eb2f6SDimitry Andric   }
56044eb2f6SDimitry Andric   return Erased;
57044eb2f6SDimitry Andric }
58044eb2f6SDimitry Andric 
writeToStream(raw_ostream & OS) const591f917f69SDimitry Andric void MachineValueTypeSet::writeToStream(raw_ostream &OS) const {
601f917f69SDimitry Andric   SmallVector<MVT, 4> Types(begin(), end());
611f917f69SDimitry Andric   array_pod_sort(Types.begin(), Types.end());
621f917f69SDimitry Andric 
631f917f69SDimitry Andric   OS << '[';
641f917f69SDimitry Andric   ListSeparator LS(" ");
651f917f69SDimitry Andric   for (const MVT &T : Types)
661f917f69SDimitry Andric     OS << LS << ValueTypeByHwMode::getMVTName(T);
671f917f69SDimitry Andric   OS << ']';
681f917f69SDimitry Andric }
691f917f69SDimitry Andric 
70044eb2f6SDimitry Andric // --- TypeSetByHwMode
71044eb2f6SDimitry Andric 
72044eb2f6SDimitry Andric // This is a parameterized type-set class. For each mode there is a list
73044eb2f6SDimitry Andric // of types that are currently possible for a given tree node. Type
74044eb2f6SDimitry Andric // inference will apply to each mode separately.
75044eb2f6SDimitry Andric 
TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList)76044eb2f6SDimitry Andric TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
777fa27ce4SDimitry Andric   // Take the address space from the first type in the list.
787fa27ce4SDimitry Andric   if (!VTList.empty())
797fa27ce4SDimitry Andric     AddrSpace = VTList[0].PtrAddrSpace;
807fa27ce4SDimitry Andric 
817fa27ce4SDimitry Andric   for (const ValueTypeByHwMode &VVT : VTList)
82044eb2f6SDimitry Andric     insert(VVT);
83044eb2f6SDimitry Andric }
84044eb2f6SDimitry Andric 
isValueTypeByHwMode(bool AllowEmpty) const85044eb2f6SDimitry Andric bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
86044eb2f6SDimitry Andric   for (const auto &I : *this) {
87044eb2f6SDimitry Andric     if (I.second.size() > 1)
88044eb2f6SDimitry Andric       return false;
89044eb2f6SDimitry Andric     if (!AllowEmpty && I.second.empty())
90044eb2f6SDimitry Andric       return false;
91044eb2f6SDimitry Andric   }
92044eb2f6SDimitry Andric   return true;
93044eb2f6SDimitry Andric }
94044eb2f6SDimitry Andric 
getValueTypeByHwMode() const95044eb2f6SDimitry Andric ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
96044eb2f6SDimitry Andric   assert(isValueTypeByHwMode(true) &&
97044eb2f6SDimitry Andric          "The type set has multiple types for at least one HW mode");
98044eb2f6SDimitry Andric   ValueTypeByHwMode VVT;
997fa27ce4SDimitry Andric   VVT.PtrAddrSpace = AddrSpace;
100e6d15924SDimitry Andric 
101044eb2f6SDimitry Andric   for (const auto &I : *this) {
102044eb2f6SDimitry Andric     MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
103044eb2f6SDimitry Andric     VVT.getOrCreateTypeForMode(I.first, T);
104044eb2f6SDimitry Andric   }
105044eb2f6SDimitry Andric   return VVT;
106044eb2f6SDimitry Andric }
107044eb2f6SDimitry Andric 
isPossible() const108044eb2f6SDimitry Andric bool TypeSetByHwMode::isPossible() const {
109044eb2f6SDimitry Andric   for (const auto &I : *this)
110044eb2f6SDimitry Andric     if (!I.second.empty())
111044eb2f6SDimitry Andric       return true;
112044eb2f6SDimitry Andric   return false;
113044eb2f6SDimitry Andric }
114044eb2f6SDimitry Andric 
insert(const ValueTypeByHwMode & VVT)115044eb2f6SDimitry Andric bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
116044eb2f6SDimitry Andric   bool Changed = false;
117d8e91e46SDimitry Andric   bool ContainsDefault = false;
118d8e91e46SDimitry Andric   MVT DT = MVT::Other;
119d8e91e46SDimitry Andric 
120044eb2f6SDimitry Andric   for (const auto &P : VVT) {
121044eb2f6SDimitry Andric     unsigned M = P.first;
122044eb2f6SDimitry Andric     // Make sure there exists a set for each specific mode from VVT.
123044eb2f6SDimitry Andric     Changed |= getOrCreate(M).insert(P.second).second;
124d8e91e46SDimitry Andric     // Cache VVT's default mode.
125d8e91e46SDimitry Andric     if (DefaultMode == M) {
126d8e91e46SDimitry Andric       ContainsDefault = true;
127d8e91e46SDimitry Andric       DT = P.second;
128d8e91e46SDimitry Andric     }
129044eb2f6SDimitry Andric   }
130044eb2f6SDimitry Andric 
131044eb2f6SDimitry Andric   // If VVT has a default mode, add the corresponding type to all
132044eb2f6SDimitry Andric   // modes in "this" that do not exist in VVT.
133d8e91e46SDimitry Andric   if (ContainsDefault)
134044eb2f6SDimitry Andric     for (auto &I : *this)
135344a3780SDimitry Andric       if (!VVT.hasMode(I.first))
136044eb2f6SDimitry Andric         Changed |= I.second.insert(DT).second;
137d8e91e46SDimitry Andric 
138044eb2f6SDimitry Andric   return Changed;
139044eb2f6SDimitry Andric }
140044eb2f6SDimitry Andric 
141044eb2f6SDimitry Andric // Constrain the type set to be the intersection with VTS.
constrain(const TypeSetByHwMode & VTS)142044eb2f6SDimitry Andric bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
143044eb2f6SDimitry Andric   bool Changed = false;
144044eb2f6SDimitry Andric   if (hasDefault()) {
145044eb2f6SDimitry Andric     for (const auto &I : VTS) {
146044eb2f6SDimitry Andric       unsigned M = I.first;
147044eb2f6SDimitry Andric       if (M == DefaultMode || hasMode(M))
148044eb2f6SDimitry Andric         continue;
149044eb2f6SDimitry Andric       Map.insert({M, Map.at(DefaultMode)});
150044eb2f6SDimitry Andric       Changed = true;
151c6910277SRoman Divacky     }
152c6910277SRoman Divacky   }
153c6910277SRoman Divacky 
154044eb2f6SDimitry Andric   for (auto &I : *this) {
155044eb2f6SDimitry Andric     unsigned M = I.first;
156044eb2f6SDimitry Andric     SetType &S = I.second;
157044eb2f6SDimitry Andric     if (VTS.hasMode(M) || VTS.hasDefault()) {
158044eb2f6SDimitry Andric       Changed |= intersect(I.second, VTS.get(M));
159044eb2f6SDimitry Andric     } else if (!S.empty()) {
160044eb2f6SDimitry Andric       S.clear();
161044eb2f6SDimitry Andric       Changed = true;
162044eb2f6SDimitry Andric     }
163044eb2f6SDimitry Andric   }
164044eb2f6SDimitry Andric   return Changed;
165c6910277SRoman Divacky }
166c6910277SRoman Divacky 
constrain(Predicate P)167ac9a064cSDimitry Andric template <typename Predicate> bool TypeSetByHwMode::constrain(Predicate P) {
168044eb2f6SDimitry Andric   bool Changed = false;
169044eb2f6SDimitry Andric   for (auto &I : *this)
170044eb2f6SDimitry Andric     Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
171044eb2f6SDimitry Andric   return Changed;
172044eb2f6SDimitry Andric }
1732f12f10aSRoman Divacky 
174044eb2f6SDimitry Andric template <typename Predicate>
assign_if(const TypeSetByHwMode & VTS,Predicate P)175044eb2f6SDimitry Andric bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
176044eb2f6SDimitry Andric   assert(empty());
177044eb2f6SDimitry Andric   for (const auto &I : VTS) {
178044eb2f6SDimitry Andric     SetType &S = getOrCreate(I.first);
179044eb2f6SDimitry Andric     for (auto J : I.second)
180044eb2f6SDimitry Andric       if (P(J))
181044eb2f6SDimitry Andric         S.insert(J);
182044eb2f6SDimitry Andric   }
183044eb2f6SDimitry Andric   return !empty();
184044eb2f6SDimitry Andric }
185044eb2f6SDimitry Andric 
writeToStream(raw_ostream & OS) const186044eb2f6SDimitry Andric void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
187044eb2f6SDimitry Andric   SmallVector<unsigned, 4> Modes;
188044eb2f6SDimitry Andric   Modes.reserve(Map.size());
189044eb2f6SDimitry Andric 
190044eb2f6SDimitry Andric   for (const auto &I : *this)
191044eb2f6SDimitry Andric     Modes.push_back(I.first);
192044eb2f6SDimitry Andric   if (Modes.empty()) {
193044eb2f6SDimitry Andric     OS << "{}";
194044eb2f6SDimitry Andric     return;
195044eb2f6SDimitry Andric   }
196044eb2f6SDimitry Andric   array_pod_sort(Modes.begin(), Modes.end());
197044eb2f6SDimitry Andric 
198044eb2f6SDimitry Andric   OS << '{';
199044eb2f6SDimitry Andric   for (unsigned M : Modes) {
200044eb2f6SDimitry Andric     OS << ' ' << getModeName(M) << ':';
2011f917f69SDimitry Andric     get(M).writeToStream(OS);
202044eb2f6SDimitry Andric   }
203044eb2f6SDimitry Andric   OS << " }";
204044eb2f6SDimitry Andric }
205044eb2f6SDimitry Andric 
operator ==(const TypeSetByHwMode & VTS) const206044eb2f6SDimitry Andric bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
207d8e91e46SDimitry Andric   // The isSimple call is much quicker than hasDefault - check this first.
208d8e91e46SDimitry Andric   bool IsSimple = isSimple();
209d8e91e46SDimitry Andric   bool VTSIsSimple = VTS.isSimple();
210d8e91e46SDimitry Andric   if (IsSimple && VTSIsSimple)
2117fa27ce4SDimitry Andric     return getSimple() == VTS.getSimple();
212d8e91e46SDimitry Andric 
213d8e91e46SDimitry Andric   // Speedup: We have a default if the set is simple.
214d8e91e46SDimitry Andric   bool HaveDefault = IsSimple || hasDefault();
215d8e91e46SDimitry Andric   bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
216d8e91e46SDimitry Andric   if (HaveDefault != VTSHaveDefault)
217044eb2f6SDimitry Andric     return false;
218044eb2f6SDimitry Andric 
219344a3780SDimitry Andric   SmallSet<unsigned, 4> Modes;
220044eb2f6SDimitry Andric   for (auto &I : *this)
221044eb2f6SDimitry Andric     Modes.insert(I.first);
222044eb2f6SDimitry Andric   for (const auto &I : VTS)
223044eb2f6SDimitry Andric     Modes.insert(I.first);
224044eb2f6SDimitry Andric 
225044eb2f6SDimitry Andric   if (HaveDefault) {
226044eb2f6SDimitry Andric     // Both sets have default mode.
227044eb2f6SDimitry Andric     for (unsigned M : Modes) {
228044eb2f6SDimitry Andric       if (get(M) != VTS.get(M))
229044eb2f6SDimitry Andric         return false;
230044eb2f6SDimitry Andric     }
231044eb2f6SDimitry Andric   } else {
232044eb2f6SDimitry Andric     // Neither set has default mode.
233044eb2f6SDimitry Andric     for (unsigned M : Modes) {
234044eb2f6SDimitry Andric       // If there is no default mode, an empty set is equivalent to not having
235044eb2f6SDimitry Andric       // the corresponding mode.
236044eb2f6SDimitry Andric       bool NoModeThis = !hasMode(M) || get(M).empty();
237044eb2f6SDimitry Andric       bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
238044eb2f6SDimitry Andric       if (NoModeThis != NoModeVTS)
239044eb2f6SDimitry Andric         return false;
240044eb2f6SDimitry Andric       if (!NoModeThis)
241044eb2f6SDimitry Andric         if (get(M) != VTS.get(M))
242044eb2f6SDimitry Andric           return false;
243044eb2f6SDimitry Andric     }
244044eb2f6SDimitry Andric   }
245044eb2f6SDimitry Andric 
246044eb2f6SDimitry Andric   return true;
247044eb2f6SDimitry Andric }
248044eb2f6SDimitry Andric 
249044eb2f6SDimitry Andric namespace llvm {
operator <<(raw_ostream & OS,const MachineValueTypeSet & T)2501f917f69SDimitry Andric raw_ostream &operator<<(raw_ostream &OS, const MachineValueTypeSet &T) {
2511f917f69SDimitry Andric   T.writeToStream(OS);
2521f917f69SDimitry Andric   return OS;
2531f917f69SDimitry Andric }
operator <<(raw_ostream & OS,const TypeSetByHwMode & T)254044eb2f6SDimitry Andric raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
255044eb2f6SDimitry Andric   T.writeToStream(OS);
256044eb2f6SDimitry Andric   return OS;
257044eb2f6SDimitry Andric }
258ac9a064cSDimitry Andric } // namespace llvm
259044eb2f6SDimitry Andric 
260044eb2f6SDimitry Andric LLVM_DUMP_METHOD
dump() const261ac9a064cSDimitry Andric void TypeSetByHwMode::dump() const { dbgs() << *this << '\n'; }
262044eb2f6SDimitry Andric 
intersect(SetType & Out,const SetType & In)263044eb2f6SDimitry Andric bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
264ac9a064cSDimitry Andric   auto IntersectP = [&](std::optional<MVT> WildVT, function_ref<bool(MVT)> P) {
265ac9a064cSDimitry Andric     // Complement of In within this partition.
266ac9a064cSDimitry Andric     auto CompIn = [&](MVT T) -> bool { return !In.count(T) && P(T); };
267044eb2f6SDimitry Andric 
268ac9a064cSDimitry Andric     if (!WildVT)
2691f917f69SDimitry Andric       return berase_if(Out, CompIn);
270044eb2f6SDimitry Andric 
271ac9a064cSDimitry Andric     bool OutW = Out.count(*WildVT), InW = In.count(*WildVT);
272ac9a064cSDimitry Andric     if (OutW == InW)
273ac9a064cSDimitry Andric       return berase_if(Out, CompIn);
274ac9a064cSDimitry Andric 
275ac9a064cSDimitry Andric     // Compute the intersection of scalars separately to account for only one
276ac9a064cSDimitry Andric     // set containing WildVT.
277ac9a064cSDimitry Andric     // The intersection of WildVT with a set of corresponding types that does
278ac9a064cSDimitry Andric     // not include WildVT will result in the most specific type:
279ac9a064cSDimitry Andric     // - WildVT is more specific than any set with two elements or more
280ac9a064cSDimitry Andric     // - WildVT is less specific than any single type.
281ac9a064cSDimitry Andric     // For example, for iPTR and scalar integer types
282044eb2f6SDimitry Andric     // { iPTR } * { i32 }     -> { i32 }
283044eb2f6SDimitry Andric     // { iPTR } * { i32 i64 } -> { iPTR }
284044eb2f6SDimitry Andric     // and
285044eb2f6SDimitry Andric     // { iPTR i32 } * { i32 }          -> { i32 }
286044eb2f6SDimitry Andric     // { iPTR i32 } * { i32 i64 }      -> { i32 i64 }
287044eb2f6SDimitry Andric     // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
288044eb2f6SDimitry Andric 
289ac9a064cSDimitry Andric     // Looking at just this partition, let In' = elements only in In,
290ac9a064cSDimitry Andric     // Out' = elements only in Out, and IO = elements common to both. Normally
291ac9a064cSDimitry Andric     // IO would be returned as the result of the intersection, but we need to
292ac9a064cSDimitry Andric     // account for WildVT being a "wildcard" of sorts. Since elements in IO are
293ac9a064cSDimitry Andric     // those that match both sets exactly, they will all belong to the output.
294ac9a064cSDimitry Andric     // If any of the "leftovers" (i.e. In' or Out') contain WildVT, it means
295ac9a064cSDimitry Andric     // that the other set doesn't have it, but it could have (1) a more
296ac9a064cSDimitry Andric     // specific type, or (2) a set of types that is less specific. The
297ac9a064cSDimitry Andric     // "leftovers" from the other set is what we want to examine more closely.
2981f917f69SDimitry Andric 
299ac9a064cSDimitry Andric     auto Leftovers = [&](const SetType &A, const SetType &B) {
3001f917f69SDimitry Andric       SetType Diff = A;
301ac9a064cSDimitry Andric       berase_if(Diff, [&](MVT T) { return B.count(T) || !P(T); });
3021f917f69SDimitry Andric       return Diff;
3031f917f69SDimitry Andric     };
3041f917f69SDimitry Andric 
305ac9a064cSDimitry Andric     if (InW) {
306ac9a064cSDimitry Andric       SetType OutLeftovers = Leftovers(Out, In);
307ac9a064cSDimitry Andric       if (OutLeftovers.size() < 2) {
308ac9a064cSDimitry Andric         // WildVT not added to Out. Keep the possible single leftover.
3091f917f69SDimitry Andric         return false;
310044eb2f6SDimitry Andric       }
311ac9a064cSDimitry Andric       // WildVT replaces the leftovers.
3121f917f69SDimitry Andric       berase_if(Out, CompIn);
313ac9a064cSDimitry Andric       Out.insert(*WildVT);
3141f917f69SDimitry Andric       return true;
3151f917f69SDimitry Andric     }
3161f917f69SDimitry Andric 
317ac9a064cSDimitry Andric     // OutW == true
318ac9a064cSDimitry Andric     SetType InLeftovers = Leftovers(In, Out);
3191f917f69SDimitry Andric     unsigned SizeOut = Out.size();
320ac9a064cSDimitry Andric     berase_if(Out, CompIn); // This will remove at least the WildVT.
321ac9a064cSDimitry Andric     if (InLeftovers.size() < 2) {
322ac9a064cSDimitry Andric       // WildVT deleted from Out. Add back the possible single leftover.
323ac9a064cSDimitry Andric       Out.insert(InLeftovers);
3241f917f69SDimitry Andric       return true;
3251f917f69SDimitry Andric     }
3261f917f69SDimitry Andric 
327ac9a064cSDimitry Andric     // Keep the WildVT in Out.
328ac9a064cSDimitry Andric     Out.insert(*WildVT);
329ac9a064cSDimitry Andric     // If WildVT was the only element initially removed from Out, then Out
3301f917f69SDimitry Andric     // has not changed.
3311f917f69SDimitry Andric     return SizeOut != Out.size();
332ac9a064cSDimitry Andric   };
333ac9a064cSDimitry Andric 
334ac9a064cSDimitry Andric   // Note: must be non-overlapping
335ac9a064cSDimitry Andric   using WildPartT = std::pair<MVT, std::function<bool(MVT)>>;
336ac9a064cSDimitry Andric   static const WildPartT WildParts[] = {
337ac9a064cSDimitry Andric       {MVT::iPTR, [](MVT T) { return T.isScalarInteger() || T == MVT::iPTR; }},
338ac9a064cSDimitry Andric   };
339ac9a064cSDimitry Andric 
340ac9a064cSDimitry Andric   bool Changed = false;
341ac9a064cSDimitry Andric   for (const auto &I : WildParts)
342ac9a064cSDimitry Andric     Changed |= IntersectP(I.first, I.second);
343ac9a064cSDimitry Andric 
344ac9a064cSDimitry Andric   Changed |= IntersectP(std::nullopt, [&](MVT T) {
345ac9a064cSDimitry Andric     return !any_of(WildParts, [=](const WildPartT &I) { return I.second(T); });
346ac9a064cSDimitry Andric   });
347ac9a064cSDimitry Andric 
348ac9a064cSDimitry Andric   return Changed;
349044eb2f6SDimitry Andric }
350044eb2f6SDimitry Andric 
validate() const351c7dac04cSDimitry Andric bool TypeSetByHwMode::validate() const {
352044eb2f6SDimitry Andric   if (empty())
353c7dac04cSDimitry Andric     return true;
354044eb2f6SDimitry Andric   bool AllEmpty = true;
355044eb2f6SDimitry Andric   for (const auto &I : *this)
356044eb2f6SDimitry Andric     AllEmpty &= I.second.empty();
357c7dac04cSDimitry Andric   return !AllEmpty;
358044eb2f6SDimitry Andric }
359044eb2f6SDimitry Andric 
360044eb2f6SDimitry Andric // --- TypeInfer
361044eb2f6SDimitry Andric 
MergeInTypeInfo(TypeSetByHwMode & Out,const TypeSetByHwMode & In) const362044eb2f6SDimitry Andric bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
3637fa27ce4SDimitry Andric                                 const TypeSetByHwMode &In) const {
364c7dac04cSDimitry Andric   ValidateOnExit _1(Out, *this);
365044eb2f6SDimitry Andric   In.validate();
366044eb2f6SDimitry Andric   if (In.empty() || Out == In || TP.hasError())
367044eb2f6SDimitry Andric     return false;
368044eb2f6SDimitry Andric   if (Out.empty()) {
369044eb2f6SDimitry Andric     Out = In;
370044eb2f6SDimitry Andric     return true;
371044eb2f6SDimitry Andric   }
372044eb2f6SDimitry Andric 
373044eb2f6SDimitry Andric   bool Changed = Out.constrain(In);
374044eb2f6SDimitry Andric   if (Changed && Out.empty())
375044eb2f6SDimitry Andric     TP.error("Type contradiction");
376044eb2f6SDimitry Andric 
377044eb2f6SDimitry Andric   return Changed;
378044eb2f6SDimitry Andric }
379044eb2f6SDimitry Andric 
forceArbitrary(TypeSetByHwMode & Out)380044eb2f6SDimitry Andric bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
381c7dac04cSDimitry Andric   ValidateOnExit _1(Out, *this);
382044eb2f6SDimitry Andric   if (TP.hasError())
383044eb2f6SDimitry Andric     return false;
384044eb2f6SDimitry Andric   assert(!Out.empty() && "cannot pick from an empty set");
385044eb2f6SDimitry Andric 
386044eb2f6SDimitry Andric   bool Changed = false;
387044eb2f6SDimitry Andric   for (auto &I : Out) {
388044eb2f6SDimitry Andric     TypeSetByHwMode::SetType &S = I.second;
389044eb2f6SDimitry Andric     if (S.size() <= 1)
390044eb2f6SDimitry Andric       continue;
391044eb2f6SDimitry Andric     MVT T = *S.begin(); // Pick the first element.
392044eb2f6SDimitry Andric     S.clear();
393044eb2f6SDimitry Andric     S.insert(T);
394044eb2f6SDimitry Andric     Changed = true;
395044eb2f6SDimitry Andric   }
396044eb2f6SDimitry Andric   return Changed;
397044eb2f6SDimitry Andric }
398044eb2f6SDimitry Andric 
EnforceInteger(TypeSetByHwMode & Out)399044eb2f6SDimitry Andric bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
400c7dac04cSDimitry Andric   ValidateOnExit _1(Out, *this);
401044eb2f6SDimitry Andric   if (TP.hasError())
402044eb2f6SDimitry Andric     return false;
403044eb2f6SDimitry Andric   if (!Out.empty())
404044eb2f6SDimitry Andric     return Out.constrain(isIntegerOrPtr);
405044eb2f6SDimitry Andric 
406044eb2f6SDimitry Andric   return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
407044eb2f6SDimitry Andric }
408044eb2f6SDimitry Andric 
EnforceFloatingPoint(TypeSetByHwMode & Out)409044eb2f6SDimitry Andric bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
410c7dac04cSDimitry Andric   ValidateOnExit _1(Out, *this);
411044eb2f6SDimitry Andric   if (TP.hasError())
412044eb2f6SDimitry Andric     return false;
413044eb2f6SDimitry Andric   if (!Out.empty())
414044eb2f6SDimitry Andric     return Out.constrain(isFloatingPoint);
415044eb2f6SDimitry Andric 
416044eb2f6SDimitry Andric   return Out.assign_if(getLegalTypes(), isFloatingPoint);
417044eb2f6SDimitry Andric }
418044eb2f6SDimitry Andric 
EnforceScalar(TypeSetByHwMode & Out)419044eb2f6SDimitry Andric bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
420c7dac04cSDimitry Andric   ValidateOnExit _1(Out, *this);
421044eb2f6SDimitry Andric   if (TP.hasError())
422044eb2f6SDimitry Andric     return false;
423044eb2f6SDimitry Andric   if (!Out.empty())
424044eb2f6SDimitry Andric     return Out.constrain(isScalar);
425044eb2f6SDimitry Andric 
426044eb2f6SDimitry Andric   return Out.assign_if(getLegalTypes(), isScalar);
427044eb2f6SDimitry Andric }
428044eb2f6SDimitry Andric 
EnforceVector(TypeSetByHwMode & Out)429044eb2f6SDimitry Andric bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
430c7dac04cSDimitry Andric   ValidateOnExit _1(Out, *this);
431044eb2f6SDimitry Andric   if (TP.hasError())
432044eb2f6SDimitry Andric     return false;
433044eb2f6SDimitry Andric   if (!Out.empty())
434044eb2f6SDimitry Andric     return Out.constrain(isVector);
435044eb2f6SDimitry Andric 
436044eb2f6SDimitry Andric   return Out.assign_if(getLegalTypes(), isVector);
437044eb2f6SDimitry Andric }
438044eb2f6SDimitry Andric 
EnforceAny(TypeSetByHwMode & Out)439044eb2f6SDimitry Andric bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
440c7dac04cSDimitry Andric   ValidateOnExit _1(Out, *this);
441044eb2f6SDimitry Andric   if (TP.hasError() || !Out.empty())
442044eb2f6SDimitry Andric     return false;
443044eb2f6SDimitry Andric 
444044eb2f6SDimitry Andric   Out = getLegalTypes();
445044eb2f6SDimitry Andric   return true;
446044eb2f6SDimitry Andric }
447044eb2f6SDimitry Andric 
448044eb2f6SDimitry Andric template <typename Iter, typename Pred, typename Less>
min_if(Iter B,Iter E,Pred P,Less L)449044eb2f6SDimitry Andric static Iter min_if(Iter B, Iter E, Pred P, Less L) {
450044eb2f6SDimitry Andric   if (B == E)
451044eb2f6SDimitry Andric     return E;
452044eb2f6SDimitry Andric   Iter Min = E;
453044eb2f6SDimitry Andric   for (Iter I = B; I != E; ++I) {
454044eb2f6SDimitry Andric     if (!P(*I))
455044eb2f6SDimitry Andric       continue;
456044eb2f6SDimitry Andric     if (Min == E || L(*I, *Min))
457044eb2f6SDimitry Andric       Min = I;
458044eb2f6SDimitry Andric   }
459044eb2f6SDimitry Andric   return Min;
460044eb2f6SDimitry Andric }
461044eb2f6SDimitry Andric 
462044eb2f6SDimitry Andric template <typename Iter, typename Pred, typename Less>
max_if(Iter B,Iter E,Pred P,Less L)463044eb2f6SDimitry Andric static Iter max_if(Iter B, Iter E, Pred P, Less L) {
464044eb2f6SDimitry Andric   if (B == E)
465044eb2f6SDimitry Andric     return E;
466044eb2f6SDimitry Andric   Iter Max = E;
467044eb2f6SDimitry Andric   for (Iter I = B; I != E; ++I) {
468044eb2f6SDimitry Andric     if (!P(*I))
469044eb2f6SDimitry Andric       continue;
470044eb2f6SDimitry Andric     if (Max == E || L(*Max, *I))
471044eb2f6SDimitry Andric       Max = I;
472044eb2f6SDimitry Andric   }
473044eb2f6SDimitry Andric   return Max;
474044eb2f6SDimitry Andric }
475044eb2f6SDimitry Andric 
476044eb2f6SDimitry Andric /// Make sure that for each type in Small, there exists a larger type in Big.
EnforceSmallerThan(TypeSetByHwMode & Small,TypeSetByHwMode & Big,bool SmallIsVT)477c0981da4SDimitry Andric bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small, TypeSetByHwMode &Big,
478c0981da4SDimitry Andric                                    bool SmallIsVT) {
479c7dac04cSDimitry Andric   ValidateOnExit _1(Small, *this), _2(Big, *this);
480044eb2f6SDimitry Andric   if (TP.hasError())
481044eb2f6SDimitry Andric     return false;
482044eb2f6SDimitry Andric   bool Changed = false;
483044eb2f6SDimitry Andric 
484c0981da4SDimitry Andric   assert((!SmallIsVT || !Small.empty()) &&
485c0981da4SDimitry Andric          "Small should not be empty for SDTCisVTSmallerThanOp");
486c0981da4SDimitry Andric 
487044eb2f6SDimitry Andric   if (Small.empty())
488044eb2f6SDimitry Andric     Changed |= EnforceAny(Small);
489044eb2f6SDimitry Andric   if (Big.empty())
490044eb2f6SDimitry Andric     Changed |= EnforceAny(Big);
491044eb2f6SDimitry Andric 
492044eb2f6SDimitry Andric   assert(Small.hasDefault() && Big.hasDefault());
493044eb2f6SDimitry Andric 
494344a3780SDimitry Andric   SmallVector<unsigned, 4> Modes;
495344a3780SDimitry Andric   union_modes(Small, Big, Modes);
496044eb2f6SDimitry Andric 
497044eb2f6SDimitry Andric   // 1. Only allow integer or floating point types and make sure that
498044eb2f6SDimitry Andric   //    both sides are both integer or both floating point.
499044eb2f6SDimitry Andric   // 2. Make sure that either both sides have vector types, or neither
500044eb2f6SDimitry Andric   //    of them does.
501044eb2f6SDimitry Andric   for (unsigned M : Modes) {
502044eb2f6SDimitry Andric     TypeSetByHwMode::SetType &S = Small.get(M);
503044eb2f6SDimitry Andric     TypeSetByHwMode::SetType &B = Big.get(M);
504044eb2f6SDimitry Andric 
505c0981da4SDimitry Andric     assert((!SmallIsVT || !S.empty()) && "Expected non-empty type");
506c0981da4SDimitry Andric 
507c0981da4SDimitry Andric     if (any_of(S, isIntegerOrPtr) && any_of(B, isIntegerOrPtr)) {
508044eb2f6SDimitry Andric       auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
509706b4fc4SDimitry Andric       Changed |= berase_if(S, NotInt);
510706b4fc4SDimitry Andric       Changed |= berase_if(B, NotInt);
511044eb2f6SDimitry Andric     } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
512044eb2f6SDimitry Andric       auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
513706b4fc4SDimitry Andric       Changed |= berase_if(S, NotFP);
514706b4fc4SDimitry Andric       Changed |= berase_if(B, NotFP);
515c0981da4SDimitry Andric     } else if (SmallIsVT && B.empty()) {
516c0981da4SDimitry Andric       // B is empty and since S is a specific VT, it will never be empty. Don't
517c0981da4SDimitry Andric       // report this as a change, just clear S and continue. This prevents an
518c0981da4SDimitry Andric       // infinite loop.
519c0981da4SDimitry Andric       S.clear();
520044eb2f6SDimitry Andric     } else if (S.empty() || B.empty()) {
521044eb2f6SDimitry Andric       Changed = !S.empty() || !B.empty();
522044eb2f6SDimitry Andric       S.clear();
523044eb2f6SDimitry Andric       B.clear();
524044eb2f6SDimitry Andric     } else {
525044eb2f6SDimitry Andric       TP.error("Incompatible types");
526044eb2f6SDimitry Andric       return Changed;
527044eb2f6SDimitry Andric     }
528044eb2f6SDimitry Andric 
529044eb2f6SDimitry Andric     if (none_of(S, isVector) || none_of(B, isVector)) {
530706b4fc4SDimitry Andric       Changed |= berase_if(S, isVector);
531706b4fc4SDimitry Andric       Changed |= berase_if(B, isVector);
532044eb2f6SDimitry Andric     }
533044eb2f6SDimitry Andric   }
534044eb2f6SDimitry Andric 
535044eb2f6SDimitry Andric   auto LT = [](MVT A, MVT B) -> bool {
536706b4fc4SDimitry Andric     // Always treat non-scalable MVTs as smaller than scalable MVTs for the
537706b4fc4SDimitry Andric     // purposes of ordering.
538ac9a064cSDimitry Andric     auto ASize = std::tuple(A.isScalableVector(), A.getScalarSizeInBits(),
539e3b55780SDimitry Andric                             A.getSizeInBits().getKnownMinValue());
540ac9a064cSDimitry Andric     auto BSize = std::tuple(B.isScalableVector(), B.getScalarSizeInBits(),
541e3b55780SDimitry Andric                             B.getSizeInBits().getKnownMinValue());
542706b4fc4SDimitry Andric     return ASize < BSize;
543044eb2f6SDimitry Andric   };
544706b4fc4SDimitry Andric   auto SameKindLE = [](MVT A, MVT B) -> bool {
545044eb2f6SDimitry Andric     // This function is used when removing elements: when a vector is compared
546706b4fc4SDimitry Andric     // to a non-vector or a scalable vector to any non-scalable MVT, it should
547706b4fc4SDimitry Andric     // return false (to avoid removal).
548ac9a064cSDimitry Andric     if (std::tuple(A.isVector(), A.isScalableVector()) !=
549ac9a064cSDimitry Andric         std::tuple(B.isVector(), B.isScalableVector()))
550044eb2f6SDimitry Andric       return false;
551044eb2f6SDimitry Andric 
552ac9a064cSDimitry Andric     return std::tuple(A.getScalarSizeInBits(),
553e3b55780SDimitry Andric                       A.getSizeInBits().getKnownMinValue()) <=
554ac9a064cSDimitry Andric            std::tuple(B.getScalarSizeInBits(),
555e3b55780SDimitry Andric                       B.getSizeInBits().getKnownMinValue());
556044eb2f6SDimitry Andric   };
557044eb2f6SDimitry Andric 
558044eb2f6SDimitry Andric   for (unsigned M : Modes) {
559044eb2f6SDimitry Andric     TypeSetByHwMode::SetType &S = Small.get(M);
560044eb2f6SDimitry Andric     TypeSetByHwMode::SetType &B = Big.get(M);
561044eb2f6SDimitry Andric     // MinS = min scalar in Small, remove all scalars from Big that are
562044eb2f6SDimitry Andric     // smaller-or-equal than MinS.
563044eb2f6SDimitry Andric     auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
564044eb2f6SDimitry Andric     if (MinS != S.end())
565ac9a064cSDimitry Andric       Changed |=
566ac9a064cSDimitry Andric           berase_if(B, std::bind(SameKindLE, std::placeholders::_1, *MinS));
567044eb2f6SDimitry Andric 
568044eb2f6SDimitry Andric     // MaxS = max scalar in Big, remove all scalars from Small that are
569044eb2f6SDimitry Andric     // larger than MaxS.
570044eb2f6SDimitry Andric     auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
571044eb2f6SDimitry Andric     if (MaxS != B.end())
572ac9a064cSDimitry Andric       Changed |=
573ac9a064cSDimitry Andric           berase_if(S, std::bind(SameKindLE, *MaxS, std::placeholders::_1));
574044eb2f6SDimitry Andric 
575044eb2f6SDimitry Andric     // MinV = min vector in Small, remove all vectors from Big that are
576044eb2f6SDimitry Andric     // smaller-or-equal than MinV.
577044eb2f6SDimitry Andric     auto MinV = min_if(S.begin(), S.end(), isVector, LT);
578044eb2f6SDimitry Andric     if (MinV != S.end())
579ac9a064cSDimitry Andric       Changed |=
580ac9a064cSDimitry Andric           berase_if(B, std::bind(SameKindLE, std::placeholders::_1, *MinV));
581044eb2f6SDimitry Andric 
582044eb2f6SDimitry Andric     // MaxV = max vector in Big, remove all vectors from Small that are
583044eb2f6SDimitry Andric     // larger than MaxV.
584044eb2f6SDimitry Andric     auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
585044eb2f6SDimitry Andric     if (MaxV != B.end())
586ac9a064cSDimitry Andric       Changed |=
587ac9a064cSDimitry Andric           berase_if(S, std::bind(SameKindLE, *MaxV, std::placeholders::_1));
588044eb2f6SDimitry Andric   }
589044eb2f6SDimitry Andric 
590044eb2f6SDimitry Andric   return Changed;
591044eb2f6SDimitry Andric }
592044eb2f6SDimitry Andric 
593044eb2f6SDimitry Andric /// 1. Ensure that for each type T in Vec, T is a vector type, and that
594044eb2f6SDimitry Andric ///    for each type U in Elem, U is a scalar type.
595044eb2f6SDimitry Andric /// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
596044eb2f6SDimitry Andric ///    type T in Vec, such that U is the element type of T.
EnforceVectorEltTypeIs(TypeSetByHwMode & Vec,TypeSetByHwMode & Elem)597044eb2f6SDimitry Andric bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
598044eb2f6SDimitry Andric                                        TypeSetByHwMode &Elem) {
599c7dac04cSDimitry Andric   ValidateOnExit _1(Vec, *this), _2(Elem, *this);
600044eb2f6SDimitry Andric   if (TP.hasError())
601044eb2f6SDimitry Andric     return false;
602044eb2f6SDimitry Andric   bool Changed = false;
603044eb2f6SDimitry Andric 
604044eb2f6SDimitry Andric   if (Vec.empty())
605044eb2f6SDimitry Andric     Changed |= EnforceVector(Vec);
606044eb2f6SDimitry Andric   if (Elem.empty())
607044eb2f6SDimitry Andric     Changed |= EnforceScalar(Elem);
608044eb2f6SDimitry Andric 
609344a3780SDimitry Andric   SmallVector<unsigned, 4> Modes;
610344a3780SDimitry Andric   union_modes(Vec, Elem, Modes);
611344a3780SDimitry Andric   for (unsigned M : Modes) {
612044eb2f6SDimitry Andric     TypeSetByHwMode::SetType &V = Vec.get(M);
613044eb2f6SDimitry Andric     TypeSetByHwMode::SetType &E = Elem.get(M);
614044eb2f6SDimitry Andric 
615044eb2f6SDimitry Andric     Changed |= berase_if(V, isScalar); // Scalar = !vector
616044eb2f6SDimitry Andric     Changed |= berase_if(E, isVector); // Vector = !scalar
617044eb2f6SDimitry Andric     assert(!V.empty() && !E.empty());
618044eb2f6SDimitry Andric 
619344a3780SDimitry Andric     MachineValueTypeSet VT, ST;
620044eb2f6SDimitry Andric     // Collect element types from the "vector" set.
621044eb2f6SDimitry Andric     for (MVT T : V)
622044eb2f6SDimitry Andric       VT.insert(T.getVectorElementType());
623044eb2f6SDimitry Andric     // Collect scalar types from the "element" set.
624044eb2f6SDimitry Andric     for (MVT T : E)
625044eb2f6SDimitry Andric       ST.insert(T);
626044eb2f6SDimitry Andric 
627044eb2f6SDimitry Andric     // Remove from V all (vector) types whose element type is not in S.
628044eb2f6SDimitry Andric     Changed |= berase_if(V, [&ST](MVT T) -> bool {
629044eb2f6SDimitry Andric       return !ST.count(T.getVectorElementType());
630044eb2f6SDimitry Andric     });
631044eb2f6SDimitry Andric     // Remove from E all (scalar) types, for which there is no corresponding
632044eb2f6SDimitry Andric     // type in V.
633044eb2f6SDimitry Andric     Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
634044eb2f6SDimitry Andric   }
635044eb2f6SDimitry Andric 
636044eb2f6SDimitry Andric   return Changed;
637044eb2f6SDimitry Andric }
638044eb2f6SDimitry Andric 
EnforceVectorEltTypeIs(TypeSetByHwMode & Vec,const ValueTypeByHwMode & VVT)639044eb2f6SDimitry Andric bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
640044eb2f6SDimitry Andric                                        const ValueTypeByHwMode &VVT) {
641044eb2f6SDimitry Andric   TypeSetByHwMode Tmp(VVT);
642c7dac04cSDimitry Andric   ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
643044eb2f6SDimitry Andric   return EnforceVectorEltTypeIs(Vec, Tmp);
644044eb2f6SDimitry Andric }
645044eb2f6SDimitry Andric 
646044eb2f6SDimitry Andric /// Ensure that for each type T in Sub, T is a vector type, and there
647044eb2f6SDimitry Andric /// exists a type U in Vec such that U is a vector type with the same
648044eb2f6SDimitry Andric /// element type as T and at least as many elements as T.
EnforceVectorSubVectorTypeIs(TypeSetByHwMode & Vec,TypeSetByHwMode & Sub)649044eb2f6SDimitry Andric bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
650044eb2f6SDimitry Andric                                              TypeSetByHwMode &Sub) {
651c7dac04cSDimitry Andric   ValidateOnExit _1(Vec, *this), _2(Sub, *this);
652522600a2SDimitry Andric   if (TP.hasError())
653522600a2SDimitry Andric     return false;
654522600a2SDimitry Andric 
655044eb2f6SDimitry Andric   /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
656044eb2f6SDimitry Andric   auto IsSubVec = [](MVT B, MVT P) -> bool {
657044eb2f6SDimitry Andric     if (!B.isVector() || !P.isVector())
658522600a2SDimitry Andric       return false;
659044eb2f6SDimitry Andric     // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
660044eb2f6SDimitry Andric     // but until there are obvious use-cases for this, keep the
661044eb2f6SDimitry Andric     // types separate.
662044eb2f6SDimitry Andric     if (B.isScalableVector() != P.isScalableVector())
663044eb2f6SDimitry Andric       return false;
664044eb2f6SDimitry Andric     if (B.getVectorElementType() != P.getVectorElementType())
665044eb2f6SDimitry Andric       return false;
666344a3780SDimitry Andric     return B.getVectorMinNumElements() < P.getVectorMinNumElements();
667044eb2f6SDimitry Andric   };
6682f12f10aSRoman Divacky 
669044eb2f6SDimitry Andric   /// Return true if S has no element (vector type) that T is a sub-vector of,
670044eb2f6SDimitry Andric   /// i.e. has the same element type as T and more elements.
671044eb2f6SDimitry Andric   auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
672706b4fc4SDimitry Andric     for (auto I : S)
673044eb2f6SDimitry Andric       if (IsSubVec(T, I))
674044eb2f6SDimitry Andric         return false;
6752f12f10aSRoman Divacky     return true;
676044eb2f6SDimitry Andric   };
677044eb2f6SDimitry Andric 
678044eb2f6SDimitry Andric   /// Return true if S has no element (vector type) that T is a super-vector
679044eb2f6SDimitry Andric   /// of, i.e. has the same element type as T and fewer elements.
680044eb2f6SDimitry Andric   auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
681706b4fc4SDimitry Andric     for (auto I : S)
682044eb2f6SDimitry Andric       if (IsSubVec(I, T))
683044eb2f6SDimitry Andric         return false;
684044eb2f6SDimitry Andric     return true;
685044eb2f6SDimitry Andric   };
686044eb2f6SDimitry Andric 
687044eb2f6SDimitry Andric   bool Changed = false;
688044eb2f6SDimitry Andric 
689044eb2f6SDimitry Andric   if (Vec.empty())
690044eb2f6SDimitry Andric     Changed |= EnforceVector(Vec);
691044eb2f6SDimitry Andric   if (Sub.empty())
692044eb2f6SDimitry Andric     Changed |= EnforceVector(Sub);
693044eb2f6SDimitry Andric 
694344a3780SDimitry Andric   SmallVector<unsigned, 4> Modes;
695344a3780SDimitry Andric   union_modes(Vec, Sub, Modes);
696344a3780SDimitry Andric   for (unsigned M : Modes) {
697044eb2f6SDimitry Andric     TypeSetByHwMode::SetType &S = Sub.get(M);
698044eb2f6SDimitry Andric     TypeSetByHwMode::SetType &V = Vec.get(M);
699044eb2f6SDimitry Andric 
700044eb2f6SDimitry Andric     Changed |= berase_if(S, isScalar);
701044eb2f6SDimitry Andric 
702044eb2f6SDimitry Andric     // Erase all types from S that are not sub-vectors of a type in V.
703044eb2f6SDimitry Andric     Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
704044eb2f6SDimitry Andric 
705044eb2f6SDimitry Andric     // Erase all types from V that are not super-vectors of a type in S.
706044eb2f6SDimitry Andric     Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
7072f12f10aSRoman Divacky   }
708c6910277SRoman Divacky 
709044eb2f6SDimitry Andric   return Changed;
710c6910277SRoman Divacky }
711c6910277SRoman Divacky 
712044eb2f6SDimitry Andric /// 1. Ensure that V has a scalar type iff W has a scalar type.
713044eb2f6SDimitry Andric /// 2. Ensure that for each vector type T in V, there exists a vector
714044eb2f6SDimitry Andric ///    type U in W, such that T and U have the same number of elements.
715044eb2f6SDimitry Andric /// 3. Ensure that for each vector type U in W, there exists a vector
716044eb2f6SDimitry Andric ///    type T in V, such that T and U have the same number of elements
717044eb2f6SDimitry Andric ///    (reverse of 2).
EnforceSameNumElts(TypeSetByHwMode & V,TypeSetByHwMode & W)718044eb2f6SDimitry Andric bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
719c7dac04cSDimitry Andric   ValidateOnExit _1(V, *this), _2(W, *this);
720044eb2f6SDimitry Andric   if (TP.hasError())
721c6910277SRoman Divacky     return false;
722c6910277SRoman Divacky 
723044eb2f6SDimitry Andric   bool Changed = false;
724044eb2f6SDimitry Andric   if (V.empty())
725044eb2f6SDimitry Andric     Changed |= EnforceAny(V);
726044eb2f6SDimitry Andric   if (W.empty())
727044eb2f6SDimitry Andric     Changed |= EnforceAny(W);
728044eb2f6SDimitry Andric 
729044eb2f6SDimitry Andric   // An actual vector type cannot have 0 elements, so we can treat scalars
730044eb2f6SDimitry Andric   // as zero-length vectors. This way both vectors and scalars can be
731044eb2f6SDimitry Andric   // processed identically.
732344a3780SDimitry Andric   auto NoLength = [](const SmallDenseSet<ElementCount> &Lengths,
733344a3780SDimitry Andric                      MVT T) -> bool {
734344a3780SDimitry Andric     return !Lengths.count(T.isVector() ? T.getVectorElementCount()
735e3b55780SDimitry Andric                                        : ElementCount());
736044eb2f6SDimitry Andric   };
737044eb2f6SDimitry Andric 
738344a3780SDimitry Andric   SmallVector<unsigned, 4> Modes;
739344a3780SDimitry Andric   union_modes(V, W, Modes);
740344a3780SDimitry Andric   for (unsigned M : Modes) {
741044eb2f6SDimitry Andric     TypeSetByHwMode::SetType &VS = V.get(M);
742044eb2f6SDimitry Andric     TypeSetByHwMode::SetType &WS = W.get(M);
743044eb2f6SDimitry Andric 
744344a3780SDimitry Andric     SmallDenseSet<ElementCount> VN, WN;
745044eb2f6SDimitry Andric     for (MVT T : VS)
746e3b55780SDimitry Andric       VN.insert(T.isVector() ? T.getVectorElementCount() : ElementCount());
747044eb2f6SDimitry Andric     for (MVT T : WS)
748e3b55780SDimitry Andric       WN.insert(T.isVector() ? T.getVectorElementCount() : ElementCount());
749044eb2f6SDimitry Andric 
750044eb2f6SDimitry Andric     Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
751044eb2f6SDimitry Andric     Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
752044eb2f6SDimitry Andric   }
753044eb2f6SDimitry Andric   return Changed;
754009b1c42SEd Schouten }
755009b1c42SEd Schouten 
756344a3780SDimitry Andric namespace {
757344a3780SDimitry Andric struct TypeSizeComparator {
operator ()__anonb5f07b3a1311::TypeSizeComparator758344a3780SDimitry Andric   bool operator()(const TypeSize &LHS, const TypeSize &RHS) const {
759ac9a064cSDimitry Andric     return std::tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
760ac9a064cSDimitry Andric            std::tuple(RHS.isScalable(), RHS.getKnownMinValue());
761344a3780SDimitry Andric   }
762344a3780SDimitry Andric };
763344a3780SDimitry Andric } // end anonymous namespace
764344a3780SDimitry Andric 
765044eb2f6SDimitry Andric /// 1. Ensure that for each type T in A, there exists a type U in B,
766044eb2f6SDimitry Andric ///    such that T and U have equal size in bits.
767044eb2f6SDimitry Andric /// 2. Ensure that for each type U in B, there exists a type T in A
768044eb2f6SDimitry Andric ///    such that T and U have equal size in bits (reverse of 1).
EnforceSameSize(TypeSetByHwMode & A,TypeSetByHwMode & B)769044eb2f6SDimitry Andric bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
770c7dac04cSDimitry Andric   ValidateOnExit _1(A, *this), _2(B, *this);
771044eb2f6SDimitry Andric   if (TP.hasError())
772044eb2f6SDimitry Andric     return false;
773044eb2f6SDimitry Andric   bool Changed = false;
774044eb2f6SDimitry Andric   if (A.empty())
775044eb2f6SDimitry Andric     Changed |= EnforceAny(A);
776044eb2f6SDimitry Andric   if (B.empty())
777044eb2f6SDimitry Andric     Changed |= EnforceAny(B);
778c6910277SRoman Divacky 
779344a3780SDimitry Andric   typedef SmallSet<TypeSize, 2, TypeSizeComparator> TypeSizeSet;
780344a3780SDimitry Andric 
781344a3780SDimitry Andric   auto NoSize = [](const TypeSizeSet &Sizes, MVT T) -> bool {
782044eb2f6SDimitry Andric     return !Sizes.count(T.getSizeInBits());
783044eb2f6SDimitry Andric   };
784044eb2f6SDimitry Andric 
785344a3780SDimitry Andric   SmallVector<unsigned, 4> Modes;
786344a3780SDimitry Andric   union_modes(A, B, Modes);
787344a3780SDimitry Andric   for (unsigned M : Modes) {
788044eb2f6SDimitry Andric     TypeSetByHwMode::SetType &AS = A.get(M);
789044eb2f6SDimitry Andric     TypeSetByHwMode::SetType &BS = B.get(M);
790344a3780SDimitry Andric     TypeSizeSet AN, BN;
791044eb2f6SDimitry Andric 
792044eb2f6SDimitry Andric     for (MVT T : AS)
793044eb2f6SDimitry Andric       AN.insert(T.getSizeInBits());
794044eb2f6SDimitry Andric     for (MVT T : BS)
795044eb2f6SDimitry Andric       BN.insert(T.getSizeInBits());
796044eb2f6SDimitry Andric 
797044eb2f6SDimitry Andric     Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
798044eb2f6SDimitry Andric     Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
799044eb2f6SDimitry Andric   }
800044eb2f6SDimitry Andric 
801044eb2f6SDimitry Andric   return Changed;
802044eb2f6SDimitry Andric }
803044eb2f6SDimitry Andric 
expandOverloads(TypeSetByHwMode & VTS) const8047fa27ce4SDimitry Andric void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) const {
805c7dac04cSDimitry Andric   ValidateOnExit _1(VTS, *this);
806d8e91e46SDimitry Andric   const TypeSetByHwMode &Legal = getLegalTypes();
8077fa27ce4SDimitry Andric   assert(Legal.isSimple() && "Default-mode only expected");
8087fa27ce4SDimitry Andric   const TypeSetByHwMode::SetType &LegalTypes = Legal.getSimple();
809044eb2f6SDimitry Andric 
810d8e91e46SDimitry Andric   for (auto &I : VTS)
811d8e91e46SDimitry Andric     expandOverloads(I.second, LegalTypes);
812044eb2f6SDimitry Andric }
813044eb2f6SDimitry Andric 
expandOverloads(TypeSetByHwMode::SetType & Out,const TypeSetByHwMode::SetType & Legal) const814044eb2f6SDimitry Andric void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
8157fa27ce4SDimitry Andric                                 const TypeSetByHwMode::SetType &Legal) const {
8167fa27ce4SDimitry Andric   if (Out.count(MVT::iPTRAny)) {
8177fa27ce4SDimitry Andric     Out.erase(MVT::iPTRAny);
818044eb2f6SDimitry Andric     Out.insert(MVT::iPTR);
8197fa27ce4SDimitry Andric   } else if (Out.count(MVT::iAny)) {
8207fa27ce4SDimitry Andric     Out.erase(MVT::iAny);
821044eb2f6SDimitry Andric     for (MVT T : MVT::integer_valuetypes())
822044eb2f6SDimitry Andric       if (Legal.count(T))
823044eb2f6SDimitry Andric         Out.insert(T);
8241d5ae102SDimitry Andric     for (MVT T : MVT::integer_fixedlen_vector_valuetypes())
8251d5ae102SDimitry Andric       if (Legal.count(T))
8261d5ae102SDimitry Andric         Out.insert(T);
8271d5ae102SDimitry Andric     for (MVT T : MVT::integer_scalable_vector_valuetypes())
828044eb2f6SDimitry Andric       if (Legal.count(T))
829044eb2f6SDimitry Andric         Out.insert(T);
8307fa27ce4SDimitry Andric   } else if (Out.count(MVT::fAny)) {
8317fa27ce4SDimitry Andric     Out.erase(MVT::fAny);
832044eb2f6SDimitry Andric     for (MVT T : MVT::fp_valuetypes())
833044eb2f6SDimitry Andric       if (Legal.count(T))
834044eb2f6SDimitry Andric         Out.insert(T);
8351d5ae102SDimitry Andric     for (MVT T : MVT::fp_fixedlen_vector_valuetypes())
8361d5ae102SDimitry Andric       if (Legal.count(T))
8371d5ae102SDimitry Andric         Out.insert(T);
8381d5ae102SDimitry Andric     for (MVT T : MVT::fp_scalable_vector_valuetypes())
839044eb2f6SDimitry Andric       if (Legal.count(T))
840044eb2f6SDimitry Andric         Out.insert(T);
8417fa27ce4SDimitry Andric   } else if (Out.count(MVT::vAny)) {
8427fa27ce4SDimitry Andric     Out.erase(MVT::vAny);
843044eb2f6SDimitry Andric     for (MVT T : MVT::vector_valuetypes())
844044eb2f6SDimitry Andric       if (Legal.count(T))
845044eb2f6SDimitry Andric         Out.insert(T);
8467fa27ce4SDimitry Andric   } else if (Out.count(MVT::Any)) {
8477fa27ce4SDimitry Andric     Out.erase(MVT::Any);
848044eb2f6SDimitry Andric     for (MVT T : MVT::all_valuetypes())
849044eb2f6SDimitry Andric       if (Legal.count(T))
850044eb2f6SDimitry Andric         Out.insert(T);
851522600a2SDimitry Andric   }
852dd58ef01SDimitry Andric }
853c6910277SRoman Divacky 
getLegalTypes() const8547fa27ce4SDimitry Andric const TypeSetByHwMode &TypeInfer::getLegalTypes() const {
855044eb2f6SDimitry Andric   if (!LegalTypesCached) {
856d8e91e46SDimitry Andric     TypeSetByHwMode::SetType &LegalTypes = LegalCache.getOrCreate(DefaultMode);
857044eb2f6SDimitry Andric     // Stuff all types from all modes into the default mode.
858044eb2f6SDimitry Andric     const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
859044eb2f6SDimitry Andric     for (const auto &I : LTS)
860d8e91e46SDimitry Andric       LegalTypes.insert(I.second);
861044eb2f6SDimitry Andric     LegalTypesCached = true;
862522600a2SDimitry Andric   }
8637fa27ce4SDimitry Andric   assert(LegalCache.isSimple() && "Default-mode only expected");
864d8e91e46SDimitry Andric   return LegalCache;
865dd58ef01SDimitry Andric }
8662f12f10aSRoman Divacky 
~ValidateOnExit()867c7dac04cSDimitry Andric TypeInfer::ValidateOnExit::~ValidateOnExit() {
868eb11fae6SDimitry Andric   if (Infer.Validate && !VTS.validate()) {
8697fa27ce4SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
8707fa27ce4SDimitry Andric     errs() << "Type set is empty for each HW mode:\n"
871c7dac04cSDimitry Andric               "possible type contradiction in the pattern below "
872c7dac04cSDimitry Andric               "(use -print-records with llvm-tblgen to see all "
873c7dac04cSDimitry Andric               "expanded records).\n";
874c7dac04cSDimitry Andric     Infer.TP.dump();
8757fa27ce4SDimitry Andric     errs() << "Generated from record:\n";
876344a3780SDimitry Andric     Infer.TP.getRecord()->dump();
8777fa27ce4SDimitry Andric #endif
878344a3780SDimitry Andric     PrintFatalError(Infer.TP.getRecord()->getLoc(),
879344a3780SDimitry Andric                     "Type set is empty for each HW mode in '" +
880344a3780SDimitry Andric                         Infer.TP.getRecord()->getName() + "'");
881c7dac04cSDimitry Andric   }
882c7dac04cSDimitry Andric }
883c7dac04cSDimitry Andric 
884d8e91e46SDimitry Andric //===----------------------------------------------------------------------===//
885d8e91e46SDimitry Andric // ScopedName Implementation
886d8e91e46SDimitry Andric //===----------------------------------------------------------------------===//
887d8e91e46SDimitry Andric 
operator ==(const ScopedName & o) const888d8e91e46SDimitry Andric bool ScopedName::operator==(const ScopedName &o) const {
889d8e91e46SDimitry Andric   return Scope == o.Scope && Identifier == o.Identifier;
890d8e91e46SDimitry Andric }
891d8e91e46SDimitry Andric 
operator !=(const ScopedName & o) const892ac9a064cSDimitry Andric bool ScopedName::operator!=(const ScopedName &o) const { return !(*this == o); }
893d8e91e46SDimitry Andric 
8946b943ff3SDimitry Andric //===----------------------------------------------------------------------===//
8956b943ff3SDimitry Andric // TreePredicateFn Implementation
8966b943ff3SDimitry Andric //===----------------------------------------------------------------------===//
8976b943ff3SDimitry Andric 
8986b943ff3SDimitry Andric /// TreePredicateFn constructor.  Here 'N' is a subclass of PatFrag.
TreePredicateFn(TreePattern * N)8996b943ff3SDimitry Andric TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
900044eb2f6SDimitry Andric   assert(
901044eb2f6SDimitry Andric       (!hasPredCode() || !hasImmCode()) &&
9026b943ff3SDimitry Andric       ".td file corrupt: can't have a node predicate *and* an imm predicate");
9036b943ff3SDimitry Andric }
9046b943ff3SDimitry Andric 
hasPredCode() const905044eb2f6SDimitry Andric bool TreePredicateFn::hasPredCode() const {
906ac9a064cSDimitry Andric   return isLoad() || isStore() || isAtomic() || hasNoUse() || hasOneUse() ||
907044eb2f6SDimitry Andric          !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
908044eb2f6SDimitry Andric }
909044eb2f6SDimitry Andric 
getPredCode() const9106b943ff3SDimitry Andric std::string TreePredicateFn::getPredCode() const {
911b60736ecSDimitry Andric   std::string Code;
912044eb2f6SDimitry Andric 
913044eb2f6SDimitry Andric   if (!isLoad() && !isStore() && !isAtomic()) {
914044eb2f6SDimitry Andric     Record *MemoryVT = getMemoryVT();
915044eb2f6SDimitry Andric 
916044eb2f6SDimitry Andric     if (MemoryVT)
917044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
918044eb2f6SDimitry Andric                       "MemoryVT requires IsLoad or IsStore");
919044eb2f6SDimitry Andric   }
920044eb2f6SDimitry Andric 
921044eb2f6SDimitry Andric   if (!isLoad() && !isStore()) {
922044eb2f6SDimitry Andric     if (isUnindexed())
923044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
924044eb2f6SDimitry Andric                       "IsUnindexed requires IsLoad or IsStore");
925044eb2f6SDimitry Andric 
926044eb2f6SDimitry Andric     Record *ScalarMemoryVT = getScalarMemoryVT();
927044eb2f6SDimitry Andric 
928044eb2f6SDimitry Andric     if (ScalarMemoryVT)
929044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
930044eb2f6SDimitry Andric                       "ScalarMemoryVT requires IsLoad or IsStore");
931044eb2f6SDimitry Andric   }
932044eb2f6SDimitry Andric 
933044eb2f6SDimitry Andric   if (isLoad() + isStore() + isAtomic() > 1)
934044eb2f6SDimitry Andric     PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
935044eb2f6SDimitry Andric                     "IsLoad, IsStore, and IsAtomic are mutually exclusive");
936044eb2f6SDimitry Andric 
937044eb2f6SDimitry Andric   if (isLoad()) {
938044eb2f6SDimitry Andric     if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
939044eb2f6SDimitry Andric         !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
9401d5ae102SDimitry Andric         getScalarMemoryVT() == nullptr && getAddressSpaces() == nullptr &&
9411d5ae102SDimitry Andric         getMinAlignment() < 1)
942044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
943044eb2f6SDimitry Andric                       "IsLoad cannot be used by itself");
944044eb2f6SDimitry Andric   } else {
945044eb2f6SDimitry Andric     if (isNonExtLoad())
946044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
947044eb2f6SDimitry Andric                       "IsNonExtLoad requires IsLoad");
948044eb2f6SDimitry Andric     if (isAnyExtLoad())
949044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
950044eb2f6SDimitry Andric                       "IsAnyExtLoad requires IsLoad");
9511f917f69SDimitry Andric 
9521f917f69SDimitry Andric     if (!isAtomic()) {
953044eb2f6SDimitry Andric       if (isSignExtLoad())
954044eb2f6SDimitry Andric         PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9551f917f69SDimitry Andric                         "IsSignExtLoad requires IsLoad or IsAtomic");
956044eb2f6SDimitry Andric       if (isZeroExtLoad())
957044eb2f6SDimitry Andric         PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
9581f917f69SDimitry Andric                         "IsZeroExtLoad requires IsLoad or IsAtomic");
9591f917f69SDimitry Andric     }
960044eb2f6SDimitry Andric   }
961044eb2f6SDimitry Andric 
962044eb2f6SDimitry Andric   if (isStore()) {
963044eb2f6SDimitry Andric     if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
9641d5ae102SDimitry Andric         getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr &&
9651d5ae102SDimitry Andric         getAddressSpaces() == nullptr && getMinAlignment() < 1)
966044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
967044eb2f6SDimitry Andric                       "IsStore cannot be used by itself");
968044eb2f6SDimitry Andric   } else {
969044eb2f6SDimitry Andric     if (isNonTruncStore())
970044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
971044eb2f6SDimitry Andric                       "IsNonTruncStore requires IsStore");
972044eb2f6SDimitry Andric     if (isTruncStore())
973044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
974044eb2f6SDimitry Andric                       "IsTruncStore requires IsStore");
975044eb2f6SDimitry Andric   }
976044eb2f6SDimitry Andric 
977044eb2f6SDimitry Andric   if (isAtomic()) {
978044eb2f6SDimitry Andric     if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
9791d5ae102SDimitry Andric         getAddressSpaces() == nullptr &&
9801f917f69SDimitry Andric         // FIXME: Should atomic loads be IsLoad, IsAtomic, or both?
9811f917f69SDimitry Andric         !isZeroExtLoad() && !isSignExtLoad() && !isAtomicOrderingAcquire() &&
9821f917f69SDimitry Andric         !isAtomicOrderingRelease() && !isAtomicOrderingAcquireRelease() &&
983044eb2f6SDimitry Andric         !isAtomicOrderingSequentiallyConsistent() &&
984044eb2f6SDimitry Andric         !isAtomicOrderingAcquireOrStronger() &&
985044eb2f6SDimitry Andric         !isAtomicOrderingReleaseOrStronger() &&
986044eb2f6SDimitry Andric         !isAtomicOrderingWeakerThanAcquire() &&
987044eb2f6SDimitry Andric         !isAtomicOrderingWeakerThanRelease())
988044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
989044eb2f6SDimitry Andric                       "IsAtomic cannot be used by itself");
990044eb2f6SDimitry Andric   } else {
991044eb2f6SDimitry Andric     if (isAtomicOrderingMonotonic())
992044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
993044eb2f6SDimitry Andric                       "IsAtomicOrderingMonotonic requires IsAtomic");
994044eb2f6SDimitry Andric     if (isAtomicOrderingAcquire())
995044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
996044eb2f6SDimitry Andric                       "IsAtomicOrderingAcquire requires IsAtomic");
997044eb2f6SDimitry Andric     if (isAtomicOrderingRelease())
998044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
999044eb2f6SDimitry Andric                       "IsAtomicOrderingRelease requires IsAtomic");
1000044eb2f6SDimitry Andric     if (isAtomicOrderingAcquireRelease())
1001044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1002044eb2f6SDimitry Andric                       "IsAtomicOrderingAcquireRelease requires IsAtomic");
1003044eb2f6SDimitry Andric     if (isAtomicOrderingSequentiallyConsistent())
1004ac9a064cSDimitry Andric       PrintFatalError(
1005ac9a064cSDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
1006044eb2f6SDimitry Andric           "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
1007044eb2f6SDimitry Andric     if (isAtomicOrderingAcquireOrStronger())
1008044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1009044eb2f6SDimitry Andric                       "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
1010044eb2f6SDimitry Andric     if (isAtomicOrderingReleaseOrStronger())
1011044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1012044eb2f6SDimitry Andric                       "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
1013044eb2f6SDimitry Andric     if (isAtomicOrderingWeakerThanAcquire())
1014044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1015044eb2f6SDimitry Andric                       "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
1016044eb2f6SDimitry Andric   }
1017044eb2f6SDimitry Andric 
1018044eb2f6SDimitry Andric   if (isLoad() || isStore() || isAtomic()) {
1019e6d15924SDimitry Andric     if (ListInit *AddressSpaces = getAddressSpaces()) {
1020e6d15924SDimitry Andric       Code += "unsigned AddrSpace = cast<MemSDNode>(N)->getAddressSpace();\n"
1021e6d15924SDimitry Andric               " if (";
1022e6d15924SDimitry Andric 
1023344a3780SDimitry Andric       ListSeparator LS(" && ");
1024e6d15924SDimitry Andric       for (Init *Val : AddressSpaces->getValues()) {
1025344a3780SDimitry Andric         Code += LS;
1026e6d15924SDimitry Andric 
1027e6d15924SDimitry Andric         IntInit *IntVal = dyn_cast<IntInit>(Val);
1028e6d15924SDimitry Andric         if (!IntVal) {
1029e6d15924SDimitry Andric           PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1030e6d15924SDimitry Andric                           "AddressSpaces element must be integer");
1031e6d15924SDimitry Andric         }
1032e6d15924SDimitry Andric 
1033e6d15924SDimitry Andric         Code += "AddrSpace != " + utostr(IntVal->getValue());
1034e6d15924SDimitry Andric       }
1035e6d15924SDimitry Andric 
1036e6d15924SDimitry Andric       Code += ")\nreturn false;\n";
1037e6d15924SDimitry Andric     }
1038044eb2f6SDimitry Andric 
10391d5ae102SDimitry Andric     int64_t MinAlign = getMinAlignment();
10401d5ae102SDimitry Andric     if (MinAlign > 0) {
1041cfca06d7SDimitry Andric       Code += "if (cast<MemSDNode>(N)->getAlign() < Align(";
10421d5ae102SDimitry Andric       Code += utostr(MinAlign);
1043cfca06d7SDimitry Andric       Code += "))\nreturn false;\n";
10441d5ae102SDimitry Andric     }
10451d5ae102SDimitry Andric 
1046044eb2f6SDimitry Andric     Record *MemoryVT = getMemoryVT();
1047044eb2f6SDimitry Andric 
1048044eb2f6SDimitry Andric     if (MemoryVT)
1049e6d15924SDimitry Andric       Code += ("if (cast<MemSDNode>(N)->getMemoryVT() != MVT::" +
1050044eb2f6SDimitry Andric                MemoryVT->getName() + ") return false;\n")
1051044eb2f6SDimitry Andric                   .str();
1052044eb2f6SDimitry Andric   }
1053044eb2f6SDimitry Andric 
1054044eb2f6SDimitry Andric   if (isAtomic() && isAtomicOrderingMonotonic())
1055344a3780SDimitry Andric     Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1056044eb2f6SDimitry Andric             "AtomicOrdering::Monotonic) return false;\n";
1057044eb2f6SDimitry Andric   if (isAtomic() && isAtomicOrderingAcquire())
1058344a3780SDimitry Andric     Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1059044eb2f6SDimitry Andric             "AtomicOrdering::Acquire) return false;\n";
1060044eb2f6SDimitry Andric   if (isAtomic() && isAtomicOrderingRelease())
1061344a3780SDimitry Andric     Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1062044eb2f6SDimitry Andric             "AtomicOrdering::Release) return false;\n";
1063044eb2f6SDimitry Andric   if (isAtomic() && isAtomicOrderingAcquireRelease())
1064344a3780SDimitry Andric     Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1065044eb2f6SDimitry Andric             "AtomicOrdering::AcquireRelease) return false;\n";
1066044eb2f6SDimitry Andric   if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
1067344a3780SDimitry Andric     Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1068044eb2f6SDimitry Andric             "AtomicOrdering::SequentiallyConsistent) return false;\n";
1069044eb2f6SDimitry Andric 
1070044eb2f6SDimitry Andric   if (isAtomic() && isAtomicOrderingAcquireOrStronger())
1071ac9a064cSDimitry Andric     Code +=
1072ac9a064cSDimitry Andric         "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1073044eb2f6SDimitry Andric         "return false;\n";
1074044eb2f6SDimitry Andric   if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
1075ac9a064cSDimitry Andric     Code +=
1076ac9a064cSDimitry Andric         "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1077044eb2f6SDimitry Andric         "return false;\n";
1078044eb2f6SDimitry Andric 
1079044eb2f6SDimitry Andric   if (isAtomic() && isAtomicOrderingReleaseOrStronger())
1080ac9a064cSDimitry Andric     Code +=
1081ac9a064cSDimitry Andric         "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1082044eb2f6SDimitry Andric         "return false;\n";
1083044eb2f6SDimitry Andric   if (isAtomic() && isAtomicOrderingWeakerThanRelease())
1084ac9a064cSDimitry Andric     Code +=
1085ac9a064cSDimitry Andric         "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1086044eb2f6SDimitry Andric         "return false;\n";
1087044eb2f6SDimitry Andric 
10881f917f69SDimitry Andric   // TODO: Handle atomic sextload/zextload normally when ATOMIC_LOAD is removed.
10891f917f69SDimitry Andric   if (isAtomic() && (isZeroExtLoad() || isSignExtLoad()))
10901f917f69SDimitry Andric     Code += "return false;\n";
10911f917f69SDimitry Andric 
1092044eb2f6SDimitry Andric   if (isLoad() || isStore()) {
1093044eb2f6SDimitry Andric     StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
1094044eb2f6SDimitry Andric 
1095044eb2f6SDimitry Andric     if (isUnindexed())
1096044eb2f6SDimitry Andric       Code += ("if (cast<" + SDNodeName +
1097044eb2f6SDimitry Andric                ">(N)->getAddressingMode() != ISD::UNINDEXED) "
1098044eb2f6SDimitry Andric                "return false;\n")
1099044eb2f6SDimitry Andric                   .str();
1100044eb2f6SDimitry Andric 
1101044eb2f6SDimitry Andric     if (isLoad()) {
1102044eb2f6SDimitry Andric       if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
1103044eb2f6SDimitry Andric            isZeroExtLoad()) > 1)
1104044eb2f6SDimitry Andric         PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1105044eb2f6SDimitry Andric                         "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
1106044eb2f6SDimitry Andric                         "IsZeroExtLoad are mutually exclusive");
1107044eb2f6SDimitry Andric       if (isNonExtLoad())
1108044eb2f6SDimitry Andric         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
1109044eb2f6SDimitry Andric                 "ISD::NON_EXTLOAD) return false;\n";
1110044eb2f6SDimitry Andric       if (isAnyExtLoad())
1111044eb2f6SDimitry Andric         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1112044eb2f6SDimitry Andric                 "return false;\n";
1113044eb2f6SDimitry Andric       if (isSignExtLoad())
1114044eb2f6SDimitry Andric         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1115044eb2f6SDimitry Andric                 "return false;\n";
1116044eb2f6SDimitry Andric       if (isZeroExtLoad())
1117044eb2f6SDimitry Andric         Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1118044eb2f6SDimitry Andric                 "return false;\n";
1119044eb2f6SDimitry Andric     } else {
1120044eb2f6SDimitry Andric       if ((isNonTruncStore() + isTruncStore()) > 1)
1121044eb2f6SDimitry Andric         PrintFatalError(
1122044eb2f6SDimitry Andric             getOrigPatFragRecord()->getRecord()->getLoc(),
1123044eb2f6SDimitry Andric             "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1124044eb2f6SDimitry Andric       if (isNonTruncStore())
1125044eb2f6SDimitry Andric         Code +=
1126044eb2f6SDimitry Andric             " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1127044eb2f6SDimitry Andric       if (isTruncStore())
1128044eb2f6SDimitry Andric         Code +=
1129044eb2f6SDimitry Andric             " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1130044eb2f6SDimitry Andric     }
1131044eb2f6SDimitry Andric 
1132044eb2f6SDimitry Andric     Record *ScalarMemoryVT = getScalarMemoryVT();
1133044eb2f6SDimitry Andric 
1134044eb2f6SDimitry Andric     if (ScalarMemoryVT)
1135044eb2f6SDimitry Andric       Code += ("if (cast<" + SDNodeName +
1136044eb2f6SDimitry Andric                ">(N)->getMemoryVT().getScalarType() != MVT::" +
1137044eb2f6SDimitry Andric                ScalarMemoryVT->getName() + ") return false;\n")
1138044eb2f6SDimitry Andric                   .str();
1139044eb2f6SDimitry Andric   }
1140044eb2f6SDimitry Andric 
11411f917f69SDimitry Andric   if (hasNoUse())
11421f917f69SDimitry Andric     Code += "if (!SDValue(N, 0).use_empty()) return false;\n";
1143ac9a064cSDimitry Andric   if (hasOneUse())
1144ac9a064cSDimitry Andric     Code += "if (!SDValue(N, 0).hasOneUse()) return false;\n";
11451f917f69SDimitry Andric 
1146cfca06d7SDimitry Andric   std::string PredicateCode =
1147cfca06d7SDimitry Andric       std::string(PatFragRec->getRecord()->getValueAsString("PredicateCode"));
1148044eb2f6SDimitry Andric 
1149044eb2f6SDimitry Andric   Code += PredicateCode;
1150044eb2f6SDimitry Andric 
1151044eb2f6SDimitry Andric   if (PredicateCode.empty() && !Code.empty())
1152044eb2f6SDimitry Andric     Code += "return true;\n";
1153044eb2f6SDimitry Andric 
1154044eb2f6SDimitry Andric   return Code;
1155044eb2f6SDimitry Andric }
1156044eb2f6SDimitry Andric 
hasImmCode() const1157044eb2f6SDimitry Andric bool TreePredicateFn::hasImmCode() const {
1158044eb2f6SDimitry Andric   return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
11596b943ff3SDimitry Andric }
11606b943ff3SDimitry Andric 
getImmCode() const11616b943ff3SDimitry Andric std::string TreePredicateFn::getImmCode() const {
1162cfca06d7SDimitry Andric   return std::string(
1163cfca06d7SDimitry Andric       PatFragRec->getRecord()->getValueAsString("ImmediateCode"));
11646b943ff3SDimitry Andric }
11656b943ff3SDimitry Andric 
immCodeUsesAPInt() const1166044eb2f6SDimitry Andric bool TreePredicateFn::immCodeUsesAPInt() const {
1167044eb2f6SDimitry Andric   return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1168044eb2f6SDimitry Andric }
1169044eb2f6SDimitry Andric 
immCodeUsesAPFloat() const1170044eb2f6SDimitry Andric bool TreePredicateFn::immCodeUsesAPFloat() const {
1171044eb2f6SDimitry Andric   bool Unset;
1172044eb2f6SDimitry Andric   // The return value will be false when IsAPFloat is unset.
1173044eb2f6SDimitry Andric   return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1174044eb2f6SDimitry Andric                                                                    Unset);
1175044eb2f6SDimitry Andric }
1176044eb2f6SDimitry Andric 
isPredefinedPredicateEqualTo(StringRef Field,bool Value) const1177044eb2f6SDimitry Andric bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1178044eb2f6SDimitry Andric                                                    bool Value) const {
1179044eb2f6SDimitry Andric   bool Unset;
1180044eb2f6SDimitry Andric   bool Result =
1181044eb2f6SDimitry Andric       getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1182044eb2f6SDimitry Andric   if (Unset)
1183044eb2f6SDimitry Andric     return false;
1184044eb2f6SDimitry Andric   return Result == Value;
1185044eb2f6SDimitry Andric }
usesOperands() const1186d8e91e46SDimitry Andric bool TreePredicateFn::usesOperands() const {
1187d8e91e46SDimitry Andric   return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
1188d8e91e46SDimitry Andric }
hasNoUse() const11891f917f69SDimitry Andric bool TreePredicateFn::hasNoUse() const {
11901f917f69SDimitry Andric   return isPredefinedPredicateEqualTo("HasNoUse", true);
11911f917f69SDimitry Andric }
hasOneUse() const1192ac9a064cSDimitry Andric bool TreePredicateFn::hasOneUse() const {
1193ac9a064cSDimitry Andric   return isPredefinedPredicateEqualTo("HasOneUse", true);
1194ac9a064cSDimitry Andric }
isLoad() const1195044eb2f6SDimitry Andric bool TreePredicateFn::isLoad() const {
1196044eb2f6SDimitry Andric   return isPredefinedPredicateEqualTo("IsLoad", true);
1197044eb2f6SDimitry Andric }
isStore() const1198044eb2f6SDimitry Andric bool TreePredicateFn::isStore() const {
1199044eb2f6SDimitry Andric   return isPredefinedPredicateEqualTo("IsStore", true);
1200044eb2f6SDimitry Andric }
isAtomic() const1201044eb2f6SDimitry Andric bool TreePredicateFn::isAtomic() const {
1202044eb2f6SDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomic", true);
1203044eb2f6SDimitry Andric }
isUnindexed() const1204044eb2f6SDimitry Andric bool TreePredicateFn::isUnindexed() const {
1205044eb2f6SDimitry Andric   return isPredefinedPredicateEqualTo("IsUnindexed", true);
1206044eb2f6SDimitry Andric }
isNonExtLoad() const1207044eb2f6SDimitry Andric bool TreePredicateFn::isNonExtLoad() const {
1208044eb2f6SDimitry Andric   return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1209044eb2f6SDimitry Andric }
isAnyExtLoad() const1210044eb2f6SDimitry Andric bool TreePredicateFn::isAnyExtLoad() const {
1211044eb2f6SDimitry Andric   return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1212044eb2f6SDimitry Andric }
isSignExtLoad() const1213044eb2f6SDimitry Andric bool TreePredicateFn::isSignExtLoad() const {
1214044eb2f6SDimitry Andric   return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1215044eb2f6SDimitry Andric }
isZeroExtLoad() const1216044eb2f6SDimitry Andric bool TreePredicateFn::isZeroExtLoad() const {
1217044eb2f6SDimitry Andric   return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1218044eb2f6SDimitry Andric }
isNonTruncStore() const1219044eb2f6SDimitry Andric bool TreePredicateFn::isNonTruncStore() const {
1220044eb2f6SDimitry Andric   return isPredefinedPredicateEqualTo("IsTruncStore", false);
1221044eb2f6SDimitry Andric }
isTruncStore() const1222044eb2f6SDimitry Andric bool TreePredicateFn::isTruncStore() const {
1223044eb2f6SDimitry Andric   return isPredefinedPredicateEqualTo("IsTruncStore", true);
1224044eb2f6SDimitry Andric }
isAtomicOrderingMonotonic() const1225044eb2f6SDimitry Andric bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1226044eb2f6SDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1227044eb2f6SDimitry Andric }
isAtomicOrderingAcquire() const1228044eb2f6SDimitry Andric bool TreePredicateFn::isAtomicOrderingAcquire() const {
1229044eb2f6SDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1230044eb2f6SDimitry Andric }
isAtomicOrderingRelease() const1231044eb2f6SDimitry Andric bool TreePredicateFn::isAtomicOrderingRelease() const {
1232044eb2f6SDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1233044eb2f6SDimitry Andric }
isAtomicOrderingAcquireRelease() const1234044eb2f6SDimitry Andric bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1235044eb2f6SDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1236044eb2f6SDimitry Andric }
isAtomicOrderingSequentiallyConsistent() const1237044eb2f6SDimitry Andric bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1238044eb2f6SDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1239044eb2f6SDimitry Andric                                       true);
1240044eb2f6SDimitry Andric }
isAtomicOrderingAcquireOrStronger() const1241044eb2f6SDimitry Andric bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1242ac9a064cSDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger",
1243ac9a064cSDimitry Andric                                       true);
1244044eb2f6SDimitry Andric }
isAtomicOrderingWeakerThanAcquire() const1245044eb2f6SDimitry Andric bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1246ac9a064cSDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger",
1247ac9a064cSDimitry Andric                                       false);
1248044eb2f6SDimitry Andric }
isAtomicOrderingReleaseOrStronger() const1249044eb2f6SDimitry Andric bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1250ac9a064cSDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger",
1251ac9a064cSDimitry Andric                                       true);
1252044eb2f6SDimitry Andric }
isAtomicOrderingWeakerThanRelease() const1253044eb2f6SDimitry Andric bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1254ac9a064cSDimitry Andric   return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger",
1255ac9a064cSDimitry Andric                                       false);
1256044eb2f6SDimitry Andric }
getMemoryVT() const1257044eb2f6SDimitry Andric Record *TreePredicateFn::getMemoryVT() const {
1258044eb2f6SDimitry Andric   Record *R = getOrigPatFragRecord()->getRecord();
1259044eb2f6SDimitry Andric   if (R->isValueUnset("MemoryVT"))
1260044eb2f6SDimitry Andric     return nullptr;
1261044eb2f6SDimitry Andric   return R->getValueAsDef("MemoryVT");
1262044eb2f6SDimitry Andric }
1263e6d15924SDimitry Andric 
getAddressSpaces() const1264e6d15924SDimitry Andric ListInit *TreePredicateFn::getAddressSpaces() const {
1265e6d15924SDimitry Andric   Record *R = getOrigPatFragRecord()->getRecord();
1266e6d15924SDimitry Andric   if (R->isValueUnset("AddressSpaces"))
1267e6d15924SDimitry Andric     return nullptr;
1268e6d15924SDimitry Andric   return R->getValueAsListInit("AddressSpaces");
1269e6d15924SDimitry Andric }
1270e6d15924SDimitry Andric 
getMinAlignment() const12711d5ae102SDimitry Andric int64_t TreePredicateFn::getMinAlignment() const {
12721d5ae102SDimitry Andric   Record *R = getOrigPatFragRecord()->getRecord();
12731d5ae102SDimitry Andric   if (R->isValueUnset("MinAlignment"))
12741d5ae102SDimitry Andric     return 0;
12751d5ae102SDimitry Andric   return R->getValueAsInt("MinAlignment");
12761d5ae102SDimitry Andric }
12771d5ae102SDimitry Andric 
getScalarMemoryVT() const1278044eb2f6SDimitry Andric Record *TreePredicateFn::getScalarMemoryVT() const {
1279044eb2f6SDimitry Andric   Record *R = getOrigPatFragRecord()->getRecord();
1280044eb2f6SDimitry Andric   if (R->isValueUnset("ScalarMemoryVT"))
1281044eb2f6SDimitry Andric     return nullptr;
1282044eb2f6SDimitry Andric   return R->getValueAsDef("ScalarMemoryVT");
1283044eb2f6SDimitry Andric }
hasGISelPredicateCode() const1284eb11fae6SDimitry Andric bool TreePredicateFn::hasGISelPredicateCode() const {
1285eb11fae6SDimitry Andric   return !PatFragRec->getRecord()
1286eb11fae6SDimitry Andric               ->getValueAsString("GISelPredicateCode")
1287eb11fae6SDimitry Andric               .empty();
1288eb11fae6SDimitry Andric }
getGISelPredicateCode() const1289eb11fae6SDimitry Andric std::string TreePredicateFn::getGISelPredicateCode() const {
1290cfca06d7SDimitry Andric   return std::string(
1291cfca06d7SDimitry Andric       PatFragRec->getRecord()->getValueAsString("GISelPredicateCode"));
1292eb11fae6SDimitry Andric }
1293044eb2f6SDimitry Andric 
getImmType() const1294044eb2f6SDimitry Andric StringRef TreePredicateFn::getImmType() const {
1295044eb2f6SDimitry Andric   if (immCodeUsesAPInt())
1296044eb2f6SDimitry Andric     return "const APInt &";
1297044eb2f6SDimitry Andric   if (immCodeUsesAPFloat())
1298044eb2f6SDimitry Andric     return "const APFloat &";
1299044eb2f6SDimitry Andric   return "int64_t";
1300044eb2f6SDimitry Andric }
1301044eb2f6SDimitry Andric 
getImmTypeIdentifier() const1302044eb2f6SDimitry Andric StringRef TreePredicateFn::getImmTypeIdentifier() const {
1303044eb2f6SDimitry Andric   if (immCodeUsesAPInt())
1304044eb2f6SDimitry Andric     return "APInt";
1305344a3780SDimitry Andric   if (immCodeUsesAPFloat())
1306044eb2f6SDimitry Andric     return "APFloat";
1307044eb2f6SDimitry Andric   return "I64";
1308044eb2f6SDimitry Andric }
13096b943ff3SDimitry Andric 
13106b943ff3SDimitry Andric /// isAlwaysTrue - Return true if this is a noop predicate.
isAlwaysTrue() const13116b943ff3SDimitry Andric bool TreePredicateFn::isAlwaysTrue() const {
1312044eb2f6SDimitry Andric   return !hasPredCode() && !hasImmCode();
13136b943ff3SDimitry Andric }
13146b943ff3SDimitry Andric 
13156b943ff3SDimitry Andric /// Return the name to use in the generated code to reference this, this is
13166b943ff3SDimitry Andric /// "Predicate_foo" if from a pattern fragment "foo".
getFnName() const13176b943ff3SDimitry Andric std::string TreePredicateFn::getFnName() const {
1318b915e9e0SDimitry Andric   return "Predicate_" + PatFragRec->getRecord()->getName().str();
13196b943ff3SDimitry Andric }
13206b943ff3SDimitry Andric 
13216b943ff3SDimitry Andric /// getCodeToRunOnSDNode - Return the code for the function body that
13226b943ff3SDimitry Andric /// evaluates this predicate.  The argument is expected to be in "Node",
13236b943ff3SDimitry Andric /// not N.  This handles casting and conversion to a concrete node type as
13246b943ff3SDimitry Andric /// appropriate.
getCodeToRunOnSDNode() const13256b943ff3SDimitry Andric std::string TreePredicateFn::getCodeToRunOnSDNode() const {
13266b943ff3SDimitry Andric   // Handle immediate predicates first.
13276b943ff3SDimitry Andric   std::string ImmCode = getImmCode();
13286b943ff3SDimitry Andric   if (!ImmCode.empty()) {
1329044eb2f6SDimitry Andric     if (isLoad())
1330044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1331044eb2f6SDimitry Andric                       "IsLoad cannot be used with ImmLeaf or its subclasses");
1332044eb2f6SDimitry Andric     if (isStore())
1333044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1334044eb2f6SDimitry Andric                       "IsStore cannot be used with ImmLeaf or its subclasses");
1335044eb2f6SDimitry Andric     if (isUnindexed())
1336044eb2f6SDimitry Andric       PrintFatalError(
1337044eb2f6SDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
1338044eb2f6SDimitry Andric           "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1339044eb2f6SDimitry Andric     if (isNonExtLoad())
1340044eb2f6SDimitry Andric       PrintFatalError(
1341044eb2f6SDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
1342044eb2f6SDimitry Andric           "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1343044eb2f6SDimitry Andric     if (isAnyExtLoad())
1344044eb2f6SDimitry Andric       PrintFatalError(
1345044eb2f6SDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
1346044eb2f6SDimitry Andric           "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1347044eb2f6SDimitry Andric     if (isSignExtLoad())
1348044eb2f6SDimitry Andric       PrintFatalError(
1349044eb2f6SDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
1350044eb2f6SDimitry Andric           "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1351044eb2f6SDimitry Andric     if (isZeroExtLoad())
1352044eb2f6SDimitry Andric       PrintFatalError(
1353044eb2f6SDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
1354044eb2f6SDimitry Andric           "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1355044eb2f6SDimitry Andric     if (isNonTruncStore())
1356044eb2f6SDimitry Andric       PrintFatalError(
1357044eb2f6SDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
1358044eb2f6SDimitry Andric           "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1359044eb2f6SDimitry Andric     if (isTruncStore())
1360044eb2f6SDimitry Andric       PrintFatalError(
1361044eb2f6SDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
1362044eb2f6SDimitry Andric           "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1363044eb2f6SDimitry Andric     if (getMemoryVT())
1364044eb2f6SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1365044eb2f6SDimitry Andric                       "MemoryVT cannot be used with ImmLeaf or its subclasses");
1366044eb2f6SDimitry Andric     if (getScalarMemoryVT())
1367044eb2f6SDimitry Andric       PrintFatalError(
1368044eb2f6SDimitry Andric           getOrigPatFragRecord()->getRecord()->getLoc(),
1369044eb2f6SDimitry Andric           "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1370044eb2f6SDimitry Andric 
1371044eb2f6SDimitry Andric     std::string Result = ("    " + getImmType() + " Imm = ").str();
1372044eb2f6SDimitry Andric     if (immCodeUsesAPFloat())
1373044eb2f6SDimitry Andric       Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1374044eb2f6SDimitry Andric     else if (immCodeUsesAPInt())
1375950076cdSDimitry Andric       Result += "Node->getAsAPIntVal();\n";
1376044eb2f6SDimitry Andric     else
1377044eb2f6SDimitry Andric       Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
13786b943ff3SDimitry Andric     return Result + ImmCode;
13796b943ff3SDimitry Andric   }
13806b943ff3SDimitry Andric 
13816b943ff3SDimitry Andric   // Handle arbitrary node predicates.
1382044eb2f6SDimitry Andric   assert(hasPredCode() && "Don't have any predicate code!");
1383706b4fc4SDimitry Andric 
1384706b4fc4SDimitry Andric   // If this is using PatFrags, there are multiple trees to search. They should
1385706b4fc4SDimitry Andric   // all have the same class.  FIXME: Is there a way to find a common
1386706b4fc4SDimitry Andric   // superclass?
1387044eb2f6SDimitry Andric   StringRef ClassName;
1388706b4fc4SDimitry Andric   for (const auto &Tree : PatFragRec->getTrees()) {
1389706b4fc4SDimitry Andric     StringRef TreeClassName;
1390706b4fc4SDimitry Andric     if (Tree->isLeaf())
1391706b4fc4SDimitry Andric       TreeClassName = "SDNode";
13926b943ff3SDimitry Andric     else {
1393706b4fc4SDimitry Andric       Record *Op = Tree->getOperator();
1394706b4fc4SDimitry Andric       const SDNodeInfo &Info = PatFragRec->getDAGPatterns().getSDNodeInfo(Op);
1395706b4fc4SDimitry Andric       TreeClassName = Info.getSDClassName();
13966b943ff3SDimitry Andric     }
1397706b4fc4SDimitry Andric 
1398706b4fc4SDimitry Andric     if (ClassName.empty())
1399706b4fc4SDimitry Andric       ClassName = TreeClassName;
1400706b4fc4SDimitry Andric     else if (ClassName != TreeClassName) {
1401706b4fc4SDimitry Andric       PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1402706b4fc4SDimitry Andric                       "PatFrags trees do not have consistent class");
1403706b4fc4SDimitry Andric     }
1404706b4fc4SDimitry Andric   }
1405706b4fc4SDimitry Andric 
14066b943ff3SDimitry Andric   std::string Result;
14076b943ff3SDimitry Andric   if (ClassName == "SDNode")
14086b943ff3SDimitry Andric     Result = "    SDNode *N = Node;\n";
14096b943ff3SDimitry Andric   else
1410044eb2f6SDimitry Andric     Result = "    auto *N = cast<" + ClassName.str() + ">(Node);\n";
14116b943ff3SDimitry Andric 
1412d8e91e46SDimitry Andric   return (Twine(Result) + "    (void)N;\n" + getPredCode()).str();
1413009b1c42SEd Schouten }
1414009b1c42SEd Schouten 
1415009b1c42SEd Schouten //===----------------------------------------------------------------------===//
1416009b1c42SEd Schouten // PatternToMatch implementation
1417009b1c42SEd Schouten //
1418009b1c42SEd Schouten 
isImmAllOnesAllZerosMatch(const TreePatternNode & P)1419ac9a064cSDimitry Andric static bool isImmAllOnesAllZerosMatch(const TreePatternNode &P) {
1420ac9a064cSDimitry Andric   if (!P.isLeaf())
1421e6d15924SDimitry Andric     return false;
1422ac9a064cSDimitry Andric   DefInit *DI = dyn_cast<DefInit>(P.getLeafValue());
1423e6d15924SDimitry Andric   if (!DI)
1424e6d15924SDimitry Andric     return false;
1425e6d15924SDimitry Andric 
1426e6d15924SDimitry Andric   Record *R = DI->getDef();
1427e6d15924SDimitry Andric   return R->getName() == "immAllOnesV" || R->getName() == "immAllZerosV";
1428e6d15924SDimitry Andric }
1429e6d15924SDimitry Andric 
1430104bd817SRoman Divacky /// getPatternSize - Return the 'size' of this pattern.  We want to match large
1431104bd817SRoman Divacky /// patterns before small ones.  This is used to determine the size of a
1432104bd817SRoman Divacky /// pattern.
getPatternSize(const TreePatternNode & P,const CodeGenDAGPatterns & CGP)1433ac9a064cSDimitry Andric static unsigned getPatternSize(const TreePatternNode &P,
1434104bd817SRoman Divacky                                const CodeGenDAGPatterns &CGP) {
1435104bd817SRoman Divacky   unsigned Size = 3; // The node itself.
1436104bd817SRoman Divacky   // If the root node is a ConstantSDNode, increases its size.
1437104bd817SRoman Divacky   // e.g. (set R32:$dst, 0).
1438ac9a064cSDimitry Andric   if (P.isLeaf() && isa<IntInit>(P.getLeafValue()))
1439104bd817SRoman Divacky     Size += 2;
1440104bd817SRoman Divacky 
1441ac9a064cSDimitry Andric   if (const ComplexPattern *AM = P.getComplexPatternInfo(CGP)) {
1442b915e9e0SDimitry Andric     Size += AM->getComplexity();
14435ca98fd9SDimitry Andric     // We don't want to count any children twice, so return early.
14445ca98fd9SDimitry Andric     return Size;
14455ca98fd9SDimitry Andric   }
14465ca98fd9SDimitry Andric 
1447104bd817SRoman Divacky   // If this node has some predicate function that must match, it adds to the
1448104bd817SRoman Divacky   // complexity of this node.
1449ac9a064cSDimitry Andric   if (!P.getPredicateCalls().empty())
1450104bd817SRoman Divacky     ++Size;
1451104bd817SRoman Divacky 
1452104bd817SRoman Divacky   // Count children in the count if they are also nodes.
1453ac9a064cSDimitry Andric   for (unsigned i = 0, e = P.getNumChildren(); i != e; ++i) {
1454ac9a064cSDimitry Andric     const TreePatternNode &Child = P.getChild(i);
1455ac9a064cSDimitry Andric     if (!Child.isLeaf() && Child.getNumTypes()) {
1456ac9a064cSDimitry Andric       const TypeSetByHwMode &T0 = Child.getExtType(0);
1457044eb2f6SDimitry Andric       // At this point, all variable type sets should be simple, i.e. only
1458044eb2f6SDimitry Andric       // have a default mode.
1459044eb2f6SDimitry Andric       if (T0.getMachineValueType() != MVT::Other) {
1460104bd817SRoman Divacky         Size += getPatternSize(Child, CGP);
1461044eb2f6SDimitry Andric         continue;
1462044eb2f6SDimitry Andric       }
1463044eb2f6SDimitry Andric     }
1464ac9a064cSDimitry Andric     if (Child.isLeaf()) {
1465ac9a064cSDimitry Andric       if (isa<IntInit>(Child.getLeafValue()))
1466104bd817SRoman Divacky         Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
1467ac9a064cSDimitry Andric       else if (Child.getComplexPatternInfo(CGP))
1468104bd817SRoman Divacky         Size += getPatternSize(Child, CGP);
1469e6d15924SDimitry Andric       else if (isImmAllOnesAllZerosMatch(Child))
1470e6d15924SDimitry Andric         Size += 4; // Matches a build_vector(+3) and a predicate (+1).
1471ac9a064cSDimitry Andric       else if (!Child.getPredicateCalls().empty())
1472104bd817SRoman Divacky         ++Size;
1473104bd817SRoman Divacky     }
1474104bd817SRoman Divacky   }
1475104bd817SRoman Divacky 
1476104bd817SRoman Divacky   return Size;
1477104bd817SRoman Divacky }
1478104bd817SRoman Divacky 
1479104bd817SRoman Divacky /// Compute the complexity metric for the input pattern.  This roughly
1480104bd817SRoman Divacky /// corresponds to the number of nodes that are covered.
getPatternComplexity(const CodeGenDAGPatterns & CGP) const1481ac9a064cSDimitry Andric int PatternToMatch::getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
1482104bd817SRoman Divacky   return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
1483104bd817SRoman Divacky }
1484104bd817SRoman Divacky 
getPredicateRecords(SmallVectorImpl<Record * > & PredicateRecs) const1485344a3780SDimitry Andric void PatternToMatch::getPredicateRecords(
1486344a3780SDimitry Andric     SmallVectorImpl<Record *> &PredicateRecs) const {
1487344a3780SDimitry Andric   for (Init *I : Predicates->getValues()) {
1488344a3780SDimitry Andric     if (DefInit *Pred = dyn_cast<DefInit>(I)) {
1489344a3780SDimitry Andric       Record *Def = Pred->getDef();
1490344a3780SDimitry Andric       if (!Def->isSubClassOf("Predicate")) {
1491344a3780SDimitry Andric #ifndef NDEBUG
1492344a3780SDimitry Andric         Def->dump();
1493344a3780SDimitry Andric #endif
1494344a3780SDimitry Andric         llvm_unreachable("Unknown predicate type!");
1495344a3780SDimitry Andric       }
1496344a3780SDimitry Andric       PredicateRecs.push_back(Def);
1497344a3780SDimitry Andric     }
1498344a3780SDimitry Andric   }
1499344a3780SDimitry Andric   // Sort so that different orders get canonicalized to the same string.
1500344a3780SDimitry Andric   llvm::sort(PredicateRecs, LessRecord());
15017fa27ce4SDimitry Andric   // Remove duplicate predicates.
1502ac9a064cSDimitry Andric   PredicateRecs.erase(llvm::unique(PredicateRecs), PredicateRecs.end());
1503344a3780SDimitry Andric }
1504344a3780SDimitry Andric 
1505009b1c42SEd Schouten /// getPredicateCheck - Return a single string containing all of this
1506009b1c42SEd Schouten /// pattern's predicates concatenated with "&&" operators.
1507009b1c42SEd Schouten ///
getPredicateCheck() const1508009b1c42SEd Schouten std::string PatternToMatch::getPredicateCheck() const {
1509344a3780SDimitry Andric   SmallVector<Record *, 4> PredicateRecs;
1510344a3780SDimitry Andric   getPredicateRecords(PredicateRecs);
1511dd58ef01SDimitry Andric 
1512344a3780SDimitry Andric   SmallString<128> PredicateCheck;
15137fa27ce4SDimitry Andric   raw_svector_ostream OS(PredicateCheck);
15147fa27ce4SDimitry Andric   ListSeparator LS(" && ");
1515344a3780SDimitry Andric   for (Record *Pred : PredicateRecs) {
1516344a3780SDimitry Andric     StringRef CondString = Pred->getValueAsString("CondString");
1517344a3780SDimitry Andric     if (CondString.empty())
1518344a3780SDimitry Andric       continue;
15197fa27ce4SDimitry Andric     OS << LS << '(' << CondString << ')';
1520009b1c42SEd Schouten   }
1521344a3780SDimitry Andric 
15227fa27ce4SDimitry Andric   if (!HwModeFeatures.empty())
15237fa27ce4SDimitry Andric     OS << LS << HwModeFeatures;
1524344a3780SDimitry Andric 
1525344a3780SDimitry Andric   return std::string(PredicateCheck);
1526009b1c42SEd Schouten }
1527009b1c42SEd Schouten 
1528009b1c42SEd Schouten //===----------------------------------------------------------------------===//
1529009b1c42SEd Schouten // SDTypeConstraint implementation
1530009b1c42SEd Schouten //
1531009b1c42SEd Schouten 
SDTypeConstraint(Record * R,const CodeGenHwModes & CGH)1532044eb2f6SDimitry Andric SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
1533009b1c42SEd Schouten   OperandNo = R->getValueAsInt("OperandNum");
1534009b1c42SEd Schouten 
1535009b1c42SEd Schouten   if (R->isSubClassOf("SDTCisVT")) {
1536009b1c42SEd Schouten     ConstraintType = SDTCisVT;
1537044eb2f6SDimitry Andric     VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1538044eb2f6SDimitry Andric     for (const auto &P : VVT)
1539044eb2f6SDimitry Andric       if (P.second == MVT::isVoid)
1540522600a2SDimitry Andric         PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
1541009b1c42SEd Schouten   } else if (R->isSubClassOf("SDTCisPtrTy")) {
1542009b1c42SEd Schouten     ConstraintType = SDTCisPtrTy;
1543009b1c42SEd Schouten   } else if (R->isSubClassOf("SDTCisInt")) {
1544009b1c42SEd Schouten     ConstraintType = SDTCisInt;
1545009b1c42SEd Schouten   } else if (R->isSubClassOf("SDTCisFP")) {
1546009b1c42SEd Schouten     ConstraintType = SDTCisFP;
154759850d08SRoman Divacky   } else if (R->isSubClassOf("SDTCisVec")) {
154859850d08SRoman Divacky     ConstraintType = SDTCisVec;
1549009b1c42SEd Schouten   } else if (R->isSubClassOf("SDTCisSameAs")) {
1550009b1c42SEd Schouten     ConstraintType = SDTCisSameAs;
1551009b1c42SEd Schouten     x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1552009b1c42SEd Schouten   } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1553009b1c42SEd Schouten     ConstraintType = SDTCisVTSmallerThanOp;
1554009b1c42SEd Schouten     x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
1555009b1c42SEd Schouten         R->getValueAsInt("OtherOperandNum");
1556009b1c42SEd Schouten   } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1557009b1c42SEd Schouten     ConstraintType = SDTCisOpSmallerThanOp;
1558009b1c42SEd Schouten     x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
1559009b1c42SEd Schouten         R->getValueAsInt("BigOperandNum");
1560009b1c42SEd Schouten   } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1561009b1c42SEd Schouten     ConstraintType = SDTCisEltOfVec;
1562c6910277SRoman Divacky     x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
1563cf099d11SDimitry Andric   } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1564cf099d11SDimitry Andric     ConstraintType = SDTCisSubVecOfVec;
1565ac9a064cSDimitry Andric     x.SDTCisSubVecOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
15665a5ac124SDimitry Andric   } else if (R->isSubClassOf("SDTCVecEltisVT")) {
15675a5ac124SDimitry Andric     ConstraintType = SDTCVecEltisVT;
1568044eb2f6SDimitry Andric     VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1569044eb2f6SDimitry Andric     for (const auto &P : VVT) {
1570044eb2f6SDimitry Andric       MVT T = P.second;
1571044eb2f6SDimitry Andric       if (T.isVector())
1572044eb2f6SDimitry Andric         PrintFatalError(R->getLoc(),
1573044eb2f6SDimitry Andric                         "Cannot use vector type as SDTCVecEltisVT");
1574044eb2f6SDimitry Andric       if (!T.isInteger() && !T.isFloatingPoint())
15755a5ac124SDimitry Andric         PrintFatalError(R->getLoc(), "Must use integer or floating point type "
15765a5ac124SDimitry Andric                                      "as SDTCVecEltisVT");
1577044eb2f6SDimitry Andric     }
15785a5ac124SDimitry Andric   } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
15795a5ac124SDimitry Andric     ConstraintType = SDTCisSameNumEltsAs;
15805a5ac124SDimitry Andric     x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
15815a5ac124SDimitry Andric         R->getValueAsInt("OtherOperandNum");
1582dd58ef01SDimitry Andric   } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1583dd58ef01SDimitry Andric     ConstraintType = SDTCisSameSizeAs;
1584dd58ef01SDimitry Andric     x.SDTCisSameSizeAs_Info.OtherOperandNum =
1585dd58ef01SDimitry Andric         R->getValueAsInt("OtherOperandNum");
1586009b1c42SEd Schouten   } else {
1587e6d15924SDimitry Andric     PrintFatalError(R->getLoc(),
1588e6d15924SDimitry Andric                     "Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
1589009b1c42SEd Schouten   }
1590009b1c42SEd Schouten }
1591009b1c42SEd Schouten 
1592009b1c42SEd Schouten /// getOperandNum - Return the node corresponding to operand #OpNo in tree
15932f12f10aSRoman Divacky /// N, and the result number in ResNo.
getOperandNum(unsigned OpNo,TreePatternNode & N,const SDNodeInfo & NodeInfo,unsigned & ResNo)1594ac9a064cSDimitry Andric static TreePatternNode &getOperandNum(unsigned OpNo, TreePatternNode &N,
15952f12f10aSRoman Divacky                                       const SDNodeInfo &NodeInfo,
15962f12f10aSRoman Divacky                                       unsigned &ResNo) {
15972f12f10aSRoman Divacky   unsigned NumResults = NodeInfo.getNumResults();
15982f12f10aSRoman Divacky   if (OpNo < NumResults) {
15992f12f10aSRoman Divacky     ResNo = OpNo;
16002f12f10aSRoman Divacky     return N;
16012f12f10aSRoman Divacky   }
1602009b1c42SEd Schouten 
16032f12f10aSRoman Divacky   OpNo -= NumResults;
16042f12f10aSRoman Divacky 
1605ac9a064cSDimitry Andric   if (OpNo >= N.getNumChildren()) {
16065a5ac124SDimitry Andric     std::string S;
16075a5ac124SDimitry Andric     raw_string_ostream OS(S);
1608ac9a064cSDimitry Andric     OS << "Invalid operand number in type constraint " << (OpNo + NumResults)
1609ac9a064cSDimitry Andric        << " ";
1610ac9a064cSDimitry Andric     N.print(OS);
161177fc4c14SDimitry Andric     PrintFatalError(S);
1612009b1c42SEd Schouten   }
1613009b1c42SEd Schouten 
1614ac9a064cSDimitry Andric   return N.getChild(OpNo);
1615009b1c42SEd Schouten }
1616009b1c42SEd Schouten 
1617009b1c42SEd Schouten /// ApplyTypeConstraint - Given a node in a pattern, apply this type
1618009b1c42SEd Schouten /// constraint to the nodes operands.  This returns true if it makes a
1619522600a2SDimitry Andric /// change, false otherwise.  If a type contradiction is found, flag an error.
ApplyTypeConstraint(TreePatternNode & N,const SDNodeInfo & NodeInfo,TreePattern & TP) const1620ac9a064cSDimitry Andric bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode &N,
1621009b1c42SEd Schouten                                            const SDNodeInfo &NodeInfo,
1622009b1c42SEd Schouten                                            TreePattern &TP) const {
1623522600a2SDimitry Andric   if (TP.hasError())
1624522600a2SDimitry Andric     return false;
1625522600a2SDimitry Andric 
16262f12f10aSRoman Divacky   unsigned ResNo = 0; // The result number being referenced.
1627ac9a064cSDimitry Andric   TreePatternNode &NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
1628044eb2f6SDimitry Andric   TypeInfer &TI = TP.getInfer();
1629009b1c42SEd Schouten 
1630009b1c42SEd Schouten   switch (ConstraintType) {
1631009b1c42SEd Schouten   case SDTCisVT:
1632009b1c42SEd Schouten     // Operand must be a particular type.
1633ac9a064cSDimitry Andric     return NodeToApply.UpdateNodeType(ResNo, VVT, TP);
1634c6910277SRoman Divacky   case SDTCisPtrTy:
1635009b1c42SEd Schouten     // Operand must be same as target pointer type.
1636ac9a064cSDimitry Andric     return NodeToApply.UpdateNodeType(ResNo, MVT::iPTR, TP);
1637c6910277SRoman Divacky   case SDTCisInt:
1638c6910277SRoman Divacky     // Require it to be one of the legal integer VTs.
1639ac9a064cSDimitry Andric     return TI.EnforceInteger(NodeToApply.getExtType(ResNo));
1640c6910277SRoman Divacky   case SDTCisFP:
1641c6910277SRoman Divacky     // Require it to be one of the legal fp VTs.
1642ac9a064cSDimitry Andric     return TI.EnforceFloatingPoint(NodeToApply.getExtType(ResNo));
1643c6910277SRoman Divacky   case SDTCisVec:
1644c6910277SRoman Divacky     // Require it to be one of the legal vector VTs.
1645ac9a064cSDimitry Andric     return TI.EnforceVector(NodeToApply.getExtType(ResNo));
1646009b1c42SEd Schouten   case SDTCisSameAs: {
16472f12f10aSRoman Divacky     unsigned OResNo = 0;
1648ac9a064cSDimitry Andric     TreePatternNode &OtherNode =
16492f12f10aSRoman Divacky         getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
1650ac9a064cSDimitry Andric     return (int)NodeToApply.UpdateNodeType(ResNo, OtherNode.getExtType(OResNo),
1651ac9a064cSDimitry Andric                                            TP) |
1652ac9a064cSDimitry Andric            (int)OtherNode.UpdateNodeType(OResNo, NodeToApply.getExtType(ResNo),
1653ac9a064cSDimitry Andric                                          TP);
1654009b1c42SEd Schouten   }
1655009b1c42SEd Schouten   case SDTCisVTSmallerThanOp: {
1656009b1c42SEd Schouten     // The NodeToApply must be a leaf node that is a VT.  OtherOperandNum must
1657009b1c42SEd Schouten     // have an integer type that is smaller than the VT.
1658ac9a064cSDimitry Andric     if (!NodeToApply.isLeaf() || !isa<DefInit>(NodeToApply.getLeafValue()) ||
1659ac9a064cSDimitry Andric         !cast<DefInit>(NodeToApply.getLeafValue())
1660ac9a064cSDimitry Andric              ->getDef()
1661522600a2SDimitry Andric              ->isSubClassOf("ValueType")) {
1662ac9a064cSDimitry Andric       TP.error(N.getOperator()->getName() + " expects a VT operand!");
1663522600a2SDimitry Andric       return false;
1664522600a2SDimitry Andric     }
1665ac9a064cSDimitry Andric     DefInit *DI = cast<DefInit>(NodeToApply.getLeafValue());
1666044eb2f6SDimitry Andric     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1667044eb2f6SDimitry Andric     auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1668044eb2f6SDimitry Andric     TypeSetByHwMode TypeListTmp(VVT);
1669009b1c42SEd Schouten 
16702f12f10aSRoman Divacky     unsigned OResNo = 0;
1671ac9a064cSDimitry Andric     TreePatternNode &OtherNode = getOperandNum(
1672ac9a064cSDimitry Andric         x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo, OResNo);
1673009b1c42SEd Schouten 
1674ac9a064cSDimitry Andric     return TI.EnforceSmallerThan(TypeListTmp, OtherNode.getExtType(OResNo),
1675c0981da4SDimitry Andric                                  /*SmallIsVT*/ true);
1676009b1c42SEd Schouten   }
1677009b1c42SEd Schouten   case SDTCisOpSmallerThanOp: {
16782f12f10aSRoman Divacky     unsigned BResNo = 0;
1679ac9a064cSDimitry Andric     TreePatternNode &BigOperand = getOperandNum(
1680ac9a064cSDimitry Andric         x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo, BResNo);
1681ac9a064cSDimitry Andric     return TI.EnforceSmallerThan(NodeToApply.getExtType(ResNo),
1682ac9a064cSDimitry Andric                                  BigOperand.getExtType(BResNo));
1683009b1c42SEd Schouten   }
1684009b1c42SEd Schouten   case SDTCisEltOfVec: {
16852f12f10aSRoman Divacky     unsigned VResNo = 0;
1686ac9a064cSDimitry Andric     TreePatternNode &VecOperand = getOperandNum(
1687ac9a064cSDimitry Andric         x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo, VResNo);
1688c6910277SRoman Divacky     // Filter vector types out of VecOperand that don't have the right element
1689c6910277SRoman Divacky     // type.
1690ac9a064cSDimitry Andric     return TI.EnforceVectorEltTypeIs(VecOperand.getExtType(VResNo),
1691ac9a064cSDimitry Andric                                      NodeToApply.getExtType(ResNo));
1692009b1c42SEd Schouten   }
1693cf099d11SDimitry Andric   case SDTCisSubVecOfVec: {
1694cf099d11SDimitry Andric     unsigned VResNo = 0;
1695ac9a064cSDimitry Andric     TreePatternNode &BigVecOperand = getOperandNum(
1696ac9a064cSDimitry Andric         x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo, VResNo);
1697cf099d11SDimitry Andric 
1698cf099d11SDimitry Andric     // Filter vector types out of BigVecOperand that don't have the
1699cf099d11SDimitry Andric     // right subvector type.
1700ac9a064cSDimitry Andric     return TI.EnforceVectorSubVectorTypeIs(BigVecOperand.getExtType(VResNo),
1701ac9a064cSDimitry Andric                                            NodeToApply.getExtType(ResNo));
1702cf099d11SDimitry Andric   }
17035a5ac124SDimitry Andric   case SDTCVecEltisVT: {
1704ac9a064cSDimitry Andric     return TI.EnforceVectorEltTypeIs(NodeToApply.getExtType(ResNo), VVT);
17055a5ac124SDimitry Andric   }
17065a5ac124SDimitry Andric   case SDTCisSameNumEltsAs: {
17075a5ac124SDimitry Andric     unsigned OResNo = 0;
1708ac9a064cSDimitry Andric     TreePatternNode &OtherNode = getOperandNum(
1709ac9a064cSDimitry Andric         x.SDTCisSameNumEltsAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
1710ac9a064cSDimitry Andric     return TI.EnforceSameNumElts(OtherNode.getExtType(OResNo),
1711ac9a064cSDimitry Andric                                  NodeToApply.getExtType(ResNo));
17125a5ac124SDimitry Andric   }
1713dd58ef01SDimitry Andric   case SDTCisSameSizeAs: {
1714dd58ef01SDimitry Andric     unsigned OResNo = 0;
1715ac9a064cSDimitry Andric     TreePatternNode &OtherNode = getOperandNum(
1716ac9a064cSDimitry Andric         x.SDTCisSameSizeAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
1717ac9a064cSDimitry Andric     return TI.EnforceSameSize(OtherNode.getExtType(OResNo),
1718ac9a064cSDimitry Andric                               NodeToApply.getExtType(ResNo));
1719dd58ef01SDimitry Andric   }
1720009b1c42SEd Schouten   }
172163faed5bSDimitry Andric   llvm_unreachable("Invalid ConstraintType!");
1722009b1c42SEd Schouten }
1723009b1c42SEd Schouten 
17244a16efa3SDimitry Andric // Update the node type to match an instruction operand or result as specified
17254a16efa3SDimitry Andric // in the ins or outs lists on the instruction definition. Return true if the
17264a16efa3SDimitry Andric // type was actually changed.
UpdateNodeTypeFromInst(unsigned ResNo,Record * Operand,TreePattern & TP)1727ac9a064cSDimitry Andric bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo, Record *Operand,
17284a16efa3SDimitry Andric                                              TreePattern &TP) {
17294a16efa3SDimitry Andric   // The 'unknown' operand indicates that types should be inferred from the
17304a16efa3SDimitry Andric   // context.
17314a16efa3SDimitry Andric   if (Operand->isSubClassOf("unknown_class"))
17324a16efa3SDimitry Andric     return false;
17334a16efa3SDimitry Andric 
17344a16efa3SDimitry Andric   // The Operand class specifies a type directly.
1735044eb2f6SDimitry Andric   if (Operand->isSubClassOf("Operand")) {
1736044eb2f6SDimitry Andric     Record *R = Operand->getValueAsDef("Type");
1737044eb2f6SDimitry Andric     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1738044eb2f6SDimitry Andric     return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1739044eb2f6SDimitry Andric   }
17404a16efa3SDimitry Andric 
17414a16efa3SDimitry Andric   // PointerLikeRegClass has a type that is determined at runtime.
17424a16efa3SDimitry Andric   if (Operand->isSubClassOf("PointerLikeRegClass"))
17434a16efa3SDimitry Andric     return UpdateNodeType(ResNo, MVT::iPTR, TP);
17444a16efa3SDimitry Andric 
17454a16efa3SDimitry Andric   // Both RegisterClass and RegisterOperand operands derive their types from a
17464a16efa3SDimitry Andric   // register class def.
17475ca98fd9SDimitry Andric   Record *RC = nullptr;
17484a16efa3SDimitry Andric   if (Operand->isSubClassOf("RegisterClass"))
17494a16efa3SDimitry Andric     RC = Operand;
17504a16efa3SDimitry Andric   else if (Operand->isSubClassOf("RegisterOperand"))
17514a16efa3SDimitry Andric     RC = Operand->getValueAsDef("RegClass");
17524a16efa3SDimitry Andric 
17534a16efa3SDimitry Andric   assert(RC && "Unknown operand type");
17544a16efa3SDimitry Andric   CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
17554a16efa3SDimitry Andric   return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
17564a16efa3SDimitry Andric }
17574a16efa3SDimitry Andric 
ContainsUnresolvedType(TreePattern & TP) const1758044eb2f6SDimitry Andric bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1759044eb2f6SDimitry Andric   for (unsigned i = 0, e = Types.size(); i != e; ++i)
1760044eb2f6SDimitry Andric     if (!TP.getInfer().isConcrete(Types[i], true))
1761044eb2f6SDimitry Andric       return true;
1762044eb2f6SDimitry Andric   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
1763ac9a064cSDimitry Andric     if (getChild(i).ContainsUnresolvedType(TP))
1764044eb2f6SDimitry Andric       return true;
1765044eb2f6SDimitry Andric   return false;
1766044eb2f6SDimitry Andric }
1767044eb2f6SDimitry Andric 
hasProperTypeByHwMode() const1768044eb2f6SDimitry Andric bool TreePatternNode::hasProperTypeByHwMode() const {
1769044eb2f6SDimitry Andric   for (const TypeSetByHwMode &S : Types)
17707fa27ce4SDimitry Andric     if (!S.isSimple())
1771044eb2f6SDimitry Andric       return true;
1772eb11fae6SDimitry Andric   for (const TreePatternNodePtr &C : Children)
1773044eb2f6SDimitry Andric     if (C->hasProperTypeByHwMode())
1774044eb2f6SDimitry Andric       return true;
1775044eb2f6SDimitry Andric   return false;
1776044eb2f6SDimitry Andric }
1777044eb2f6SDimitry Andric 
hasPossibleType() const1778044eb2f6SDimitry Andric bool TreePatternNode::hasPossibleType() const {
1779044eb2f6SDimitry Andric   for (const TypeSetByHwMode &S : Types)
1780044eb2f6SDimitry Andric     if (!S.isPossible())
1781044eb2f6SDimitry Andric       return false;
1782eb11fae6SDimitry Andric   for (const TreePatternNodePtr &C : Children)
1783044eb2f6SDimitry Andric     if (!C->hasPossibleType())
1784044eb2f6SDimitry Andric       return false;
1785044eb2f6SDimitry Andric   return true;
1786044eb2f6SDimitry Andric }
1787044eb2f6SDimitry Andric 
setDefaultMode(unsigned Mode)1788044eb2f6SDimitry Andric bool TreePatternNode::setDefaultMode(unsigned Mode) {
1789044eb2f6SDimitry Andric   for (TypeSetByHwMode &S : Types) {
1790044eb2f6SDimitry Andric     S.makeSimple(Mode);
1791044eb2f6SDimitry Andric     // Check if the selected mode had a type conflict.
1792044eb2f6SDimitry Andric     if (S.get(DefaultMode).empty())
1793044eb2f6SDimitry Andric       return false;
1794044eb2f6SDimitry Andric   }
1795eb11fae6SDimitry Andric   for (const TreePatternNodePtr &C : Children)
1796044eb2f6SDimitry Andric     if (!C->setDefaultMode(Mode))
1797044eb2f6SDimitry Andric       return false;
1798044eb2f6SDimitry Andric   return true;
1799044eb2f6SDimitry Andric }
18004a16efa3SDimitry Andric 
1801009b1c42SEd Schouten //===----------------------------------------------------------------------===//
1802009b1c42SEd Schouten // SDNodeInfo implementation
1803009b1c42SEd Schouten //
SDNodeInfo(Record * R,const CodeGenHwModes & CGH)1804044eb2f6SDimitry Andric SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
1805009b1c42SEd Schouten   EnumName = R->getValueAsString("Opcode");
1806009b1c42SEd Schouten   SDClassName = R->getValueAsString("SDClass");
1807009b1c42SEd Schouten   Record *TypeProfile = R->getValueAsDef("TypeProfile");
1808009b1c42SEd Schouten   NumResults = TypeProfile->getValueAsInt("NumResults");
1809009b1c42SEd Schouten   NumOperands = TypeProfile->getValueAsInt("NumOperands");
1810009b1c42SEd Schouten 
1811009b1c42SEd Schouten   // Parse the properties.
1812c7dac04cSDimitry Andric   Properties = parseSDPatternOperatorProperties(R);
1813009b1c42SEd Schouten 
1814009b1c42SEd Schouten   // Parse the type constraints.
1815009b1c42SEd Schouten   std::vector<Record *> ConstraintList =
1816009b1c42SEd Schouten       TypeProfile->getValueAsListOfDefs("Constraints");
1817044eb2f6SDimitry Andric   for (Record *R : ConstraintList)
1818044eb2f6SDimitry Andric     TypeConstraints.emplace_back(R, CGH);
1819009b1c42SEd Schouten }
1820009b1c42SEd Schouten 
182167a71b31SRoman Divacky /// getKnownType - If the type constraints on this node imply a fixed type
182267a71b31SRoman Divacky /// (e.g. all stores return void, etc), then return it as an
18232f12f10aSRoman Divacky /// MVT::SimpleValueType.  Otherwise, return EEVT::Other.
getKnownType(unsigned ResNo) const1824104bd817SRoman Divacky MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
182567a71b31SRoman Divacky   unsigned NumResults = getNumResults();
182667a71b31SRoman Divacky   assert(NumResults <= 1 &&
182767a71b31SRoman Divacky          "We only work with nodes with zero or one result so far!");
1828104bd817SRoman Divacky   assert(ResNo == 0 && "Only handles single result nodes so far");
182967a71b31SRoman Divacky 
1830dd58ef01SDimitry Andric   for (const SDTypeConstraint &Constraint : TypeConstraints) {
183167a71b31SRoman Divacky     // Make sure that this applies to the correct node result.
1832dd58ef01SDimitry Andric     if (Constraint.OperandNo >= NumResults) // FIXME: need value #
183367a71b31SRoman Divacky       continue;
183467a71b31SRoman Divacky 
1835dd58ef01SDimitry Andric     switch (Constraint.ConstraintType) {
1836ac9a064cSDimitry Andric     default:
1837ac9a064cSDimitry Andric       break;
183867a71b31SRoman Divacky     case SDTypeConstraint::SDTCisVT:
1839044eb2f6SDimitry Andric       if (Constraint.VVT.isSimple())
1840044eb2f6SDimitry Andric         return Constraint.VVT.getSimple().SimpleTy;
1841044eb2f6SDimitry Andric       break;
184267a71b31SRoman Divacky     case SDTypeConstraint::SDTCisPtrTy:
184367a71b31SRoman Divacky       return MVT::iPTR;
184467a71b31SRoman Divacky     }
184567a71b31SRoman Divacky   }
18462f12f10aSRoman Divacky   return MVT::Other;
184767a71b31SRoman Divacky }
184867a71b31SRoman Divacky 
1849009b1c42SEd Schouten //===----------------------------------------------------------------------===//
1850009b1c42SEd Schouten // TreePatternNode implementation
1851009b1c42SEd Schouten //
1852009b1c42SEd Schouten 
GetNumNodeResults(Record * Operator,CodeGenDAGPatterns & CDP)18532f12f10aSRoman Divacky static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1854ac9a064cSDimitry Andric   if (Operator->getName() == "set" || Operator->getName() == "implicit")
18552f12f10aSRoman Divacky     return 0; // All return nothing.
185667a71b31SRoman Divacky 
1857104bd817SRoman Divacky   if (Operator->isSubClassOf("Intrinsic"))
18587fa27ce4SDimitry Andric     return CDP.getIntrinsic(Operator).IS.RetTys.size();
1859009b1c42SEd Schouten 
18602f12f10aSRoman Divacky   if (Operator->isSubClassOf("SDNode"))
18612f12f10aSRoman Divacky     return CDP.getSDNodeInfo(Operator).getNumResults();
18622f12f10aSRoman Divacky 
1863eb11fae6SDimitry Andric   if (Operator->isSubClassOf("PatFrags")) {
18642f12f10aSRoman Divacky     // If we've already parsed this pattern fragment, get it.  Otherwise, handle
18652f12f10aSRoman Divacky     // the forward reference case where one pattern fragment references another
18662f12f10aSRoman Divacky     // before it is processed.
1867eb11fae6SDimitry Andric     if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
1868eb11fae6SDimitry Andric       // The number of results of a fragment with alternative records is the
1869eb11fae6SDimitry Andric       // maximum number of results across all alternatives.
1870eb11fae6SDimitry Andric       unsigned NumResults = 0;
1871344a3780SDimitry Andric       for (const auto &T : PFRec->getTrees())
1872eb11fae6SDimitry Andric         NumResults = std::max(NumResults, T->getNumTypes());
1873eb11fae6SDimitry Andric       return NumResults;
1874eb11fae6SDimitry Andric     }
18752f12f10aSRoman Divacky 
1876eb11fae6SDimitry Andric     ListInit *LI = Operator->getValueAsListInit("Fragments");
1877eb11fae6SDimitry Andric     assert(LI && "Invalid Fragment");
1878eb11fae6SDimitry Andric     unsigned NumResults = 0;
1879eb11fae6SDimitry Andric     for (Init *I : LI->getValues()) {
18805ca98fd9SDimitry Andric       Record *Op = nullptr;
1881eb11fae6SDimitry Andric       if (DagInit *Dag = dyn_cast<DagInit>(I))
1882eb11fae6SDimitry Andric         if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
1883522600a2SDimitry Andric           Op = DI->getDef();
18842f12f10aSRoman Divacky       assert(Op && "Invalid Fragment");
1885eb11fae6SDimitry Andric       NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
1886eb11fae6SDimitry Andric     }
1887eb11fae6SDimitry Andric     return NumResults;
18882f12f10aSRoman Divacky   }
18892f12f10aSRoman Divacky 
18902f12f10aSRoman Divacky   if (Operator->isSubClassOf("Instruction")) {
18912f12f10aSRoman Divacky     CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
18922f12f10aSRoman Divacky 
18935a5ac124SDimitry Andric     unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
18945a5ac124SDimitry Andric 
18955a5ac124SDimitry Andric     // Subtract any defaulted outputs.
18965a5ac124SDimitry Andric     for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
18975a5ac124SDimitry Andric       Record *OperandNode = InstInfo.Operands[i].Rec;
18985a5ac124SDimitry Andric 
18995a5ac124SDimitry Andric       if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
19005a5ac124SDimitry Andric           !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
19015a5ac124SDimitry Andric         --NumDefsToAdd;
19025a5ac124SDimitry Andric     }
19032f12f10aSRoman Divacky 
19042f12f10aSRoman Divacky     // Add on one implicit def if it has a resolvable type.
1905ac9a064cSDimitry Andric     if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=
1906ac9a064cSDimitry Andric         MVT::Other)
1907104bd817SRoman Divacky       ++NumDefsToAdd;
1908104bd817SRoman Divacky     return NumDefsToAdd;
19092f12f10aSRoman Divacky   }
19102f12f10aSRoman Divacky 
19112f12f10aSRoman Divacky   if (Operator->isSubClassOf("SDNodeXForm"))
19122f12f10aSRoman Divacky     return 1; // FIXME: Generalize SDNodeXForm
19132f12f10aSRoman Divacky 
19145ca98fd9SDimitry Andric   if (Operator->isSubClassOf("ValueType"))
19155ca98fd9SDimitry Andric     return 1; // A type-cast of one result.
19165ca98fd9SDimitry Andric 
19175ca98fd9SDimitry Andric   if (Operator->isSubClassOf("ComplexPattern"))
19185ca98fd9SDimitry Andric     return 1;
19195ca98fd9SDimitry Andric 
192071d5a254SDimitry Andric   errs() << *Operator;
19215a5ac124SDimitry Andric   PrintFatalError("Unhandled node in GetNumNodeResults");
19222f12f10aSRoman Divacky }
19232f12f10aSRoman Divacky 
print(raw_ostream & OS) const19242f12f10aSRoman Divacky void TreePatternNode::print(raw_ostream &OS) const {
19252f12f10aSRoman Divacky   if (isLeaf())
19262f12f10aSRoman Divacky     OS << *getLeafValue();
19272f12f10aSRoman Divacky   else
19282f12f10aSRoman Divacky     OS << '(' << getOperator()->getName();
19292f12f10aSRoman Divacky 
1930044eb2f6SDimitry Andric   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1931044eb2f6SDimitry Andric     OS << ':';
1932044eb2f6SDimitry Andric     getExtType(i).writeToStream(OS);
1933044eb2f6SDimitry Andric   }
1934009b1c42SEd Schouten 
1935009b1c42SEd Schouten   if (!isLeaf()) {
1936009b1c42SEd Schouten     if (getNumChildren() != 0) {
1937009b1c42SEd Schouten       OS << " ";
1938344a3780SDimitry Andric       ListSeparator LS;
1939344a3780SDimitry Andric       for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
1940344a3780SDimitry Andric         OS << LS;
1941ac9a064cSDimitry Andric         getChild(i).print(OS);
1942009b1c42SEd Schouten       }
1943009b1c42SEd Schouten     }
1944009b1c42SEd Schouten     OS << ")";
1945009b1c42SEd Schouten   }
1946009b1c42SEd Schouten 
1947d8e91e46SDimitry Andric   for (const TreePredicateCall &Pred : PredicateCalls) {
1948d8e91e46SDimitry Andric     OS << "<<P:";
1949d8e91e46SDimitry Andric     if (Pred.Scope)
1950d8e91e46SDimitry Andric       OS << Pred.Scope << ":";
1951d8e91e46SDimitry Andric     OS << Pred.Fn.getFnName() << ">>";
1952d8e91e46SDimitry Andric   }
1953009b1c42SEd Schouten   if (TransformFn)
1954009b1c42SEd Schouten     OS << "<<X:" << TransformFn->getName() << ">>";
1955009b1c42SEd Schouten   if (!getName().empty())
1956009b1c42SEd Schouten     OS << ":$" << getName();
1957009b1c42SEd Schouten 
1958d8e91e46SDimitry Andric   for (const ScopedName &Name : NamesAsPredicateArg)
1959d8e91e46SDimitry Andric     OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();
1960009b1c42SEd Schouten }
dump() const1961ac9a064cSDimitry Andric void TreePatternNode::dump() const { print(errs()); }
1962009b1c42SEd Schouten 
1963009b1c42SEd Schouten /// isIsomorphicTo - Return true if this node is recursively
1964009b1c42SEd Schouten /// isomorphic to the specified node.  For this comparison, the node's
1965009b1c42SEd Schouten /// entire state is considered. The assigned name is ignored, since
1966009b1c42SEd Schouten /// nodes with differing names are considered isomorphic. However, if
1967009b1c42SEd Schouten /// the assigned name is present in the dependent variable set, then
1968009b1c42SEd Schouten /// the assigned name is considered significant and the node is
1969009b1c42SEd Schouten /// isomorphic if the names match.
isIsomorphicTo(const TreePatternNode & N,const MultipleUseVarSet & DepVars) const1970ac9a064cSDimitry Andric bool TreePatternNode::isIsomorphicTo(const TreePatternNode &N,
1971009b1c42SEd Schouten                                      const MultipleUseVarSet &DepVars) const {
1972ac9a064cSDimitry Andric   if (&N == this)
1973ac9a064cSDimitry Andric     return true;
1974ac9a064cSDimitry Andric   if (N.isLeaf() != isLeaf())
19757fa27ce4SDimitry Andric     return false;
19767fa27ce4SDimitry Andric 
19777fa27ce4SDimitry Andric   // Check operator of non-leaves early since it can be cheaper than checking
19787fa27ce4SDimitry Andric   // types.
19797fa27ce4SDimitry Andric   if (!isLeaf())
1980ac9a064cSDimitry Andric     if (N.getOperator() != getOperator() ||
1981ac9a064cSDimitry Andric         N.getNumChildren() != getNumChildren())
19827fa27ce4SDimitry Andric       return false;
19837fa27ce4SDimitry Andric 
1984ac9a064cSDimitry Andric   if (getExtTypes() != N.getExtTypes() ||
1985ac9a064cSDimitry Andric       getPredicateCalls() != N.getPredicateCalls() ||
1986ac9a064cSDimitry Andric       getTransformFn() != N.getTransformFn())
1987009b1c42SEd Schouten     return false;
1988009b1c42SEd Schouten 
1989009b1c42SEd Schouten   if (isLeaf()) {
1990522600a2SDimitry Andric     if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
1991ac9a064cSDimitry Andric       if (DefInit *NDI = dyn_cast<DefInit>(N.getLeafValue())) {
19927fa27ce4SDimitry Andric         return ((DI->getDef() == NDI->getDef()) &&
1993ac9a064cSDimitry Andric                 (!DepVars.contains(getName()) || getName() == N.getName()));
1994009b1c42SEd Schouten       }
1995009b1c42SEd Schouten     }
1996ac9a064cSDimitry Andric     return getLeafValue() == N.getLeafValue();
1997009b1c42SEd Schouten   }
1998009b1c42SEd Schouten 
1999009b1c42SEd Schouten   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2000ac9a064cSDimitry Andric     if (!getChild(i).isIsomorphicTo(N.getChild(i), DepVars))
2001009b1c42SEd Schouten       return false;
2002009b1c42SEd Schouten   return true;
2003009b1c42SEd Schouten }
2004009b1c42SEd Schouten 
2005009b1c42SEd Schouten /// clone - Make a copy of this tree and all of its children.
2006009b1c42SEd Schouten ///
clone() const2007eb11fae6SDimitry Andric TreePatternNodePtr TreePatternNode::clone() const {
2008eb11fae6SDimitry Andric   TreePatternNodePtr New;
2009009b1c42SEd Schouten   if (isLeaf()) {
20107fa27ce4SDimitry Andric     New = makeIntrusiveRefCnt<TreePatternNode>(getLeafValue(), getNumTypes());
2011009b1c42SEd Schouten   } else {
2012eb11fae6SDimitry Andric     std::vector<TreePatternNodePtr> CChildren;
2013009b1c42SEd Schouten     CChildren.reserve(Children.size());
2014009b1c42SEd Schouten     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2015ac9a064cSDimitry Andric       CChildren.push_back(getChild(i).clone());
20167fa27ce4SDimitry Andric     New = makeIntrusiveRefCnt<TreePatternNode>(
20177fa27ce4SDimitry Andric         getOperator(), std::move(CChildren), getNumTypes());
2018009b1c42SEd Schouten   }
2019009b1c42SEd Schouten   New->setName(getName());
2020d8e91e46SDimitry Andric   New->setNamesAsPredicateArg(getNamesAsPredicateArg());
20212f12f10aSRoman Divacky   New->Types = Types;
2022d8e91e46SDimitry Andric   New->setPredicateCalls(getPredicateCalls());
20237fa27ce4SDimitry Andric   New->setGISelFlagsRecord(getGISelFlagsRecord());
2024009b1c42SEd Schouten   New->setTransformFn(getTransformFn());
2025009b1c42SEd Schouten   return New;
2026009b1c42SEd Schouten }
2027009b1c42SEd Schouten 
20286fe5c7aaSRoman Divacky /// RemoveAllTypes - Recursively strip all the types of this tree.
RemoveAllTypes()20296fe5c7aaSRoman Divacky void TreePatternNode::RemoveAllTypes() {
2030dd58ef01SDimitry Andric   // Reset to unknown type.
2031044eb2f6SDimitry Andric   std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
2032ac9a064cSDimitry Andric   if (isLeaf())
2033ac9a064cSDimitry Andric     return;
20346fe5c7aaSRoman Divacky   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2035ac9a064cSDimitry Andric     getChild(i).RemoveAllTypes();
20366fe5c7aaSRoman Divacky }
20376fe5c7aaSRoman Divacky 
2038009b1c42SEd Schouten /// SubstituteFormalArguments - Replace the formal arguments in this tree
2039009b1c42SEd Schouten /// with actual values specified by ArgMap.
SubstituteFormalArguments(std::map<std::string,TreePatternNodePtr> & ArgMap)2040eb11fae6SDimitry Andric void TreePatternNode::SubstituteFormalArguments(
2041eb11fae6SDimitry Andric     std::map<std::string, TreePatternNodePtr> &ArgMap) {
2042ac9a064cSDimitry Andric   if (isLeaf())
2043ac9a064cSDimitry Andric     return;
2044009b1c42SEd Schouten 
2045009b1c42SEd Schouten   for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
2046ac9a064cSDimitry Andric     TreePatternNode &Child = getChild(i);
2047ac9a064cSDimitry Andric     if (Child.isLeaf()) {
2048ac9a064cSDimitry Andric       Init *Val = Child.getLeafValue();
20495ca98fd9SDimitry Andric       // Note that, when substituting into an output pattern, Val might be an
20505ca98fd9SDimitry Andric       // UnsetInit.
2051ac9a064cSDimitry Andric       if (isa<UnsetInit>(Val) ||
2052ac9a064cSDimitry Andric           (isa<DefInit>(Val) &&
20535ca98fd9SDimitry Andric            cast<DefInit>(Val)->getDef()->getName() == "node")) {
2054009b1c42SEd Schouten         // We found a use of a formal argument, replace it with its value.
2055ac9a064cSDimitry Andric         TreePatternNodePtr NewChild = ArgMap[Child.getName()];
2056009b1c42SEd Schouten         assert(NewChild && "Couldn't find formal argument!");
2057ac9a064cSDimitry Andric         assert((Child.getPredicateCalls().empty() ||
2058ac9a064cSDimitry Andric                 NewChild->getPredicateCalls() == Child.getPredicateCalls()) &&
2059009b1c42SEd Schouten                "Non-empty child predicate clobbered!");
2060eb11fae6SDimitry Andric         setChild(i, std::move(NewChild));
2061009b1c42SEd Schouten       }
2062009b1c42SEd Schouten     } else {
2063ac9a064cSDimitry Andric       getChild(i).SubstituteFormalArguments(ArgMap);
2064009b1c42SEd Schouten     }
2065009b1c42SEd Schouten   }
2066009b1c42SEd Schouten }
2067009b1c42SEd Schouten 
2068009b1c42SEd Schouten /// InlinePatternFragments - If this pattern refers to any pattern
2069eb11fae6SDimitry Andric /// fragments, return the set of inlined versions (this can be more than
2070eb11fae6SDimitry Andric /// one if a PatFrags record has multiple alternatives).
InlinePatternFragments(TreePattern & TP,std::vector<TreePatternNodePtr> & OutAlternatives)2071eb11fae6SDimitry Andric void TreePatternNode::InlinePatternFragments(
20727fa27ce4SDimitry Andric     TreePattern &TP, std::vector<TreePatternNodePtr> &OutAlternatives) {
2073522600a2SDimitry Andric 
2074eb11fae6SDimitry Andric   if (TP.hasError())
2075eb11fae6SDimitry Andric     return;
2076eb11fae6SDimitry Andric 
2077eb11fae6SDimitry Andric   if (isLeaf()) {
20787fa27ce4SDimitry Andric     OutAlternatives.push_back(this); // nothing to do.
2079eb11fae6SDimitry Andric     return;
2080eb11fae6SDimitry Andric   }
2081eb11fae6SDimitry Andric 
2082009b1c42SEd Schouten   Record *Op = getOperator();
2083009b1c42SEd Schouten 
2084eb11fae6SDimitry Andric   if (!Op->isSubClassOf("PatFrags")) {
2085eb11fae6SDimitry Andric     if (getNumChildren() == 0) {
20867fa27ce4SDimitry Andric       OutAlternatives.push_back(this);
2087eb11fae6SDimitry Andric       return;
2088eb11fae6SDimitry Andric     }
2089009b1c42SEd Schouten 
2090eb11fae6SDimitry Andric     // Recursively inline children nodes.
20917fa27ce4SDimitry Andric     std::vector<std::vector<TreePatternNodePtr>> ChildAlternatives(
20927fa27ce4SDimitry Andric         getNumChildren());
2093eb11fae6SDimitry Andric     for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
2094eb11fae6SDimitry Andric       TreePatternNodePtr Child = getChildShared(i);
20957fa27ce4SDimitry Andric       Child->InlinePatternFragments(TP, ChildAlternatives[i]);
2096eb11fae6SDimitry Andric       // If there are no alternatives for any child, there are no
2097eb11fae6SDimitry Andric       // alternatives for this expression as whole.
2098eb11fae6SDimitry Andric       if (ChildAlternatives[i].empty())
2099eb11fae6SDimitry Andric         return;
2100eb11fae6SDimitry Andric 
2101d8e91e46SDimitry Andric       assert((Child->getPredicateCalls().empty() ||
2102344a3780SDimitry Andric               llvm::all_of(ChildAlternatives[i],
2103344a3780SDimitry Andric                            [&](const TreePatternNodePtr &NewChild) {
2104344a3780SDimitry Andric                              return NewChild->getPredicateCalls() ==
2105344a3780SDimitry Andric                                     Child->getPredicateCalls();
2106344a3780SDimitry Andric                            })) &&
2107009b1c42SEd Schouten              "Non-empty child predicate clobbered!");
2108009b1c42SEd Schouten     }
2109eb11fae6SDimitry Andric 
2110eb11fae6SDimitry Andric     // The end result is an all-pairs construction of the resultant pattern.
21117fa27ce4SDimitry Andric     std::vector<unsigned> Idxs(ChildAlternatives.size());
2112eb11fae6SDimitry Andric     bool NotDone;
2113eb11fae6SDimitry Andric     do {
2114eb11fae6SDimitry Andric       // Create the variant and add it to the output list.
2115eb11fae6SDimitry Andric       std::vector<TreePatternNodePtr> NewChildren;
21167fa27ce4SDimitry Andric       NewChildren.reserve(ChildAlternatives.size());
2117eb11fae6SDimitry Andric       for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
2118eb11fae6SDimitry Andric         NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
21197fa27ce4SDimitry Andric       TreePatternNodePtr R = makeIntrusiveRefCnt<TreePatternNode>(
2120eb11fae6SDimitry Andric           getOperator(), std::move(NewChildren), getNumTypes());
2121eb11fae6SDimitry Andric 
2122eb11fae6SDimitry Andric       // Copy over properties.
2123eb11fae6SDimitry Andric       R->setName(getName());
2124d8e91e46SDimitry Andric       R->setNamesAsPredicateArg(getNamesAsPredicateArg());
2125d8e91e46SDimitry Andric       R->setPredicateCalls(getPredicateCalls());
21267fa27ce4SDimitry Andric       R->setGISelFlagsRecord(getGISelFlagsRecord());
2127eb11fae6SDimitry Andric       R->setTransformFn(getTransformFn());
2128eb11fae6SDimitry Andric       for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
2129eb11fae6SDimitry Andric         R->setType(i, getExtType(i));
2130d8e91e46SDimitry Andric       for (unsigned i = 0, e = getNumResults(); i != e; ++i)
2131d8e91e46SDimitry Andric         R->setResultIndex(i, getResultIndex(i));
2132eb11fae6SDimitry Andric 
2133eb11fae6SDimitry Andric       // Register alternative.
2134eb11fae6SDimitry Andric       OutAlternatives.push_back(R);
2135eb11fae6SDimitry Andric 
2136eb11fae6SDimitry Andric       // Increment indices to the next permutation by incrementing the
2137eb11fae6SDimitry Andric       // indices from last index backward, e.g., generate the sequence
2138eb11fae6SDimitry Andric       // [0, 0], [0, 1], [1, 0], [1, 1].
2139eb11fae6SDimitry Andric       int IdxsIdx;
2140eb11fae6SDimitry Andric       for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2141eb11fae6SDimitry Andric         if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
2142eb11fae6SDimitry Andric           Idxs[IdxsIdx] = 0;
2143eb11fae6SDimitry Andric         else
2144eb11fae6SDimitry Andric           break;
2145eb11fae6SDimitry Andric       }
2146eb11fae6SDimitry Andric       NotDone = (IdxsIdx >= 0);
2147eb11fae6SDimitry Andric     } while (NotDone);
2148eb11fae6SDimitry Andric 
2149eb11fae6SDimitry Andric     return;
2150009b1c42SEd Schouten   }
2151009b1c42SEd Schouten 
2152009b1c42SEd Schouten   // Otherwise, we found a reference to a fragment.  First, look up its
2153009b1c42SEd Schouten   // TreePattern record.
2154009b1c42SEd Schouten   TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
2155009b1c42SEd Schouten 
2156009b1c42SEd Schouten   // Verify that we are passing the right number of operands.
21577fa27ce4SDimitry Andric   if (Frag->getNumArgs() != getNumChildren()) {
2158009b1c42SEd Schouten     TP.error("'" + Op->getName() + "' fragment requires " +
2159b2b7c066SDimitry Andric              Twine(Frag->getNumArgs()) + " operands!");
2160eb11fae6SDimitry Andric     return;
2161522600a2SDimitry Andric   }
2162009b1c42SEd Schouten 
2163d8e91e46SDimitry Andric   TreePredicateFn PredFn(Frag);
2164d8e91e46SDimitry Andric   unsigned Scope = 0;
2165d8e91e46SDimitry Andric   if (TreePredicateFn(Frag).usesOperands())
2166d8e91e46SDimitry Andric     Scope = TP.getDAGPatterns().allocateScope();
2167d8e91e46SDimitry Andric 
2168eb11fae6SDimitry Andric   // Compute the map of formal to actual arguments.
2169eb11fae6SDimitry Andric   std::map<std::string, TreePatternNodePtr> ArgMap;
2170eb11fae6SDimitry Andric   for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
2171d8e91e46SDimitry Andric     TreePatternNodePtr Child = getChildShared(i);
2172d8e91e46SDimitry Andric     if (Scope != 0) {
2173d8e91e46SDimitry Andric       Child = Child->clone();
2174d8e91e46SDimitry Andric       Child->addNameAsPredicateArg(ScopedName(Scope, Frag->getArgName(i)));
2175d8e91e46SDimitry Andric     }
2176eb11fae6SDimitry Andric     ArgMap[Frag->getArgName(i)] = Child;
2177eb11fae6SDimitry Andric   }
2178eb11fae6SDimitry Andric 
2179eb11fae6SDimitry Andric   // Loop over all fragment alternatives.
2180344a3780SDimitry Andric   for (const auto &Alternative : Frag->getTrees()) {
2181eb11fae6SDimitry Andric     TreePatternNodePtr FragTree = Alternative->clone();
2182009b1c42SEd Schouten 
21836b943ff3SDimitry Andric     if (!PredFn.isAlwaysTrue())
2184d8e91e46SDimitry Andric       FragTree->addPredicateCall(PredFn, Scope);
2185009b1c42SEd Schouten 
2186009b1c42SEd Schouten     // Resolve formal arguments to their actual value.
2187eb11fae6SDimitry Andric     if (Frag->getNumArgs())
2188009b1c42SEd Schouten       FragTree->SubstituteFormalArguments(ArgMap);
2189009b1c42SEd Schouten 
2190eb11fae6SDimitry Andric     // Transfer types.  Note that the resolved alternative may have fewer
2191eb11fae6SDimitry Andric     // (but not more) results than the PatFrags node.
2192009b1c42SEd Schouten     FragTree->setName(getName());
2193eb11fae6SDimitry Andric     for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
21942f12f10aSRoman Divacky       FragTree->UpdateNodeType(i, getExtType(i), TP);
2195009b1c42SEd Schouten 
21967fa27ce4SDimitry Andric     if (Op->isSubClassOf("GISelFlags"))
21977fa27ce4SDimitry Andric       FragTree->setGISelFlagsRecord(Op);
21987fa27ce4SDimitry Andric 
2199009b1c42SEd Schouten     // Transfer in the old predicates.
2200d8e91e46SDimitry Andric     for (const TreePredicateCall &Pred : getPredicateCalls())
2201d8e91e46SDimitry Andric       FragTree->addPredicateCall(Pred);
2202009b1c42SEd Schouten 
2203009b1c42SEd Schouten     // The fragment we inlined could have recursive inlining that is needed. See
2204009b1c42SEd Schouten     // if there are any pattern fragments in it and inline them as needed.
22057fa27ce4SDimitry Andric     FragTree->InlinePatternFragments(TP, OutAlternatives);
2206eb11fae6SDimitry Andric   }
2207009b1c42SEd Schouten }
2208009b1c42SEd Schouten 
2209009b1c42SEd Schouten /// getImplicitType - Check to see if the specified record has an implicit
2210b2f21fb0SEd Schouten /// type which should be applied to it.  This will infer the type of register
2211009b1c42SEd Schouten /// references from the register file information, for example.
2212009b1c42SEd Schouten ///
22134a16efa3SDimitry Andric /// When Unnamed is set, return the type of a DAG operand with no name, such as
22144a16efa3SDimitry Andric /// the F8RC register class argument in:
22154a16efa3SDimitry Andric ///
22164a16efa3SDimitry Andric ///   (COPY_TO_REGCLASS GPR:$src, F8RC)
22174a16efa3SDimitry Andric ///
22184a16efa3SDimitry Andric /// When Unnamed is false, return the type of a named DAG operand such as the
22194a16efa3SDimitry Andric /// GPR:$src operand above.
22204a16efa3SDimitry Andric ///
getImplicitType(Record * R,unsigned ResNo,bool NotRegisters,bool Unnamed,TreePattern & TP)2221044eb2f6SDimitry Andric static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
2222ac9a064cSDimitry Andric                                        bool NotRegisters, bool Unnamed,
22234a16efa3SDimitry Andric                                        TreePattern &TP) {
2224044eb2f6SDimitry Andric   CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2225044eb2f6SDimitry Andric 
2226411bd29eSDimitry Andric   // Check to see if this is a register operand.
2227411bd29eSDimitry Andric   if (R->isSubClassOf("RegisterOperand")) {
2228411bd29eSDimitry Andric     assert(ResNo == 0 && "Regoperand ref only has one result!");
2229411bd29eSDimitry Andric     if (NotRegisters)
2230044eb2f6SDimitry Andric       return TypeSetByHwMode(); // Unknown.
2231411bd29eSDimitry Andric     Record *RegClass = R->getValueAsDef("RegClass");
2232411bd29eSDimitry Andric     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2233044eb2f6SDimitry Andric     return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
2234411bd29eSDimitry Andric   }
2235411bd29eSDimitry Andric 
2236c6910277SRoman Divacky   // Check to see if this is a register or a register class.
2237009b1c42SEd Schouten   if (R->isSubClassOf("RegisterClass")) {
2238104bd817SRoman Divacky     assert(ResNo == 0 && "Regclass ref only has one result!");
22394a16efa3SDimitry Andric     // An unnamed register class represents itself as an i32 immediate, for
22404a16efa3SDimitry Andric     // example on a COPY_TO_REGCLASS instruction.
22414a16efa3SDimitry Andric     if (Unnamed)
2242044eb2f6SDimitry Andric       return TypeSetByHwMode(MVT::i32);
22434a16efa3SDimitry Andric 
22444a16efa3SDimitry Andric     // In a named operand, the register class provides the possible set of
22454a16efa3SDimitry Andric     // types.
2246009b1c42SEd Schouten     if (NotRegisters)
2247044eb2f6SDimitry Andric       return TypeSetByHwMode(); // Unknown.
2248c6910277SRoman Divacky     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2249044eb2f6SDimitry Andric     return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
2250104bd817SRoman Divacky   }
2251104bd817SRoman Divacky 
2252eb11fae6SDimitry Andric   if (R->isSubClassOf("PatFrags")) {
2253104bd817SRoman Divacky     assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
2254009b1c42SEd Schouten     // Pattern fragment types will be resolved when they are inlined.
2255044eb2f6SDimitry Andric     return TypeSetByHwMode(); // Unknown.
2256104bd817SRoman Divacky   }
2257104bd817SRoman Divacky 
2258104bd817SRoman Divacky   if (R->isSubClassOf("Register")) {
2259104bd817SRoman Divacky     assert(ResNo == 0 && "Registers only produce one result!");
2260009b1c42SEd Schouten     if (NotRegisters)
2261044eb2f6SDimitry Andric       return TypeSetByHwMode(); // Unknown.
2262009b1c42SEd Schouten     const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2263044eb2f6SDimitry Andric     return TypeSetByHwMode(T.getRegisterVTs(R));
2264104bd817SRoman Divacky   }
2265abdf259dSRoman Divacky 
2266abdf259dSRoman Divacky   if (R->isSubClassOf("SubRegIndex")) {
2267abdf259dSRoman Divacky     assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
2268044eb2f6SDimitry Andric     return TypeSetByHwMode(MVT::i32);
2269abdf259dSRoman Divacky   }
2270104bd817SRoman Divacky 
22714a16efa3SDimitry Andric   if (R->isSubClassOf("ValueType")) {
2272104bd817SRoman Divacky     assert(ResNo == 0 && "This node only has one result!");
22734a16efa3SDimitry Andric     // An unnamed VTSDNode represents itself as an MVT::Other immediate.
22744a16efa3SDimitry Andric     //
22754a16efa3SDimitry Andric     //   (sext_inreg GPR:$src, i16)
22764a16efa3SDimitry Andric     //                         ~~~
22774a16efa3SDimitry Andric     if (Unnamed)
2278044eb2f6SDimitry Andric       return TypeSetByHwMode(MVT::Other);
22794a16efa3SDimitry Andric     // With a name, the ValueType simply provides the type of the named
22804a16efa3SDimitry Andric     // variable.
22814a16efa3SDimitry Andric     //
22824a16efa3SDimitry Andric     //   (sext_inreg i32:$src, i16)
22834a16efa3SDimitry Andric     //               ~~~~~~~~
22844a16efa3SDimitry Andric     if (NotRegisters)
2285044eb2f6SDimitry Andric       return TypeSetByHwMode(); // Unknown.
2286044eb2f6SDimitry Andric     const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2287044eb2f6SDimitry Andric     return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
22884a16efa3SDimitry Andric   }
22894a16efa3SDimitry Andric 
22904a16efa3SDimitry Andric   if (R->isSubClassOf("CondCode")) {
22914a16efa3SDimitry Andric     assert(ResNo == 0 && "This node only has one result!");
22924a16efa3SDimitry Andric     // Using a CondCodeSDNode.
2293044eb2f6SDimitry Andric     return TypeSetByHwMode(MVT::Other);
2294104bd817SRoman Divacky   }
2295104bd817SRoman Divacky 
2296104bd817SRoman Divacky   if (R->isSubClassOf("ComplexPattern")) {
2297104bd817SRoman Divacky     assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
2298009b1c42SEd Schouten     if (NotRegisters)
2299044eb2f6SDimitry Andric       return TypeSetByHwMode(); // Unknown.
230077fc4c14SDimitry Andric     Record *T = CDP.getComplexPattern(R).getValueType();
230177fc4c14SDimitry Andric     const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
230277fc4c14SDimitry Andric     return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2303104bd817SRoman Divacky   }
2304104bd817SRoman Divacky   if (R->isSubClassOf("PointerLikeRegClass")) {
2305104bd817SRoman Divacky     assert(ResNo == 0 && "Regclass can only have one result!");
2306044eb2f6SDimitry Andric     TypeSetByHwMode VTS(MVT::iPTR);
2307044eb2f6SDimitry Andric     TP.getInfer().expandOverloads(VTS);
2308044eb2f6SDimitry Andric     return VTS;
2309104bd817SRoman Divacky   }
2310104bd817SRoman Divacky 
2311104bd817SRoman Divacky   if (R->getName() == "node" || R->getName() == "srcvalue" ||
2312e6d15924SDimitry Andric       R->getName() == "zero_reg" || R->getName() == "immAllOnesV" ||
2313e6d15924SDimitry Andric       R->getName() == "immAllZerosV" || R->getName() == "undef_tied_input") {
2314009b1c42SEd Schouten     // Placeholder.
2315044eb2f6SDimitry Andric     return TypeSetByHwMode(); // Unknown.
2316009b1c42SEd Schouten   }
2317009b1c42SEd Schouten 
2318044eb2f6SDimitry Andric   if (R->isSubClassOf("Operand")) {
2319044eb2f6SDimitry Andric     const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2320044eb2f6SDimitry Andric     Record *T = R->getValueAsDef("Type");
2321044eb2f6SDimitry Andric     return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2322044eb2f6SDimitry Andric   }
23235ca98fd9SDimitry Andric 
2324009b1c42SEd Schouten   TP.error("Unknown node flavor used in pattern: " + R->getName());
2325044eb2f6SDimitry Andric   return TypeSetByHwMode(MVT::Other);
2326009b1c42SEd Schouten }
2327009b1c42SEd Schouten 
2328009b1c42SEd Schouten /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2329009b1c42SEd Schouten /// CodeGenIntrinsic information for it, otherwise return a null pointer.
2330ac9a064cSDimitry Andric const CodeGenIntrinsic *
getIntrinsicInfo(const CodeGenDAGPatterns & CDP) const2331ac9a064cSDimitry Andric TreePatternNode::getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2332009b1c42SEd Schouten   if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2333009b1c42SEd Schouten       getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2334009b1c42SEd Schouten       getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
23355ca98fd9SDimitry Andric     return nullptr;
2336009b1c42SEd Schouten 
2337ac9a064cSDimitry Andric   unsigned IID = cast<IntInit>(getChild(0).getLeafValue())->getValue();
2338009b1c42SEd Schouten   return &CDP.getIntrinsicInfo(IID);
2339009b1c42SEd Schouten }
2340009b1c42SEd Schouten 
23416fe5c7aaSRoman Divacky /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
23426fe5c7aaSRoman Divacky /// return the ComplexPattern information, otherwise return null.
23436fe5c7aaSRoman Divacky const ComplexPattern *
getComplexPatternInfo(const CodeGenDAGPatterns & CGP) const23446fe5c7aaSRoman Divacky TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
23455ca98fd9SDimitry Andric   Record *Rec;
23465ca98fd9SDimitry Andric   if (isLeaf()) {
2347522600a2SDimitry Andric     DefInit *DI = dyn_cast<DefInit>(getLeafValue());
23485ca98fd9SDimitry Andric     if (!DI)
23495ca98fd9SDimitry Andric       return nullptr;
23505ca98fd9SDimitry Andric     Rec = DI->getDef();
23515ca98fd9SDimitry Andric   } else
23525ca98fd9SDimitry Andric     Rec = getOperator();
23535ca98fd9SDimitry Andric 
23545ca98fd9SDimitry Andric   if (!Rec->isSubClassOf("ComplexPattern"))
23555ca98fd9SDimitry Andric     return nullptr;
23565ca98fd9SDimitry Andric   return &CGP.getComplexPattern(Rec);
23575ca98fd9SDimitry Andric }
23585ca98fd9SDimitry Andric 
getNumMIResults(const CodeGenDAGPatterns & CGP) const23595ca98fd9SDimitry Andric unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
23605ca98fd9SDimitry Andric   // A ComplexPattern specifically declares how many results it fills in.
23615ca98fd9SDimitry Andric   if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
23625ca98fd9SDimitry Andric     return CP->getNumOperands();
23635ca98fd9SDimitry Andric 
23645ca98fd9SDimitry Andric   // If MIOperandInfo is specified, that gives the count.
23655ca98fd9SDimitry Andric   if (isLeaf()) {
23665ca98fd9SDimitry Andric     DefInit *DI = dyn_cast<DefInit>(getLeafValue());
23675ca98fd9SDimitry Andric     if (DI && DI->getDef()->isSubClassOf("Operand")) {
23685ca98fd9SDimitry Andric       DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
23695ca98fd9SDimitry Andric       if (MIOps->getNumArgs())
23705ca98fd9SDimitry Andric         return MIOps->getNumArgs();
23715ca98fd9SDimitry Andric     }
23725ca98fd9SDimitry Andric   }
23735ca98fd9SDimitry Andric 
23745ca98fd9SDimitry Andric   // Otherwise there is just one result.
23755ca98fd9SDimitry Andric   return 1;
23766fe5c7aaSRoman Divacky }
23776fe5c7aaSRoman Divacky 
23786fe5c7aaSRoman Divacky /// NodeHasProperty - Return true if this node has the specified property.
NodeHasProperty(SDNP Property,const CodeGenDAGPatterns & CGP) const23796fe5c7aaSRoman Divacky bool TreePatternNode::NodeHasProperty(SDNP Property,
23806fe5c7aaSRoman Divacky                                       const CodeGenDAGPatterns &CGP) const {
23816fe5c7aaSRoman Divacky   if (isLeaf()) {
23826fe5c7aaSRoman Divacky     if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
23836fe5c7aaSRoman Divacky       return CP->hasProperty(Property);
2384c7dac04cSDimitry Andric 
23856fe5c7aaSRoman Divacky     return false;
23866fe5c7aaSRoman Divacky   }
23876fe5c7aaSRoman Divacky 
2388c7dac04cSDimitry Andric   if (Property != SDNPHasChain) {
2389c7dac04cSDimitry Andric     // The chain proprety is already present on the different intrinsic node
2390c7dac04cSDimitry Andric     // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2391c7dac04cSDimitry Andric     // on the intrinsic. Anything else is specific to the individual intrinsic.
2392c7dac04cSDimitry Andric     if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2393c7dac04cSDimitry Andric       return Int->hasProperty(Property);
2394c7dac04cSDimitry Andric   }
2395c7dac04cSDimitry Andric 
23967fa27ce4SDimitry Andric   if (!getOperator()->isSubClassOf("SDPatternOperator"))
2397c7dac04cSDimitry Andric     return false;
23986fe5c7aaSRoman Divacky 
23997fa27ce4SDimitry Andric   return CGP.getSDNodeInfo(getOperator()).hasProperty(Property);
24006fe5c7aaSRoman Divacky }
24016fe5c7aaSRoman Divacky 
24026fe5c7aaSRoman Divacky /// TreeHasProperty - Return true if any node in this tree has the specified
24036fe5c7aaSRoman Divacky /// property.
TreeHasProperty(SDNP Property,const CodeGenDAGPatterns & CGP) const24046fe5c7aaSRoman Divacky bool TreePatternNode::TreeHasProperty(SDNP Property,
24056fe5c7aaSRoman Divacky                                       const CodeGenDAGPatterns &CGP) const {
24066fe5c7aaSRoman Divacky   if (NodeHasProperty(Property, CGP))
24076fe5c7aaSRoman Divacky     return true;
24086fe5c7aaSRoman Divacky   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2409ac9a064cSDimitry Andric     if (getChild(i).TreeHasProperty(Property, CGP))
24106fe5c7aaSRoman Divacky       return true;
24116fe5c7aaSRoman Divacky   return false;
24126fe5c7aaSRoman Divacky }
24136fe5c7aaSRoman Divacky 
2414009b1c42SEd Schouten /// isCommutativeIntrinsic - Return true if the node corresponds to a
2415009b1c42SEd Schouten /// commutative intrinsic.
isCommutativeIntrinsic(const CodeGenDAGPatterns & CDP) const2416ac9a064cSDimitry Andric bool TreePatternNode::isCommutativeIntrinsic(
2417ac9a064cSDimitry Andric     const CodeGenDAGPatterns &CDP) const {
2418009b1c42SEd Schouten   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2419009b1c42SEd Schouten     return Int->isCommutative;
2420009b1c42SEd Schouten   return false;
2421009b1c42SEd Schouten }
2422009b1c42SEd Schouten 
isOperandClass(const TreePatternNode & N,StringRef Class)2423ac9a064cSDimitry Andric static bool isOperandClass(const TreePatternNode &N, StringRef Class) {
2424ac9a064cSDimitry Andric   if (!N.isLeaf())
2425ac9a064cSDimitry Andric     return N.getOperator()->isSubClassOf(Class);
242667c32a98SDimitry Andric 
2427ac9a064cSDimitry Andric   DefInit *DI = dyn_cast<DefInit>(N.getLeafValue());
242867c32a98SDimitry Andric   if (DI && DI->getDef()->isSubClassOf(Class))
242967c32a98SDimitry Andric     return true;
243067c32a98SDimitry Andric 
243167c32a98SDimitry Andric   return false;
243267c32a98SDimitry Andric }
243367c32a98SDimitry Andric 
emitTooManyOperandsError(TreePattern & TP,StringRef InstName,unsigned Expected,unsigned Actual)2434ac9a064cSDimitry Andric static void emitTooManyOperandsError(TreePattern &TP, StringRef InstName,
2435ac9a064cSDimitry Andric                                      unsigned Expected, unsigned Actual) {
243667c32a98SDimitry Andric   TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
243767c32a98SDimitry Andric            " operands but expected only " + Twine(Expected) + "!");
243867c32a98SDimitry Andric }
243967c32a98SDimitry Andric 
emitTooFewOperandsError(TreePattern & TP,StringRef InstName,unsigned Actual)2440ac9a064cSDimitry Andric static void emitTooFewOperandsError(TreePattern &TP, StringRef InstName,
244167c32a98SDimitry Andric                                     unsigned Actual) {
2442ac9a064cSDimitry Andric   TP.error("Instruction '" + InstName + "' expects more than the provided " +
2443ac9a064cSDimitry Andric            Twine(Actual) + " operands!");
244467c32a98SDimitry Andric }
2445009b1c42SEd Schouten 
2446009b1c42SEd Schouten /// ApplyTypeConstraints - Apply all of the type constraints relevant to
2447009b1c42SEd Schouten /// this node and its children in the tree.  This returns true if it makes a
2448522600a2SDimitry Andric /// change, false otherwise.  If a type contradiction is found, flag an error.
ApplyTypeConstraints(TreePattern & TP,bool NotRegisters)2449009b1c42SEd Schouten bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
2450522600a2SDimitry Andric   if (TP.hasError())
2451522600a2SDimitry Andric     return false;
2452522600a2SDimitry Andric 
2453009b1c42SEd Schouten   CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2454009b1c42SEd Schouten   if (isLeaf()) {
2455522600a2SDimitry Andric     if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
2456009b1c42SEd Schouten       // If it's a regclass or something else known, include the type.
24572f12f10aSRoman Divacky       bool MadeChange = false;
24582f12f10aSRoman Divacky       for (unsigned i = 0, e = Types.size(); i != e; ++i)
2459ac9a064cSDimitry Andric         MadeChange |= UpdateNodeType(
2460ac9a064cSDimitry Andric             i, getImplicitType(DI->getDef(), i, NotRegisters, !hasName(), TP),
2461ac9a064cSDimitry Andric             TP);
24622f12f10aSRoman Divacky       return MadeChange;
24636fe5c7aaSRoman Divacky     }
24646fe5c7aaSRoman Divacky 
2465522600a2SDimitry Andric     if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
24662f12f10aSRoman Divacky       assert(Types.size() == 1 && "Invalid IntInit");
2467009b1c42SEd Schouten 
24682f12f10aSRoman Divacky       // Int inits are always integers. :)
2469044eb2f6SDimitry Andric       bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
24702f12f10aSRoman Divacky 
2471044eb2f6SDimitry Andric       if (!TP.getInfer().isConcrete(Types[0], false))
2472c6910277SRoman Divacky         return MadeChange;
2473009b1c42SEd Schouten 
2474044eb2f6SDimitry Andric       ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2475044eb2f6SDimitry Andric       for (auto &P : VVT) {
2476044eb2f6SDimitry Andric         MVT::SimpleValueType VT = P.second.SimpleTy;
2477c6910277SRoman Divacky         if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2478044eb2f6SDimitry Andric           continue;
2479b60736ecSDimitry Andric         unsigned Size = MVT(VT).getFixedSizeInBits();
2480009b1c42SEd Schouten         // Make sure that the value is representable for this type.
2481044eb2f6SDimitry Andric         if (Size >= 32)
2482044eb2f6SDimitry Andric           continue;
2483044eb2f6SDimitry Andric         // Check that the value doesn't use more bits than we have. It must
2484044eb2f6SDimitry Andric         // either be a sign- or zero-extended equivalent of the original.
2485522600a2SDimitry Andric         int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2486044eb2f6SDimitry Andric         if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2487044eb2f6SDimitry Andric             SignBitAndAbove == 1)
2488044eb2f6SDimitry Andric           continue;
2489009b1c42SEd Schouten 
2490b2b7c066SDimitry Andric         TP.error("Integer value '" + Twine(II->getValue()) +
2491044eb2f6SDimitry Andric                  "' is out of range for type '" + getEnumName(VT) + "'!");
2492044eb2f6SDimitry Andric         break;
2493009b1c42SEd Schouten       }
2494044eb2f6SDimitry Andric       return MadeChange;
2495044eb2f6SDimitry Andric     }
2496044eb2f6SDimitry Andric 
2497009b1c42SEd Schouten     return false;
2498009b1c42SEd Schouten   }
2499009b1c42SEd Schouten 
250067a71b31SRoman Divacky   if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
2501009b1c42SEd Schouten     bool MadeChange = false;
2502009b1c42SEd Schouten 
2503009b1c42SEd Schouten     // Apply the result type to the node.
25047fa27ce4SDimitry Andric     unsigned NumRetVTs = Int->IS.RetTys.size();
25057fa27ce4SDimitry Andric     unsigned NumParamVTs = Int->IS.ParamTys.size();
2506009b1c42SEd Schouten 
2507009b1c42SEd Schouten     for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
25087fa27ce4SDimitry Andric       MadeChange |= UpdateNodeType(
25097fa27ce4SDimitry Andric           i, getValueType(Int->IS.RetTys[i]->getValueAsDef("VT")), TP);
2510009b1c42SEd Schouten 
2511522600a2SDimitry Andric     if (getNumChildren() != NumParamVTs + 1) {
2512b2b7c066SDimitry Andric       TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2513b2b7c066SDimitry Andric                " operands, not " + Twine(getNumChildren() - 1) + " operands!");
2514522600a2SDimitry Andric       return false;
2515522600a2SDimitry Andric     }
2516009b1c42SEd Schouten 
2517009b1c42SEd Schouten     // Apply type info to the intrinsic ID.
2518ac9a064cSDimitry Andric     MadeChange |= getChild(0).UpdateNodeType(0, MVT::iPTR, TP);
2519009b1c42SEd Schouten 
25202f12f10aSRoman Divacky     for (unsigned i = 0, e = getNumChildren() - 1; i != e; ++i) {
2521ac9a064cSDimitry Andric       MadeChange |= getChild(i + 1).ApplyTypeConstraints(TP, NotRegisters);
25222f12f10aSRoman Divacky 
25237fa27ce4SDimitry Andric       MVT::SimpleValueType OpVT =
25247fa27ce4SDimitry Andric           getValueType(Int->IS.ParamTys[i]->getValueAsDef("VT"));
2525ac9a064cSDimitry Andric       assert(getChild(i + 1).getNumTypes() == 1 && "Unhandled case");
2526ac9a064cSDimitry Andric       MadeChange |= getChild(i + 1).UpdateNodeType(0, OpVT, TP);
2527009b1c42SEd Schouten     }
2528009b1c42SEd Schouten     return MadeChange;
252967a71b31SRoman Divacky   }
253067a71b31SRoman Divacky 
253167a71b31SRoman Divacky   if (getOperator()->isSubClassOf("SDNode")) {
2532009b1c42SEd Schouten     const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
2533009b1c42SEd Schouten 
2534104bd817SRoman Divacky     // Check that the number of operands is sane.  Negative operands -> varargs.
2535104bd817SRoman Divacky     if (NI.getNumOperands() >= 0 &&
2536522600a2SDimitry Andric         getNumChildren() != (unsigned)NI.getNumOperands()) {
2537104bd817SRoman Divacky       TP.error(getOperator()->getName() + " node requires exactly " +
2538b2b7c066SDimitry Andric                Twine(NI.getNumOperands()) + " operands!");
2539522600a2SDimitry Andric       return false;
2540522600a2SDimitry Andric     }
2541104bd817SRoman Divacky 
2542044eb2f6SDimitry Andric     bool MadeChange = false;
2543009b1c42SEd Schouten     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2544ac9a064cSDimitry Andric       MadeChange |= getChild(i).ApplyTypeConstraints(TP, NotRegisters);
2545ac9a064cSDimitry Andric     MadeChange |= NI.ApplyTypeConstraints(*this, TP);
2546009b1c42SEd Schouten     return MadeChange;
254767a71b31SRoman Divacky   }
254867a71b31SRoman Divacky 
254967a71b31SRoman Divacky   if (getOperator()->isSubClassOf("Instruction")) {
2550009b1c42SEd Schouten     const DAGInstruction &Inst = CDP.getInstruction(getOperator());
2551009b1c42SEd Schouten     CodeGenInstruction &InstInfo =
25522f12f10aSRoman Divacky         CDP.getTargetInfo().getInstruction(getOperator());
25532f12f10aSRoman Divacky 
2554104bd817SRoman Divacky     bool MadeChange = false;
25552f12f10aSRoman Divacky 
2556104bd817SRoman Divacky     // Apply the result types to the node, these come from the things in the
2557104bd817SRoman Divacky     // (outs) list of the instruction.
2558ac9a064cSDimitry Andric     unsigned NumResultsToAdd =
2559ac9a064cSDimitry Andric         std::min(InstInfo.Operands.NumDefs, Inst.getNumResults());
25604a16efa3SDimitry Andric     for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
25614a16efa3SDimitry Andric       MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
2562009b1c42SEd Schouten 
2563104bd817SRoman Divacky     // If the instruction has implicit defs, we apply the first one as a result.
2564104bd817SRoman Divacky     // FIXME: This sucks, it should apply all implicit defs.
2565104bd817SRoman Divacky     if (!InstInfo.ImplicitDefs.empty()) {
2566104bd817SRoman Divacky       unsigned ResNo = NumResultsToAdd;
25672f12f10aSRoman Divacky 
2568104bd817SRoman Divacky       // FIXME: Generalize to multiple possible types and multiple possible
2569104bd817SRoman Divacky       // ImplicitDefs.
2570104bd817SRoman Divacky       MVT::SimpleValueType VT =
2571104bd817SRoman Divacky           InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
2572104bd817SRoman Divacky 
2573104bd817SRoman Divacky       if (VT != MVT::Other)
2574104bd817SRoman Divacky         MadeChange |= UpdateNodeType(ResNo, VT, TP);
2575104bd817SRoman Divacky     }
25762f12f10aSRoman Divacky 
2577c6910277SRoman Divacky     // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2578c6910277SRoman Divacky     // be the same.
2579c6910277SRoman Divacky     if (getOperator()->getName() == "INSERT_SUBREG") {
2580ac9a064cSDimitry Andric       assert(getChild(0).getNumTypes() == 1 && "FIXME: Unhandled");
2581ac9a064cSDimitry Andric       MadeChange |= UpdateNodeType(0, getChild(0).getExtType(0), TP);
2582ac9a064cSDimitry Andric       MadeChange |= getChild(0).UpdateNodeType(0, getExtType(0), TP);
258367c32a98SDimitry Andric     } else if (getOperator()->getName() == "REG_SEQUENCE") {
258467c32a98SDimitry Andric       // We need to do extra, custom typechecking for REG_SEQUENCE since it is
258567c32a98SDimitry Andric       // variadic.
258667c32a98SDimitry Andric 
258767c32a98SDimitry Andric       unsigned NChild = getNumChildren();
258867c32a98SDimitry Andric       if (NChild < 3) {
258967c32a98SDimitry Andric         TP.error("REG_SEQUENCE requires at least 3 operands!");
259067c32a98SDimitry Andric         return false;
259167c32a98SDimitry Andric       }
259267c32a98SDimitry Andric 
259367c32a98SDimitry Andric       if (NChild % 2 == 0) {
259467c32a98SDimitry Andric         TP.error("REG_SEQUENCE requires an odd number of operands!");
259567c32a98SDimitry Andric         return false;
259667c32a98SDimitry Andric       }
259767c32a98SDimitry Andric 
259867c32a98SDimitry Andric       if (!isOperandClass(getChild(0), "RegisterClass")) {
259967c32a98SDimitry Andric         TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
260067c32a98SDimitry Andric         return false;
260167c32a98SDimitry Andric       }
260267c32a98SDimitry Andric 
260367c32a98SDimitry Andric       for (unsigned I = 1; I < NChild; I += 2) {
2604ac9a064cSDimitry Andric         TreePatternNode &SubIdxChild = getChild(I + 1);
260567c32a98SDimitry Andric         if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
260667c32a98SDimitry Andric           TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
2607b2b7c066SDimitry Andric                    Twine(I + 1) + "!");
260867c32a98SDimitry Andric           return false;
260967c32a98SDimitry Andric         }
261067c32a98SDimitry Andric       }
2611c6910277SRoman Divacky     }
2612c6910277SRoman Divacky 
2613cfca06d7SDimitry Andric     unsigned NumResults = Inst.getNumResults();
2614cfca06d7SDimitry Andric     unsigned NumFixedOperands = InstInfo.Operands.size();
2615cfca06d7SDimitry Andric 
2616e6d15924SDimitry Andric     // If one or more operands with a default value appear at the end of the
2617e6d15924SDimitry Andric     // formal operand list for an instruction, we allow them to be overridden
2618e6d15924SDimitry Andric     // by optional operands provided in the pattern.
2619e6d15924SDimitry Andric     //
2620e6d15924SDimitry Andric     // But if an operand B without a default appears at any point after an
2621e6d15924SDimitry Andric     // operand A with a default, then we don't allow A to be overridden,
2622e6d15924SDimitry Andric     // because there would be no way to specify whether the next operand in
2623e6d15924SDimitry Andric     // the pattern was intended to override A or skip it.
2624cfca06d7SDimitry Andric     unsigned NonOverridableOperands = NumFixedOperands;
2625cfca06d7SDimitry Andric     while (NonOverridableOperands > NumResults &&
2626ac9a064cSDimitry Andric            CDP.operandHasDefault(
2627ac9a064cSDimitry Andric                InstInfo.Operands[NonOverridableOperands - 1].Rec))
2628e6d15924SDimitry Andric       --NonOverridableOperands;
2629e6d15924SDimitry Andric 
2630009b1c42SEd Schouten     unsigned ChildNo = 0;
2631cfca06d7SDimitry Andric     assert(NumResults <= NumFixedOperands);
2632cfca06d7SDimitry Andric     for (unsigned i = NumResults, e = NumFixedOperands; i != e; ++i) {
2633cfca06d7SDimitry Andric       Record *OperandNode = InstInfo.Operands[i].Rec;
2634009b1c42SEd Schouten 
2635e6d15924SDimitry Andric       // If the operand has a default value, do we use it? We must use the
2636e6d15924SDimitry Andric       // default if we've run out of children of the pattern DAG to consume,
2637e6d15924SDimitry Andric       // or if the operand is followed by a non-defaulted one.
2638e6d15924SDimitry Andric       if (CDP.operandHasDefault(OperandNode) &&
2639e6d15924SDimitry Andric           (i < NonOverridableOperands || ChildNo >= getNumChildren()))
2640009b1c42SEd Schouten         continue;
2641009b1c42SEd Schouten 
2642e6d15924SDimitry Andric       // If we have run out of child nodes and there _isn't_ a default
2643e6d15924SDimitry Andric       // value we can use for the next operand, give an error.
2644522600a2SDimitry Andric       if (ChildNo >= getNumChildren()) {
264567c32a98SDimitry Andric         emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
2646522600a2SDimitry Andric         return false;
2647522600a2SDimitry Andric       }
2648009b1c42SEd Schouten 
2649ac9a064cSDimitry Andric       TreePatternNode *Child = &getChild(ChildNo++);
2650104bd817SRoman Divacky       unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
26512f12f10aSRoman Divacky 
26524a16efa3SDimitry Andric       // If the operand has sub-operands, they may be provided by distinct
26534a16efa3SDimitry Andric       // child patterns, so attempt to match each sub-operand separately.
26544a16efa3SDimitry Andric       if (OperandNode->isSubClassOf("Operand")) {
26554a16efa3SDimitry Andric         DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
26564a16efa3SDimitry Andric         if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
26574a16efa3SDimitry Andric           // But don't do that if the whole operand is being provided by
26585ca98fd9SDimitry Andric           // a single ComplexPattern-related Operand.
26595ca98fd9SDimitry Andric 
26605ca98fd9SDimitry Andric           if (Child->getNumMIResults(CDP) < NumArgs) {
26614a16efa3SDimitry Andric             // Match first sub-operand against the child we already have.
26624a16efa3SDimitry Andric             Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2663ac9a064cSDimitry Andric             MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
266463faed5bSDimitry Andric 
26654a16efa3SDimitry Andric             // And the remaining sub-operands against subsequent children.
26664a16efa3SDimitry Andric             for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
26674a16efa3SDimitry Andric               if (ChildNo >= getNumChildren()) {
266867c32a98SDimitry Andric                 emitTooFewOperandsError(TP, getOperator()->getName(),
266967c32a98SDimitry Andric                                         getNumChildren());
26704a16efa3SDimitry Andric                 return false;
26714a16efa3SDimitry Andric               }
2672ac9a064cSDimitry Andric               Child = &getChild(ChildNo++);
26734a16efa3SDimitry Andric 
26744a16efa3SDimitry Andric               SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
26754a16efa3SDimitry Andric               MadeChange |=
26764a16efa3SDimitry Andric                   Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
26774a16efa3SDimitry Andric             }
26784a16efa3SDimitry Andric             continue;
26794a16efa3SDimitry Andric           }
26804a16efa3SDimitry Andric         }
26814a16efa3SDimitry Andric       }
26824a16efa3SDimitry Andric 
26834a16efa3SDimitry Andric       // If we didn't match by pieces above, attempt to match the whole
26844a16efa3SDimitry Andric       // operand now.
26854a16efa3SDimitry Andric       MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
2686009b1c42SEd Schouten     }
2687009b1c42SEd Schouten 
268867c32a98SDimitry Andric     if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
2689ac9a064cSDimitry Andric       emitTooManyOperandsError(TP, getOperator()->getName(), ChildNo,
2690ac9a064cSDimitry Andric                                getNumChildren());
2691522600a2SDimitry Andric       return false;
2692522600a2SDimitry Andric     }
2693009b1c42SEd Schouten 
26944a16efa3SDimitry Andric     for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2695ac9a064cSDimitry Andric       MadeChange |= getChild(i).ApplyTypeConstraints(TP, NotRegisters);
2696009b1c42SEd Schouten     return MadeChange;
269767a71b31SRoman Divacky   }
269867a71b31SRoman Divacky 
26995ca98fd9SDimitry Andric   if (getOperator()->isSubClassOf("ComplexPattern")) {
27005ca98fd9SDimitry Andric     bool MadeChange = false;
27015ca98fd9SDimitry Andric 
270277fc4c14SDimitry Andric     if (!NotRegisters) {
270377fc4c14SDimitry Andric       assert(Types.size() == 1 && "ComplexPatterns only produce one result!");
270477fc4c14SDimitry Andric       Record *T = CDP.getComplexPattern(getOperator()).getValueType();
270577fc4c14SDimitry Andric       const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
270677fc4c14SDimitry Andric       const ValueTypeByHwMode VVT = getValueTypeByHwMode(T, CGH);
270777fc4c14SDimitry Andric       // TODO: AArch64 and AMDGPU use ComplexPattern<untyped, ...> and then
270877fc4c14SDimitry Andric       // exclusively use those as non-leaf nodes with explicit type casts, so
270977fc4c14SDimitry Andric       // for backwards compatibility we do no inference in that case. This is
271077fc4c14SDimitry Andric       // not supported when the ComplexPattern is used as a leaf value,
271177fc4c14SDimitry Andric       // however; this inconsistency should be resolved, either by adding this
271277fc4c14SDimitry Andric       // case there or by altering the backends to not do this (e.g. using Any
271377fc4c14SDimitry Andric       // instead may work).
271477fc4c14SDimitry Andric       if (!VVT.isSimple() || VVT.getSimple() != MVT::Untyped)
271577fc4c14SDimitry Andric         MadeChange |= UpdateNodeType(0, VVT, TP);
271677fc4c14SDimitry Andric     }
271777fc4c14SDimitry Andric 
27185ca98fd9SDimitry Andric     for (unsigned i = 0; i < getNumChildren(); ++i)
2719ac9a064cSDimitry Andric       MadeChange |= getChild(i).ApplyTypeConstraints(TP, NotRegisters);
27205ca98fd9SDimitry Andric 
27215ca98fd9SDimitry Andric     return MadeChange;
27225ca98fd9SDimitry Andric   }
27235ca98fd9SDimitry Andric 
2724009b1c42SEd Schouten   assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
2725009b1c42SEd Schouten 
2726009b1c42SEd Schouten   // Node transforms always take one operand.
2727522600a2SDimitry Andric   if (getNumChildren() != 1) {
2728009b1c42SEd Schouten     TP.error("Node transform '" + getOperator()->getName() +
2729009b1c42SEd Schouten              "' requires one operand!");
2730522600a2SDimitry Andric     return false;
2731522600a2SDimitry Andric   }
2732009b1c42SEd Schouten 
2733ac9a064cSDimitry Andric   bool MadeChange = getChild(0).ApplyTypeConstraints(TP, NotRegisters);
2734c6910277SRoman Divacky   return MadeChange;
2735009b1c42SEd Schouten }
2736009b1c42SEd Schouten 
2737009b1c42SEd Schouten /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2738009b1c42SEd Schouten /// RHS of a commutative operation, not the on LHS.
OnlyOnRHSOfCommutative(TreePatternNode & N)2739ac9a064cSDimitry Andric static bool OnlyOnRHSOfCommutative(TreePatternNode &N) {
2740ac9a064cSDimitry Andric   if (!N.isLeaf() && N.getOperator()->getName() == "imm")
2741009b1c42SEd Schouten     return true;
2742ac9a064cSDimitry Andric   if (N.isLeaf() && isa<IntInit>(N.getLeafValue()))
2743009b1c42SEd Schouten     return true;
2744344a3780SDimitry Andric   if (isImmAllOnesAllZerosMatch(N))
2745344a3780SDimitry Andric     return true;
2746009b1c42SEd Schouten   return false;
2747009b1c42SEd Schouten }
2748009b1c42SEd Schouten 
2749009b1c42SEd Schouten /// canPatternMatch - If it is impossible for this pattern to match on this
2750009b1c42SEd Schouten /// target, fill in Reason and return false.  Otherwise, return true.  This is
2751009b1c42SEd Schouten /// used as a sanity check for .td files (to prevent people from writing stuff
2752009b1c42SEd Schouten /// that can never possibly work), and to prevent the pattern permuter from
2753009b1c42SEd Schouten /// generating stuff that is useless.
canPatternMatch(std::string & Reason,const CodeGenDAGPatterns & CDP)2754009b1c42SEd Schouten bool TreePatternNode::canPatternMatch(std::string &Reason,
2755009b1c42SEd Schouten                                       const CodeGenDAGPatterns &CDP) {
2756ac9a064cSDimitry Andric   if (isLeaf())
2757ac9a064cSDimitry Andric     return true;
2758009b1c42SEd Schouten 
2759009b1c42SEd Schouten   for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2760ac9a064cSDimitry Andric     if (!getChild(i).canPatternMatch(Reason, CDP))
2761009b1c42SEd Schouten       return false;
2762009b1c42SEd Schouten 
2763009b1c42SEd Schouten   // If this is an intrinsic, handle cases that would make it not match.  For
2764009b1c42SEd Schouten   // example, if an operand is required to be an immediate.
2765009b1c42SEd Schouten   if (getOperator()->isSubClassOf("Intrinsic")) {
2766009b1c42SEd Schouten     // TODO:
2767009b1c42SEd Schouten     return true;
2768009b1c42SEd Schouten   }
2769009b1c42SEd Schouten 
27705ca98fd9SDimitry Andric   if (getOperator()->isSubClassOf("ComplexPattern"))
27715ca98fd9SDimitry Andric     return true;
27725ca98fd9SDimitry Andric 
2773009b1c42SEd Schouten   // If this node is a commutative operator, check that the LHS isn't an
2774009b1c42SEd Schouten   // immediate.
2775009b1c42SEd Schouten   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
2776009b1c42SEd Schouten   bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2777009b1c42SEd Schouten   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
2778009b1c42SEd Schouten     // Scan all of the operands of the node and make sure that only the last one
2779009b1c42SEd Schouten     // is a constant node, unless the RHS also is.
2780009b1c42SEd Schouten     if (!OnlyOnRHSOfCommutative(getChild(getNumChildren() - 1))) {
2781b915e9e0SDimitry Andric       unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2782009b1c42SEd Schouten       for (unsigned i = Skip, e = getNumChildren() - 1; i != e; ++i)
2783009b1c42SEd Schouten         if (OnlyOnRHSOfCommutative(getChild(i))) {
2784ac9a064cSDimitry Andric           Reason =
2785ac9a064cSDimitry Andric               "Immediate value must be on the RHS of commutative operators!";
2786009b1c42SEd Schouten           return false;
2787009b1c42SEd Schouten         }
2788009b1c42SEd Schouten     }
2789009b1c42SEd Schouten   }
2790009b1c42SEd Schouten 
2791009b1c42SEd Schouten   return true;
2792009b1c42SEd Schouten }
2793009b1c42SEd Schouten 
2794009b1c42SEd Schouten //===----------------------------------------------------------------------===//
2795009b1c42SEd Schouten // TreePattern implementation
2796009b1c42SEd Schouten //
2797009b1c42SEd Schouten 
TreePattern(Record * TheRec,ListInit * RawPat,bool isInput,CodeGenDAGPatterns & cdp)2798009b1c42SEd Schouten TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
2799ac9a064cSDimitry Andric                          CodeGenDAGPatterns &cdp)
2800ac9a064cSDimitry Andric     : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2801044eb2f6SDimitry Andric       Infer(*this) {
280285d8b2bbSDimitry Andric   for (Init *I : RawPat->getValues())
280385d8b2bbSDimitry Andric     Trees.push_back(ParseTreePattern(I, ""));
2804009b1c42SEd Schouten }
2805009b1c42SEd Schouten 
TreePattern(Record * TheRec,DagInit * Pat,bool isInput,CodeGenDAGPatterns & cdp)2806009b1c42SEd Schouten TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
2807ac9a064cSDimitry Andric                          CodeGenDAGPatterns &cdp)
2808ac9a064cSDimitry Andric     : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2809044eb2f6SDimitry Andric       Infer(*this) {
2810104bd817SRoman Divacky   Trees.push_back(ParseTreePattern(Pat, ""));
2811009b1c42SEd Schouten }
2812009b1c42SEd Schouten 
TreePattern(Record * TheRec,TreePatternNodePtr Pat,bool isInput,CodeGenDAGPatterns & cdp)2813eb11fae6SDimitry Andric TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
2814eb11fae6SDimitry Andric                          CodeGenDAGPatterns &cdp)
2815eb11fae6SDimitry Andric     : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2816044eb2f6SDimitry Andric       Infer(*this) {
2817009b1c42SEd Schouten   Trees.push_back(Pat);
2818009b1c42SEd Schouten }
2819009b1c42SEd Schouten 
error(const Twine & Msg)282067c32a98SDimitry Andric void TreePattern::error(const Twine &Msg) {
2821522600a2SDimitry Andric   if (HasError)
2822522600a2SDimitry Andric     return;
2823009b1c42SEd Schouten   dump();
2824522600a2SDimitry Andric   PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2825522600a2SDimitry Andric   HasError = true;
2826009b1c42SEd Schouten }
2827009b1c42SEd Schouten 
ComputeNamedNodes()2828c6910277SRoman Divacky void TreePattern::ComputeNamedNodes() {
2829eb11fae6SDimitry Andric   for (TreePatternNodePtr &Tree : Trees)
2830ac9a064cSDimitry Andric     ComputeNamedNodes(*Tree);
2831c6910277SRoman Divacky }
2832c6910277SRoman Divacky 
ComputeNamedNodes(TreePatternNode & N)2833ac9a064cSDimitry Andric void TreePattern::ComputeNamedNodes(TreePatternNode &N) {
2834ac9a064cSDimitry Andric   if (!N.getName().empty())
2835ac9a064cSDimitry Andric     NamedNodes[N.getName()].push_back(&N);
2836c6910277SRoman Divacky 
2837ac9a064cSDimitry Andric   for (unsigned i = 0, e = N.getNumChildren(); i != e; ++i)
2838ac9a064cSDimitry Andric     ComputeNamedNodes(N.getChild(i));
2839c6910277SRoman Divacky }
2840c6910277SRoman Divacky 
ParseTreePattern(Init * TheInit,StringRef OpName)2841eb11fae6SDimitry Andric TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
2842eb11fae6SDimitry Andric                                                  StringRef OpName) {
2843145449b1SDimitry Andric   RecordKeeper &RK = TheInit->getRecordKeeper();
2844522600a2SDimitry Andric   if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
2845104bd817SRoman Divacky     Record *R = DI->getDef();
2846104bd817SRoman Divacky 
2847104bd817SRoman Divacky     // Direct reference to a leaf DagNode or PatFrag?  Turn it into a
2848411bd29eSDimitry Andric     // TreePatternNode of its own.  For example:
2849104bd817SRoman Divacky     ///   (foo GPR, imm) -> (foo GPR, (imm))
2850eb11fae6SDimitry Andric     if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
285130815c53SDimitry Andric       return ParseTreePattern(
2852b915e9e0SDimitry Andric           DagInit::get(DI, nullptr,
2853b915e9e0SDimitry Andric                        std::vector<std::pair<Init *, StringInit *>>()),
2854104bd817SRoman Divacky           OpName);
2855104bd817SRoman Divacky 
2856104bd817SRoman Divacky     // Input argument?
28577fa27ce4SDimitry Andric     TreePatternNodePtr Res = makeIntrusiveRefCnt<TreePatternNode>(DI, 1);
2858104bd817SRoman Divacky     if (R->getName() == "node" && !OpName.empty()) {
2859104bd817SRoman Divacky       if (OpName.empty())
2860104bd817SRoman Divacky         error("'node' argument requires a name to match with operand list");
2861cfca06d7SDimitry Andric       Args.push_back(std::string(OpName));
2862104bd817SRoman Divacky     }
2863104bd817SRoman Divacky 
2864104bd817SRoman Divacky     Res->setName(OpName);
2865104bd817SRoman Divacky     return Res;
2866104bd817SRoman Divacky   }
2867104bd817SRoman Divacky 
28684a16efa3SDimitry Andric   // ?:$name or just $name.
28695a5ac124SDimitry Andric   if (isa<UnsetInit>(TheInit)) {
28704a16efa3SDimitry Andric     if (OpName.empty())
28714a16efa3SDimitry Andric       error("'?' argument requires a name to match with operand list");
28727fa27ce4SDimitry Andric     TreePatternNodePtr Res = makeIntrusiveRefCnt<TreePatternNode>(TheInit, 1);
2873cfca06d7SDimitry Andric     Args.push_back(std::string(OpName));
28744a16efa3SDimitry Andric     Res->setName(OpName);
28754a16efa3SDimitry Andric     return Res;
28764a16efa3SDimitry Andric   }
28774a16efa3SDimitry Andric 
2878eb11fae6SDimitry Andric   if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
2879104bd817SRoman Divacky     if (!OpName.empty())
2880eb11fae6SDimitry Andric       error("Constant int or bit argument should not have a name!");
2881eb11fae6SDimitry Andric     if (isa<BitInit>(TheInit))
2882145449b1SDimitry Andric       TheInit = TheInit->convertInitializerTo(IntRecTy::get(RK));
28837fa27ce4SDimitry Andric     return makeIntrusiveRefCnt<TreePatternNode>(TheInit, 1);
2884104bd817SRoman Divacky   }
2885104bd817SRoman Divacky 
2886522600a2SDimitry Andric   if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
2887104bd817SRoman Divacky     // Turn this into an IntInit.
2888145449b1SDimitry Andric     Init *II = BI->convertInitializerTo(IntRecTy::get(RK));
28895ca98fd9SDimitry Andric     if (!II || !isa<IntInit>(II))
2890104bd817SRoman Divacky       error("Bits value must be constants!");
28917fa27ce4SDimitry Andric     return II ? ParseTreePattern(II, OpName) : nullptr;
2892104bd817SRoman Divacky   }
2893104bd817SRoman Divacky 
2894522600a2SDimitry Andric   DagInit *Dag = dyn_cast<DagInit>(TheInit);
2895104bd817SRoman Divacky   if (!Dag) {
289671d5a254SDimitry Andric     TheInit->print(errs());
2897104bd817SRoman Divacky     error("Pattern has unexpected init kind!");
28987fa27ce4SDimitry Andric     return nullptr;
2899104bd817SRoman Divacky   }
2900522600a2SDimitry Andric   DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
29017fa27ce4SDimitry Andric   if (!OpDef) {
29027fa27ce4SDimitry Andric     error("Pattern has unexpected operator type!");
29037fa27ce4SDimitry Andric     return nullptr;
29047fa27ce4SDimitry Andric   }
2905009b1c42SEd Schouten   Record *Operator = OpDef->getDef();
2906009b1c42SEd Schouten 
2907009b1c42SEd Schouten   if (Operator->isSubClassOf("ValueType")) {
2908009b1c42SEd Schouten     // If the operator is a ValueType, then this must be "type cast" of a leaf
2909009b1c42SEd Schouten     // node.
2910009b1c42SEd Schouten     if (Dag->getNumArgs() != 1)
2911009b1c42SEd Schouten       error("Type cast only takes one operand!");
2912009b1c42SEd Schouten 
2913eb11fae6SDimitry Andric     TreePatternNodePtr New =
2914eb11fae6SDimitry Andric         ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
2915009b1c42SEd Schouten 
2916009b1c42SEd Schouten     // Apply the type cast.
2917344a3780SDimitry Andric     if (New->getNumTypes() != 1)
2918344a3780SDimitry Andric       error("Type cast can only have one type!");
2919044eb2f6SDimitry Andric     const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2920044eb2f6SDimitry Andric     New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
2921104bd817SRoman Divacky 
2922104bd817SRoman Divacky     if (!OpName.empty())
2923104bd817SRoman Divacky       error("ValueType cast should not have a name!");
2924009b1c42SEd Schouten     return New;
2925009b1c42SEd Schouten   }
2926009b1c42SEd Schouten 
2927009b1c42SEd Schouten   // Verify that this is something that makes sense for an operator.
2928eb11fae6SDimitry Andric   if (!Operator->isSubClassOf("PatFrags") &&
2929009b1c42SEd Schouten       !Operator->isSubClassOf("SDNode") &&
2930009b1c42SEd Schouten       !Operator->isSubClassOf("Instruction") &&
2931009b1c42SEd Schouten       !Operator->isSubClassOf("SDNodeXForm") &&
2932009b1c42SEd Schouten       !Operator->isSubClassOf("Intrinsic") &&
29335ca98fd9SDimitry Andric       !Operator->isSubClassOf("ComplexPattern") &&
2934ac9a064cSDimitry Andric       Operator->getName() != "set" && Operator->getName() != "implicit")
2935009b1c42SEd Schouten     error("Unrecognized node '" + Operator->getName() + "'!");
2936009b1c42SEd Schouten 
2937009b1c42SEd Schouten   //  Check to see if this is something that is illegal in an input pattern.
2938104bd817SRoman Divacky   if (isInputPattern) {
2939104bd817SRoman Divacky     if (Operator->isSubClassOf("Instruction") ||
2940104bd817SRoman Divacky         Operator->isSubClassOf("SDNodeXForm"))
2941009b1c42SEd Schouten       error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2942104bd817SRoman Divacky   } else {
2943104bd817SRoman Divacky     if (Operator->isSubClassOf("Intrinsic"))
2944104bd817SRoman Divacky       error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2945104bd817SRoman Divacky 
2946ac9a064cSDimitry Andric     if (Operator->isSubClassOf("SDNode") && Operator->getName() != "imm" &&
2947ac9a064cSDimitry Andric         Operator->getName() != "timm" && Operator->getName() != "fpimm" &&
2948104bd817SRoman Divacky         Operator->getName() != "tglobaltlsaddr" &&
2949104bd817SRoman Divacky         Operator->getName() != "tconstpool" &&
2950104bd817SRoman Divacky         Operator->getName() != "tjumptable" &&
2951104bd817SRoman Divacky         Operator->getName() != "tframeindex" &&
2952104bd817SRoman Divacky         Operator->getName() != "texternalsym" &&
2953104bd817SRoman Divacky         Operator->getName() != "tblockaddress" &&
2954ac9a064cSDimitry Andric         Operator->getName() != "tglobaladdr" && Operator->getName() != "bb" &&
2955ac9a064cSDimitry Andric         Operator->getName() != "vt" && Operator->getName() != "mcsym")
2956104bd817SRoman Divacky       error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2957104bd817SRoman Divacky   }
2958009b1c42SEd Schouten 
2959eb11fae6SDimitry Andric   std::vector<TreePatternNodePtr> Children;
2960009b1c42SEd Schouten 
2961104bd817SRoman Divacky   // Parse all the operands.
2962104bd817SRoman Divacky   for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
2963b915e9e0SDimitry Andric     Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
2964009b1c42SEd Schouten 
2965ac9a064cSDimitry Andric   // Get the actual number of results before Operator is converted to an
2966ac9a064cSDimitry Andric   // intrinsic node (which is hard-coded to have either zero or one result).
2967eb11fae6SDimitry Andric   unsigned NumResults = GetNumNodeResults(Operator, CDP);
2968eb11fae6SDimitry Andric 
2969eb11fae6SDimitry Andric   // If the operator is an intrinsic, then this is just syntactic sugar for
2970009b1c42SEd Schouten   // (intrinsic_* <number>, ..children..).  Pick the right intrinsic node, and
2971009b1c42SEd Schouten   // convert the intrinsic name to a number.
2972009b1c42SEd Schouten   if (Operator->isSubClassOf("Intrinsic")) {
2973009b1c42SEd Schouten     const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2974009b1c42SEd Schouten     unsigned IID = getDAGPatterns().getIntrinsicID(Operator) + 1;
2975009b1c42SEd Schouten 
2976009b1c42SEd Schouten     // If this intrinsic returns void, it must have side-effects and thus a
2977009b1c42SEd Schouten     // chain.
29787fa27ce4SDimitry Andric     if (Int.IS.RetTys.empty())
2979009b1c42SEd Schouten       Operator = getDAGPatterns().get_intrinsic_void_sdnode();
2980e3b55780SDimitry Andric     else if (!Int.ME.doesNotAccessMemory() || Int.hasSideEffects)
2981009b1c42SEd Schouten       // Has side-effects, requires chain.
2982009b1c42SEd Schouten       Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
2983104bd817SRoman Divacky     else // Otherwise, no chain.
2984009b1c42SEd Schouten       Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
2985009b1c42SEd Schouten 
29867fa27ce4SDimitry Andric     Children.insert(Children.begin(), makeIntrusiveRefCnt<TreePatternNode>(
2987145449b1SDimitry Andric                                           IntInit::get(RK, IID), 1));
2988009b1c42SEd Schouten   }
2989009b1c42SEd Schouten 
29905ca98fd9SDimitry Andric   if (Operator->isSubClassOf("ComplexPattern")) {
29915ca98fd9SDimitry Andric     for (unsigned i = 0; i < Children.size(); ++i) {
2992eb11fae6SDimitry Andric       TreePatternNodePtr Child = Children[i];
29935ca98fd9SDimitry Andric 
29945ca98fd9SDimitry Andric       if (Child->getName().empty())
29955ca98fd9SDimitry Andric         error("All arguments to a ComplexPattern must be named");
29965ca98fd9SDimitry Andric 
29975ca98fd9SDimitry Andric       // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
29985ca98fd9SDimitry Andric       // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
29995ca98fd9SDimitry Andric       // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
3000ac9a064cSDimitry Andric       auto OperandId = std::pair(Operator, i);
30015ca98fd9SDimitry Andric       auto PrevOp = ComplexPatternOperands.find(Child->getName());
30025ca98fd9SDimitry Andric       if (PrevOp != ComplexPatternOperands.end()) {
30035ca98fd9SDimitry Andric         if (PrevOp->getValue() != OperandId)
30045ca98fd9SDimitry Andric           error("All ComplexPattern operands must appear consistently: "
30055ca98fd9SDimitry Andric                 "in the same order in just one ComplexPattern instance.");
30065ca98fd9SDimitry Andric       } else
30075ca98fd9SDimitry Andric         ComplexPatternOperands[Child->getName()] = OperandId;
30085ca98fd9SDimitry Andric     }
30095ca98fd9SDimitry Andric   }
30105ca98fd9SDimitry Andric 
30117fa27ce4SDimitry Andric   TreePatternNodePtr Result = makeIntrusiveRefCnt<TreePatternNode>(
30127fa27ce4SDimitry Andric       Operator, std::move(Children), NumResults);
3013104bd817SRoman Divacky   Result->setName(OpName);
3014104bd817SRoman Divacky 
3015b915e9e0SDimitry Andric   if (Dag->getName()) {
3016104bd817SRoman Divacky     assert(Result->getName().empty());
3017b915e9e0SDimitry Andric     Result->setName(Dag->getNameStr());
3018104bd817SRoman Divacky   }
3019009b1c42SEd Schouten   return Result;
3020009b1c42SEd Schouten }
3021009b1c42SEd Schouten 
3022104bd817SRoman Divacky /// SimplifyTree - See if we can simplify this tree to eliminate something that
3023104bd817SRoman Divacky /// will never match in favor of something obvious that will.  This is here
3024104bd817SRoman Divacky /// strictly as a convenience to target authors because it allows them to write
3025104bd817SRoman Divacky /// more type generic things and have useless type casts fold away.
3026104bd817SRoman Divacky ///
3027104bd817SRoman Divacky /// This returns true if any change is made.
SimplifyTree(TreePatternNodePtr & N)3028eb11fae6SDimitry Andric static bool SimplifyTree(TreePatternNodePtr &N) {
3029104bd817SRoman Divacky   if (N->isLeaf())
3030104bd817SRoman Divacky     return false;
3031104bd817SRoman Divacky 
3032104bd817SRoman Divacky   // If we have a bitconvert with a resolved type and if the source and
3033104bd817SRoman Divacky   // destination types are the same, then the bitconvert is useless, remove it.
3034cfca06d7SDimitry Andric   //
3035cfca06d7SDimitry Andric   // We make an exception if the types are completely empty. This can come up
3036cfca06d7SDimitry Andric   // when the pattern being simplified is in the Fragments list of a PatFrags,
3037cfca06d7SDimitry Andric   // so that the operand is just an untyped "node". In that situation we leave
3038cfca06d7SDimitry Andric   // bitconverts unsimplified, and simplify them later once the fragment is
3039cfca06d7SDimitry Andric   // expanded into its true context.
3040104bd817SRoman Divacky   if (N->getOperator()->getName() == "bitconvert" &&
3041044eb2f6SDimitry Andric       N->getExtType(0).isValueTypeByHwMode(false) &&
3042cfca06d7SDimitry Andric       !N->getExtType(0).empty() &&
3043ac9a064cSDimitry Andric       N->getExtType(0) == N->getChild(0).getExtType(0) &&
3044104bd817SRoman Divacky       N->getName().empty()) {
3045f56b67c4SDimitry Andric     if (!N->getPredicateCalls().empty()) {
3046f56b67c4SDimitry Andric       std::string Str;
3047f56b67c4SDimitry Andric       raw_string_ostream OS(Str);
3048f56b67c4SDimitry Andric       OS << *N
3049f56b67c4SDimitry Andric          << "\n trivial bitconvert node should not have predicate calls\n";
3050f56b67c4SDimitry Andric       PrintFatalError(Str);
3051f56b67c4SDimitry Andric       return false;
3052f56b67c4SDimitry Andric     }
3053eb11fae6SDimitry Andric     N = N->getChildShared(0);
3054104bd817SRoman Divacky     SimplifyTree(N);
3055104bd817SRoman Divacky     return true;
3056104bd817SRoman Divacky   }
3057104bd817SRoman Divacky 
3058104bd817SRoman Divacky   // Walk all children.
3059104bd817SRoman Divacky   bool MadeChange = false;
30607fa27ce4SDimitry Andric   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
30617fa27ce4SDimitry Andric     MadeChange |= SimplifyTree(N->getChildSharedPtr(i));
30627fa27ce4SDimitry Andric 
3063104bd817SRoman Divacky   return MadeChange;
3064104bd817SRoman Divacky }
3065104bd817SRoman Divacky 
3066009b1c42SEd Schouten /// InferAllTypes - Infer/propagate as many types throughout the expression
3067009b1c42SEd Schouten /// patterns as possible.  Return true if all types are inferred, false
3068522600a2SDimitry Andric /// otherwise.  Flags an error if a type contradiction is found.
InferAllTypes(const StringMap<SmallVector<TreePatternNode *,1>> * InNamedTypes)3069ac9a064cSDimitry Andric bool TreePattern::InferAllTypes(
3070ac9a064cSDimitry Andric     const StringMap<SmallVector<TreePatternNode *, 1>> *InNamedTypes) {
3071c6910277SRoman Divacky   if (NamedNodes.empty())
3072c6910277SRoman Divacky     ComputeNamedNodes();
3073c6910277SRoman Divacky 
3074009b1c42SEd Schouten   bool MadeChange = true;
3075009b1c42SEd Schouten   while (MadeChange) {
3076009b1c42SEd Schouten     MadeChange = false;
3077eb11fae6SDimitry Andric     for (TreePatternNodePtr &Tree : Trees) {
3078dd58ef01SDimitry Andric       MadeChange |= Tree->ApplyTypeConstraints(*this, false);
3079dd58ef01SDimitry Andric       MadeChange |= SimplifyTree(Tree);
3080104bd817SRoman Divacky     }
3081c6910277SRoman Divacky 
3082c6910277SRoman Divacky     // If there are constraints on our named nodes, apply them.
3083dd58ef01SDimitry Andric     for (auto &Entry : NamedNodes) {
3084dd58ef01SDimitry Andric       SmallVectorImpl<TreePatternNode *> &Nodes = Entry.second;
3085c6910277SRoman Divacky 
3086c6910277SRoman Divacky       // If we have input named node types, propagate their types to the named
3087c6910277SRoman Divacky       // values here.
3088c6910277SRoman Divacky       if (InNamedTypes) {
3089dd58ef01SDimitry Andric         if (!InNamedTypes->count(Entry.getKey())) {
3090dd58ef01SDimitry Andric           error("Node '" + std::string(Entry.getKey()) +
30915ca98fd9SDimitry Andric                 "' in output pattern but not input pattern");
30925ca98fd9SDimitry Andric           return true;
30935ca98fd9SDimitry Andric         }
3094c6910277SRoman Divacky 
3095c6910277SRoman Divacky         const SmallVectorImpl<TreePatternNode *> &InNodes =
3096dd58ef01SDimitry Andric             InNamedTypes->find(Entry.getKey())->second;
3097c6910277SRoman Divacky 
3098c6910277SRoman Divacky         // The input types should be fully resolved by now.
3099dd58ef01SDimitry Andric         for (TreePatternNode *Node : Nodes) {
3100c6910277SRoman Divacky           // If this node is a register class, and it is the root of the pattern
3101c6910277SRoman Divacky           // then we're mapping something onto an input register.  We allow
3102c6910277SRoman Divacky           // changing the type of the input register in this case.  This allows
3103c6910277SRoman Divacky           // us to match things like:
3104c6910277SRoman Divacky           //  def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
3105eb11fae6SDimitry Andric           if (Node == Trees[0].get() && Node->isLeaf()) {
3106dd58ef01SDimitry Andric             DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
3107411bd29eSDimitry Andric             if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3108411bd29eSDimitry Andric                        DI->getDef()->isSubClassOf("RegisterOperand")))
3109c6910277SRoman Divacky               continue;
3110c6910277SRoman Divacky           }
3111c6910277SRoman Divacky 
3112ac9a064cSDimitry Andric           assert(Node->getNumTypes() == 1 && InNodes[0]->getNumTypes() == 1 &&
31132f12f10aSRoman Divacky                  "FIXME: cannot name multiple result nodes yet");
3114ac9a064cSDimitry Andric           MadeChange |=
3115ac9a064cSDimitry Andric               Node->UpdateNodeType(0, InNodes[0]->getExtType(0), *this);
3116c6910277SRoman Divacky         }
3117c6910277SRoman Divacky       }
3118c6910277SRoman Divacky 
3119c6910277SRoman Divacky       // If there are multiple nodes with the same name, they must all have the
3120c6910277SRoman Divacky       // same type.
3121dd58ef01SDimitry Andric       if (Entry.second.size() > 1) {
3122c6910277SRoman Divacky         for (unsigned i = 0, e = Nodes.size() - 1; i != e; ++i) {
31232f12f10aSRoman Divacky           TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i + 1];
31242f12f10aSRoman Divacky           assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
31252f12f10aSRoman Divacky                  "FIXME: cannot name multiple result nodes yet");
31262f12f10aSRoman Divacky 
31272f12f10aSRoman Divacky           MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
31282f12f10aSRoman Divacky           MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
3129c6910277SRoman Divacky         }
3130c6910277SRoman Divacky       }
3131c6910277SRoman Divacky     }
3132009b1c42SEd Schouten   }
3133009b1c42SEd Schouten 
3134009b1c42SEd Schouten   bool HasUnresolvedTypes = false;
3135eb11fae6SDimitry Andric   for (const TreePatternNodePtr &Tree : Trees)
3136044eb2f6SDimitry Andric     HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
3137009b1c42SEd Schouten   return !HasUnresolvedTypes;
3138009b1c42SEd Schouten }
3139009b1c42SEd Schouten 
print(raw_ostream & OS) const314018f153bdSEd Schouten void TreePattern::print(raw_ostream &OS) const {
3141009b1c42SEd Schouten   OS << getRecord()->getName();
3142009b1c42SEd Schouten   if (!Args.empty()) {
3143344a3780SDimitry Andric     OS << "(";
3144344a3780SDimitry Andric     ListSeparator LS;
3145344a3780SDimitry Andric     for (const std::string &Arg : Args)
3146344a3780SDimitry Andric       OS << LS << Arg;
3147009b1c42SEd Schouten     OS << ")";
3148009b1c42SEd Schouten   }
3149009b1c42SEd Schouten   OS << ": ";
3150009b1c42SEd Schouten 
3151009b1c42SEd Schouten   if (Trees.size() > 1)
3152009b1c42SEd Schouten     OS << "[\n";
3153eb11fae6SDimitry Andric   for (const TreePatternNodePtr &Tree : Trees) {
3154009b1c42SEd Schouten     OS << "\t";
3155dd58ef01SDimitry Andric     Tree->print(OS);
3156009b1c42SEd Schouten     OS << "\n";
3157009b1c42SEd Schouten   }
3158009b1c42SEd Schouten 
3159009b1c42SEd Schouten   if (Trees.size() > 1)
3160009b1c42SEd Schouten     OS << "]\n";
3161009b1c42SEd Schouten }
3162009b1c42SEd Schouten 
dump() const316318f153bdSEd Schouten void TreePattern::dump() const { print(errs()); }
3164009b1c42SEd Schouten 
3165009b1c42SEd Schouten //===----------------------------------------------------------------------===//
3166009b1c42SEd Schouten // CodeGenDAGPatterns implementation
3167009b1c42SEd Schouten //
3168009b1c42SEd Schouten 
CodeGenDAGPatterns(RecordKeeper & R,PatternRewriterFn PatternRewriter)3169044eb2f6SDimitry Andric CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
3170044eb2f6SDimitry Andric                                        PatternRewriterFn PatternRewriter)
3171044eb2f6SDimitry Andric     : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
3172044eb2f6SDimitry Andric       PatternRewriter(PatternRewriter) {
3173cf099d11SDimitry Andric 
3174706b4fc4SDimitry Andric   Intrinsics = CodeGenIntrinsicTable(Records);
3175009b1c42SEd Schouten   ParseNodeInfo();
3176009b1c42SEd Schouten   ParseNodeTransforms();
3177009b1c42SEd Schouten   ParseComplexPatterns();
3178009b1c42SEd Schouten   ParsePatternFragments();
3179009b1c42SEd Schouten   ParseDefaultOperands();
3180009b1c42SEd Schouten   ParseInstructions();
31815ca98fd9SDimitry Andric   ParsePatternFragments(/*OutFrags*/ true);
3182009b1c42SEd Schouten   ParsePatterns();
3183009b1c42SEd Schouten 
3184344a3780SDimitry Andric   // Generate variants.  For example, commutative patterns can match
3185344a3780SDimitry Andric   // multiple ways.  Add them to PatternsToMatch as well.
3186344a3780SDimitry Andric   GenerateVariants();
3187344a3780SDimitry Andric 
3188044eb2f6SDimitry Andric   // Break patterns with parameterized types into a series of patterns,
3189044eb2f6SDimitry Andric   // where each one has a fixed type and is predicated on the conditions
3190044eb2f6SDimitry Andric   // of the associated HW mode.
3191044eb2f6SDimitry Andric   ExpandHwModeBasedTypes();
3192044eb2f6SDimitry Andric 
3193009b1c42SEd Schouten   // Infer instruction flags.  For example, we can detect loads,
3194009b1c42SEd Schouten   // stores, and side effects in many cases by examining an
3195009b1c42SEd Schouten   // instruction's pattern.
3196009b1c42SEd Schouten   InferInstructionFlags();
3197522600a2SDimitry Andric 
3198522600a2SDimitry Andric   // Verify that instruction flags match the patterns.
3199522600a2SDimitry Andric   VerifyInstructionFlags();
3200009b1c42SEd Schouten }
3201009b1c42SEd Schouten 
getSDNodeNamed(StringRef Name) const3202b60736ecSDimitry Andric Record *CodeGenDAGPatterns::getSDNodeNamed(StringRef Name) const {
3203009b1c42SEd Schouten   Record *N = Records.getDef(Name);
32045a5ac124SDimitry Andric   if (!N || !N->isSubClassOf("SDNode"))
32055a5ac124SDimitry Andric     PrintFatalError("Error getting SDNode '" + Name + "'!");
32065a5ac124SDimitry Andric 
3207009b1c42SEd Schouten   return N;
3208009b1c42SEd Schouten }
3209009b1c42SEd Schouten 
3210009b1c42SEd Schouten // Parse all of the SDNode definitions for the target, populating SDNodes.
ParseNodeInfo()3211009b1c42SEd Schouten void CodeGenDAGPatterns::ParseNodeInfo() {
3212009b1c42SEd Schouten   std::vector<Record *> Nodes = Records.getAllDerivedDefinitions("SDNode");
3213044eb2f6SDimitry Andric   const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3214044eb2f6SDimitry Andric 
3215009b1c42SEd Schouten   while (!Nodes.empty()) {
3216044eb2f6SDimitry Andric     Record *R = Nodes.back();
3217ac9a064cSDimitry Andric     SDNodes.insert(std::pair(R, SDNodeInfo(R, CGH)));
3218009b1c42SEd Schouten     Nodes.pop_back();
3219009b1c42SEd Schouten   }
3220009b1c42SEd Schouten 
3221009b1c42SEd Schouten   // Get the builtin intrinsic nodes.
3222009b1c42SEd Schouten   intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
3223009b1c42SEd Schouten   intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
3224009b1c42SEd Schouten   intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
3225009b1c42SEd Schouten }
3226009b1c42SEd Schouten 
3227009b1c42SEd Schouten /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
3228009b1c42SEd Schouten /// map, and emit them to the file as functions.
ParseNodeTransforms()3229009b1c42SEd Schouten void CodeGenDAGPatterns::ParseNodeTransforms() {
3230ac9a064cSDimitry Andric   std::vector<Record *> Xforms =
3231ac9a064cSDimitry Andric       Records.getAllDerivedDefinitions("SDNodeXForm");
3232009b1c42SEd Schouten   while (!Xforms.empty()) {
3233009b1c42SEd Schouten     Record *XFormNode = Xforms.back();
3234009b1c42SEd Schouten     Record *SDNode = XFormNode->getValueAsDef("Opcode");
3235f382538dSDimitry Andric     StringRef Code = XFormNode->getValueAsString("XFormFunction");
3236cfca06d7SDimitry Andric     SDNodeXForms.insert(
3237ac9a064cSDimitry Andric         std::pair(XFormNode, NodeXForm(SDNode, std::string(Code))));
3238009b1c42SEd Schouten 
3239009b1c42SEd Schouten     Xforms.pop_back();
3240009b1c42SEd Schouten   }
3241009b1c42SEd Schouten }
3242009b1c42SEd Schouten 
ParseComplexPatterns()3243009b1c42SEd Schouten void CodeGenDAGPatterns::ParseComplexPatterns() {
3244ac9a064cSDimitry Andric   std::vector<Record *> AMs =
3245ac9a064cSDimitry Andric       Records.getAllDerivedDefinitions("ComplexPattern");
3246009b1c42SEd Schouten   while (!AMs.empty()) {
3247ac9a064cSDimitry Andric     ComplexPatterns.insert(std::pair(AMs.back(), AMs.back()));
3248009b1c42SEd Schouten     AMs.pop_back();
3249009b1c42SEd Schouten   }
3250009b1c42SEd Schouten }
3251009b1c42SEd Schouten 
3252009b1c42SEd Schouten /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3253009b1c42SEd Schouten /// file, building up the PatternFragments map.  After we've collected them all,
3254009b1c42SEd Schouten /// inline fragments together as necessary, so that there are no references left
3255009b1c42SEd Schouten /// inside a pattern fragment to a pattern fragment.
3256009b1c42SEd Schouten ///
ParsePatternFragments(bool OutFrags)32575ca98fd9SDimitry Andric void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
3258ac9a064cSDimitry Andric   std::vector<Record *> Fragments =
3259ac9a064cSDimitry Andric       Records.getAllDerivedDefinitions("PatFrags");
3260009b1c42SEd Schouten 
3261009b1c42SEd Schouten   // First step, parse all of the fragments.
3262dd58ef01SDimitry Andric   for (Record *Frag : Fragments) {
3263dd58ef01SDimitry Andric     if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
32645ca98fd9SDimitry Andric       continue;
32655ca98fd9SDimitry Andric 
3266eb11fae6SDimitry Andric     ListInit *LI = Frag->getValueAsListInit("Fragments");
3267ac9a064cSDimitry Andric     TreePattern *P = (PatternFragments[Frag] = std::make_unique<TreePattern>(
3268ac9a064cSDimitry Andric                           Frag, LI, !Frag->isSubClassOf("OutPatFrag"), *this))
3269ac9a064cSDimitry Andric                          .get();
3270009b1c42SEd Schouten 
3271009b1c42SEd Schouten     // Validate the argument list, converting it to set, to discard duplicates.
3272009b1c42SEd Schouten     std::vector<std::string> &Args = P->getArgList();
3273044eb2f6SDimitry Andric     // Copy the args so we can take StringRefs to them.
3274044eb2f6SDimitry Andric     auto ArgsCopy = Args;
3275044eb2f6SDimitry Andric     SmallDenseSet<StringRef, 4> OperandsSet;
3276044eb2f6SDimitry Andric     OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
3277009b1c42SEd Schouten 
3278009b1c42SEd Schouten     if (OperandsSet.count(""))
3279009b1c42SEd Schouten       P->error("Cannot have unnamed 'node' values in pattern fragment!");
3280009b1c42SEd Schouten 
3281009b1c42SEd Schouten     // Parse the operands list.
3282dd58ef01SDimitry Andric     DagInit *OpsList = Frag->getValueAsDag("Operands");
3283522600a2SDimitry Andric     DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
3284009b1c42SEd Schouten     // Special cases: ops == outs == ins. Different names are used to
3285009b1c42SEd Schouten     // improve readability.
3286ac9a064cSDimitry Andric     if (!OpsOp || (OpsOp->getDef()->getName() != "ops" &&
3287009b1c42SEd Schouten                    OpsOp->getDef()->getName() != "outs" &&
3288009b1c42SEd Schouten                    OpsOp->getDef()->getName() != "ins"))
3289009b1c42SEd Schouten       P->error("Operands list should start with '(ops ... '!");
3290009b1c42SEd Schouten 
3291009b1c42SEd Schouten     // Copy over the arguments.
3292009b1c42SEd Schouten     Args.clear();
3293009b1c42SEd Schouten     for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
3294522600a2SDimitry Andric       if (!isa<DefInit>(OpsList->getArg(j)) ||
3295522600a2SDimitry Andric           cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
3296009b1c42SEd Schouten         P->error("Operands list should all be 'node' values.");
3297b915e9e0SDimitry Andric       if (!OpsList->getArgName(j))
3298009b1c42SEd Schouten         P->error("Operands list should have names for each operand!");
3299b915e9e0SDimitry Andric       StringRef ArgNameStr = OpsList->getArgNameStr(j);
3300b915e9e0SDimitry Andric       if (!OperandsSet.count(ArgNameStr))
3301b915e9e0SDimitry Andric         P->error("'" + ArgNameStr +
3302009b1c42SEd Schouten                  "' does not occur in pattern or was multiply specified!");
3303b915e9e0SDimitry Andric       OperandsSet.erase(ArgNameStr);
3304cfca06d7SDimitry Andric       Args.push_back(std::string(ArgNameStr));
3305009b1c42SEd Schouten     }
3306009b1c42SEd Schouten 
3307009b1c42SEd Schouten     if (!OperandsSet.empty())
3308009b1c42SEd Schouten       P->error("Operands list does not contain an entry for operand '" +
3309009b1c42SEd Schouten                *OperandsSet.begin() + "'!");
3310009b1c42SEd Schouten 
3311009b1c42SEd Schouten     // If there is a node transformation corresponding to this, keep track of
3312009b1c42SEd Schouten     // it.
3313dd58ef01SDimitry Andric     Record *Transform = Frag->getValueAsDef("OperandTransform");
3314009b1c42SEd Schouten     if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
3315344a3780SDimitry Andric       for (const auto &T : P->getTrees())
3316eb11fae6SDimitry Andric         T->setTransformFn(Transform);
3317009b1c42SEd Schouten   }
3318009b1c42SEd Schouten 
3319009b1c42SEd Schouten   // Now that we've parsed all of the tree fragments, do a closure on them so
3320009b1c42SEd Schouten   // that there are not references to PatFrags left inside of them.
3321dd58ef01SDimitry Andric   for (Record *Frag : Fragments) {
3322dd58ef01SDimitry Andric     if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
33235ca98fd9SDimitry Andric       continue;
33245ca98fd9SDimitry Andric 
3325dd58ef01SDimitry Andric     TreePattern &ThePat = *PatternFragments[Frag];
332667c32a98SDimitry Andric     ThePat.InlinePatternFragments();
3327009b1c42SEd Schouten 
3328009b1c42SEd Schouten     // Infer as many types as possible.  Don't worry about it if we don't infer
3329eb11fae6SDimitry Andric     // all of them, some may depend on the inputs of the pattern.  Also, don't
3330eb11fae6SDimitry Andric     // validate type sets; validation may cause spurious failures e.g. if a
3331eb11fae6SDimitry Andric     // fragment needs floating-point types but the current target does not have
3332eb11fae6SDimitry Andric     // any (this is only an error if that fragment is ever used!).
3333eb11fae6SDimitry Andric     {
3334eb11fae6SDimitry Andric       TypeInfer::SuppressValidation SV(ThePat.getInfer());
333567c32a98SDimitry Andric       ThePat.InferAllTypes();
333667c32a98SDimitry Andric       ThePat.resetError();
3337eb11fae6SDimitry Andric     }
3338009b1c42SEd Schouten 
3339009b1c42SEd Schouten     // If debugging, print out the pattern fragment result.
3340eb11fae6SDimitry Andric     LLVM_DEBUG(ThePat.dump());
3341009b1c42SEd Schouten   }
3342009b1c42SEd Schouten }
3343009b1c42SEd Schouten 
ParseDefaultOperands()3344009b1c42SEd Schouten void CodeGenDAGPatterns::ParseDefaultOperands() {
3345522600a2SDimitry Andric   std::vector<Record *> DefaultOps;
3346522600a2SDimitry Andric   DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
3347009b1c42SEd Schouten 
3348009b1c42SEd Schouten   // Find some SDNode.
3349009b1c42SEd Schouten   assert(!SDNodes.empty() && "No SDNodes parsed?");
335030815c53SDimitry Andric   Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
3351009b1c42SEd Schouten 
3352522600a2SDimitry Andric   for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3353522600a2SDimitry Andric     DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
3354009b1c42SEd Schouten 
3355009b1c42SEd Schouten     // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3356009b1c42SEd Schouten     // SomeSDnode so that we can parse this.
3357b915e9e0SDimitry Andric     std::vector<std::pair<Init *, StringInit *>> Ops;
3358009b1c42SEd Schouten     for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3359ac9a064cSDimitry Andric       Ops.push_back(
3360ac9a064cSDimitry Andric           std::pair(DefaultInfo->getArg(op), DefaultInfo->getArgName(op)));
3361b915e9e0SDimitry Andric     DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
3362009b1c42SEd Schouten 
3363009b1c42SEd Schouten     // Create a TreePattern to parse this.
3364522600a2SDimitry Andric     TreePattern P(DefaultOps[i], DI, false, *this);
3365009b1c42SEd Schouten     assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
3366009b1c42SEd Schouten 
3367009b1c42SEd Schouten     // Copy the operands over into a DAGDefaultOperand.
3368009b1c42SEd Schouten     DAGDefaultOperand DefaultOpInfo;
3369009b1c42SEd Schouten 
3370eb11fae6SDimitry Andric     const TreePatternNodePtr &T = P.getTree(0);
3371009b1c42SEd Schouten     for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
3372eb11fae6SDimitry Andric       TreePatternNodePtr TPN = T->getChildShared(op);
3373009b1c42SEd Schouten       while (TPN->ApplyTypeConstraints(P, false))
3374009b1c42SEd Schouten         /* Resolve all types */;
3375009b1c42SEd Schouten 
3376044eb2f6SDimitry Andric       if (TPN->ContainsUnresolvedType(P)) {
33775ca98fd9SDimitry Andric         PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
33785ca98fd9SDimitry Andric                         DefaultOps[i]->getName() +
33795ca98fd9SDimitry Andric                         "' doesn't have a concrete type!");
3380009b1c42SEd Schouten       }
3381eb11fae6SDimitry Andric       DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
3382009b1c42SEd Schouten     }
3383009b1c42SEd Schouten 
3384009b1c42SEd Schouten     // Insert it into the DefaultOperands map so we can find it later.
3385522600a2SDimitry Andric     DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
3386009b1c42SEd Schouten   }
3387009b1c42SEd Schouten }
3388009b1c42SEd Schouten 
3389009b1c42SEd Schouten /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3390009b1c42SEd Schouten /// instruction input.  Return true if this is a real use.
HandleUse(TreePattern & I,TreePatternNodePtr Pat,std::map<std::string,TreePatternNodePtr> & InstInputs)3391eb11fae6SDimitry Andric static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
3392eb11fae6SDimitry Andric                       std::map<std::string, TreePatternNodePtr> &InstInputs) {
3393009b1c42SEd Schouten   // No name -> not interesting.
3394009b1c42SEd Schouten   if (Pat->getName().empty()) {
3395009b1c42SEd Schouten     if (Pat->isLeaf()) {
3396522600a2SDimitry Andric       DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
3397411bd29eSDimitry Andric       if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3398411bd29eSDimitry Andric                  DI->getDef()->isSubClassOf("RegisterOperand")))
3399eb11fae6SDimitry Andric         I.error("Input " + DI->getDef()->getName() + " must be named!");
3400009b1c42SEd Schouten     }
3401009b1c42SEd Schouten     return false;
3402009b1c42SEd Schouten   }
3403009b1c42SEd Schouten 
3404009b1c42SEd Schouten   Record *Rec;
3405009b1c42SEd Schouten   if (Pat->isLeaf()) {
3406522600a2SDimitry Andric     DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
3407eb11fae6SDimitry Andric     if (!DI)
3408eb11fae6SDimitry Andric       I.error("Input $" + Pat->getName() + " must be an identifier!");
3409009b1c42SEd Schouten     Rec = DI->getDef();
3410009b1c42SEd Schouten   } else {
3411009b1c42SEd Schouten     Rec = Pat->getOperator();
3412009b1c42SEd Schouten   }
3413009b1c42SEd Schouten 
3414009b1c42SEd Schouten   // SRCVALUE nodes are ignored.
3415009b1c42SEd Schouten   if (Rec->getName() == "srcvalue")
3416009b1c42SEd Schouten     return false;
3417009b1c42SEd Schouten 
3418eb11fae6SDimitry Andric   TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
3419009b1c42SEd Schouten   if (!Slot) {
3420009b1c42SEd Schouten     Slot = Pat;
342167a71b31SRoman Divacky     return true;
342267a71b31SRoman Divacky   }
3423009b1c42SEd Schouten   Record *SlotRec;
3424009b1c42SEd Schouten   if (Slot->isLeaf()) {
3425522600a2SDimitry Andric     SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
3426009b1c42SEd Schouten   } else {
3427009b1c42SEd Schouten     assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3428009b1c42SEd Schouten     SlotRec = Slot->getOperator();
3429009b1c42SEd Schouten   }
3430009b1c42SEd Schouten 
3431009b1c42SEd Schouten   // Ensure that the inputs agree if we've already seen this input.
3432009b1c42SEd Schouten   if (Rec != SlotRec)
3433eb11fae6SDimitry Andric     I.error("All $" + Pat->getName() + " inputs must agree with each other");
3434eb11fae6SDimitry Andric   // Ensure that the types can agree as well.
3435eb11fae6SDimitry Andric   Slot->UpdateNodeType(0, Pat->getExtType(0), I);
3436eb11fae6SDimitry Andric   Pat->UpdateNodeType(0, Slot->getExtType(0), I);
34372f12f10aSRoman Divacky   if (Slot->getExtTypes() != Pat->getExtTypes())
3438eb11fae6SDimitry Andric     I.error("All $" + Pat->getName() + " inputs must agree with each other");
3439009b1c42SEd Schouten   return true;
3440009b1c42SEd Schouten }
3441009b1c42SEd Schouten 
3442009b1c42SEd Schouten /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3443009b1c42SEd Schouten /// part of "I", the instruction), computing the set of inputs and outputs of
3444009b1c42SEd Schouten /// the pattern.  Report errors if we see anything naughty.
FindPatternInputsAndOutputs(TreePattern & I,TreePatternNodePtr Pat,std::map<std::string,TreePatternNodePtr> & InstInputs,MapVector<std::string,TreePatternNodePtr,std::map<std::string,unsigned>> & InstResults,std::vector<Record * > & InstImpResults)3445eb11fae6SDimitry Andric void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
3446eb11fae6SDimitry Andric     TreePattern &I, TreePatternNodePtr Pat,
3447eb11fae6SDimitry Andric     std::map<std::string, TreePatternNodePtr> &InstInputs,
3448d8e91e46SDimitry Andric     MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3449d8e91e46SDimitry Andric         &InstResults,
3450009b1c42SEd Schouten     std::vector<Record *> &InstImpResults) {
3451eb11fae6SDimitry Andric 
3452eb11fae6SDimitry Andric   // The instruction pattern still has unresolved fragments.  For *named*
3453eb11fae6SDimitry Andric   // nodes we must resolve those here.  This may not result in multiple
3454eb11fae6SDimitry Andric   // alternatives.
3455eb11fae6SDimitry Andric   if (!Pat->getName().empty()) {
3456eb11fae6SDimitry Andric     TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3457eb11fae6SDimitry Andric     SrcPattern.InlinePatternFragments();
3458eb11fae6SDimitry Andric     SrcPattern.InferAllTypes();
3459eb11fae6SDimitry Andric     Pat = SrcPattern.getOnlyTree();
3460eb11fae6SDimitry Andric   }
3461eb11fae6SDimitry Andric 
3462009b1c42SEd Schouten   if (Pat->isLeaf()) {
3463d7f7719eSRoman Divacky     bool isUse = HandleUse(I, Pat, InstInputs);
3464009b1c42SEd Schouten     if (!isUse && Pat->getTransformFn())
3465eb11fae6SDimitry Andric       I.error("Cannot specify a transform function for a non-input value!");
3466009b1c42SEd Schouten     return;
346767a71b31SRoman Divacky   }
346867a71b31SRoman Divacky 
346967a71b31SRoman Divacky   if (Pat->getOperator()->getName() == "implicit") {
3470009b1c42SEd Schouten     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3471ac9a064cSDimitry Andric       TreePatternNode &Dest = Pat->getChild(i);
3472ac9a064cSDimitry Andric       if (!Dest.isLeaf())
3473eb11fae6SDimitry Andric         I.error("implicitly defined value should be a register!");
3474009b1c42SEd Schouten 
3475ac9a064cSDimitry Andric       DefInit *Val = dyn_cast<DefInit>(Dest.getLeafValue());
3476009b1c42SEd Schouten       if (!Val || !Val->getDef()->isSubClassOf("Register"))
3477eb11fae6SDimitry Andric         I.error("implicitly defined value should be a register!");
34787fa27ce4SDimitry Andric       if (Val)
3479009b1c42SEd Schouten         InstImpResults.push_back(Val->getDef());
3480009b1c42SEd Schouten     }
3481009b1c42SEd Schouten     return;
348267a71b31SRoman Divacky   }
348367a71b31SRoman Divacky 
348467a71b31SRoman Divacky   if (Pat->getOperator()->getName() != "set") {
3485009b1c42SEd Schouten     // If this is not a set, verify that the children nodes are not void typed,
3486009b1c42SEd Schouten     // and recurse.
3487009b1c42SEd Schouten     for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3488ac9a064cSDimitry Andric       if (Pat->getChild(i).getNumTypes() == 0)
3489eb11fae6SDimitry Andric         I.error("Cannot have void nodes inside of patterns!");
3490eb11fae6SDimitry Andric       FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3491eb11fae6SDimitry Andric                                   InstResults, InstImpResults);
3492009b1c42SEd Schouten     }
3493009b1c42SEd Schouten 
3494009b1c42SEd Schouten     // If this is a non-leaf node with no children, treat it basically as if
3495009b1c42SEd Schouten     // it were a leaf.  This handles nodes like (imm).
3496d7f7719eSRoman Divacky     bool isUse = HandleUse(I, Pat, InstInputs);
3497009b1c42SEd Schouten 
3498009b1c42SEd Schouten     if (!isUse && Pat->getTransformFn())
3499eb11fae6SDimitry Andric       I.error("Cannot specify a transform function for a non-input value!");
3500009b1c42SEd Schouten     return;
3501009b1c42SEd Schouten   }
3502009b1c42SEd Schouten 
3503009b1c42SEd Schouten   // Otherwise, this is a set, validate and collect instruction results.
3504009b1c42SEd Schouten   if (Pat->getNumChildren() == 0)
3505eb11fae6SDimitry Andric     I.error("set requires operands!");
3506009b1c42SEd Schouten 
3507009b1c42SEd Schouten   if (Pat->getTransformFn())
3508eb11fae6SDimitry Andric     I.error("Cannot specify a transform function on a set node!");
3509009b1c42SEd Schouten 
3510009b1c42SEd Schouten   // Check the set destinations.
3511009b1c42SEd Schouten   unsigned NumDests = Pat->getNumChildren() - 1;
3512009b1c42SEd Schouten   for (unsigned i = 0; i != NumDests; ++i) {
3513eb11fae6SDimitry Andric     TreePatternNodePtr Dest = Pat->getChildShared(i);
3514eb11fae6SDimitry Andric     // For set destinations we also must resolve fragments here.
3515eb11fae6SDimitry Andric     TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3516eb11fae6SDimitry Andric     DestPattern.InlinePatternFragments();
3517eb11fae6SDimitry Andric     DestPattern.InferAllTypes();
3518eb11fae6SDimitry Andric     Dest = DestPattern.getOnlyTree();
3519eb11fae6SDimitry Andric 
3520009b1c42SEd Schouten     if (!Dest->isLeaf())
3521eb11fae6SDimitry Andric       I.error("set destination should be a register!");
3522009b1c42SEd Schouten 
3523522600a2SDimitry Andric     DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
352467c32a98SDimitry Andric     if (!Val) {
3525eb11fae6SDimitry Andric       I.error("set destination should be a register!");
352667c32a98SDimitry Andric       continue;
352767c32a98SDimitry Andric     }
3528009b1c42SEd Schouten 
3529009b1c42SEd Schouten     if (Val->getDef()->isSubClassOf("RegisterClass") ||
35304a16efa3SDimitry Andric         Val->getDef()->isSubClassOf("ValueType") ||
3531411bd29eSDimitry Andric         Val->getDef()->isSubClassOf("RegisterOperand") ||
353259850d08SRoman Divacky         Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
3533009b1c42SEd Schouten       if (Dest->getName().empty())
3534eb11fae6SDimitry Andric         I.error("set destination must have a name!");
3535009b1c42SEd Schouten       if (InstResults.count(Dest->getName()))
3536eb11fae6SDimitry Andric         I.error("cannot set '" + Dest->getName() + "' multiple times");
3537009b1c42SEd Schouten       InstResults[Dest->getName()] = Dest;
3538009b1c42SEd Schouten     } else if (Val->getDef()->isSubClassOf("Register")) {
3539009b1c42SEd Schouten       InstImpResults.push_back(Val->getDef());
3540009b1c42SEd Schouten     } else {
3541eb11fae6SDimitry Andric       I.error("set destination should be a register!");
3542009b1c42SEd Schouten     }
3543009b1c42SEd Schouten   }
3544009b1c42SEd Schouten 
3545009b1c42SEd Schouten   // Verify and collect info from the computation.
3546eb11fae6SDimitry Andric   FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3547eb11fae6SDimitry Andric                               InstResults, InstImpResults);
3548009b1c42SEd Schouten }
3549009b1c42SEd Schouten 
3550009b1c42SEd Schouten //===----------------------------------------------------------------------===//
3551009b1c42SEd Schouten // Instruction Analysis
3552009b1c42SEd Schouten //===----------------------------------------------------------------------===//
3553009b1c42SEd Schouten 
3554009b1c42SEd Schouten class InstAnalyzer {
3555009b1c42SEd Schouten   const CodeGenDAGPatterns &CDP;
3556ac9a064cSDimitry Andric 
3557009b1c42SEd Schouten public:
3558522600a2SDimitry Andric   bool hasSideEffects;
3559522600a2SDimitry Andric   bool mayStore;
3560522600a2SDimitry Andric   bool mayLoad;
3561522600a2SDimitry Andric   bool isBitcast;
3562522600a2SDimitry Andric   bool isVariadic;
3563eb11fae6SDimitry Andric   bool hasChain;
3564522600a2SDimitry Andric 
InstAnalyzer(const CodeGenDAGPatterns & cdp)3565522600a2SDimitry Andric   InstAnalyzer(const CodeGenDAGPatterns &cdp)
3566522600a2SDimitry Andric       : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
3567eb11fae6SDimitry Andric         isBitcast(false), isVariadic(false), hasChain(false) {}
3568009b1c42SEd Schouten 
Analyze(const PatternToMatch & Pat)356908bbd35aSDimitry Andric   void Analyze(const PatternToMatch &Pat) {
3570ac9a064cSDimitry Andric     const TreePatternNode &N = Pat.getSrcPattern();
3571eb11fae6SDimitry Andric     AnalyzeNode(N);
3572eb11fae6SDimitry Andric     // These properties are detected only on the root node.
3573eb11fae6SDimitry Andric     isBitcast = IsNodeBitcast(N);
3574009b1c42SEd Schouten   }
3575009b1c42SEd Schouten 
3576009b1c42SEd Schouten private:
IsNodeBitcast(const TreePatternNode & N) const3577ac9a064cSDimitry Andric   bool IsNodeBitcast(const TreePatternNode &N) const {
3578522600a2SDimitry Andric     if (hasSideEffects || mayLoad || mayStore || isVariadic)
35796b943ff3SDimitry Andric       return false;
35806b943ff3SDimitry Andric 
3581ac9a064cSDimitry Andric     if (N.isLeaf())
3582eb11fae6SDimitry Andric       return false;
3583ac9a064cSDimitry Andric     if (N.getNumChildren() != 1 || !N.getChild(0).isLeaf())
35846b943ff3SDimitry Andric       return false;
35856b943ff3SDimitry Andric 
3586ac9a064cSDimitry Andric     if (N.getOperator()->isSubClassOf("ComplexPattern"))
3587344a3780SDimitry Andric       return false;
3588344a3780SDimitry Andric 
3589ac9a064cSDimitry Andric     const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N.getOperator());
35906b943ff3SDimitry Andric     if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
35916b943ff3SDimitry Andric       return false;
35926b943ff3SDimitry Andric     return OpInfo.getEnumName() == "ISD::BITCAST";
35936b943ff3SDimitry Andric   }
35946b943ff3SDimitry Andric 
3595522600a2SDimitry Andric public:
AnalyzeNode(const TreePatternNode & N)3596ac9a064cSDimitry Andric   void AnalyzeNode(const TreePatternNode &N) {
3597ac9a064cSDimitry Andric     if (N.isLeaf()) {
3598ac9a064cSDimitry Andric       if (DefInit *DI = dyn_cast<DefInit>(N.getLeafValue())) {
3599009b1c42SEd Schouten         Record *LeafRec = DI->getDef();
3600009b1c42SEd Schouten         // Handle ComplexPattern leaves.
3601009b1c42SEd Schouten         if (LeafRec->isSubClassOf("ComplexPattern")) {
3602009b1c42SEd Schouten           const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3603ac9a064cSDimitry Andric           if (CP.hasProperty(SDNPMayStore))
3604ac9a064cSDimitry Andric             mayStore = true;
3605ac9a064cSDimitry Andric           if (CP.hasProperty(SDNPMayLoad))
3606ac9a064cSDimitry Andric             mayLoad = true;
3607ac9a064cSDimitry Andric           if (CP.hasProperty(SDNPSideEffect))
3608ac9a064cSDimitry Andric             hasSideEffects = true;
3609009b1c42SEd Schouten         }
3610009b1c42SEd Schouten       }
3611009b1c42SEd Schouten       return;
3612009b1c42SEd Schouten     }
3613009b1c42SEd Schouten 
3614009b1c42SEd Schouten     // Analyze children.
3615ac9a064cSDimitry Andric     for (unsigned i = 0, e = N.getNumChildren(); i != e; ++i)
3616ac9a064cSDimitry Andric       AnalyzeNode(N.getChild(i));
3617009b1c42SEd Schouten 
3618009b1c42SEd Schouten     // Notice properties of the node.
3619ac9a064cSDimitry Andric     if (N.NodeHasProperty(SDNPMayStore, CDP))
3620ac9a064cSDimitry Andric       mayStore = true;
3621ac9a064cSDimitry Andric     if (N.NodeHasProperty(SDNPMayLoad, CDP))
3622ac9a064cSDimitry Andric       mayLoad = true;
3623ac9a064cSDimitry Andric     if (N.NodeHasProperty(SDNPSideEffect, CDP))
3624ac9a064cSDimitry Andric       hasSideEffects = true;
3625ac9a064cSDimitry Andric     if (N.NodeHasProperty(SDNPVariadic, CDP))
3626ac9a064cSDimitry Andric       isVariadic = true;
3627ac9a064cSDimitry Andric     if (N.NodeHasProperty(SDNPHasChain, CDP))
3628ac9a064cSDimitry Andric       hasChain = true;
3629009b1c42SEd Schouten 
3630ac9a064cSDimitry Andric     if (const CodeGenIntrinsic *IntInfo = N.getIntrinsicInfo(CDP)) {
3631e3b55780SDimitry Andric       ModRefInfo MR = IntInfo->ME.getModRef();
3632009b1c42SEd Schouten       // If this is an intrinsic, analyze it.
3633e3b55780SDimitry Andric       if (isRefSet(MR))
3634009b1c42SEd Schouten         mayLoad = true; // These may load memory.
3635009b1c42SEd Schouten 
3636e3b55780SDimitry Andric       if (isModSet(MR))
3637009b1c42SEd Schouten         mayStore = true; // Intrinsics that can write to memory are 'mayStore'.
3638009b1c42SEd Schouten 
3639e3b55780SDimitry Andric       // Consider intrinsics that don't specify any restrictions on memory
3640e3b55780SDimitry Andric       // effects as having a side-effect.
3641e3b55780SDimitry Andric       if (IntInfo->ME == MemoryEffects::unknown() || IntInfo->hasSideEffects)
3642522600a2SDimitry Andric         hasSideEffects = true;
3643009b1c42SEd Schouten     }
3644009b1c42SEd Schouten   }
3645009b1c42SEd Schouten };
3646009b1c42SEd Schouten 
InferFromPattern(CodeGenInstruction & InstInfo,const InstAnalyzer & PatInfo,Record * PatDef)3647522600a2SDimitry Andric static bool InferFromPattern(CodeGenInstruction &InstInfo,
3648ac9a064cSDimitry Andric                              const InstAnalyzer &PatInfo, Record *PatDef) {
3649522600a2SDimitry Andric   bool Error = false;
3650009b1c42SEd Schouten 
3651522600a2SDimitry Andric   // Remember where InstInfo got its flags.
3652522600a2SDimitry Andric   if (InstInfo.hasUndefFlags())
3653522600a2SDimitry Andric     InstInfo.InferredFrom = PatDef;
3654009b1c42SEd Schouten 
3655522600a2SDimitry Andric   // Check explicitly set flags for consistency.
3656522600a2SDimitry Andric   if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3657522600a2SDimitry Andric       !InstInfo.hasSideEffects_Unset) {
3658522600a2SDimitry Andric     // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3659522600a2SDimitry Andric     // the pattern has no side effects. That could be useful for div/rem
3660522600a2SDimitry Andric     // instructions that may trap.
3661522600a2SDimitry Andric     if (!InstInfo.hasSideEffects) {
3662522600a2SDimitry Andric       Error = true;
3663522600a2SDimitry Andric       PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3664522600a2SDimitry Andric                                        Twine(InstInfo.hasSideEffects));
3665522600a2SDimitry Andric     }
3666009b1c42SEd Schouten   }
3667009b1c42SEd Schouten 
3668522600a2SDimitry Andric   if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3669522600a2SDimitry Andric     Error = true;
3670ac9a064cSDimitry Andric     PrintError(PatDef->getLoc(),
3671ac9a064cSDimitry Andric                "Pattern doesn't match mayStore = " + Twine(InstInfo.mayStore));
3672009b1c42SEd Schouten   }
3673009b1c42SEd Schouten 
3674522600a2SDimitry Andric   if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3675522600a2SDimitry Andric     // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
3676dd58ef01SDimitry Andric     // Some targets translate immediates to loads.
3677522600a2SDimitry Andric     if (!InstInfo.mayLoad) {
3678522600a2SDimitry Andric       Error = true;
3679ac9a064cSDimitry Andric       PrintError(PatDef->getLoc(),
3680ac9a064cSDimitry Andric                  "Pattern doesn't match mayLoad = " + Twine(InstInfo.mayLoad));
3681522600a2SDimitry Andric     }
3682009b1c42SEd Schouten   }
3683009b1c42SEd Schouten 
3684522600a2SDimitry Andric   // Transfer inferred flags.
3685522600a2SDimitry Andric   InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3686522600a2SDimitry Andric   InstInfo.mayStore |= PatInfo.mayStore;
3687522600a2SDimitry Andric   InstInfo.mayLoad |= PatInfo.mayLoad;
36882f12f10aSRoman Divacky 
3689522600a2SDimitry Andric   // These flags are silently added without any verification.
3690eb11fae6SDimitry Andric   // FIXME: To match historical behavior of TableGen, for now add those flags
3691eb11fae6SDimitry Andric   // only when we're inferring from the primary instruction pattern.
3692eb11fae6SDimitry Andric   if (PatDef->isSubClassOf("Instruction")) {
3693522600a2SDimitry Andric     InstInfo.isBitcast |= PatInfo.isBitcast;
3694eb11fae6SDimitry Andric     InstInfo.hasChain |= PatInfo.hasChain;
3695eb11fae6SDimitry Andric     InstInfo.hasChain_Inferred = true;
3696eb11fae6SDimitry Andric   }
3697522600a2SDimitry Andric 
3698522600a2SDimitry Andric   // Don't infer isVariadic. This flag means something different on SDNodes and
3699522600a2SDimitry Andric   // instructions. For example, a CALL SDNode is variadic because it has the
3700522600a2SDimitry Andric   // call arguments as operands, but a CALL instruction is not variadic - it
3701522600a2SDimitry Andric   // has argument registers as implicit, not explicit uses.
3702522600a2SDimitry Andric 
3703522600a2SDimitry Andric   return Error;
3704009b1c42SEd Schouten }
3705009b1c42SEd Schouten 
370658b69754SDimitry Andric /// hasNullFragReference - Return true if the DAG has any reference to the
370758b69754SDimitry Andric /// null_frag operator.
hasNullFragReference(DagInit * DI)370858b69754SDimitry Andric static bool hasNullFragReference(DagInit *DI) {
3709522600a2SDimitry Andric   DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
3710ac9a064cSDimitry Andric   if (!OpDef)
3711ac9a064cSDimitry Andric     return false;
371258b69754SDimitry Andric   Record *Operator = OpDef->getDef();
371358b69754SDimitry Andric 
371458b69754SDimitry Andric   // If this is the null fragment, return true.
3715ac9a064cSDimitry Andric   if (Operator->getName() == "null_frag")
3716ac9a064cSDimitry Andric     return true;
371758b69754SDimitry Andric   // If any of the arguments reference the null fragment, return true.
371858b69754SDimitry Andric   for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
3719b60736ecSDimitry Andric     if (auto Arg = dyn_cast<DefInit>(DI->getArg(i)))
3720b60736ecSDimitry Andric       if (Arg->getDef()->getName() == "null_frag")
3721b60736ecSDimitry Andric         return true;
3722522600a2SDimitry Andric     DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
372358b69754SDimitry Andric     if (Arg && hasNullFragReference(Arg))
372458b69754SDimitry Andric       return true;
372558b69754SDimitry Andric   }
372658b69754SDimitry Andric 
372758b69754SDimitry Andric   return false;
372858b69754SDimitry Andric }
372958b69754SDimitry Andric 
373058b69754SDimitry Andric /// hasNullFragReference - Return true if any DAG in the list references
373158b69754SDimitry Andric /// the null_frag operator.
hasNullFragReference(ListInit * LI)373258b69754SDimitry Andric static bool hasNullFragReference(ListInit *LI) {
373385d8b2bbSDimitry Andric   for (Init *I : LI->getValues()) {
373485d8b2bbSDimitry Andric     DagInit *DI = dyn_cast<DagInit>(I);
373558b69754SDimitry Andric     assert(DI && "non-dag in an instruction Pattern list?!");
373658b69754SDimitry Andric     if (hasNullFragReference(DI))
373758b69754SDimitry Andric       return true;
373858b69754SDimitry Andric   }
373958b69754SDimitry Andric   return false;
374058b69754SDimitry Andric }
374158b69754SDimitry Andric 
3742522600a2SDimitry Andric /// Get all the instructions in a tree.
getInstructionsInTree(TreePatternNode & Tree,SmallVectorImpl<Record * > & Instrs)3743ac9a064cSDimitry Andric static void getInstructionsInTree(TreePatternNode &Tree,
3744ac9a064cSDimitry Andric                                   SmallVectorImpl<Record *> &Instrs) {
3745ac9a064cSDimitry Andric   if (Tree.isLeaf())
3746522600a2SDimitry Andric     return;
3747ac9a064cSDimitry Andric   if (Tree.getOperator()->isSubClassOf("Instruction"))
3748ac9a064cSDimitry Andric     Instrs.push_back(Tree.getOperator());
3749ac9a064cSDimitry Andric   for (unsigned i = 0, e = Tree.getNumChildren(); i != e; ++i)
3750ac9a064cSDimitry Andric     getInstructionsInTree(Tree.getChild(i), Instrs);
3751522600a2SDimitry Andric }
3752522600a2SDimitry Andric 
37534a16efa3SDimitry Andric /// Check the class of a pattern leaf node against the instruction operand it
37544a16efa3SDimitry Andric /// represents.
checkOperandClass(CGIOperandList::OperandInfo & OI,Record * Leaf)3755ac9a064cSDimitry Andric static bool checkOperandClass(CGIOperandList::OperandInfo &OI, Record *Leaf) {
37564a16efa3SDimitry Andric   if (OI.Rec == Leaf)
37574a16efa3SDimitry Andric     return true;
37584a16efa3SDimitry Andric 
37594a16efa3SDimitry Andric   // Allow direct value types to be used in instruction set patterns.
37604a16efa3SDimitry Andric   // The type will be checked later.
37614a16efa3SDimitry Andric   if (Leaf->isSubClassOf("ValueType"))
37624a16efa3SDimitry Andric     return true;
37634a16efa3SDimitry Andric 
37644a16efa3SDimitry Andric   // Patterns can also be ComplexPattern instances.
37654a16efa3SDimitry Andric   if (Leaf->isSubClassOf("ComplexPattern"))
37664a16efa3SDimitry Andric     return true;
37674a16efa3SDimitry Andric 
37684a16efa3SDimitry Andric   return false;
37694a16efa3SDimitry Andric }
37704a16efa3SDimitry Andric 
parseInstructionPattern(CodeGenInstruction & CGI,ListInit * Pat,DAGInstMap & DAGInsts)3771ac9a064cSDimitry Andric void CodeGenDAGPatterns::parseInstructionPattern(CodeGenInstruction &CGI,
3772ac9a064cSDimitry Andric                                                  ListInit *Pat,
3773ac9a064cSDimitry Andric                                                  DAGInstMap &DAGInsts) {
3774009b1c42SEd Schouten 
3775f8af5cf6SDimitry Andric   assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
3776009b1c42SEd Schouten 
3777009b1c42SEd Schouten   // Parse the instruction.
3778eb11fae6SDimitry Andric   TreePattern I(CGI.TheDef, Pat, true, *this);
3779009b1c42SEd Schouten 
3780009b1c42SEd Schouten   // InstInputs - Keep track of all of the inputs of the instruction, along
3781009b1c42SEd Schouten   // with the record they are declared as.
3782eb11fae6SDimitry Andric   std::map<std::string, TreePatternNodePtr> InstInputs;
3783009b1c42SEd Schouten 
3784009b1c42SEd Schouten   // InstResults - Keep track of all the virtual registers that are 'set'
3785009b1c42SEd Schouten   // in the instruction, including what reg class they are.
3786d8e91e46SDimitry Andric   MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3787d8e91e46SDimitry Andric       InstResults;
3788009b1c42SEd Schouten 
3789009b1c42SEd Schouten   std::vector<Record *> InstImpResults;
3790009b1c42SEd Schouten 
3791009b1c42SEd Schouten   // Verify that the top-level forms in the instruction are of void type, and
3792009b1c42SEd Schouten   // fill in the InstResults map.
3793044eb2f6SDimitry Andric   SmallString<32> TypesString;
3794eb11fae6SDimitry Andric   for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
3795044eb2f6SDimitry Andric     TypesString.clear();
3796eb11fae6SDimitry Andric     TreePatternNodePtr Pat = I.getTree(j);
379701095a5dSDimitry Andric     if (Pat->getNumTypes() != 0) {
3798044eb2f6SDimitry Andric       raw_svector_ostream OS(TypesString);
3799344a3780SDimitry Andric       ListSeparator LS;
380001095a5dSDimitry Andric       for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3801344a3780SDimitry Andric         OS << LS;
3802044eb2f6SDimitry Andric         Pat->getExtType(k).writeToStream(OS);
380301095a5dSDimitry Andric       }
3804eb11fae6SDimitry Andric       I.error("Top-level forms in instruction pattern should have"
3805044eb2f6SDimitry Andric               " void types, has types " +
3806044eb2f6SDimitry Andric               OS.str());
380701095a5dSDimitry Andric     }
3808009b1c42SEd Schouten 
3809009b1c42SEd Schouten     // Find inputs and outputs, and verify the structure of the uses/defs.
3810009b1c42SEd Schouten     FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3811d7f7719eSRoman Divacky                                 InstImpResults);
3812009b1c42SEd Schouten   }
3813009b1c42SEd Schouten 
3814009b1c42SEd Schouten   // Now that we have inputs and outputs of the pattern, inspect the operands
3815009b1c42SEd Schouten   // list for the instruction.  This determines the order that operands are
3816009b1c42SEd Schouten   // added to the machine instruction the node corresponds to.
3817009b1c42SEd Schouten   unsigned NumResults = InstResults.size();
3818009b1c42SEd Schouten 
3819009b1c42SEd Schouten   // Parse the operands list from the (ops) list, validating it.
3820eb11fae6SDimitry Andric   assert(I.getArgList().empty() && "Args list should still be empty here!");
3821009b1c42SEd Schouten 
3822009b1c42SEd Schouten   // Check that all of the results occur first in the list.
3823009b1c42SEd Schouten   std::vector<Record *> Results;
3824d8e91e46SDimitry Andric   std::vector<unsigned> ResultIndices;
3825eb11fae6SDimitry Andric   SmallVector<TreePatternNodePtr, 2> ResNodes;
3826009b1c42SEd Schouten   for (unsigned i = 0; i != NumResults; ++i) {
3827d8e91e46SDimitry Andric     if (i == CGI.Operands.size()) {
3828d8e91e46SDimitry Andric       const std::string &OpName =
3829b60736ecSDimitry Andric           llvm::find_if(
3830b60736ecSDimitry Andric               InstResults,
3831d8e91e46SDimitry Andric               [](const std::pair<std::string, TreePatternNodePtr> &P) {
3832d8e91e46SDimitry Andric                 return P.second;
3833d8e91e46SDimitry Andric               })
3834d8e91e46SDimitry Andric               ->first;
3835d8e91e46SDimitry Andric 
3836d8e91e46SDimitry Andric       I.error("'" + OpName + "' set but does not appear in operand list!");
3837d8e91e46SDimitry Andric     }
3838d8e91e46SDimitry Andric 
3839cf099d11SDimitry Andric     const std::string &OpName = CGI.Operands[i].Name;
3840009b1c42SEd Schouten 
3841009b1c42SEd Schouten     // Check that it exists in InstResults.
3842d8e91e46SDimitry Andric     auto InstResultIter = InstResults.find(OpName);
3843d8e91e46SDimitry Andric     if (InstResultIter == InstResults.end() || !InstResultIter->second)
3844eb11fae6SDimitry Andric       I.error("Operand $" + OpName + " does not exist in operand list!");
3845009b1c42SEd Schouten 
3846d8e91e46SDimitry Andric     TreePatternNodePtr RNode = InstResultIter->second;
3847522600a2SDimitry Andric     Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
3848eb11fae6SDimitry Andric     ResNodes.push_back(std::move(RNode));
38495ca98fd9SDimitry Andric     if (!R)
3850ac9a064cSDimitry Andric       I.error("Operand $" + OpName +
3851ac9a064cSDimitry Andric               " should be a set destination: all "
3852009b1c42SEd Schouten               "outputs must occur before inputs in operand list!");
3853009b1c42SEd Schouten 
38544a16efa3SDimitry Andric     if (!checkOperandClass(CGI.Operands[i], R))
3855eb11fae6SDimitry Andric       I.error("Operand $" + OpName + " class mismatch!");
3856009b1c42SEd Schouten 
3857009b1c42SEd Schouten     // Remember the return type.
3858cf099d11SDimitry Andric     Results.push_back(CGI.Operands[i].Rec);
3859009b1c42SEd Schouten 
3860d8e91e46SDimitry Andric     // Remember the result index.
3861d8e91e46SDimitry Andric     ResultIndices.push_back(std::distance(InstResults.begin(), InstResultIter));
3862d8e91e46SDimitry Andric 
3863009b1c42SEd Schouten     // Okay, this one checks out.
3864d8e91e46SDimitry Andric     InstResultIter->second = nullptr;
3865009b1c42SEd Schouten   }
3866009b1c42SEd Schouten 
3867eb11fae6SDimitry Andric   // Loop over the inputs next.
3868eb11fae6SDimitry Andric   std::vector<TreePatternNodePtr> ResultNodeOperands;
3869009b1c42SEd Schouten   std::vector<Record *> Operands;
3870cf099d11SDimitry Andric   for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3871cf099d11SDimitry Andric     CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3872009b1c42SEd Schouten     const std::string &OpName = Op.Name;
3873ac9a064cSDimitry Andric     if (OpName.empty()) {
3874eb11fae6SDimitry Andric       I.error("Operand #" + Twine(i) + " in operands list has no name!");
3875ac9a064cSDimitry Andric       continue;
3876ac9a064cSDimitry Andric     }
3877009b1c42SEd Schouten 
3878eb11fae6SDimitry Andric     if (!InstInputs.count(OpName)) {
3879522600a2SDimitry Andric       // If this is an operand with a DefaultOps set filled in, we can ignore
3880522600a2SDimitry Andric       // this.  When we codegen it, we will do so as always executed.
3881522600a2SDimitry Andric       if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3882009b1c42SEd Schouten         // Does it have a non-empty DefaultOps field?  If so, ignore this
3883009b1c42SEd Schouten         // operand.
3884009b1c42SEd Schouten         if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3885009b1c42SEd Schouten           continue;
3886009b1c42SEd Schouten       }
3887eb11fae6SDimitry Andric       I.error("Operand $" + OpName +
3888009b1c42SEd Schouten               " does not appear in the instruction pattern");
3889ac9a064cSDimitry Andric       continue;
3890009b1c42SEd Schouten     }
3891eb11fae6SDimitry Andric     TreePatternNodePtr InVal = InstInputs[OpName];
3892eb11fae6SDimitry Andric     InstInputs.erase(OpName); // It occurred, remove from map.
3893009b1c42SEd Schouten 
3894522600a2SDimitry Andric     if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3895c0981da4SDimitry Andric       Record *InRec = cast<DefInit>(InVal->getLeafValue())->getDef();
3896ac9a064cSDimitry Andric       if (!checkOperandClass(Op, InRec)) {
3897ac9a064cSDimitry Andric         I.error("Operand $" + OpName +
3898ac9a064cSDimitry Andric                 "'s register class disagrees"
3899009b1c42SEd Schouten                 " between the operand and pattern");
3900ac9a064cSDimitry Andric         continue;
3901ac9a064cSDimitry Andric       }
3902009b1c42SEd Schouten     }
3903009b1c42SEd Schouten     Operands.push_back(Op.Rec);
3904009b1c42SEd Schouten 
3905009b1c42SEd Schouten     // Construct the result for the dest-pattern operand list.
3906eb11fae6SDimitry Andric     TreePatternNodePtr OpNode = InVal->clone();
3907009b1c42SEd Schouten 
3908009b1c42SEd Schouten     // No predicate is useful on the result.
3909d8e91e46SDimitry Andric     OpNode->clearPredicateCalls();
3910009b1c42SEd Schouten 
3911009b1c42SEd Schouten     // Promote the xform function to be an explicit node if set.
3912009b1c42SEd Schouten     if (Record *Xform = OpNode->getTransformFn()) {
39135ca98fd9SDimitry Andric       OpNode->setTransformFn(nullptr);
3914eb11fae6SDimitry Andric       std::vector<TreePatternNodePtr> Children;
3915009b1c42SEd Schouten       Children.push_back(OpNode);
39167fa27ce4SDimitry Andric       OpNode = makeIntrusiveRefCnt<TreePatternNode>(Xform, std::move(Children),
3917eb11fae6SDimitry Andric                                                     OpNode->getNumTypes());
3918009b1c42SEd Schouten     }
3919009b1c42SEd Schouten 
3920eb11fae6SDimitry Andric     ResultNodeOperands.push_back(std::move(OpNode));
3921009b1c42SEd Schouten   }
3922009b1c42SEd Schouten 
3923eb11fae6SDimitry Andric   if (!InstInputs.empty())
3924eb11fae6SDimitry Andric     I.error("Input operand $" + InstInputs.begin()->first +
3925009b1c42SEd Schouten             " occurs in pattern but not in operands list!");
3926009b1c42SEd Schouten 
39277fa27ce4SDimitry Andric   TreePatternNodePtr ResultPattern = makeIntrusiveRefCnt<TreePatternNode>(
3928eb11fae6SDimitry Andric       I.getRecord(), std::move(ResultNodeOperands),
3929eb11fae6SDimitry Andric       GetNumNodeResults(I.getRecord(), *this));
39305a5ac124SDimitry Andric   // Copy fully inferred output node types to instruction result pattern.
39315a5ac124SDimitry Andric   for (unsigned i = 0; i != NumResults; ++i) {
39325a5ac124SDimitry Andric     assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
39335a5ac124SDimitry Andric     ResultPattern->setType(i, ResNodes[i]->getExtType(0));
3934d8e91e46SDimitry Andric     ResultPattern->setResultIndex(i, ResultIndices[i]);
39355a5ac124SDimitry Andric   }
3936009b1c42SEd Schouten 
3937eb11fae6SDimitry Andric   // FIXME: Assume only the first tree is the pattern. The others are clobber
3938eb11fae6SDimitry Andric   // nodes.
3939eb11fae6SDimitry Andric   TreePatternNodePtr Pattern = I.getTree(0);
3940eb11fae6SDimitry Andric   TreePatternNodePtr SrcPattern;
3941eb11fae6SDimitry Andric   if (Pattern->getOperator()->getName() == "set") {
3942ac9a064cSDimitry Andric     SrcPattern = Pattern->getChild(Pattern->getNumChildren() - 1).clone();
3943eb11fae6SDimitry Andric   } else {
3944eb11fae6SDimitry Andric     // Not a set (store or something?)
3945eb11fae6SDimitry Andric     SrcPattern = Pattern;
3946eb11fae6SDimitry Andric   }
3947eb11fae6SDimitry Andric 
3948009b1c42SEd Schouten   // Create and insert the instruction.
3949d7f7719eSRoman Divacky   // FIXME: InstImpResults should not be part of DAGInstruction.
3950eb11fae6SDimitry Andric   Record *R = I.getRecord();
39517fa27ce4SDimitry Andric   DAGInsts.try_emplace(R, std::move(Results), std::move(Operands),
39527fa27ce4SDimitry Andric                        std::move(InstImpResults), SrcPattern, ResultPattern);
3953009b1c42SEd Schouten 
3954eb11fae6SDimitry Andric   LLVM_DEBUG(I.dump());
3955f8af5cf6SDimitry Andric }
3956f8af5cf6SDimitry Andric 
3957f8af5cf6SDimitry Andric /// ParseInstructions - Parse all of the instructions, inlining and resolving
3958f8af5cf6SDimitry Andric /// any fragments involved.  This populates the Instructions list with fully
3959f8af5cf6SDimitry Andric /// resolved instructions.
ParseInstructions()3960f8af5cf6SDimitry Andric void CodeGenDAGPatterns::ParseInstructions() {
3961ac9a064cSDimitry Andric   std::vector<Record *> Instrs =
3962ac9a064cSDimitry Andric       Records.getAllDerivedDefinitions("Instruction");
3963f8af5cf6SDimitry Andric 
3964dd58ef01SDimitry Andric   for (Record *Instr : Instrs) {
39655ca98fd9SDimitry Andric     ListInit *LI = nullptr;
3966f8af5cf6SDimitry Andric 
3967dd58ef01SDimitry Andric     if (isa<ListInit>(Instr->getValueInit("Pattern")))
3968dd58ef01SDimitry Andric       LI = Instr->getValueAsListInit("Pattern");
3969f8af5cf6SDimitry Andric 
3970f8af5cf6SDimitry Andric     // If there is no pattern, only collect minimal information about the
3971f8af5cf6SDimitry Andric     // instruction for its operand list.  We have to assume that there is one
3972f8af5cf6SDimitry Andric     // result, as we have no detailed info. A pattern which references the
3973f8af5cf6SDimitry Andric     // null_frag operator is as-if no pattern were specified. Normally this
3974f8af5cf6SDimitry Andric     // is from a multiclass expansion w/ a SDPatternOperator passed in as
3975f8af5cf6SDimitry Andric     // null_frag.
39765a5ac124SDimitry Andric     if (!LI || LI->empty() || hasNullFragReference(LI)) {
3977f8af5cf6SDimitry Andric       std::vector<Record *> Results;
3978f8af5cf6SDimitry Andric       std::vector<Record *> Operands;
3979f8af5cf6SDimitry Andric 
3980dd58ef01SDimitry Andric       CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
3981f8af5cf6SDimitry Andric 
3982f8af5cf6SDimitry Andric       if (InstInfo.Operands.size() != 0) {
39835a5ac124SDimitry Andric         for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
39845a5ac124SDimitry Andric           Results.push_back(InstInfo.Operands[j].Rec);
3985f8af5cf6SDimitry Andric 
3986f8af5cf6SDimitry Andric         // The rest are inputs.
39875a5ac124SDimitry Andric         for (unsigned j = InstInfo.Operands.NumDefs,
3988ac9a064cSDimitry Andric                       e = InstInfo.Operands.size();
3989ac9a064cSDimitry Andric              j < e; ++j)
3990f8af5cf6SDimitry Andric           Operands.push_back(InstInfo.Operands[j].Rec);
3991f8af5cf6SDimitry Andric       }
3992f8af5cf6SDimitry Andric 
3993f8af5cf6SDimitry Andric       // Create and insert the instruction.
39947fa27ce4SDimitry Andric       Instructions.try_emplace(Instr, std::move(Results), std::move(Operands),
39957fa27ce4SDimitry Andric                                std::vector<Record *>());
3996f8af5cf6SDimitry Andric       continue; // no pattern.
3997f8af5cf6SDimitry Andric     }
3998f8af5cf6SDimitry Andric 
3999dd58ef01SDimitry Andric     CodeGenInstruction &CGI = Target.getInstruction(Instr);
4000eb11fae6SDimitry Andric     parseInstructionPattern(CGI, LI, Instructions);
4001009b1c42SEd Schouten   }
4002009b1c42SEd Schouten 
4003009b1c42SEd Schouten   // If we can, convert the instructions to be patterns that are matched!
4004dd58ef01SDimitry Andric   for (auto &Entry : Instructions) {
4005dd58ef01SDimitry Andric     Record *Instr = Entry.first;
4006eb11fae6SDimitry Andric     DAGInstruction &TheInst = Entry.second;
4007eb11fae6SDimitry Andric     TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
4008eb11fae6SDimitry Andric     TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
4009eb11fae6SDimitry Andric 
4010eb11fae6SDimitry Andric     if (SrcPattern && ResultPattern) {
4011eb11fae6SDimitry Andric       TreePattern Pattern(Instr, SrcPattern, true, *this);
4012eb11fae6SDimitry Andric       TreePattern Result(Instr, ResultPattern, false, *this);
4013eb11fae6SDimitry Andric       ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
4014eb11fae6SDimitry Andric     }
4015009b1c42SEd Schouten   }
4016009b1c42SEd Schouten }
4017009b1c42SEd Schouten 
4018eb11fae6SDimitry Andric typedef std::pair<TreePatternNode *, unsigned> NameRecord;
4019009b1c42SEd Schouten 
FindNames(TreePatternNode & P,std::map<std::string,NameRecord> & Names,TreePattern * PatternTop)4020ac9a064cSDimitry Andric static void FindNames(TreePatternNode &P,
402167a71b31SRoman Divacky                       std::map<std::string, NameRecord> &Names,
4022522600a2SDimitry Andric                       TreePattern *PatternTop) {
4023ac9a064cSDimitry Andric   if (!P.getName().empty()) {
4024ac9a064cSDimitry Andric     NameRecord &Rec = Names[P.getName()];
402567a71b31SRoman Divacky     // If this is the first instance of the name, remember the node.
402667a71b31SRoman Divacky     if (Rec.second++ == 0)
4027ac9a064cSDimitry Andric       Rec.first = &P;
4028ac9a064cSDimitry Andric     else if (Rec.first->getExtTypes() != P.getExtTypes())
4029ac9a064cSDimitry Andric       PatternTop->error("repetition of value: $" + P.getName() +
403067a71b31SRoman Divacky                         " where different uses have different types!");
403167a71b31SRoman Divacky   }
403267a71b31SRoman Divacky 
4033ac9a064cSDimitry Andric   if (!P.isLeaf()) {
4034ac9a064cSDimitry Andric     for (unsigned i = 0, e = P.getNumChildren(); i != e; ++i)
4035ac9a064cSDimitry Andric       FindNames(P.getChild(i), Names, PatternTop);
403667a71b31SRoman Divacky   }
403767a71b31SRoman Divacky }
403867a71b31SRoman Divacky 
AddPatternToMatch(TreePattern * Pattern,PatternToMatch && PTM)4039522600a2SDimitry Andric void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
404008bbd35aSDimitry Andric                                            PatternToMatch &&PTM) {
404167a71b31SRoman Divacky   // Do some sanity checking on the pattern we're about to match.
404267a71b31SRoman Divacky   std::string Reason;
4043ac9a064cSDimitry Andric   if (!PTM.getSrcPattern().canPatternMatch(Reason, *this)) {
4044522600a2SDimitry Andric     PrintWarning(Pattern->getRecord()->getLoc(),
4045522600a2SDimitry Andric                  Twine("Pattern can never match: ") + Reason);
4046522600a2SDimitry Andric     return;
4047522600a2SDimitry Andric   }
404867a71b31SRoman Divacky 
404967a71b31SRoman Divacky   // If the source pattern's root is a complex pattern, that complex pattern
405067a71b31SRoman Divacky   // must specify the nodes it can potentially match.
405167a71b31SRoman Divacky   if (const ComplexPattern *CP =
4052ac9a064cSDimitry Andric           PTM.getSrcPattern().getComplexPatternInfo(*this))
405367a71b31SRoman Divacky     if (CP->getRootNodes().empty())
405467a71b31SRoman Divacky       Pattern->error("ComplexPattern at root must specify list of opcodes it"
405567a71b31SRoman Divacky                      " could match");
405667a71b31SRoman Divacky 
405767a71b31SRoman Divacky   // Find all of the named values in the input and output, ensure they have the
405867a71b31SRoman Divacky   // same type.
405967a71b31SRoman Divacky   std::map<std::string, NameRecord> SrcNames, DstNames;
406067a71b31SRoman Divacky   FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
406167a71b31SRoman Divacky   FindNames(PTM.getDstPattern(), DstNames, Pattern);
406267a71b31SRoman Divacky 
406367a71b31SRoman Divacky   // Scan all of the named values in the destination pattern, rejecting them if
406467a71b31SRoman Divacky   // they don't exist in the input pattern.
4065dd58ef01SDimitry Andric   for (const auto &Entry : DstNames) {
4066dd58ef01SDimitry Andric     if (SrcNames[Entry.first].first == nullptr)
406767a71b31SRoman Divacky       Pattern->error("Pattern has input without matching name in output: $" +
4068dd58ef01SDimitry Andric                      Entry.first);
406967a71b31SRoman Divacky   }
407067a71b31SRoman Divacky 
407167a71b31SRoman Divacky   // Scan all of the named values in the source pattern, rejecting them if the
407267a71b31SRoman Divacky   // name isn't used in the dest, and isn't used to tie two values together.
4073dd58ef01SDimitry Andric   for (const auto &Entry : SrcNames)
4074dd58ef01SDimitry Andric     if (DstNames[Entry.first].first == nullptr &&
4075dd58ef01SDimitry Andric         SrcNames[Entry.first].second == 1)
4076dd58ef01SDimitry Andric       Pattern->error("Pattern has dead named input: $" + Entry.first);
407767a71b31SRoman Divacky 
4078344a3780SDimitry Andric   PatternsToMatch.push_back(std::move(PTM));
407967a71b31SRoman Divacky }
408067a71b31SRoman Divacky 
InferInstructionFlags()4081009b1c42SEd Schouten void CodeGenDAGPatterns::InferInstructionFlags() {
408201095a5dSDimitry Andric   ArrayRef<const CodeGenInstruction *> Instructions =
40832f12f10aSRoman Divacky       Target.getInstructionsByEnumValue();
4084522600a2SDimitry Andric 
4085522600a2SDimitry Andric   unsigned Errors = 0;
408630815c53SDimitry Andric 
4087eb11fae6SDimitry Andric   // Try to infer flags from all patterns in PatternToMatch.  These include
4088eb11fae6SDimitry Andric   // both the primary instruction patterns (which always come first) and
4089eb11fae6SDimitry Andric   // patterns defined outside the instruction.
409008bbd35aSDimitry Andric   for (const PatternToMatch &PTM : ptms()) {
4091522600a2SDimitry Andric     // We can only infer from single-instruction patterns, otherwise we won't
4092522600a2SDimitry Andric     // know which instruction should get the flags.
4093522600a2SDimitry Andric     SmallVector<Record *, 8> PatInstrs;
4094522600a2SDimitry Andric     getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
4095522600a2SDimitry Andric     if (PatInstrs.size() != 1)
4096522600a2SDimitry Andric       continue;
4097522600a2SDimitry Andric 
4098522600a2SDimitry Andric     // Get the single instruction.
4099522600a2SDimitry Andric     CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
4100522600a2SDimitry Andric 
4101522600a2SDimitry Andric     // Only infer properties from the first pattern. We'll verify the others.
4102522600a2SDimitry Andric     if (InstInfo.InferredFrom)
4103522600a2SDimitry Andric       continue;
4104522600a2SDimitry Andric 
4105522600a2SDimitry Andric     InstAnalyzer PatInfo(*this);
410608bbd35aSDimitry Andric     PatInfo.Analyze(PTM);
4107522600a2SDimitry Andric     Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
4108522600a2SDimitry Andric   }
4109522600a2SDimitry Andric 
4110522600a2SDimitry Andric   if (Errors)
4111522600a2SDimitry Andric     PrintFatalError("pattern conflicts");
4112522600a2SDimitry Andric 
4113eb11fae6SDimitry Andric   // If requested by the target, guess any undefined properties.
4114522600a2SDimitry Andric   if (Target.guessInstructionProperties()) {
4115eb11fae6SDimitry Andric     for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
4116eb11fae6SDimitry Andric       CodeGenInstruction *InstInfo =
4117eb11fae6SDimitry Andric           const_cast<CodeGenInstruction *>(Instructions[i]);
4118dd58ef01SDimitry Andric       if (InstInfo->InferredFrom)
4119522600a2SDimitry Andric         continue;
4120522600a2SDimitry Andric       // The mayLoad and mayStore flags default to false.
4121522600a2SDimitry Andric       // Conservatively assume hasSideEffects if it wasn't explicit.
4122dd58ef01SDimitry Andric       if (InstInfo->hasSideEffects_Unset)
4123dd58ef01SDimitry Andric         InstInfo->hasSideEffects = true;
4124522600a2SDimitry Andric     }
4125522600a2SDimitry Andric     return;
4126522600a2SDimitry Andric   }
4127522600a2SDimitry Andric 
4128522600a2SDimitry Andric   // Complain about any flags that are still undefined.
4129eb11fae6SDimitry Andric   for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
4130eb11fae6SDimitry Andric     CodeGenInstruction *InstInfo =
4131eb11fae6SDimitry Andric         const_cast<CodeGenInstruction *>(Instructions[i]);
4132dd58ef01SDimitry Andric     if (InstInfo->InferredFrom)
4133522600a2SDimitry Andric       continue;
4134dd58ef01SDimitry Andric     if (InstInfo->hasSideEffects_Unset)
4135dd58ef01SDimitry Andric       PrintError(InstInfo->TheDef->getLoc(),
4136522600a2SDimitry Andric                  "Can't infer hasSideEffects from patterns");
4137dd58ef01SDimitry Andric     if (InstInfo->mayStore_Unset)
4138dd58ef01SDimitry Andric       PrintError(InstInfo->TheDef->getLoc(),
4139522600a2SDimitry Andric                  "Can't infer mayStore from patterns");
4140dd58ef01SDimitry Andric     if (InstInfo->mayLoad_Unset)
4141dd58ef01SDimitry Andric       PrintError(InstInfo->TheDef->getLoc(),
4142522600a2SDimitry Andric                  "Can't infer mayLoad from patterns");
4143522600a2SDimitry Andric   }
4144522600a2SDimitry Andric }
4145522600a2SDimitry Andric 
4146522600a2SDimitry Andric /// Verify instruction flags against pattern node properties.
VerifyInstructionFlags()4147522600a2SDimitry Andric void CodeGenDAGPatterns::VerifyInstructionFlags() {
4148522600a2SDimitry Andric   unsigned Errors = 0;
4149344a3780SDimitry Andric   for (const PatternToMatch &PTM : ptms()) {
4150522600a2SDimitry Andric     SmallVector<Record *, 8> Instrs;
4151522600a2SDimitry Andric     getInstructionsInTree(PTM.getDstPattern(), Instrs);
4152522600a2SDimitry Andric     if (Instrs.empty())
4153522600a2SDimitry Andric       continue;
4154522600a2SDimitry Andric 
4155522600a2SDimitry Andric     // Count the number of instructions with each flag set.
4156522600a2SDimitry Andric     unsigned NumSideEffects = 0;
4157522600a2SDimitry Andric     unsigned NumStores = 0;
4158522600a2SDimitry Andric     unsigned NumLoads = 0;
4159dd58ef01SDimitry Andric     for (const Record *Instr : Instrs) {
4160dd58ef01SDimitry Andric       const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
4161522600a2SDimitry Andric       NumSideEffects += InstInfo.hasSideEffects;
4162522600a2SDimitry Andric       NumStores += InstInfo.mayStore;
4163522600a2SDimitry Andric       NumLoads += InstInfo.mayLoad;
4164522600a2SDimitry Andric     }
4165522600a2SDimitry Andric 
4166522600a2SDimitry Andric     // Analyze the source pattern.
4167522600a2SDimitry Andric     InstAnalyzer PatInfo(*this);
416808bbd35aSDimitry Andric     PatInfo.Analyze(PTM);
4169522600a2SDimitry Andric 
4170522600a2SDimitry Andric     // Collect error messages.
4171522600a2SDimitry Andric     SmallVector<std::string, 4> Msgs;
4172522600a2SDimitry Andric 
4173522600a2SDimitry Andric     // Check for missing flags in the output.
4174522600a2SDimitry Andric     // Permit extra flags for now at least.
4175522600a2SDimitry Andric     if (PatInfo.hasSideEffects && !NumSideEffects)
4176522600a2SDimitry Andric       Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
4177522600a2SDimitry Andric 
4178522600a2SDimitry Andric     // Don't verify store flags on instructions with side effects. At least for
4179522600a2SDimitry Andric     // intrinsics, side effects implies mayStore.
4180522600a2SDimitry Andric     if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
4181522600a2SDimitry Andric       Msgs.push_back("pattern may store, but mayStore isn't set");
4182522600a2SDimitry Andric 
4183522600a2SDimitry Andric     // Similarly, mayStore implies mayLoad on intrinsics.
4184522600a2SDimitry Andric     if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
4185522600a2SDimitry Andric       Msgs.push_back("pattern may load, but mayLoad isn't set");
4186522600a2SDimitry Andric 
4187522600a2SDimitry Andric     // Print error messages.
4188522600a2SDimitry Andric     if (Msgs.empty())
4189522600a2SDimitry Andric       continue;
4190522600a2SDimitry Andric     ++Errors;
4191522600a2SDimitry Andric 
4192dd58ef01SDimitry Andric     for (const std::string &Msg : Msgs)
4193ac9a064cSDimitry Andric       PrintError(
4194ac9a064cSDimitry Andric           PTM.getSrcRecord()->getLoc(),
4195ac9a064cSDimitry Andric           Twine(Msg) + " on the " +
4196ac9a064cSDimitry Andric               (Instrs.size() == 1 ? "instruction" : "output instructions"));
4197522600a2SDimitry Andric     // Provide the location of the relevant instruction definitions.
4198dd58ef01SDimitry Andric     for (const Record *Instr : Instrs) {
4199dd58ef01SDimitry Andric       if (Instr != PTM.getSrcRecord())
4200dd58ef01SDimitry Andric         PrintError(Instr->getLoc(), "defined here");
4201dd58ef01SDimitry Andric       const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
4202ac9a064cSDimitry Andric       if (InstInfo.InferredFrom && InstInfo.InferredFrom != InstInfo.TheDef &&
4203522600a2SDimitry Andric           InstInfo.InferredFrom != PTM.getSrcRecord())
4204dd58ef01SDimitry Andric         PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
4205522600a2SDimitry Andric     }
4206522600a2SDimitry Andric   }
4207522600a2SDimitry Andric   if (Errors)
4208522600a2SDimitry Andric     PrintFatalError("Errors in DAG patterns");
4209009b1c42SEd Schouten }
4210009b1c42SEd Schouten 
4211c6910277SRoman Divacky /// Given a pattern result with an unresolved type, see if we can find one
4212c6910277SRoman Divacky /// instruction with an unresolved result type.  Force this result type to an
4213c6910277SRoman Divacky /// arbitrary element if it's possible types to converge results.
ForceArbitraryInstResultType(TreePatternNode & N,TreePattern & TP)4214ac9a064cSDimitry Andric static bool ForceArbitraryInstResultType(TreePatternNode &N, TreePattern &TP) {
4215ac9a064cSDimitry Andric   if (N.isLeaf())
4216c6910277SRoman Divacky     return false;
4217c6910277SRoman Divacky 
4218c6910277SRoman Divacky   // Analyze children.
4219ac9a064cSDimitry Andric   for (unsigned i = 0, e = N.getNumChildren(); i != e; ++i)
4220ac9a064cSDimitry Andric     if (ForceArbitraryInstResultType(N.getChild(i), TP))
4221c6910277SRoman Divacky       return true;
4222c6910277SRoman Divacky 
4223ac9a064cSDimitry Andric   if (!N.getOperator()->isSubClassOf("Instruction"))
4224c6910277SRoman Divacky     return false;
4225c6910277SRoman Divacky 
4226c6910277SRoman Divacky   // If this type is already concrete or completely unknown we can't do
4227c6910277SRoman Divacky   // anything.
4228044eb2f6SDimitry Andric   TypeInfer &TI = TP.getInfer();
4229ac9a064cSDimitry Andric   for (unsigned i = 0, e = N.getNumTypes(); i != e; ++i) {
4230ac9a064cSDimitry Andric     if (N.getExtType(i).empty() || TI.isConcrete(N.getExtType(i), false))
42312f12f10aSRoman Divacky       continue;
4232c6910277SRoman Divacky 
4233044eb2f6SDimitry Andric     // Otherwise, force its type to an arbitrary choice.
4234ac9a064cSDimitry Andric     if (TI.forceArbitrary(N.getExtType(i)))
42352f12f10aSRoman Divacky       return true;
42362f12f10aSRoman Divacky   }
42372f12f10aSRoman Divacky 
42382f12f10aSRoman Divacky   return false;
4239c6910277SRoman Divacky }
4240c6910277SRoman Divacky 
4241b7eb8e35SDimitry Andric // Promote xform function to be an explicit node wherever set.
PromoteXForms(TreePatternNodePtr N)4242b7eb8e35SDimitry Andric static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
4243b7eb8e35SDimitry Andric   if (Record *Xform = N->getTransformFn()) {
4244b7eb8e35SDimitry Andric     N->setTransformFn(nullptr);
4245b7eb8e35SDimitry Andric     std::vector<TreePatternNodePtr> Children;
4246b7eb8e35SDimitry Andric     Children.push_back(PromoteXForms(N));
42477fa27ce4SDimitry Andric     return makeIntrusiveRefCnt<TreePatternNode>(Xform, std::move(Children),
4248b7eb8e35SDimitry Andric                                                 N->getNumTypes());
4249b7eb8e35SDimitry Andric   }
4250b7eb8e35SDimitry Andric 
4251b7eb8e35SDimitry Andric   if (!N->isLeaf())
4252b7eb8e35SDimitry Andric     for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4253b7eb8e35SDimitry Andric       TreePatternNodePtr Child = N->getChildShared(i);
4254b7eb8e35SDimitry Andric       N->setChild(i, PromoteXForms(Child));
4255b7eb8e35SDimitry Andric     }
4256b7eb8e35SDimitry Andric   return N;
4257b7eb8e35SDimitry Andric }
4258b7eb8e35SDimitry Andric 
ParseOnePattern(Record * TheDef,TreePattern & Pattern,TreePattern & Result,const std::vector<Record * > & InstImpResults,bool ShouldIgnore)4259ac9a064cSDimitry Andric void CodeGenDAGPatterns::ParseOnePattern(
4260ac9a064cSDimitry Andric     Record *TheDef, TreePattern &Pattern, TreePattern &Result,
4261ac9a064cSDimitry Andric     const std::vector<Record *> &InstImpResults, bool ShouldIgnore) {
4262009b1c42SEd Schouten 
4263eb11fae6SDimitry Andric   // Inline pattern fragments and expand multiple alternatives.
4264eb11fae6SDimitry Andric   Pattern.InlinePatternFragments();
426567c32a98SDimitry Andric   Result.InlinePatternFragments();
4266009b1c42SEd Schouten 
426767c32a98SDimitry Andric   if (Result.getNumTrees() != 1)
4268eb11fae6SDimitry Andric     Result.error("Cannot use multi-alternative fragments in result pattern!");
4269009b1c42SEd Schouten 
4270eb11fae6SDimitry Andric   // Infer types.
4271009b1c42SEd Schouten   bool IterateInference;
4272009b1c42SEd Schouten   bool InferredAllPatternTypes, InferredAllResultTypes;
4273009b1c42SEd Schouten   do {
4274009b1c42SEd Schouten     // Infer as many types as possible.  If we cannot infer all of them, we
4275009b1c42SEd Schouten     // can never do anything with this pattern: report it to the user.
4276c6910277SRoman Divacky     InferredAllPatternTypes =
4277eb11fae6SDimitry Andric         Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
4278009b1c42SEd Schouten 
4279009b1c42SEd Schouten     // Infer as many types as possible.  If we cannot infer all of them, we
4280009b1c42SEd Schouten     // can never do anything with this pattern: report it to the user.
4281ac9a064cSDimitry Andric     InferredAllResultTypes = Result.InferAllTypes(&Pattern.getNamedNodesMap());
4282009b1c42SEd Schouten 
42832f12f10aSRoman Divacky     IterateInference = false;
42842f12f10aSRoman Divacky 
4285009b1c42SEd Schouten     // Apply the type of the result to the source pattern.  This helps us
4286009b1c42SEd Schouten     // resolve cases where the input type is known to be a pointer type (which
4287009b1c42SEd Schouten     // is considered resolved), but the result knows it needs to be 32- or
4288009b1c42SEd Schouten     // 64-bits.  Infer the other way for good measure.
4289344a3780SDimitry Andric     for (const auto &T : Pattern.getTrees())
4290eb11fae6SDimitry Andric       for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
4291eb11fae6SDimitry Andric                                         T->getNumTypes());
42922f12f10aSRoman Divacky            i != e; ++i) {
4293ac9a064cSDimitry Andric         IterateInference |=
4294ac9a064cSDimitry Andric             T->UpdateNodeType(i, Result.getOnlyTree()->getExtType(i), Result);
4295ac9a064cSDimitry Andric         IterateInference |=
4296ac9a064cSDimitry Andric             Result.getOnlyTree()->UpdateNodeType(i, T->getExtType(i), Result);
42972f12f10aSRoman Divacky       }
4298c6910277SRoman Divacky 
4299c6910277SRoman Divacky     // If our iteration has converged and the input pattern's types are fully
4300c6910277SRoman Divacky     // resolved but the result pattern is not fully resolved, we may have a
4301c6910277SRoman Divacky     // situation where we have two instructions in the result pattern and
4302c6910277SRoman Divacky     // the instructions require a common register class, but don't care about
4303c6910277SRoman Divacky     // what actual MVT is used.  This is actually a bug in our modelling:
4304c6910277SRoman Divacky     // output patterns should have register classes, not MVTs.
4305c6910277SRoman Divacky     //
4306c6910277SRoman Divacky     // In any case, to handle this, we just go through and disambiguate some
4307c6910277SRoman Divacky     // arbitrary types to the result pattern's nodes.
4308ac9a064cSDimitry Andric     if (!IterateInference && InferredAllPatternTypes && !InferredAllResultTypes)
430967c32a98SDimitry Andric       IterateInference =
4310ac9a064cSDimitry Andric           ForceArbitraryInstResultType(*Result.getTree(0), Result);
4311009b1c42SEd Schouten   } while (IterateInference);
4312009b1c42SEd Schouten 
4313009b1c42SEd Schouten   // Verify that we inferred enough types that we can do something with the
4314009b1c42SEd Schouten   // pattern and result.  If these fire the user has to add type casts.
4315009b1c42SEd Schouten   if (!InferredAllPatternTypes)
4316eb11fae6SDimitry Andric     Pattern.error("Could not infer all types in pattern!");
4317c6910277SRoman Divacky   if (!InferredAllResultTypes) {
4318eb11fae6SDimitry Andric     Pattern.dump();
431967c32a98SDimitry Andric     Result.error("Could not infer all types in pattern result!");
4320c6910277SRoman Divacky   }
4321009b1c42SEd Schouten 
4322b7eb8e35SDimitry Andric   // Promote xform function to be an explicit node wherever set.
4323b7eb8e35SDimitry Andric   TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
43242f12f10aSRoman Divacky 
4325eb11fae6SDimitry Andric   TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4326009b1c42SEd Schouten   Temp.InferAllTypes();
4327009b1c42SEd Schouten 
4328eb11fae6SDimitry Andric   ListInit *Preds = TheDef->getValueAsListInit("Predicates");
4329eb11fae6SDimitry Andric   int Complexity = TheDef->getValueAsInt("AddedComplexity");
4330eb11fae6SDimitry Andric 
4331eb11fae6SDimitry Andric   if (PatternRewriter)
4332eb11fae6SDimitry Andric     PatternRewriter(&Pattern);
4333eb11fae6SDimitry Andric 
4334044eb2f6SDimitry Andric   // A pattern may end up with an "impossible" type, i.e. a situation
4335044eb2f6SDimitry Andric   // where all types have been eliminated for some node in this pattern.
4336044eb2f6SDimitry Andric   // This could occur for intrinsics that only make sense for a specific
4337044eb2f6SDimitry Andric   // value type, and use a specific register class. If, for some mode,
4338044eb2f6SDimitry Andric   // that register class does not accept that type, the type inference
4339044eb2f6SDimitry Andric   // will lead to a contradiction, which is not an error however, but
4340044eb2f6SDimitry Andric   // a sign that this pattern will simply never match.
43417fa27ce4SDimitry Andric   if (Temp.getOnlyTree()->hasPossibleType()) {
43427fa27ce4SDimitry Andric     for (const auto &T : Pattern.getTrees()) {
4343eb11fae6SDimitry Andric       if (T->hasPossibleType())
4344eb11fae6SDimitry Andric         AddPatternToMatch(&Pattern,
4345344a3780SDimitry Andric                           PatternToMatch(TheDef, Preds, T, Temp.getOnlyTree(),
4346eb11fae6SDimitry Andric                                          InstImpResults, Complexity,
4347ac9a064cSDimitry Andric                                          TheDef->getID(), ShouldIgnore));
4348009b1c42SEd Schouten     }
43497fa27ce4SDimitry Andric   } else {
43507fa27ce4SDimitry Andric     // Show a message about a dropped pattern with some info to make it
43517fa27ce4SDimitry Andric     // easier to identify it in the .td files.
43527fa27ce4SDimitry Andric     LLVM_DEBUG({
43537fa27ce4SDimitry Andric       dbgs() << "Dropping: ";
43547fa27ce4SDimitry Andric       Pattern.dump();
43557fa27ce4SDimitry Andric       Temp.getOnlyTree()->dump();
43567fa27ce4SDimitry Andric       dbgs() << "\n";
43577fa27ce4SDimitry Andric     });
43587fa27ce4SDimitry Andric   }
43597fa27ce4SDimitry Andric }
4360eb11fae6SDimitry Andric 
ParsePatterns()4361eb11fae6SDimitry Andric void CodeGenDAGPatterns::ParsePatterns() {
4362eb11fae6SDimitry Andric   std::vector<Record *> Patterns = Records.getAllDerivedDefinitions("Pattern");
4363eb11fae6SDimitry Andric 
4364eb11fae6SDimitry Andric   for (Record *CurPattern : Patterns) {
4365eb11fae6SDimitry Andric     DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
4366eb11fae6SDimitry Andric 
4367eb11fae6SDimitry Andric     // If the pattern references the null_frag, there's nothing to do.
4368eb11fae6SDimitry Andric     if (hasNullFragReference(Tree))
4369eb11fae6SDimitry Andric       continue;
4370eb11fae6SDimitry Andric 
4371eb11fae6SDimitry Andric     TreePattern Pattern(CurPattern, Tree, true, *this);
4372eb11fae6SDimitry Andric 
4373eb11fae6SDimitry Andric     ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
4374ac9a064cSDimitry Andric     if (LI->empty())
4375ac9a064cSDimitry Andric       continue; // no pattern.
4376eb11fae6SDimitry Andric 
4377eb11fae6SDimitry Andric     // Parse the instruction.
4378eb11fae6SDimitry Andric     TreePattern Result(CurPattern, LI, false, *this);
4379eb11fae6SDimitry Andric 
4380eb11fae6SDimitry Andric     if (Result.getNumTrees() != 1)
4381eb11fae6SDimitry Andric       Result.error("Cannot handle instructions producing instructions "
4382eb11fae6SDimitry Andric                    "with temporaries yet!");
4383eb11fae6SDimitry Andric 
4384eb11fae6SDimitry Andric     // Validate that the input pattern is correct.
4385eb11fae6SDimitry Andric     std::map<std::string, TreePatternNodePtr> InstInputs;
4386d8e91e46SDimitry Andric     MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
4387d8e91e46SDimitry Andric         InstResults;
4388eb11fae6SDimitry Andric     std::vector<Record *> InstImpResults;
4389eb11fae6SDimitry Andric     for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
4390eb11fae6SDimitry Andric       FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
4391eb11fae6SDimitry Andric                                   InstResults, InstImpResults);
4392eb11fae6SDimitry Andric 
4393ac9a064cSDimitry Andric     ParseOnePattern(CurPattern, Pattern, Result, InstImpResults,
4394ac9a064cSDimitry Andric                     CurPattern->getValueAsBit("GISelShouldIgnore"));
4395009b1c42SEd Schouten   }
4396044eb2f6SDimitry Andric }
4397044eb2f6SDimitry Andric 
collectModes(std::set<unsigned> & Modes,const TreePatternNode & N)4398ac9a064cSDimitry Andric static void collectModes(std::set<unsigned> &Modes, const TreePatternNode &N) {
4399ac9a064cSDimitry Andric   for (const TypeSetByHwMode &VTS : N.getExtTypes())
4400044eb2f6SDimitry Andric     for (const auto &I : VTS)
4401044eb2f6SDimitry Andric       Modes.insert(I.first);
4402044eb2f6SDimitry Andric 
4403ac9a064cSDimitry Andric   for (unsigned i = 0, e = N.getNumChildren(); i != e; ++i)
4404ac9a064cSDimitry Andric     collectModes(Modes, N.getChild(i));
4405044eb2f6SDimitry Andric }
4406044eb2f6SDimitry Andric 
ExpandHwModeBasedTypes()4407044eb2f6SDimitry Andric void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4408044eb2f6SDimitry Andric   const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
44097fa27ce4SDimitry Andric   if (CGH.getNumModeIds() == 1)
44107fa27ce4SDimitry Andric     return;
44117fa27ce4SDimitry Andric 
4412344a3780SDimitry Andric   std::vector<PatternToMatch> Copy;
4413344a3780SDimitry Andric   PatternsToMatch.swap(Copy);
4414044eb2f6SDimitry Andric 
4415344a3780SDimitry Andric   auto AppendPattern = [this](PatternToMatch &P, unsigned Mode,
4416344a3780SDimitry Andric                               StringRef Check) {
4417ac9a064cSDimitry Andric     TreePatternNodePtr NewSrc = P.getSrcPattern().clone();
4418ac9a064cSDimitry Andric     TreePatternNodePtr NewDst = P.getDstPattern().clone();
4419044eb2f6SDimitry Andric     if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
4420044eb2f6SDimitry Andric       return;
4421044eb2f6SDimitry Andric     }
4422044eb2f6SDimitry Andric 
4423ac9a064cSDimitry Andric     PatternsToMatch.emplace_back(
4424ac9a064cSDimitry Andric         P.getSrcRecord(), P.getPredicates(), std::move(NewSrc),
4425ac9a064cSDimitry Andric         std::move(NewDst), P.getDstRegs(), P.getAddedComplexity(),
4426ac9a064cSDimitry Andric         Record::getNewUID(Records), P.getGISelShouldIgnore(), Check);
4427044eb2f6SDimitry Andric   };
4428044eb2f6SDimitry Andric 
4429044eb2f6SDimitry Andric   for (PatternToMatch &P : Copy) {
44307fa27ce4SDimitry Andric     const TreePatternNode *SrcP = nullptr, *DstP = nullptr;
4431ac9a064cSDimitry Andric     if (P.getSrcPattern().hasProperTypeByHwMode())
4432ac9a064cSDimitry Andric       SrcP = &P.getSrcPattern();
4433ac9a064cSDimitry Andric     if (P.getDstPattern().hasProperTypeByHwMode())
4434ac9a064cSDimitry Andric       DstP = &P.getDstPattern();
4435044eb2f6SDimitry Andric     if (!SrcP && !DstP) {
4436044eb2f6SDimitry Andric       PatternsToMatch.push_back(P);
4437044eb2f6SDimitry Andric       continue;
4438044eb2f6SDimitry Andric     }
4439044eb2f6SDimitry Andric 
4440044eb2f6SDimitry Andric     std::set<unsigned> Modes;
4441044eb2f6SDimitry Andric     if (SrcP)
4442ac9a064cSDimitry Andric       collectModes(Modes, *SrcP);
4443044eb2f6SDimitry Andric     if (DstP)
4444ac9a064cSDimitry Andric       collectModes(Modes, *DstP);
4445044eb2f6SDimitry Andric 
4446044eb2f6SDimitry Andric     // The predicate for the default mode needs to be constructed for each
4447044eb2f6SDimitry Andric     // pattern separately.
4448044eb2f6SDimitry Andric     // Since not all modes must be present in each pattern, if a mode m is
4449044eb2f6SDimitry Andric     // absent, then there is no point in constructing a check for m. If such
4450044eb2f6SDimitry Andric     // a check was created, it would be equivalent to checking the default
4451044eb2f6SDimitry Andric     // mode, except not all modes' predicates would be a part of the checking
4452044eb2f6SDimitry Andric     // code. The subsequently generated check for the default mode would then
4453044eb2f6SDimitry Andric     // have the exact same patterns, but a different predicate code. To avoid
4454044eb2f6SDimitry Andric     // duplicated patterns with different predicate checks, construct the
4455044eb2f6SDimitry Andric     // default check as a negation of all predicates that are actually present
4456044eb2f6SDimitry Andric     // in the source/destination patterns.
4457344a3780SDimitry Andric     SmallString<128> DefaultCheck;
4458044eb2f6SDimitry Andric 
4459044eb2f6SDimitry Andric     for (unsigned M : Modes) {
4460044eb2f6SDimitry Andric       if (M == DefaultMode)
4461044eb2f6SDimitry Andric         continue;
4462044eb2f6SDimitry Andric 
4463044eb2f6SDimitry Andric       // Fill the map entry for this mode.
4464044eb2f6SDimitry Andric       const HwMode &HM = CGH.getMode(M);
44657fa27ce4SDimitry Andric       AppendPattern(P, M, HM.Predicates);
4466044eb2f6SDimitry Andric 
4467044eb2f6SDimitry Andric       // Add negations of the HM's predicates to the default predicate.
4468344a3780SDimitry Andric       if (!DefaultCheck.empty())
4469344a3780SDimitry Andric         DefaultCheck += " && ";
44707fa27ce4SDimitry Andric       DefaultCheck += "!(";
44717fa27ce4SDimitry Andric       DefaultCheck += HM.Predicates;
44727fa27ce4SDimitry Andric       DefaultCheck += ")";
4473044eb2f6SDimitry Andric     }
4474044eb2f6SDimitry Andric 
4475044eb2f6SDimitry Andric     bool HasDefault = Modes.count(DefaultMode);
4476044eb2f6SDimitry Andric     if (HasDefault)
4477344a3780SDimitry Andric       AppendPattern(P, DefaultMode, DefaultCheck);
4478044eb2f6SDimitry Andric   }
4479044eb2f6SDimitry Andric }
4480044eb2f6SDimitry Andric 
4481044eb2f6SDimitry Andric /// Dependent variable map for CodeGenDAGPattern variant generation
4482044eb2f6SDimitry Andric typedef StringMap<int> DepVarMap;
4483044eb2f6SDimitry Andric 
FindDepVarsOf(TreePatternNode & N,DepVarMap & DepMap)4484ac9a064cSDimitry Andric static void FindDepVarsOf(TreePatternNode &N, DepVarMap &DepMap) {
4485ac9a064cSDimitry Andric   if (N.isLeaf()) {
4486ac9a064cSDimitry Andric     if (N.hasName() && isa<DefInit>(N.getLeafValue()))
4487ac9a064cSDimitry Andric       DepMap[N.getName()]++;
4488044eb2f6SDimitry Andric   } else {
4489ac9a064cSDimitry Andric     for (size_t i = 0, e = N.getNumChildren(); i != e; ++i)
4490ac9a064cSDimitry Andric       FindDepVarsOf(N.getChild(i), DepMap);
4491044eb2f6SDimitry Andric   }
4492044eb2f6SDimitry Andric }
4493044eb2f6SDimitry Andric 
4494044eb2f6SDimitry Andric /// Find dependent variables within child patterns
FindDepVars(TreePatternNode & N,MultipleUseVarSet & DepVars)4495ac9a064cSDimitry Andric static void FindDepVars(TreePatternNode &N, MultipleUseVarSet &DepVars) {
4496044eb2f6SDimitry Andric   DepVarMap depcounts;
4497044eb2f6SDimitry Andric   FindDepVarsOf(N, depcounts);
4498044eb2f6SDimitry Andric   for (const auto &Pair : depcounts) {
4499044eb2f6SDimitry Andric     if (Pair.getValue() > 1)
4500044eb2f6SDimitry Andric       DepVars.insert(Pair.getKey());
4501044eb2f6SDimitry Andric   }
4502044eb2f6SDimitry Andric }
4503044eb2f6SDimitry Andric 
4504044eb2f6SDimitry Andric #ifndef NDEBUG
4505044eb2f6SDimitry Andric /// Dump the dependent variable set:
DumpDepVars(MultipleUseVarSet & DepVars)4506044eb2f6SDimitry Andric static void DumpDepVars(MultipleUseVarSet &DepVars) {
4507044eb2f6SDimitry Andric   if (DepVars.empty()) {
4508eb11fae6SDimitry Andric     LLVM_DEBUG(errs() << "<empty set>");
4509044eb2f6SDimitry Andric   } else {
4510eb11fae6SDimitry Andric     LLVM_DEBUG(errs() << "[ ");
4511044eb2f6SDimitry Andric     for (const auto &DepVar : DepVars) {
4512eb11fae6SDimitry Andric       LLVM_DEBUG(errs() << DepVar.getKey() << " ");
4513044eb2f6SDimitry Andric     }
4514eb11fae6SDimitry Andric     LLVM_DEBUG(errs() << "]");
4515044eb2f6SDimitry Andric   }
4516044eb2f6SDimitry Andric }
4517044eb2f6SDimitry Andric #endif
4518044eb2f6SDimitry Andric 
4519009b1c42SEd Schouten /// CombineChildVariants - Given a bunch of permutations of each child of the
4520009b1c42SEd Schouten /// 'operator' node, put them together in all possible ways.
CombineChildVariants(TreePatternNodePtr Orig,const std::vector<std::vector<TreePatternNodePtr>> & ChildVariants,std::vector<TreePatternNodePtr> & OutVariants,CodeGenDAGPatterns & CDP,const MultipleUseVarSet & DepVars)4521eb11fae6SDimitry Andric static void CombineChildVariants(
4522eb11fae6SDimitry Andric     TreePatternNodePtr Orig,
4523eb11fae6SDimitry Andric     const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4524eb11fae6SDimitry Andric     std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4525009b1c42SEd Schouten     const MultipleUseVarSet &DepVars) {
4526009b1c42SEd Schouten   // Make sure that each operand has at least one variant to choose from.
4527dd58ef01SDimitry Andric   for (const auto &Variants : ChildVariants)
4528dd58ef01SDimitry Andric     if (Variants.empty())
4529009b1c42SEd Schouten       return;
4530009b1c42SEd Schouten 
4531009b1c42SEd Schouten   // The end result is an all-pairs construction of the resultant pattern.
45327fa27ce4SDimitry Andric   std::vector<unsigned> Idxs(ChildVariants.size());
4533009b1c42SEd Schouten   bool NotDone;
4534009b1c42SEd Schouten   do {
4535009b1c42SEd Schouten #ifndef NDEBUG
4536eb11fae6SDimitry Andric     LLVM_DEBUG(if (!Idxs.empty()) {
453718f153bdSEd Schouten       errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
4538dd58ef01SDimitry Andric       for (unsigned Idx : Idxs) {
4539dd58ef01SDimitry Andric         errs() << Idx << " ";
4540009b1c42SEd Schouten       }
454118f153bdSEd Schouten       errs() << "]\n";
454267a71b31SRoman Divacky     });
4543009b1c42SEd Schouten #endif
4544009b1c42SEd Schouten     // Create the variant and add it to the output list.
4545eb11fae6SDimitry Andric     std::vector<TreePatternNodePtr> NewChildren;
45467fa27ce4SDimitry Andric     NewChildren.reserve(ChildVariants.size());
4547009b1c42SEd Schouten     for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4548009b1c42SEd Schouten       NewChildren.push_back(ChildVariants[i][Idxs[i]]);
45497fa27ce4SDimitry Andric     TreePatternNodePtr R = makeIntrusiveRefCnt<TreePatternNode>(
4550eb11fae6SDimitry Andric         Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
4551009b1c42SEd Schouten 
4552009b1c42SEd Schouten     // Copy over properties.
4553009b1c42SEd Schouten     R->setName(Orig->getName());
4554d8e91e46SDimitry Andric     R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
4555d8e91e46SDimitry Andric     R->setPredicateCalls(Orig->getPredicateCalls());
45567fa27ce4SDimitry Andric     R->setGISelFlagsRecord(Orig->getGISelFlagsRecord());
4557009b1c42SEd Schouten     R->setTransformFn(Orig->getTransformFn());
45582f12f10aSRoman Divacky     for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
45592f12f10aSRoman Divacky       R->setType(i, Orig->getExtType(i));
4560009b1c42SEd Schouten 
4561009b1c42SEd Schouten     // If this pattern cannot match, do not include it as a variant.
4562009b1c42SEd Schouten     std::string ErrString;
4563009b1c42SEd Schouten     // Scan to see if this pattern has already been emitted.  We can get
4564009b1c42SEd Schouten     // duplication due to things like commuting:
4565009b1c42SEd Schouten     //   (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4566009b1c42SEd Schouten     // which are the same pattern.  Ignore the dups.
4567dd58ef01SDimitry Andric     if (R->canPatternMatch(ErrString, CDP) &&
4568eb11fae6SDimitry Andric         none_of(OutVariants, [&](TreePatternNodePtr Variant) {
4569ac9a064cSDimitry Andric           return R->isIsomorphicTo(*Variant, DepVars);
4570dd58ef01SDimitry Andric         }))
4571eb11fae6SDimitry Andric       OutVariants.push_back(R);
4572009b1c42SEd Schouten 
4573009b1c42SEd Schouten     // Increment indices to the next permutation by incrementing the
4574dd58ef01SDimitry Andric     // indices from last index backward, e.g., generate the sequence
4575009b1c42SEd Schouten     // [0, 0], [0, 1], [1, 0], [1, 1].
4576009b1c42SEd Schouten     int IdxsIdx;
4577009b1c42SEd Schouten     for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4578009b1c42SEd Schouten       if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4579009b1c42SEd Schouten         Idxs[IdxsIdx] = 0;
4580009b1c42SEd Schouten       else
4581009b1c42SEd Schouten         break;
4582009b1c42SEd Schouten     }
4583009b1c42SEd Schouten     NotDone = (IdxsIdx >= 0);
4584009b1c42SEd Schouten   } while (NotDone);
4585009b1c42SEd Schouten }
4586009b1c42SEd Schouten 
4587009b1c42SEd Schouten /// CombineChildVariants - A helper function for binary operators.
4588009b1c42SEd Schouten ///
CombineChildVariants(TreePatternNodePtr Orig,const std::vector<TreePatternNodePtr> & LHS,const std::vector<TreePatternNodePtr> & RHS,std::vector<TreePatternNodePtr> & OutVariants,CodeGenDAGPatterns & CDP,const MultipleUseVarSet & DepVars)4589eb11fae6SDimitry Andric static void CombineChildVariants(TreePatternNodePtr Orig,
4590eb11fae6SDimitry Andric                                  const std::vector<TreePatternNodePtr> &LHS,
4591eb11fae6SDimitry Andric                                  const std::vector<TreePatternNodePtr> &RHS,
4592eb11fae6SDimitry Andric                                  std::vector<TreePatternNodePtr> &OutVariants,
4593009b1c42SEd Schouten                                  CodeGenDAGPatterns &CDP,
4594009b1c42SEd Schouten                                  const MultipleUseVarSet &DepVars) {
4595eb11fae6SDimitry Andric   std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
4596009b1c42SEd Schouten   ChildVariants.push_back(LHS);
4597009b1c42SEd Schouten   ChildVariants.push_back(RHS);
4598009b1c42SEd Schouten   CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
4599009b1c42SEd Schouten }
4600009b1c42SEd Schouten 
4601eb11fae6SDimitry Andric static void
GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,std::vector<TreePatternNodePtr> & Children)4602eb11fae6SDimitry Andric GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
4603eb11fae6SDimitry Andric                                   std::vector<TreePatternNodePtr> &Children) {
4604ac9a064cSDimitry Andric   assert(N->getNumChildren() == 2 &&
4605ac9a064cSDimitry Andric          "Associative but doesn't have 2 children!");
4606009b1c42SEd Schouten   Record *Operator = N->getOperator();
4607009b1c42SEd Schouten 
4608009b1c42SEd Schouten   // Only permit raw nodes.
4609d8e91e46SDimitry Andric   if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
4610009b1c42SEd Schouten       N->getTransformFn()) {
4611009b1c42SEd Schouten     Children.push_back(N);
4612009b1c42SEd Schouten     return;
4613009b1c42SEd Schouten   }
4614009b1c42SEd Schouten 
4615ac9a064cSDimitry Andric   if (N->getChild(0).isLeaf() || N->getChild(0).getOperator() != Operator)
4616eb11fae6SDimitry Andric     Children.push_back(N->getChildShared(0));
4617009b1c42SEd Schouten   else
4618eb11fae6SDimitry Andric     GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
4619009b1c42SEd Schouten 
4620ac9a064cSDimitry Andric   if (N->getChild(1).isLeaf() || N->getChild(1).getOperator() != Operator)
4621eb11fae6SDimitry Andric     Children.push_back(N->getChildShared(1));
4622009b1c42SEd Schouten   else
4623eb11fae6SDimitry Andric     GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
4624009b1c42SEd Schouten }
4625009b1c42SEd Schouten 
4626009b1c42SEd Schouten /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4627009b1c42SEd Schouten /// the (potentially recursive) pattern by using algebraic laws.
4628009b1c42SEd Schouten ///
GenerateVariantsOf(TreePatternNodePtr N,std::vector<TreePatternNodePtr> & OutVariants,CodeGenDAGPatterns & CDP,const MultipleUseVarSet & DepVars)4629eb11fae6SDimitry Andric static void GenerateVariantsOf(TreePatternNodePtr N,
4630eb11fae6SDimitry Andric                                std::vector<TreePatternNodePtr> &OutVariants,
4631009b1c42SEd Schouten                                CodeGenDAGPatterns &CDP,
4632009b1c42SEd Schouten                                const MultipleUseVarSet &DepVars) {
46335ca98fd9SDimitry Andric   // We cannot permute leaves or ComplexPattern uses.
46345ca98fd9SDimitry Andric   if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
4635009b1c42SEd Schouten     OutVariants.push_back(N);
4636009b1c42SEd Schouten     return;
4637009b1c42SEd Schouten   }
4638009b1c42SEd Schouten 
4639009b1c42SEd Schouten   // Look up interesting info about the node.
4640009b1c42SEd Schouten   const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4641009b1c42SEd Schouten 
4642009b1c42SEd Schouten   // If this node is associative, re-associate.
4643009b1c42SEd Schouten   if (NodeInfo.hasProperty(SDNPAssociative)) {
4644009b1c42SEd Schouten     // Re-associate by pulling together all of the linked operators
4645eb11fae6SDimitry Andric     std::vector<TreePatternNodePtr> MaximalChildren;
4646009b1c42SEd Schouten     GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4647009b1c42SEd Schouten 
4648009b1c42SEd Schouten     // Only handle child sizes of 3.  Otherwise we'll end up trying too many
4649009b1c42SEd Schouten     // permutations.
4650009b1c42SEd Schouten     if (MaximalChildren.size() == 3) {
4651009b1c42SEd Schouten       // Find the variants of all of our maximal children.
4652eb11fae6SDimitry Andric       std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
4653009b1c42SEd Schouten       GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4654009b1c42SEd Schouten       GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4655009b1c42SEd Schouten       GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
4656009b1c42SEd Schouten 
4657009b1c42SEd Schouten       // There are only two ways we can permute the tree:
4658009b1c42SEd Schouten       //   (A op B) op C    and    A op (B op C)
4659009b1c42SEd Schouten       // Within these forms, we can also permute A/B/C.
4660009b1c42SEd Schouten 
4661009b1c42SEd Schouten       // Generate legal pair permutations of A/B/C.
4662eb11fae6SDimitry Andric       std::vector<TreePatternNodePtr> ABVariants;
4663eb11fae6SDimitry Andric       std::vector<TreePatternNodePtr> BAVariants;
4664eb11fae6SDimitry Andric       std::vector<TreePatternNodePtr> ACVariants;
4665eb11fae6SDimitry Andric       std::vector<TreePatternNodePtr> CAVariants;
4666eb11fae6SDimitry Andric       std::vector<TreePatternNodePtr> BCVariants;
4667eb11fae6SDimitry Andric       std::vector<TreePatternNodePtr> CBVariants;
4668009b1c42SEd Schouten       CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4669009b1c42SEd Schouten       CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4670009b1c42SEd Schouten       CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4671009b1c42SEd Schouten       CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4672009b1c42SEd Schouten       CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4673009b1c42SEd Schouten       CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
4674009b1c42SEd Schouten 
4675009b1c42SEd Schouten       // Combine those into the result: (x op x) op x
4676009b1c42SEd Schouten       CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4677009b1c42SEd Schouten       CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4678009b1c42SEd Schouten       CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4679009b1c42SEd Schouten       CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4680009b1c42SEd Schouten       CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4681009b1c42SEd Schouten       CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
4682009b1c42SEd Schouten 
4683009b1c42SEd Schouten       // Combine those into the result: x op (x op x)
4684009b1c42SEd Schouten       CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4685009b1c42SEd Schouten       CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4686009b1c42SEd Schouten       CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4687009b1c42SEd Schouten       CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4688009b1c42SEd Schouten       CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4689009b1c42SEd Schouten       CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
4690009b1c42SEd Schouten       return;
4691009b1c42SEd Schouten     }
4692009b1c42SEd Schouten   }
4693009b1c42SEd Schouten 
4694009b1c42SEd Schouten   // Compute permutations of all children.
46957fa27ce4SDimitry Andric   std::vector<std::vector<TreePatternNodePtr>> ChildVariants(
46967fa27ce4SDimitry Andric       N->getNumChildren());
4697009b1c42SEd Schouten   for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4698eb11fae6SDimitry Andric     GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
4699009b1c42SEd Schouten 
4700009b1c42SEd Schouten   // Build all permutations based on how the children were formed.
4701009b1c42SEd Schouten   CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
4702009b1c42SEd Schouten 
4703009b1c42SEd Schouten   // If this node is commutative, consider the commuted order.
4704009b1c42SEd Schouten   bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4705009b1c42SEd Schouten   if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
4706ecbca9f5SDimitry Andric     unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
4707ecbca9f5SDimitry Andric     assert(N->getNumChildren() >= (2 + Skip) &&
4708009b1c42SEd Schouten            "Commutative but doesn't have 2 children!");
4709ecbca9f5SDimitry Andric     // Don't allow commuting children which are actually register references.
4710ecbca9f5SDimitry Andric     bool NoRegisters = true;
4711ecbca9f5SDimitry Andric     unsigned i = 0 + Skip;
4712ecbca9f5SDimitry Andric     unsigned e = 2 + Skip;
4713ecbca9f5SDimitry Andric     for (; i != e; ++i) {
4714ac9a064cSDimitry Andric       TreePatternNode &Child = N->getChild(i);
4715ac9a064cSDimitry Andric       if (Child.isLeaf())
4716ac9a064cSDimitry Andric         if (DefInit *DI = dyn_cast<DefInit>(Child.getLeafValue())) {
4717009b1c42SEd Schouten           Record *RR = DI->getDef();
4718009b1c42SEd Schouten           if (RR->isSubClassOf("Register"))
4719ecbca9f5SDimitry Andric             NoRegisters = false;
4720009b1c42SEd Schouten         }
4721009b1c42SEd Schouten     }
4722009b1c42SEd Schouten     // Consider the commuted order.
4723ecbca9f5SDimitry Andric     if (NoRegisters) {
47247fa27ce4SDimitry Andric       // Swap the first two operands after the intrinsic id, if present.
47257fa27ce4SDimitry Andric       unsigned i = isCommIntrinsic ? 1 : 0;
47267fa27ce4SDimitry Andric       std::swap(ChildVariants[i], ChildVariants[i + 1]);
47277fa27ce4SDimitry Andric       CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
4728044eb2f6SDimitry Andric     }
4729009b1c42SEd Schouten   }
4730009b1c42SEd Schouten }
4731009b1c42SEd Schouten 
4732009b1c42SEd Schouten // GenerateVariants - Generate variants.  For example, commutative patterns can
4733009b1c42SEd Schouten // match multiple ways.  Add them to PatternsToMatch as well.
GenerateVariants()4734009b1c42SEd Schouten void CodeGenDAGPatterns::GenerateVariants() {
4735eb11fae6SDimitry Andric   LLVM_DEBUG(errs() << "Generating instruction variants.\n");
4736009b1c42SEd Schouten 
4737009b1c42SEd Schouten   // Loop over all of the patterns we've collected, checking to see if we can
4738009b1c42SEd Schouten   // generate variants of the instruction, through the exploitation of
4739009b1c42SEd Schouten   // identities.  This permits the target to provide aggressive matching without
4740009b1c42SEd Schouten   // the .td file having to contain tons of variants of instructions.
4741009b1c42SEd Schouten   //
4742009b1c42SEd Schouten   // Note that this loop adds new patterns to the PatternsToMatch list, but we
4743009b1c42SEd Schouten   // intentionally do not reconsider these.  Any variants of added patterns have
4744009b1c42SEd Schouten   // already been added.
4745009b1c42SEd Schouten   //
4746344a3780SDimitry Andric   for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
4747009b1c42SEd Schouten     MultipleUseVarSet DepVars;
4748eb11fae6SDimitry Andric     std::vector<TreePatternNodePtr> Variants;
4749009b1c42SEd Schouten     FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
4750eb11fae6SDimitry Andric     LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4751eb11fae6SDimitry Andric     LLVM_DEBUG(DumpDepVars(DepVars));
4752eb11fae6SDimitry Andric     LLVM_DEBUG(errs() << "\n");
4753eb11fae6SDimitry Andric     GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4754eb11fae6SDimitry Andric                        *this, DepVars);
4755009b1c42SEd Schouten 
4756344a3780SDimitry Andric     assert(PatternsToMatch[i].getHwModeFeatures().empty() &&
4757344a3780SDimitry Andric            "HwModes should not have been expanded yet!");
4758344a3780SDimitry Andric 
4759009b1c42SEd Schouten     assert(!Variants.empty() && "Must create at least original variant!");
47607c7aba6eSDimitry Andric     if (Variants.size() == 1) // No additional variants for this pattern.
4761009b1c42SEd Schouten       continue;
4762009b1c42SEd Schouten 
4763eb11fae6SDimitry Andric     LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4764ac9a064cSDimitry Andric                PatternsToMatch[i].getSrcPattern().dump(); errs() << "\n");
4765009b1c42SEd Schouten 
4766009b1c42SEd Schouten     for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4767eb11fae6SDimitry Andric       TreePatternNodePtr Variant = Variants[v];
4768009b1c42SEd Schouten 
4769eb11fae6SDimitry Andric       LLVM_DEBUG(errs() << "  VAR#" << v << ": "; Variant->dump();
477059850d08SRoman Divacky                  errs() << "\n");
4771009b1c42SEd Schouten 
4772009b1c42SEd Schouten       // Scan to see if an instruction or explicit pattern already matches this.
4773009b1c42SEd Schouten       bool AlreadyExists = false;
4774009b1c42SEd Schouten       for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
4775f859468fSEd Schouten         // Skip if the top level predicates do not match.
4776344a3780SDimitry Andric         if ((i != p) && (PatternsToMatch[i].getPredicates() !=
4777344a3780SDimitry Andric                          PatternsToMatch[p].getPredicates()))
4778f859468fSEd Schouten           continue;
4779009b1c42SEd Schouten         // Check to see if this variant already exists.
4780cf099d11SDimitry Andric         if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
4781cf099d11SDimitry Andric                                     DepVars)) {
4782eb11fae6SDimitry Andric           LLVM_DEBUG(errs() << "  *** ALREADY EXISTS, ignoring variant.\n");
4783009b1c42SEd Schouten           AlreadyExists = true;
4784009b1c42SEd Schouten           break;
4785009b1c42SEd Schouten         }
4786009b1c42SEd Schouten       }
4787009b1c42SEd Schouten       // If we already have it, ignore the variant.
4788ac9a064cSDimitry Andric       if (AlreadyExists)
4789ac9a064cSDimitry Andric         continue;
4790009b1c42SEd Schouten 
4791009b1c42SEd Schouten       // Otherwise, add it to the list of patterns we have.
4792344a3780SDimitry Andric       PatternsToMatch.emplace_back(
479385d8b2bbSDimitry Andric           PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
4794eb11fae6SDimitry Andric           Variant, PatternsToMatch[i].getDstPatternShared(),
4795009b1c42SEd Schouten           PatternsToMatch[i].getDstRegs(),
4796145449b1SDimitry Andric           PatternsToMatch[i].getAddedComplexity(), Record::getNewUID(Records),
4797ac9a064cSDimitry Andric           PatternsToMatch[i].getGISelShouldIgnore(),
4798344a3780SDimitry Andric           PatternsToMatch[i].getHwModeFeatures());
4799009b1c42SEd Schouten     }
4800009b1c42SEd Schouten 
4801eb11fae6SDimitry Andric     LLVM_DEBUG(errs() << "\n");
4802009b1c42SEd Schouten   }
4803009b1c42SEd Schouten }
4804