Path: blob/main/contrib/llvm-project/llvm/utils/TableGen/Common/CodeGenDAGPatterns.cpp
35290 views
//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the CodeGenDAGPatterns class, which is used to read and9// represent the patterns present in a .td file for instructions.10//11//===----------------------------------------------------------------------===//1213#include "CodeGenDAGPatterns.h"14#include "CodeGenInstruction.h"15#include "CodeGenRegisters.h"16#include "llvm/ADT/DenseSet.h"17#include "llvm/ADT/MapVector.h"18#include "llvm/ADT/STLExtras.h"19#include "llvm/ADT/SmallSet.h"20#include "llvm/ADT/SmallString.h"21#include "llvm/ADT/StringExtras.h"22#include "llvm/ADT/StringMap.h"23#include "llvm/ADT/Twine.h"24#include "llvm/Support/Debug.h"25#include "llvm/Support/ErrorHandling.h"26#include "llvm/Support/TypeSize.h"27#include "llvm/TableGen/Error.h"28#include "llvm/TableGen/Record.h"29#include <algorithm>30#include <cstdio>31#include <iterator>32#include <set>33using namespace llvm;3435#define DEBUG_TYPE "dag-patterns"3637static inline bool isIntegerOrPtr(MVT VT) {38return VT.isInteger() || VT == MVT::iPTR;39}40static inline bool isFloatingPoint(MVT VT) { return VT.isFloatingPoint(); }41static inline bool isVector(MVT VT) { return VT.isVector(); }42static inline bool isScalar(MVT VT) { return !VT.isVector(); }4344template <typename Predicate>45static bool berase_if(MachineValueTypeSet &S, Predicate P) {46bool Erased = false;47// It is ok to iterate over MachineValueTypeSet and remove elements from it48// at the same time.49for (MVT T : S) {50if (!P(T))51continue;52Erased = true;53S.erase(T);54}55return Erased;56}5758void MachineValueTypeSet::writeToStream(raw_ostream &OS) const {59SmallVector<MVT, 4> Types(begin(), end());60array_pod_sort(Types.begin(), Types.end());6162OS << '[';63ListSeparator LS(" ");64for (const MVT &T : Types)65OS << LS << ValueTypeByHwMode::getMVTName(T);66OS << ']';67}6869// --- TypeSetByHwMode7071// This is a parameterized type-set class. For each mode there is a list72// of types that are currently possible for a given tree node. Type73// inference will apply to each mode separately.7475TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {76// Take the address space from the first type in the list.77if (!VTList.empty())78AddrSpace = VTList[0].PtrAddrSpace;7980for (const ValueTypeByHwMode &VVT : VTList)81insert(VVT);82}8384bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {85for (const auto &I : *this) {86if (I.second.size() > 1)87return false;88if (!AllowEmpty && I.second.empty())89return false;90}91return true;92}9394ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {95assert(isValueTypeByHwMode(true) &&96"The type set has multiple types for at least one HW mode");97ValueTypeByHwMode VVT;98VVT.PtrAddrSpace = AddrSpace;99100for (const auto &I : *this) {101MVT T = I.second.empty() ? MVT::Other : *I.second.begin();102VVT.getOrCreateTypeForMode(I.first, T);103}104return VVT;105}106107bool TypeSetByHwMode::isPossible() const {108for (const auto &I : *this)109if (!I.second.empty())110return true;111return false;112}113114bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {115bool Changed = false;116bool ContainsDefault = false;117MVT DT = MVT::Other;118119for (const auto &P : VVT) {120unsigned M = P.first;121// Make sure there exists a set for each specific mode from VVT.122Changed |= getOrCreate(M).insert(P.second).second;123// Cache VVT's default mode.124if (DefaultMode == M) {125ContainsDefault = true;126DT = P.second;127}128}129130// If VVT has a default mode, add the corresponding type to all131// modes in "this" that do not exist in VVT.132if (ContainsDefault)133for (auto &I : *this)134if (!VVT.hasMode(I.first))135Changed |= I.second.insert(DT).second;136137return Changed;138}139140// Constrain the type set to be the intersection with VTS.141bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {142bool Changed = false;143if (hasDefault()) {144for (const auto &I : VTS) {145unsigned M = I.first;146if (M == DefaultMode || hasMode(M))147continue;148Map.insert({M, Map.at(DefaultMode)});149Changed = true;150}151}152153for (auto &I : *this) {154unsigned M = I.first;155SetType &S = I.second;156if (VTS.hasMode(M) || VTS.hasDefault()) {157Changed |= intersect(I.second, VTS.get(M));158} else if (!S.empty()) {159S.clear();160Changed = true;161}162}163return Changed;164}165166template <typename Predicate> bool TypeSetByHwMode::constrain(Predicate P) {167bool Changed = false;168for (auto &I : *this)169Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });170return Changed;171}172173template <typename Predicate>174bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {175assert(empty());176for (const auto &I : VTS) {177SetType &S = getOrCreate(I.first);178for (auto J : I.second)179if (P(J))180S.insert(J);181}182return !empty();183}184185void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {186SmallVector<unsigned, 4> Modes;187Modes.reserve(Map.size());188189for (const auto &I : *this)190Modes.push_back(I.first);191if (Modes.empty()) {192OS << "{}";193return;194}195array_pod_sort(Modes.begin(), Modes.end());196197OS << '{';198for (unsigned M : Modes) {199OS << ' ' << getModeName(M) << ':';200get(M).writeToStream(OS);201}202OS << " }";203}204205bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {206// The isSimple call is much quicker than hasDefault - check this first.207bool IsSimple = isSimple();208bool VTSIsSimple = VTS.isSimple();209if (IsSimple && VTSIsSimple)210return getSimple() == VTS.getSimple();211212// Speedup: We have a default if the set is simple.213bool HaveDefault = IsSimple || hasDefault();214bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();215if (HaveDefault != VTSHaveDefault)216return false;217218SmallSet<unsigned, 4> Modes;219for (auto &I : *this)220Modes.insert(I.first);221for (const auto &I : VTS)222Modes.insert(I.first);223224if (HaveDefault) {225// Both sets have default mode.226for (unsigned M : Modes) {227if (get(M) != VTS.get(M))228return false;229}230} else {231// Neither set has default mode.232for (unsigned M : Modes) {233// If there is no default mode, an empty set is equivalent to not having234// the corresponding mode.235bool NoModeThis = !hasMode(M) || get(M).empty();236bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();237if (NoModeThis != NoModeVTS)238return false;239if (!NoModeThis)240if (get(M) != VTS.get(M))241return false;242}243}244245return true;246}247248namespace llvm {249raw_ostream &operator<<(raw_ostream &OS, const MachineValueTypeSet &T) {250T.writeToStream(OS);251return OS;252}253raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {254T.writeToStream(OS);255return OS;256}257} // namespace llvm258259LLVM_DUMP_METHOD260void TypeSetByHwMode::dump() const { dbgs() << *this << '\n'; }261262bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {263auto IntersectP = [&](std::optional<MVT> WildVT, function_ref<bool(MVT)> P) {264// Complement of In within this partition.265auto CompIn = [&](MVT T) -> bool { return !In.count(T) && P(T); };266267if (!WildVT)268return berase_if(Out, CompIn);269270bool OutW = Out.count(*WildVT), InW = In.count(*WildVT);271if (OutW == InW)272return berase_if(Out, CompIn);273274// Compute the intersection of scalars separately to account for only one275// set containing WildVT.276// The intersection of WildVT with a set of corresponding types that does277// not include WildVT will result in the most specific type:278// - WildVT is more specific than any set with two elements or more279// - WildVT is less specific than any single type.280// For example, for iPTR and scalar integer types281// { iPTR } * { i32 } -> { i32 }282// { iPTR } * { i32 i64 } -> { iPTR }283// and284// { iPTR i32 } * { i32 } -> { i32 }285// { iPTR i32 } * { i32 i64 } -> { i32 i64 }286// { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }287288// Looking at just this partition, let In' = elements only in In,289// Out' = elements only in Out, and IO = elements common to both. Normally290// IO would be returned as the result of the intersection, but we need to291// account for WildVT being a "wildcard" of sorts. Since elements in IO are292// those that match both sets exactly, they will all belong to the output.293// If any of the "leftovers" (i.e. In' or Out') contain WildVT, it means294// that the other set doesn't have it, but it could have (1) a more295// specific type, or (2) a set of types that is less specific. The296// "leftovers" from the other set is what we want to examine more closely.297298auto Leftovers = [&](const SetType &A, const SetType &B) {299SetType Diff = A;300berase_if(Diff, [&](MVT T) { return B.count(T) || !P(T); });301return Diff;302};303304if (InW) {305SetType OutLeftovers = Leftovers(Out, In);306if (OutLeftovers.size() < 2) {307// WildVT not added to Out. Keep the possible single leftover.308return false;309}310// WildVT replaces the leftovers.311berase_if(Out, CompIn);312Out.insert(*WildVT);313return true;314}315316// OutW == true317SetType InLeftovers = Leftovers(In, Out);318unsigned SizeOut = Out.size();319berase_if(Out, CompIn); // This will remove at least the WildVT.320if (InLeftovers.size() < 2) {321// WildVT deleted from Out. Add back the possible single leftover.322Out.insert(InLeftovers);323return true;324}325326// Keep the WildVT in Out.327Out.insert(*WildVT);328// If WildVT was the only element initially removed from Out, then Out329// has not changed.330return SizeOut != Out.size();331};332333// Note: must be non-overlapping334using WildPartT = std::pair<MVT, std::function<bool(MVT)>>;335static const WildPartT WildParts[] = {336{MVT::iPTR, [](MVT T) { return T.isScalarInteger() || T == MVT::iPTR; }},337};338339bool Changed = false;340for (const auto &I : WildParts)341Changed |= IntersectP(I.first, I.second);342343Changed |= IntersectP(std::nullopt, [&](MVT T) {344return !any_of(WildParts, [=](const WildPartT &I) { return I.second(T); });345});346347return Changed;348}349350bool TypeSetByHwMode::validate() const {351if (empty())352return true;353bool AllEmpty = true;354for (const auto &I : *this)355AllEmpty &= I.second.empty();356return !AllEmpty;357}358359// --- TypeInfer360361bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,362const TypeSetByHwMode &In) const {363ValidateOnExit _1(Out, *this);364In.validate();365if (In.empty() || Out == In || TP.hasError())366return false;367if (Out.empty()) {368Out = In;369return true;370}371372bool Changed = Out.constrain(In);373if (Changed && Out.empty())374TP.error("Type contradiction");375376return Changed;377}378379bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {380ValidateOnExit _1(Out, *this);381if (TP.hasError())382return false;383assert(!Out.empty() && "cannot pick from an empty set");384385bool Changed = false;386for (auto &I : Out) {387TypeSetByHwMode::SetType &S = I.second;388if (S.size() <= 1)389continue;390MVT T = *S.begin(); // Pick the first element.391S.clear();392S.insert(T);393Changed = true;394}395return Changed;396}397398bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {399ValidateOnExit _1(Out, *this);400if (TP.hasError())401return false;402if (!Out.empty())403return Out.constrain(isIntegerOrPtr);404405return Out.assign_if(getLegalTypes(), isIntegerOrPtr);406}407408bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {409ValidateOnExit _1(Out, *this);410if (TP.hasError())411return false;412if (!Out.empty())413return Out.constrain(isFloatingPoint);414415return Out.assign_if(getLegalTypes(), isFloatingPoint);416}417418bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {419ValidateOnExit _1(Out, *this);420if (TP.hasError())421return false;422if (!Out.empty())423return Out.constrain(isScalar);424425return Out.assign_if(getLegalTypes(), isScalar);426}427428bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {429ValidateOnExit _1(Out, *this);430if (TP.hasError())431return false;432if (!Out.empty())433return Out.constrain(isVector);434435return Out.assign_if(getLegalTypes(), isVector);436}437438bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {439ValidateOnExit _1(Out, *this);440if (TP.hasError() || !Out.empty())441return false;442443Out = getLegalTypes();444return true;445}446447template <typename Iter, typename Pred, typename Less>448static Iter min_if(Iter B, Iter E, Pred P, Less L) {449if (B == E)450return E;451Iter Min = E;452for (Iter I = B; I != E; ++I) {453if (!P(*I))454continue;455if (Min == E || L(*I, *Min))456Min = I;457}458return Min;459}460461template <typename Iter, typename Pred, typename Less>462static Iter max_if(Iter B, Iter E, Pred P, Less L) {463if (B == E)464return E;465Iter Max = E;466for (Iter I = B; I != E; ++I) {467if (!P(*I))468continue;469if (Max == E || L(*Max, *I))470Max = I;471}472return Max;473}474475/// Make sure that for each type in Small, there exists a larger type in Big.476bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small, TypeSetByHwMode &Big,477bool SmallIsVT) {478ValidateOnExit _1(Small, *this), _2(Big, *this);479if (TP.hasError())480return false;481bool Changed = false;482483assert((!SmallIsVT || !Small.empty()) &&484"Small should not be empty for SDTCisVTSmallerThanOp");485486if (Small.empty())487Changed |= EnforceAny(Small);488if (Big.empty())489Changed |= EnforceAny(Big);490491assert(Small.hasDefault() && Big.hasDefault());492493SmallVector<unsigned, 4> Modes;494union_modes(Small, Big, Modes);495496// 1. Only allow integer or floating point types and make sure that497// both sides are both integer or both floating point.498// 2. Make sure that either both sides have vector types, or neither499// of them does.500for (unsigned M : Modes) {501TypeSetByHwMode::SetType &S = Small.get(M);502TypeSetByHwMode::SetType &B = Big.get(M);503504assert((!SmallIsVT || !S.empty()) && "Expected non-empty type");505506if (any_of(S, isIntegerOrPtr) && any_of(B, isIntegerOrPtr)) {507auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };508Changed |= berase_if(S, NotInt);509Changed |= berase_if(B, NotInt);510} else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {511auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };512Changed |= berase_if(S, NotFP);513Changed |= berase_if(B, NotFP);514} else if (SmallIsVT && B.empty()) {515// B is empty and since S is a specific VT, it will never be empty. Don't516// report this as a change, just clear S and continue. This prevents an517// infinite loop.518S.clear();519} else if (S.empty() || B.empty()) {520Changed = !S.empty() || !B.empty();521S.clear();522B.clear();523} else {524TP.error("Incompatible types");525return Changed;526}527528if (none_of(S, isVector) || none_of(B, isVector)) {529Changed |= berase_if(S, isVector);530Changed |= berase_if(B, isVector);531}532}533534auto LT = [](MVT A, MVT B) -> bool {535// Always treat non-scalable MVTs as smaller than scalable MVTs for the536// purposes of ordering.537auto ASize = std::tuple(A.isScalableVector(), A.getScalarSizeInBits(),538A.getSizeInBits().getKnownMinValue());539auto BSize = std::tuple(B.isScalableVector(), B.getScalarSizeInBits(),540B.getSizeInBits().getKnownMinValue());541return ASize < BSize;542};543auto SameKindLE = [](MVT A, MVT B) -> bool {544// This function is used when removing elements: when a vector is compared545// to a non-vector or a scalable vector to any non-scalable MVT, it should546// return false (to avoid removal).547if (std::tuple(A.isVector(), A.isScalableVector()) !=548std::tuple(B.isVector(), B.isScalableVector()))549return false;550551return std::tuple(A.getScalarSizeInBits(),552A.getSizeInBits().getKnownMinValue()) <=553std::tuple(B.getScalarSizeInBits(),554B.getSizeInBits().getKnownMinValue());555};556557for (unsigned M : Modes) {558TypeSetByHwMode::SetType &S = Small.get(M);559TypeSetByHwMode::SetType &B = Big.get(M);560// MinS = min scalar in Small, remove all scalars from Big that are561// smaller-or-equal than MinS.562auto MinS = min_if(S.begin(), S.end(), isScalar, LT);563if (MinS != S.end())564Changed |=565berase_if(B, std::bind(SameKindLE, std::placeholders::_1, *MinS));566567// MaxS = max scalar in Big, remove all scalars from Small that are568// larger than MaxS.569auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);570if (MaxS != B.end())571Changed |=572berase_if(S, std::bind(SameKindLE, *MaxS, std::placeholders::_1));573574// MinV = min vector in Small, remove all vectors from Big that are575// smaller-or-equal than MinV.576auto MinV = min_if(S.begin(), S.end(), isVector, LT);577if (MinV != S.end())578Changed |=579berase_if(B, std::bind(SameKindLE, std::placeholders::_1, *MinV));580581// MaxV = max vector in Big, remove all vectors from Small that are582// larger than MaxV.583auto MaxV = max_if(B.begin(), B.end(), isVector, LT);584if (MaxV != B.end())585Changed |=586berase_if(S, std::bind(SameKindLE, *MaxV, std::placeholders::_1));587}588589return Changed;590}591592/// 1. Ensure that for each type T in Vec, T is a vector type, and that593/// for each type U in Elem, U is a scalar type.594/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)595/// type T in Vec, such that U is the element type of T.596bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,597TypeSetByHwMode &Elem) {598ValidateOnExit _1(Vec, *this), _2(Elem, *this);599if (TP.hasError())600return false;601bool Changed = false;602603if (Vec.empty())604Changed |= EnforceVector(Vec);605if (Elem.empty())606Changed |= EnforceScalar(Elem);607608SmallVector<unsigned, 4> Modes;609union_modes(Vec, Elem, Modes);610for (unsigned M : Modes) {611TypeSetByHwMode::SetType &V = Vec.get(M);612TypeSetByHwMode::SetType &E = Elem.get(M);613614Changed |= berase_if(V, isScalar); // Scalar = !vector615Changed |= berase_if(E, isVector); // Vector = !scalar616assert(!V.empty() && !E.empty());617618MachineValueTypeSet VT, ST;619// Collect element types from the "vector" set.620for (MVT T : V)621VT.insert(T.getVectorElementType());622// Collect scalar types from the "element" set.623for (MVT T : E)624ST.insert(T);625626// Remove from V all (vector) types whose element type is not in S.627Changed |= berase_if(V, [&ST](MVT T) -> bool {628return !ST.count(T.getVectorElementType());629});630// Remove from E all (scalar) types, for which there is no corresponding631// type in V.632Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });633}634635return Changed;636}637638bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,639const ValueTypeByHwMode &VVT) {640TypeSetByHwMode Tmp(VVT);641ValidateOnExit _1(Vec, *this), _2(Tmp, *this);642return EnforceVectorEltTypeIs(Vec, Tmp);643}644645/// Ensure that for each type T in Sub, T is a vector type, and there646/// exists a type U in Vec such that U is a vector type with the same647/// element type as T and at least as many elements as T.648bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,649TypeSetByHwMode &Sub) {650ValidateOnExit _1(Vec, *this), _2(Sub, *this);651if (TP.hasError())652return false;653654/// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.655auto IsSubVec = [](MVT B, MVT P) -> bool {656if (!B.isVector() || !P.isVector())657return false;658// Logically a <4 x i32> is a valid subvector of <n x 4 x i32>659// but until there are obvious use-cases for this, keep the660// types separate.661if (B.isScalableVector() != P.isScalableVector())662return false;663if (B.getVectorElementType() != P.getVectorElementType())664return false;665return B.getVectorMinNumElements() < P.getVectorMinNumElements();666};667668/// Return true if S has no element (vector type) that T is a sub-vector of,669/// i.e. has the same element type as T and more elements.670auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {671for (auto I : S)672if (IsSubVec(T, I))673return false;674return true;675};676677/// Return true if S has no element (vector type) that T is a super-vector678/// of, i.e. has the same element type as T and fewer elements.679auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {680for (auto I : S)681if (IsSubVec(I, T))682return false;683return true;684};685686bool Changed = false;687688if (Vec.empty())689Changed |= EnforceVector(Vec);690if (Sub.empty())691Changed |= EnforceVector(Sub);692693SmallVector<unsigned, 4> Modes;694union_modes(Vec, Sub, Modes);695for (unsigned M : Modes) {696TypeSetByHwMode::SetType &S = Sub.get(M);697TypeSetByHwMode::SetType &V = Vec.get(M);698699Changed |= berase_if(S, isScalar);700701// Erase all types from S that are not sub-vectors of a type in V.702Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));703704// Erase all types from V that are not super-vectors of a type in S.705Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));706}707708return Changed;709}710711/// 1. Ensure that V has a scalar type iff W has a scalar type.712/// 2. Ensure that for each vector type T in V, there exists a vector713/// type U in W, such that T and U have the same number of elements.714/// 3. Ensure that for each vector type U in W, there exists a vector715/// type T in V, such that T and U have the same number of elements716/// (reverse of 2).717bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {718ValidateOnExit _1(V, *this), _2(W, *this);719if (TP.hasError())720return false;721722bool Changed = false;723if (V.empty())724Changed |= EnforceAny(V);725if (W.empty())726Changed |= EnforceAny(W);727728// An actual vector type cannot have 0 elements, so we can treat scalars729// as zero-length vectors. This way both vectors and scalars can be730// processed identically.731auto NoLength = [](const SmallDenseSet<ElementCount> &Lengths,732MVT T) -> bool {733return !Lengths.count(T.isVector() ? T.getVectorElementCount()734: ElementCount());735};736737SmallVector<unsigned, 4> Modes;738union_modes(V, W, Modes);739for (unsigned M : Modes) {740TypeSetByHwMode::SetType &VS = V.get(M);741TypeSetByHwMode::SetType &WS = W.get(M);742743SmallDenseSet<ElementCount> VN, WN;744for (MVT T : VS)745VN.insert(T.isVector() ? T.getVectorElementCount() : ElementCount());746for (MVT T : WS)747WN.insert(T.isVector() ? T.getVectorElementCount() : ElementCount());748749Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));750Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));751}752return Changed;753}754755namespace {756struct TypeSizeComparator {757bool operator()(const TypeSize &LHS, const TypeSize &RHS) const {758return std::tuple(LHS.isScalable(), LHS.getKnownMinValue()) <759std::tuple(RHS.isScalable(), RHS.getKnownMinValue());760}761};762} // end anonymous namespace763764/// 1. Ensure that for each type T in A, there exists a type U in B,765/// such that T and U have equal size in bits.766/// 2. Ensure that for each type U in B, there exists a type T in A767/// such that T and U have equal size in bits (reverse of 1).768bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {769ValidateOnExit _1(A, *this), _2(B, *this);770if (TP.hasError())771return false;772bool Changed = false;773if (A.empty())774Changed |= EnforceAny(A);775if (B.empty())776Changed |= EnforceAny(B);777778typedef SmallSet<TypeSize, 2, TypeSizeComparator> TypeSizeSet;779780auto NoSize = [](const TypeSizeSet &Sizes, MVT T) -> bool {781return !Sizes.count(T.getSizeInBits());782};783784SmallVector<unsigned, 4> Modes;785union_modes(A, B, Modes);786for (unsigned M : Modes) {787TypeSetByHwMode::SetType &AS = A.get(M);788TypeSetByHwMode::SetType &BS = B.get(M);789TypeSizeSet AN, BN;790791for (MVT T : AS)792AN.insert(T.getSizeInBits());793for (MVT T : BS)794BN.insert(T.getSizeInBits());795796Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));797Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));798}799800return Changed;801}802803void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) const {804ValidateOnExit _1(VTS, *this);805const TypeSetByHwMode &Legal = getLegalTypes();806assert(Legal.isSimple() && "Default-mode only expected");807const TypeSetByHwMode::SetType &LegalTypes = Legal.getSimple();808809for (auto &I : VTS)810expandOverloads(I.second, LegalTypes);811}812813void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,814const TypeSetByHwMode::SetType &Legal) const {815if (Out.count(MVT::iPTRAny)) {816Out.erase(MVT::iPTRAny);817Out.insert(MVT::iPTR);818} else if (Out.count(MVT::iAny)) {819Out.erase(MVT::iAny);820for (MVT T : MVT::integer_valuetypes())821if (Legal.count(T))822Out.insert(T);823for (MVT T : MVT::integer_fixedlen_vector_valuetypes())824if (Legal.count(T))825Out.insert(T);826for (MVT T : MVT::integer_scalable_vector_valuetypes())827if (Legal.count(T))828Out.insert(T);829} else if (Out.count(MVT::fAny)) {830Out.erase(MVT::fAny);831for (MVT T : MVT::fp_valuetypes())832if (Legal.count(T))833Out.insert(T);834for (MVT T : MVT::fp_fixedlen_vector_valuetypes())835if (Legal.count(T))836Out.insert(T);837for (MVT T : MVT::fp_scalable_vector_valuetypes())838if (Legal.count(T))839Out.insert(T);840} else if (Out.count(MVT::vAny)) {841Out.erase(MVT::vAny);842for (MVT T : MVT::vector_valuetypes())843if (Legal.count(T))844Out.insert(T);845} else if (Out.count(MVT::Any)) {846Out.erase(MVT::Any);847for (MVT T : MVT::all_valuetypes())848if (Legal.count(T))849Out.insert(T);850}851}852853const TypeSetByHwMode &TypeInfer::getLegalTypes() const {854if (!LegalTypesCached) {855TypeSetByHwMode::SetType &LegalTypes = LegalCache.getOrCreate(DefaultMode);856// Stuff all types from all modes into the default mode.857const TypeSetByHwMode <S = TP.getDAGPatterns().getLegalTypes();858for (const auto &I : LTS)859LegalTypes.insert(I.second);860LegalTypesCached = true;861}862assert(LegalCache.isSimple() && "Default-mode only expected");863return LegalCache;864}865866TypeInfer::ValidateOnExit::~ValidateOnExit() {867if (Infer.Validate && !VTS.validate()) {868#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)869errs() << "Type set is empty for each HW mode:\n"870"possible type contradiction in the pattern below "871"(use -print-records with llvm-tblgen to see all "872"expanded records).\n";873Infer.TP.dump();874errs() << "Generated from record:\n";875Infer.TP.getRecord()->dump();876#endif877PrintFatalError(Infer.TP.getRecord()->getLoc(),878"Type set is empty for each HW mode in '" +879Infer.TP.getRecord()->getName() + "'");880}881}882883//===----------------------------------------------------------------------===//884// ScopedName Implementation885//===----------------------------------------------------------------------===//886887bool ScopedName::operator==(const ScopedName &o) const {888return Scope == o.Scope && Identifier == o.Identifier;889}890891bool ScopedName::operator!=(const ScopedName &o) const { return !(*this == o); }892893//===----------------------------------------------------------------------===//894// TreePredicateFn Implementation895//===----------------------------------------------------------------------===//896897/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.898TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {899assert(900(!hasPredCode() || !hasImmCode()) &&901".td file corrupt: can't have a node predicate *and* an imm predicate");902}903904bool TreePredicateFn::hasPredCode() const {905return isLoad() || isStore() || isAtomic() || hasNoUse() || hasOneUse() ||906!PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();907}908909std::string TreePredicateFn::getPredCode() const {910std::string Code;911912if (!isLoad() && !isStore() && !isAtomic()) {913Record *MemoryVT = getMemoryVT();914915if (MemoryVT)916PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),917"MemoryVT requires IsLoad or IsStore");918}919920if (!isLoad() && !isStore()) {921if (isUnindexed())922PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),923"IsUnindexed requires IsLoad or IsStore");924925Record *ScalarMemoryVT = getScalarMemoryVT();926927if (ScalarMemoryVT)928PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),929"ScalarMemoryVT requires IsLoad or IsStore");930}931932if (isLoad() + isStore() + isAtomic() > 1)933PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),934"IsLoad, IsStore, and IsAtomic are mutually exclusive");935936if (isLoad()) {937if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&938!isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&939getScalarMemoryVT() == nullptr && getAddressSpaces() == nullptr &&940getMinAlignment() < 1)941PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),942"IsLoad cannot be used by itself");943} else {944if (isNonExtLoad())945PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),946"IsNonExtLoad requires IsLoad");947if (isAnyExtLoad())948PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),949"IsAnyExtLoad requires IsLoad");950951if (!isAtomic()) {952if (isSignExtLoad())953PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),954"IsSignExtLoad requires IsLoad or IsAtomic");955if (isZeroExtLoad())956PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),957"IsZeroExtLoad requires IsLoad or IsAtomic");958}959}960961if (isStore()) {962if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&963getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr &&964getAddressSpaces() == nullptr && getMinAlignment() < 1)965PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),966"IsStore cannot be used by itself");967} else {968if (isNonTruncStore())969PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),970"IsNonTruncStore requires IsStore");971if (isTruncStore())972PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),973"IsTruncStore requires IsStore");974}975976if (isAtomic()) {977if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&978getAddressSpaces() == nullptr &&979// FIXME: Should atomic loads be IsLoad, IsAtomic, or both?980!isZeroExtLoad() && !isSignExtLoad() && !isAtomicOrderingAcquire() &&981!isAtomicOrderingRelease() && !isAtomicOrderingAcquireRelease() &&982!isAtomicOrderingSequentiallyConsistent() &&983!isAtomicOrderingAcquireOrStronger() &&984!isAtomicOrderingReleaseOrStronger() &&985!isAtomicOrderingWeakerThanAcquire() &&986!isAtomicOrderingWeakerThanRelease())987PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),988"IsAtomic cannot be used by itself");989} else {990if (isAtomicOrderingMonotonic())991PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),992"IsAtomicOrderingMonotonic requires IsAtomic");993if (isAtomicOrderingAcquire())994PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),995"IsAtomicOrderingAcquire requires IsAtomic");996if (isAtomicOrderingRelease())997PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),998"IsAtomicOrderingRelease requires IsAtomic");999if (isAtomicOrderingAcquireRelease())1000PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),1001"IsAtomicOrderingAcquireRelease requires IsAtomic");1002if (isAtomicOrderingSequentiallyConsistent())1003PrintFatalError(1004getOrigPatFragRecord()->getRecord()->getLoc(),1005"IsAtomicOrderingSequentiallyConsistent requires IsAtomic");1006if (isAtomicOrderingAcquireOrStronger())1007PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),1008"IsAtomicOrderingAcquireOrStronger requires IsAtomic");1009if (isAtomicOrderingReleaseOrStronger())1010PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),1011"IsAtomicOrderingReleaseOrStronger requires IsAtomic");1012if (isAtomicOrderingWeakerThanAcquire())1013PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),1014"IsAtomicOrderingWeakerThanAcquire requires IsAtomic");1015}10161017if (isLoad() || isStore() || isAtomic()) {1018if (ListInit *AddressSpaces = getAddressSpaces()) {1019Code += "unsigned AddrSpace = cast<MemSDNode>(N)->getAddressSpace();\n"1020" if (";10211022ListSeparator LS(" && ");1023for (Init *Val : AddressSpaces->getValues()) {1024Code += LS;10251026IntInit *IntVal = dyn_cast<IntInit>(Val);1027if (!IntVal) {1028PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),1029"AddressSpaces element must be integer");1030}10311032Code += "AddrSpace != " + utostr(IntVal->getValue());1033}10341035Code += ")\nreturn false;\n";1036}10371038int64_t MinAlign = getMinAlignment();1039if (MinAlign > 0) {1040Code += "if (cast<MemSDNode>(N)->getAlign() < Align(";1041Code += utostr(MinAlign);1042Code += "))\nreturn false;\n";1043}10441045Record *MemoryVT = getMemoryVT();10461047if (MemoryVT)1048Code += ("if (cast<MemSDNode>(N)->getMemoryVT() != MVT::" +1049MemoryVT->getName() + ") return false;\n")1050.str();1051}10521053if (isAtomic() && isAtomicOrderingMonotonic())1054Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "1055"AtomicOrdering::Monotonic) return false;\n";1056if (isAtomic() && isAtomicOrderingAcquire())1057Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "1058"AtomicOrdering::Acquire) return false;\n";1059if (isAtomic() && isAtomicOrderingRelease())1060Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "1061"AtomicOrdering::Release) return false;\n";1062if (isAtomic() && isAtomicOrderingAcquireRelease())1063Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "1064"AtomicOrdering::AcquireRelease) return false;\n";1065if (isAtomic() && isAtomicOrderingSequentiallyConsistent())1066Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "1067"AtomicOrdering::SequentiallyConsistent) return false;\n";10681069if (isAtomic() && isAtomicOrderingAcquireOrStronger())1070Code +=1071"if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "1072"return false;\n";1073if (isAtomic() && isAtomicOrderingWeakerThanAcquire())1074Code +=1075"if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "1076"return false;\n";10771078if (isAtomic() && isAtomicOrderingReleaseOrStronger())1079Code +=1080"if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "1081"return false;\n";1082if (isAtomic() && isAtomicOrderingWeakerThanRelease())1083Code +=1084"if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "1085"return false;\n";10861087// TODO: Handle atomic sextload/zextload normally when ATOMIC_LOAD is removed.1088if (isAtomic() && (isZeroExtLoad() || isSignExtLoad()))1089Code += "return false;\n";10901091if (isLoad() || isStore()) {1092StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";10931094if (isUnindexed())1095Code += ("if (cast<" + SDNodeName +1096">(N)->getAddressingMode() != ISD::UNINDEXED) "1097"return false;\n")1098.str();10991100if (isLoad()) {1101if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +1102isZeroExtLoad()) > 1)1103PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),1104"IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "1105"IsZeroExtLoad are mutually exclusive");1106if (isNonExtLoad())1107Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "1108"ISD::NON_EXTLOAD) return false;\n";1109if (isAnyExtLoad())1110Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "1111"return false;\n";1112if (isSignExtLoad())1113Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "1114"return false;\n";1115if (isZeroExtLoad())1116Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "1117"return false;\n";1118} else {1119if ((isNonTruncStore() + isTruncStore()) > 1)1120PrintFatalError(1121getOrigPatFragRecord()->getRecord()->getLoc(),1122"IsNonTruncStore, and IsTruncStore are mutually exclusive");1123if (isNonTruncStore())1124Code +=1125" if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";1126if (isTruncStore())1127Code +=1128" if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";1129}11301131Record *ScalarMemoryVT = getScalarMemoryVT();11321133if (ScalarMemoryVT)1134Code += ("if (cast<" + SDNodeName +1135">(N)->getMemoryVT().getScalarType() != MVT::" +1136ScalarMemoryVT->getName() + ") return false;\n")1137.str();1138}11391140if (hasNoUse())1141Code += "if (!SDValue(N, 0).use_empty()) return false;\n";1142if (hasOneUse())1143Code += "if (!SDValue(N, 0).hasOneUse()) return false;\n";11441145std::string PredicateCode =1146std::string(PatFragRec->getRecord()->getValueAsString("PredicateCode"));11471148Code += PredicateCode;11491150if (PredicateCode.empty() && !Code.empty())1151Code += "return true;\n";11521153return Code;1154}11551156bool TreePredicateFn::hasImmCode() const {1157return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();1158}11591160std::string TreePredicateFn::getImmCode() const {1161return std::string(1162PatFragRec->getRecord()->getValueAsString("ImmediateCode"));1163}11641165bool TreePredicateFn::immCodeUsesAPInt() const {1166return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");1167}11681169bool TreePredicateFn::immCodeUsesAPFloat() const {1170bool Unset;1171// The return value will be false when IsAPFloat is unset.1172return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",1173Unset);1174}11751176bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,1177bool Value) const {1178bool Unset;1179bool Result =1180getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);1181if (Unset)1182return false;1183return Result == Value;1184}1185bool TreePredicateFn::usesOperands() const {1186return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);1187}1188bool TreePredicateFn::hasNoUse() const {1189return isPredefinedPredicateEqualTo("HasNoUse", true);1190}1191bool TreePredicateFn::hasOneUse() const {1192return isPredefinedPredicateEqualTo("HasOneUse", true);1193}1194bool TreePredicateFn::isLoad() const {1195return isPredefinedPredicateEqualTo("IsLoad", true);1196}1197bool TreePredicateFn::isStore() const {1198return isPredefinedPredicateEqualTo("IsStore", true);1199}1200bool TreePredicateFn::isAtomic() const {1201return isPredefinedPredicateEqualTo("IsAtomic", true);1202}1203bool TreePredicateFn::isUnindexed() const {1204return isPredefinedPredicateEqualTo("IsUnindexed", true);1205}1206bool TreePredicateFn::isNonExtLoad() const {1207return isPredefinedPredicateEqualTo("IsNonExtLoad", true);1208}1209bool TreePredicateFn::isAnyExtLoad() const {1210return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);1211}1212bool TreePredicateFn::isSignExtLoad() const {1213return isPredefinedPredicateEqualTo("IsSignExtLoad", true);1214}1215bool TreePredicateFn::isZeroExtLoad() const {1216return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);1217}1218bool TreePredicateFn::isNonTruncStore() const {1219return isPredefinedPredicateEqualTo("IsTruncStore", false);1220}1221bool TreePredicateFn::isTruncStore() const {1222return isPredefinedPredicateEqualTo("IsTruncStore", true);1223}1224bool TreePredicateFn::isAtomicOrderingMonotonic() const {1225return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);1226}1227bool TreePredicateFn::isAtomicOrderingAcquire() const {1228return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);1229}1230bool TreePredicateFn::isAtomicOrderingRelease() const {1231return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);1232}1233bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {1234return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);1235}1236bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {1237return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",1238true);1239}1240bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {1241return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger",1242true);1243}1244bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {1245return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger",1246false);1247}1248bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {1249return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger",1250true);1251}1252bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {1253return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger",1254false);1255}1256Record *TreePredicateFn::getMemoryVT() const {1257Record *R = getOrigPatFragRecord()->getRecord();1258if (R->isValueUnset("MemoryVT"))1259return nullptr;1260return R->getValueAsDef("MemoryVT");1261}12621263ListInit *TreePredicateFn::getAddressSpaces() const {1264Record *R = getOrigPatFragRecord()->getRecord();1265if (R->isValueUnset("AddressSpaces"))1266return nullptr;1267return R->getValueAsListInit("AddressSpaces");1268}12691270int64_t TreePredicateFn::getMinAlignment() const {1271Record *R = getOrigPatFragRecord()->getRecord();1272if (R->isValueUnset("MinAlignment"))1273return 0;1274return R->getValueAsInt("MinAlignment");1275}12761277Record *TreePredicateFn::getScalarMemoryVT() const {1278Record *R = getOrigPatFragRecord()->getRecord();1279if (R->isValueUnset("ScalarMemoryVT"))1280return nullptr;1281return R->getValueAsDef("ScalarMemoryVT");1282}1283bool TreePredicateFn::hasGISelPredicateCode() const {1284return !PatFragRec->getRecord()1285->getValueAsString("GISelPredicateCode")1286.empty();1287}1288std::string TreePredicateFn::getGISelPredicateCode() const {1289return std::string(1290PatFragRec->getRecord()->getValueAsString("GISelPredicateCode"));1291}12921293StringRef TreePredicateFn::getImmType() const {1294if (immCodeUsesAPInt())1295return "const APInt &";1296if (immCodeUsesAPFloat())1297return "const APFloat &";1298return "int64_t";1299}13001301StringRef TreePredicateFn::getImmTypeIdentifier() const {1302if (immCodeUsesAPInt())1303return "APInt";1304if (immCodeUsesAPFloat())1305return "APFloat";1306return "I64";1307}13081309/// isAlwaysTrue - Return true if this is a noop predicate.1310bool TreePredicateFn::isAlwaysTrue() const {1311return !hasPredCode() && !hasImmCode();1312}13131314/// Return the name to use in the generated code to reference this, this is1315/// "Predicate_foo" if from a pattern fragment "foo".1316std::string TreePredicateFn::getFnName() const {1317return "Predicate_" + PatFragRec->getRecord()->getName().str();1318}13191320/// getCodeToRunOnSDNode - Return the code for the function body that1321/// evaluates this predicate. The argument is expected to be in "Node",1322/// not N. This handles casting and conversion to a concrete node type as1323/// appropriate.1324std::string TreePredicateFn::getCodeToRunOnSDNode() const {1325// Handle immediate predicates first.1326std::string ImmCode = getImmCode();1327if (!ImmCode.empty()) {1328if (isLoad())1329PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),1330"IsLoad cannot be used with ImmLeaf or its subclasses");1331if (isStore())1332PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),1333"IsStore cannot be used with ImmLeaf or its subclasses");1334if (isUnindexed())1335PrintFatalError(1336getOrigPatFragRecord()->getRecord()->getLoc(),1337"IsUnindexed cannot be used with ImmLeaf or its subclasses");1338if (isNonExtLoad())1339PrintFatalError(1340getOrigPatFragRecord()->getRecord()->getLoc(),1341"IsNonExtLoad cannot be used with ImmLeaf or its subclasses");1342if (isAnyExtLoad())1343PrintFatalError(1344getOrigPatFragRecord()->getRecord()->getLoc(),1345"IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");1346if (isSignExtLoad())1347PrintFatalError(1348getOrigPatFragRecord()->getRecord()->getLoc(),1349"IsSignExtLoad cannot be used with ImmLeaf or its subclasses");1350if (isZeroExtLoad())1351PrintFatalError(1352getOrigPatFragRecord()->getRecord()->getLoc(),1353"IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");1354if (isNonTruncStore())1355PrintFatalError(1356getOrigPatFragRecord()->getRecord()->getLoc(),1357"IsNonTruncStore cannot be used with ImmLeaf or its subclasses");1358if (isTruncStore())1359PrintFatalError(1360getOrigPatFragRecord()->getRecord()->getLoc(),1361"IsTruncStore cannot be used with ImmLeaf or its subclasses");1362if (getMemoryVT())1363PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),1364"MemoryVT cannot be used with ImmLeaf or its subclasses");1365if (getScalarMemoryVT())1366PrintFatalError(1367getOrigPatFragRecord()->getRecord()->getLoc(),1368"ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");13691370std::string Result = (" " + getImmType() + " Imm = ").str();1371if (immCodeUsesAPFloat())1372Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";1373else if (immCodeUsesAPInt())1374Result += "Node->getAsAPIntVal();\n";1375else1376Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";1377return Result + ImmCode;1378}13791380// Handle arbitrary node predicates.1381assert(hasPredCode() && "Don't have any predicate code!");13821383// If this is using PatFrags, there are multiple trees to search. They should1384// all have the same class. FIXME: Is there a way to find a common1385// superclass?1386StringRef ClassName;1387for (const auto &Tree : PatFragRec->getTrees()) {1388StringRef TreeClassName;1389if (Tree->isLeaf())1390TreeClassName = "SDNode";1391else {1392Record *Op = Tree->getOperator();1393const SDNodeInfo &Info = PatFragRec->getDAGPatterns().getSDNodeInfo(Op);1394TreeClassName = Info.getSDClassName();1395}13961397if (ClassName.empty())1398ClassName = TreeClassName;1399else if (ClassName != TreeClassName) {1400PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),1401"PatFrags trees do not have consistent class");1402}1403}14041405std::string Result;1406if (ClassName == "SDNode")1407Result = " SDNode *N = Node;\n";1408else1409Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";14101411return (Twine(Result) + " (void)N;\n" + getPredCode()).str();1412}14131414//===----------------------------------------------------------------------===//1415// PatternToMatch implementation1416//14171418static bool isImmAllOnesAllZerosMatch(const TreePatternNode &P) {1419if (!P.isLeaf())1420return false;1421DefInit *DI = dyn_cast<DefInit>(P.getLeafValue());1422if (!DI)1423return false;14241425Record *R = DI->getDef();1426return R->getName() == "immAllOnesV" || R->getName() == "immAllZerosV";1427}14281429/// getPatternSize - Return the 'size' of this pattern. We want to match large1430/// patterns before small ones. This is used to determine the size of a1431/// pattern.1432static unsigned getPatternSize(const TreePatternNode &P,1433const CodeGenDAGPatterns &CGP) {1434unsigned Size = 3; // The node itself.1435// If the root node is a ConstantSDNode, increases its size.1436// e.g. (set R32:$dst, 0).1437if (P.isLeaf() && isa<IntInit>(P.getLeafValue()))1438Size += 2;14391440if (const ComplexPattern *AM = P.getComplexPatternInfo(CGP)) {1441Size += AM->getComplexity();1442// We don't want to count any children twice, so return early.1443return Size;1444}14451446// If this node has some predicate function that must match, it adds to the1447// complexity of this node.1448if (!P.getPredicateCalls().empty())1449++Size;14501451// Count children in the count if they are also nodes.1452for (unsigned i = 0, e = P.getNumChildren(); i != e; ++i) {1453const TreePatternNode &Child = P.getChild(i);1454if (!Child.isLeaf() && Child.getNumTypes()) {1455const TypeSetByHwMode &T0 = Child.getExtType(0);1456// At this point, all variable type sets should be simple, i.e. only1457// have a default mode.1458if (T0.getMachineValueType() != MVT::Other) {1459Size += getPatternSize(Child, CGP);1460continue;1461}1462}1463if (Child.isLeaf()) {1464if (isa<IntInit>(Child.getLeafValue()))1465Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).1466else if (Child.getComplexPatternInfo(CGP))1467Size += getPatternSize(Child, CGP);1468else if (isImmAllOnesAllZerosMatch(Child))1469Size += 4; // Matches a build_vector(+3) and a predicate (+1).1470else if (!Child.getPredicateCalls().empty())1471++Size;1472}1473}14741475return Size;1476}14771478/// Compute the complexity metric for the input pattern. This roughly1479/// corresponds to the number of nodes that are covered.1480int PatternToMatch::getPatternComplexity(const CodeGenDAGPatterns &CGP) const {1481return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();1482}14831484void PatternToMatch::getPredicateRecords(1485SmallVectorImpl<Record *> &PredicateRecs) const {1486for (Init *I : Predicates->getValues()) {1487if (DefInit *Pred = dyn_cast<DefInit>(I)) {1488Record *Def = Pred->getDef();1489if (!Def->isSubClassOf("Predicate")) {1490#ifndef NDEBUG1491Def->dump();1492#endif1493llvm_unreachable("Unknown predicate type!");1494}1495PredicateRecs.push_back(Def);1496}1497}1498// Sort so that different orders get canonicalized to the same string.1499llvm::sort(PredicateRecs, LessRecord());1500// Remove duplicate predicates.1501PredicateRecs.erase(llvm::unique(PredicateRecs), PredicateRecs.end());1502}15031504/// getPredicateCheck - Return a single string containing all of this1505/// pattern's predicates concatenated with "&&" operators.1506///1507std::string PatternToMatch::getPredicateCheck() const {1508SmallVector<Record *, 4> PredicateRecs;1509getPredicateRecords(PredicateRecs);15101511SmallString<128> PredicateCheck;1512raw_svector_ostream OS(PredicateCheck);1513ListSeparator LS(" && ");1514for (Record *Pred : PredicateRecs) {1515StringRef CondString = Pred->getValueAsString("CondString");1516if (CondString.empty())1517continue;1518OS << LS << '(' << CondString << ')';1519}15201521if (!HwModeFeatures.empty())1522OS << LS << HwModeFeatures;15231524return std::string(PredicateCheck);1525}15261527//===----------------------------------------------------------------------===//1528// SDTypeConstraint implementation1529//15301531SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {1532OperandNo = R->getValueAsInt("OperandNum");15331534if (R->isSubClassOf("SDTCisVT")) {1535ConstraintType = SDTCisVT;1536VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);1537for (const auto &P : VVT)1538if (P.second == MVT::isVoid)1539PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");1540} else if (R->isSubClassOf("SDTCisPtrTy")) {1541ConstraintType = SDTCisPtrTy;1542} else if (R->isSubClassOf("SDTCisInt")) {1543ConstraintType = SDTCisInt;1544} else if (R->isSubClassOf("SDTCisFP")) {1545ConstraintType = SDTCisFP;1546} else if (R->isSubClassOf("SDTCisVec")) {1547ConstraintType = SDTCisVec;1548} else if (R->isSubClassOf("SDTCisSameAs")) {1549ConstraintType = SDTCisSameAs;1550x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");1551} else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {1552ConstraintType = SDTCisVTSmallerThanOp;1553x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =1554R->getValueAsInt("OtherOperandNum");1555} else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {1556ConstraintType = SDTCisOpSmallerThanOp;1557x.SDTCisOpSmallerThanOp_Info.BigOperandNum =1558R->getValueAsInt("BigOperandNum");1559} else if (R->isSubClassOf("SDTCisEltOfVec")) {1560ConstraintType = SDTCisEltOfVec;1561x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");1562} else if (R->isSubClassOf("SDTCisSubVecOfVec")) {1563ConstraintType = SDTCisSubVecOfVec;1564x.SDTCisSubVecOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");1565} else if (R->isSubClassOf("SDTCVecEltisVT")) {1566ConstraintType = SDTCVecEltisVT;1567VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);1568for (const auto &P : VVT) {1569MVT T = P.second;1570if (T.isVector())1571PrintFatalError(R->getLoc(),1572"Cannot use vector type as SDTCVecEltisVT");1573if (!T.isInteger() && !T.isFloatingPoint())1574PrintFatalError(R->getLoc(), "Must use integer or floating point type "1575"as SDTCVecEltisVT");1576}1577} else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {1578ConstraintType = SDTCisSameNumEltsAs;1579x.SDTCisSameNumEltsAs_Info.OtherOperandNum =1580R->getValueAsInt("OtherOperandNum");1581} else if (R->isSubClassOf("SDTCisSameSizeAs")) {1582ConstraintType = SDTCisSameSizeAs;1583x.SDTCisSameSizeAs_Info.OtherOperandNum =1584R->getValueAsInt("OtherOperandNum");1585} else {1586PrintFatalError(R->getLoc(),1587"Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");1588}1589}15901591/// getOperandNum - Return the node corresponding to operand #OpNo in tree1592/// N, and the result number in ResNo.1593static TreePatternNode &getOperandNum(unsigned OpNo, TreePatternNode &N,1594const SDNodeInfo &NodeInfo,1595unsigned &ResNo) {1596unsigned NumResults = NodeInfo.getNumResults();1597if (OpNo < NumResults) {1598ResNo = OpNo;1599return N;1600}16011602OpNo -= NumResults;16031604if (OpNo >= N.getNumChildren()) {1605std::string S;1606raw_string_ostream OS(S);1607OS << "Invalid operand number in type constraint " << (OpNo + NumResults)1608<< " ";1609N.print(OS);1610PrintFatalError(S);1611}16121613return N.getChild(OpNo);1614}16151616/// ApplyTypeConstraint - Given a node in a pattern, apply this type1617/// constraint to the nodes operands. This returns true if it makes a1618/// change, false otherwise. If a type contradiction is found, flag an error.1619bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode &N,1620const SDNodeInfo &NodeInfo,1621TreePattern &TP) const {1622if (TP.hasError())1623return false;16241625unsigned ResNo = 0; // The result number being referenced.1626TreePatternNode &NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);1627TypeInfer &TI = TP.getInfer();16281629switch (ConstraintType) {1630case SDTCisVT:1631// Operand must be a particular type.1632return NodeToApply.UpdateNodeType(ResNo, VVT, TP);1633case SDTCisPtrTy:1634// Operand must be same as target pointer type.1635return NodeToApply.UpdateNodeType(ResNo, MVT::iPTR, TP);1636case SDTCisInt:1637// Require it to be one of the legal integer VTs.1638return TI.EnforceInteger(NodeToApply.getExtType(ResNo));1639case SDTCisFP:1640// Require it to be one of the legal fp VTs.1641return TI.EnforceFloatingPoint(NodeToApply.getExtType(ResNo));1642case SDTCisVec:1643// Require it to be one of the legal vector VTs.1644return TI.EnforceVector(NodeToApply.getExtType(ResNo));1645case SDTCisSameAs: {1646unsigned OResNo = 0;1647TreePatternNode &OtherNode =1648getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);1649return (int)NodeToApply.UpdateNodeType(ResNo, OtherNode.getExtType(OResNo),1650TP) |1651(int)OtherNode.UpdateNodeType(OResNo, NodeToApply.getExtType(ResNo),1652TP);1653}1654case SDTCisVTSmallerThanOp: {1655// The NodeToApply must be a leaf node that is a VT. OtherOperandNum must1656// have an integer type that is smaller than the VT.1657if (!NodeToApply.isLeaf() || !isa<DefInit>(NodeToApply.getLeafValue()) ||1658!cast<DefInit>(NodeToApply.getLeafValue())1659->getDef()1660->isSubClassOf("ValueType")) {1661TP.error(N.getOperator()->getName() + " expects a VT operand!");1662return false;1663}1664DefInit *DI = cast<DefInit>(NodeToApply.getLeafValue());1665const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();1666auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());1667TypeSetByHwMode TypeListTmp(VVT);16681669unsigned OResNo = 0;1670TreePatternNode &OtherNode = getOperandNum(1671x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo, OResNo);16721673return TI.EnforceSmallerThan(TypeListTmp, OtherNode.getExtType(OResNo),1674/*SmallIsVT*/ true);1675}1676case SDTCisOpSmallerThanOp: {1677unsigned BResNo = 0;1678TreePatternNode &BigOperand = getOperandNum(1679x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo, BResNo);1680return TI.EnforceSmallerThan(NodeToApply.getExtType(ResNo),1681BigOperand.getExtType(BResNo));1682}1683case SDTCisEltOfVec: {1684unsigned VResNo = 0;1685TreePatternNode &VecOperand = getOperandNum(1686x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo, VResNo);1687// Filter vector types out of VecOperand that don't have the right element1688// type.1689return TI.EnforceVectorEltTypeIs(VecOperand.getExtType(VResNo),1690NodeToApply.getExtType(ResNo));1691}1692case SDTCisSubVecOfVec: {1693unsigned VResNo = 0;1694TreePatternNode &BigVecOperand = getOperandNum(1695x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo, VResNo);16961697// Filter vector types out of BigVecOperand that don't have the1698// right subvector type.1699return TI.EnforceVectorSubVectorTypeIs(BigVecOperand.getExtType(VResNo),1700NodeToApply.getExtType(ResNo));1701}1702case SDTCVecEltisVT: {1703return TI.EnforceVectorEltTypeIs(NodeToApply.getExtType(ResNo), VVT);1704}1705case SDTCisSameNumEltsAs: {1706unsigned OResNo = 0;1707TreePatternNode &OtherNode = getOperandNum(1708x.SDTCisSameNumEltsAs_Info.OtherOperandNum, N, NodeInfo, OResNo);1709return TI.EnforceSameNumElts(OtherNode.getExtType(OResNo),1710NodeToApply.getExtType(ResNo));1711}1712case SDTCisSameSizeAs: {1713unsigned OResNo = 0;1714TreePatternNode &OtherNode = getOperandNum(1715x.SDTCisSameSizeAs_Info.OtherOperandNum, N, NodeInfo, OResNo);1716return TI.EnforceSameSize(OtherNode.getExtType(OResNo),1717NodeToApply.getExtType(ResNo));1718}1719}1720llvm_unreachable("Invalid ConstraintType!");1721}17221723// Update the node type to match an instruction operand or result as specified1724// in the ins or outs lists on the instruction definition. Return true if the1725// type was actually changed.1726bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo, Record *Operand,1727TreePattern &TP) {1728// The 'unknown' operand indicates that types should be inferred from the1729// context.1730if (Operand->isSubClassOf("unknown_class"))1731return false;17321733// The Operand class specifies a type directly.1734if (Operand->isSubClassOf("Operand")) {1735Record *R = Operand->getValueAsDef("Type");1736const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();1737return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);1738}17391740// PointerLikeRegClass has a type that is determined at runtime.1741if (Operand->isSubClassOf("PointerLikeRegClass"))1742return UpdateNodeType(ResNo, MVT::iPTR, TP);17431744// Both RegisterClass and RegisterOperand operands derive their types from a1745// register class def.1746Record *RC = nullptr;1747if (Operand->isSubClassOf("RegisterClass"))1748RC = Operand;1749else if (Operand->isSubClassOf("RegisterOperand"))1750RC = Operand->getValueAsDef("RegClass");17511752assert(RC && "Unknown operand type");1753CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();1754return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);1755}17561757bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {1758for (unsigned i = 0, e = Types.size(); i != e; ++i)1759if (!TP.getInfer().isConcrete(Types[i], true))1760return true;1761for (unsigned i = 0, e = getNumChildren(); i != e; ++i)1762if (getChild(i).ContainsUnresolvedType(TP))1763return true;1764return false;1765}17661767bool TreePatternNode::hasProperTypeByHwMode() const {1768for (const TypeSetByHwMode &S : Types)1769if (!S.isSimple())1770return true;1771for (const TreePatternNodePtr &C : Children)1772if (C->hasProperTypeByHwMode())1773return true;1774return false;1775}17761777bool TreePatternNode::hasPossibleType() const {1778for (const TypeSetByHwMode &S : Types)1779if (!S.isPossible())1780return false;1781for (const TreePatternNodePtr &C : Children)1782if (!C->hasPossibleType())1783return false;1784return true;1785}17861787bool TreePatternNode::setDefaultMode(unsigned Mode) {1788for (TypeSetByHwMode &S : Types) {1789S.makeSimple(Mode);1790// Check if the selected mode had a type conflict.1791if (S.get(DefaultMode).empty())1792return false;1793}1794for (const TreePatternNodePtr &C : Children)1795if (!C->setDefaultMode(Mode))1796return false;1797return true;1798}17991800//===----------------------------------------------------------------------===//1801// SDNodeInfo implementation1802//1803SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {1804EnumName = R->getValueAsString("Opcode");1805SDClassName = R->getValueAsString("SDClass");1806Record *TypeProfile = R->getValueAsDef("TypeProfile");1807NumResults = TypeProfile->getValueAsInt("NumResults");1808NumOperands = TypeProfile->getValueAsInt("NumOperands");18091810// Parse the properties.1811Properties = parseSDPatternOperatorProperties(R);18121813// Parse the type constraints.1814std::vector<Record *> ConstraintList =1815TypeProfile->getValueAsListOfDefs("Constraints");1816for (Record *R : ConstraintList)1817TypeConstraints.emplace_back(R, CGH);1818}18191820/// getKnownType - If the type constraints on this node imply a fixed type1821/// (e.g. all stores return void, etc), then return it as an1822/// MVT::SimpleValueType. Otherwise, return EEVT::Other.1823MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {1824unsigned NumResults = getNumResults();1825assert(NumResults <= 1 &&1826"We only work with nodes with zero or one result so far!");1827assert(ResNo == 0 && "Only handles single result nodes so far");18281829for (const SDTypeConstraint &Constraint : TypeConstraints) {1830// Make sure that this applies to the correct node result.1831if (Constraint.OperandNo >= NumResults) // FIXME: need value #1832continue;18331834switch (Constraint.ConstraintType) {1835default:1836break;1837case SDTypeConstraint::SDTCisVT:1838if (Constraint.VVT.isSimple())1839return Constraint.VVT.getSimple().SimpleTy;1840break;1841case SDTypeConstraint::SDTCisPtrTy:1842return MVT::iPTR;1843}1844}1845return MVT::Other;1846}18471848//===----------------------------------------------------------------------===//1849// TreePatternNode implementation1850//18511852static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {1853if (Operator->getName() == "set" || Operator->getName() == "implicit")1854return 0; // All return nothing.18551856if (Operator->isSubClassOf("Intrinsic"))1857return CDP.getIntrinsic(Operator).IS.RetTys.size();18581859if (Operator->isSubClassOf("SDNode"))1860return CDP.getSDNodeInfo(Operator).getNumResults();18611862if (Operator->isSubClassOf("PatFrags")) {1863// If we've already parsed this pattern fragment, get it. Otherwise, handle1864// the forward reference case where one pattern fragment references another1865// before it is processed.1866if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {1867// The number of results of a fragment with alternative records is the1868// maximum number of results across all alternatives.1869unsigned NumResults = 0;1870for (const auto &T : PFRec->getTrees())1871NumResults = std::max(NumResults, T->getNumTypes());1872return NumResults;1873}18741875ListInit *LI = Operator->getValueAsListInit("Fragments");1876assert(LI && "Invalid Fragment");1877unsigned NumResults = 0;1878for (Init *I : LI->getValues()) {1879Record *Op = nullptr;1880if (DagInit *Dag = dyn_cast<DagInit>(I))1881if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))1882Op = DI->getDef();1883assert(Op && "Invalid Fragment");1884NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));1885}1886return NumResults;1887}18881889if (Operator->isSubClassOf("Instruction")) {1890CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);18911892unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;18931894// Subtract any defaulted outputs.1895for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {1896Record *OperandNode = InstInfo.Operands[i].Rec;18971898if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&1899!CDP.getDefaultOperand(OperandNode).DefaultOps.empty())1900--NumDefsToAdd;1901}19021903// Add on one implicit def if it has a resolvable type.1904if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=1905MVT::Other)1906++NumDefsToAdd;1907return NumDefsToAdd;1908}19091910if (Operator->isSubClassOf("SDNodeXForm"))1911return 1; // FIXME: Generalize SDNodeXForm19121913if (Operator->isSubClassOf("ValueType"))1914return 1; // A type-cast of one result.19151916if (Operator->isSubClassOf("ComplexPattern"))1917return 1;19181919errs() << *Operator;1920PrintFatalError("Unhandled node in GetNumNodeResults");1921}19221923void TreePatternNode::print(raw_ostream &OS) const {1924if (isLeaf())1925OS << *getLeafValue();1926else1927OS << '(' << getOperator()->getName();19281929for (unsigned i = 0, e = Types.size(); i != e; ++i) {1930OS << ':';1931getExtType(i).writeToStream(OS);1932}19331934if (!isLeaf()) {1935if (getNumChildren() != 0) {1936OS << " ";1937ListSeparator LS;1938for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {1939OS << LS;1940getChild(i).print(OS);1941}1942}1943OS << ")";1944}19451946for (const TreePredicateCall &Pred : PredicateCalls) {1947OS << "<<P:";1948if (Pred.Scope)1949OS << Pred.Scope << ":";1950OS << Pred.Fn.getFnName() << ">>";1951}1952if (TransformFn)1953OS << "<<X:" << TransformFn->getName() << ">>";1954if (!getName().empty())1955OS << ":$" << getName();19561957for (const ScopedName &Name : NamesAsPredicateArg)1958OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();1959}1960void TreePatternNode::dump() const { print(errs()); }19611962/// isIsomorphicTo - Return true if this node is recursively1963/// isomorphic to the specified node. For this comparison, the node's1964/// entire state is considered. The assigned name is ignored, since1965/// nodes with differing names are considered isomorphic. However, if1966/// the assigned name is present in the dependent variable set, then1967/// the assigned name is considered significant and the node is1968/// isomorphic if the names match.1969bool TreePatternNode::isIsomorphicTo(const TreePatternNode &N,1970const MultipleUseVarSet &DepVars) const {1971if (&N == this)1972return true;1973if (N.isLeaf() != isLeaf())1974return false;19751976// Check operator of non-leaves early since it can be cheaper than checking1977// types.1978if (!isLeaf())1979if (N.getOperator() != getOperator() ||1980N.getNumChildren() != getNumChildren())1981return false;19821983if (getExtTypes() != N.getExtTypes() ||1984getPredicateCalls() != N.getPredicateCalls() ||1985getTransformFn() != N.getTransformFn())1986return false;19871988if (isLeaf()) {1989if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {1990if (DefInit *NDI = dyn_cast<DefInit>(N.getLeafValue())) {1991return ((DI->getDef() == NDI->getDef()) &&1992(!DepVars.contains(getName()) || getName() == N.getName()));1993}1994}1995return getLeafValue() == N.getLeafValue();1996}19971998for (unsigned i = 0, e = getNumChildren(); i != e; ++i)1999if (!getChild(i).isIsomorphicTo(N.getChild(i), DepVars))2000return false;2001return true;2002}20032004/// clone - Make a copy of this tree and all of its children.2005///2006TreePatternNodePtr TreePatternNode::clone() const {2007TreePatternNodePtr New;2008if (isLeaf()) {2009New = makeIntrusiveRefCnt<TreePatternNode>(getLeafValue(), getNumTypes());2010} else {2011std::vector<TreePatternNodePtr> CChildren;2012CChildren.reserve(Children.size());2013for (unsigned i = 0, e = getNumChildren(); i != e; ++i)2014CChildren.push_back(getChild(i).clone());2015New = makeIntrusiveRefCnt<TreePatternNode>(2016getOperator(), std::move(CChildren), getNumTypes());2017}2018New->setName(getName());2019New->setNamesAsPredicateArg(getNamesAsPredicateArg());2020New->Types = Types;2021New->setPredicateCalls(getPredicateCalls());2022New->setGISelFlagsRecord(getGISelFlagsRecord());2023New->setTransformFn(getTransformFn());2024return New;2025}20262027/// RemoveAllTypes - Recursively strip all the types of this tree.2028void TreePatternNode::RemoveAllTypes() {2029// Reset to unknown type.2030std::fill(Types.begin(), Types.end(), TypeSetByHwMode());2031if (isLeaf())2032return;2033for (unsigned i = 0, e = getNumChildren(); i != e; ++i)2034getChild(i).RemoveAllTypes();2035}20362037/// SubstituteFormalArguments - Replace the formal arguments in this tree2038/// with actual values specified by ArgMap.2039void TreePatternNode::SubstituteFormalArguments(2040std::map<std::string, TreePatternNodePtr> &ArgMap) {2041if (isLeaf())2042return;20432044for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {2045TreePatternNode &Child = getChild(i);2046if (Child.isLeaf()) {2047Init *Val = Child.getLeafValue();2048// Note that, when substituting into an output pattern, Val might be an2049// UnsetInit.2050if (isa<UnsetInit>(Val) ||2051(isa<DefInit>(Val) &&2052cast<DefInit>(Val)->getDef()->getName() == "node")) {2053// We found a use of a formal argument, replace it with its value.2054TreePatternNodePtr NewChild = ArgMap[Child.getName()];2055assert(NewChild && "Couldn't find formal argument!");2056assert((Child.getPredicateCalls().empty() ||2057NewChild->getPredicateCalls() == Child.getPredicateCalls()) &&2058"Non-empty child predicate clobbered!");2059setChild(i, std::move(NewChild));2060}2061} else {2062getChild(i).SubstituteFormalArguments(ArgMap);2063}2064}2065}20662067/// InlinePatternFragments - If this pattern refers to any pattern2068/// fragments, return the set of inlined versions (this can be more than2069/// one if a PatFrags record has multiple alternatives).2070void TreePatternNode::InlinePatternFragments(2071TreePattern &TP, std::vector<TreePatternNodePtr> &OutAlternatives) {20722073if (TP.hasError())2074return;20752076if (isLeaf()) {2077OutAlternatives.push_back(this); // nothing to do.2078return;2079}20802081Record *Op = getOperator();20822083if (!Op->isSubClassOf("PatFrags")) {2084if (getNumChildren() == 0) {2085OutAlternatives.push_back(this);2086return;2087}20882089// Recursively inline children nodes.2090std::vector<std::vector<TreePatternNodePtr>> ChildAlternatives(2091getNumChildren());2092for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {2093TreePatternNodePtr Child = getChildShared(i);2094Child->InlinePatternFragments(TP, ChildAlternatives[i]);2095// If there are no alternatives for any child, there are no2096// alternatives for this expression as whole.2097if (ChildAlternatives[i].empty())2098return;20992100assert((Child->getPredicateCalls().empty() ||2101llvm::all_of(ChildAlternatives[i],2102[&](const TreePatternNodePtr &NewChild) {2103return NewChild->getPredicateCalls() ==2104Child->getPredicateCalls();2105})) &&2106"Non-empty child predicate clobbered!");2107}21082109// The end result is an all-pairs construction of the resultant pattern.2110std::vector<unsigned> Idxs(ChildAlternatives.size());2111bool NotDone;2112do {2113// Create the variant and add it to the output list.2114std::vector<TreePatternNodePtr> NewChildren;2115NewChildren.reserve(ChildAlternatives.size());2116for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)2117NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);2118TreePatternNodePtr R = makeIntrusiveRefCnt<TreePatternNode>(2119getOperator(), std::move(NewChildren), getNumTypes());21202121// Copy over properties.2122R->setName(getName());2123R->setNamesAsPredicateArg(getNamesAsPredicateArg());2124R->setPredicateCalls(getPredicateCalls());2125R->setGISelFlagsRecord(getGISelFlagsRecord());2126R->setTransformFn(getTransformFn());2127for (unsigned i = 0, e = getNumTypes(); i != e; ++i)2128R->setType(i, getExtType(i));2129for (unsigned i = 0, e = getNumResults(); i != e; ++i)2130R->setResultIndex(i, getResultIndex(i));21312132// Register alternative.2133OutAlternatives.push_back(R);21342135// Increment indices to the next permutation by incrementing the2136// indices from last index backward, e.g., generate the sequence2137// [0, 0], [0, 1], [1, 0], [1, 1].2138int IdxsIdx;2139for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {2140if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())2141Idxs[IdxsIdx] = 0;2142else2143break;2144}2145NotDone = (IdxsIdx >= 0);2146} while (NotDone);21472148return;2149}21502151// Otherwise, we found a reference to a fragment. First, look up its2152// TreePattern record.2153TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);21542155// Verify that we are passing the right number of operands.2156if (Frag->getNumArgs() != getNumChildren()) {2157TP.error("'" + Op->getName() + "' fragment requires " +2158Twine(Frag->getNumArgs()) + " operands!");2159return;2160}21612162TreePredicateFn PredFn(Frag);2163unsigned Scope = 0;2164if (TreePredicateFn(Frag).usesOperands())2165Scope = TP.getDAGPatterns().allocateScope();21662167// Compute the map of formal to actual arguments.2168std::map<std::string, TreePatternNodePtr> ArgMap;2169for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {2170TreePatternNodePtr Child = getChildShared(i);2171if (Scope != 0) {2172Child = Child->clone();2173Child->addNameAsPredicateArg(ScopedName(Scope, Frag->getArgName(i)));2174}2175ArgMap[Frag->getArgName(i)] = Child;2176}21772178// Loop over all fragment alternatives.2179for (const auto &Alternative : Frag->getTrees()) {2180TreePatternNodePtr FragTree = Alternative->clone();21812182if (!PredFn.isAlwaysTrue())2183FragTree->addPredicateCall(PredFn, Scope);21842185// Resolve formal arguments to their actual value.2186if (Frag->getNumArgs())2187FragTree->SubstituteFormalArguments(ArgMap);21882189// Transfer types. Note that the resolved alternative may have fewer2190// (but not more) results than the PatFrags node.2191FragTree->setName(getName());2192for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)2193FragTree->UpdateNodeType(i, getExtType(i), TP);21942195if (Op->isSubClassOf("GISelFlags"))2196FragTree->setGISelFlagsRecord(Op);21972198// Transfer in the old predicates.2199for (const TreePredicateCall &Pred : getPredicateCalls())2200FragTree->addPredicateCall(Pred);22012202// The fragment we inlined could have recursive inlining that is needed. See2203// if there are any pattern fragments in it and inline them as needed.2204FragTree->InlinePatternFragments(TP, OutAlternatives);2205}2206}22072208/// getImplicitType - Check to see if the specified record has an implicit2209/// type which should be applied to it. This will infer the type of register2210/// references from the register file information, for example.2211///2212/// When Unnamed is set, return the type of a DAG operand with no name, such as2213/// the F8RC register class argument in:2214///2215/// (COPY_TO_REGCLASS GPR:$src, F8RC)2216///2217/// When Unnamed is false, return the type of a named DAG operand such as the2218/// GPR:$src operand above.2219///2220static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,2221bool NotRegisters, bool Unnamed,2222TreePattern &TP) {2223CodeGenDAGPatterns &CDP = TP.getDAGPatterns();22242225// Check to see if this is a register operand.2226if (R->isSubClassOf("RegisterOperand")) {2227assert(ResNo == 0 && "Regoperand ref only has one result!");2228if (NotRegisters)2229return TypeSetByHwMode(); // Unknown.2230Record *RegClass = R->getValueAsDef("RegClass");2231const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();2232return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());2233}22342235// Check to see if this is a register or a register class.2236if (R->isSubClassOf("RegisterClass")) {2237assert(ResNo == 0 && "Regclass ref only has one result!");2238// An unnamed register class represents itself as an i32 immediate, for2239// example on a COPY_TO_REGCLASS instruction.2240if (Unnamed)2241return TypeSetByHwMode(MVT::i32);22422243// In a named operand, the register class provides the possible set of2244// types.2245if (NotRegisters)2246return TypeSetByHwMode(); // Unknown.2247const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();2248return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());2249}22502251if (R->isSubClassOf("PatFrags")) {2252assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");2253// Pattern fragment types will be resolved when they are inlined.2254return TypeSetByHwMode(); // Unknown.2255}22562257if (R->isSubClassOf("Register")) {2258assert(ResNo == 0 && "Registers only produce one result!");2259if (NotRegisters)2260return TypeSetByHwMode(); // Unknown.2261const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();2262return TypeSetByHwMode(T.getRegisterVTs(R));2263}22642265if (R->isSubClassOf("SubRegIndex")) {2266assert(ResNo == 0 && "SubRegisterIndices only produce one result!");2267return TypeSetByHwMode(MVT::i32);2268}22692270if (R->isSubClassOf("ValueType")) {2271assert(ResNo == 0 && "This node only has one result!");2272// An unnamed VTSDNode represents itself as an MVT::Other immediate.2273//2274// (sext_inreg GPR:$src, i16)2275// ~~~2276if (Unnamed)2277return TypeSetByHwMode(MVT::Other);2278// With a name, the ValueType simply provides the type of the named2279// variable.2280//2281// (sext_inreg i32:$src, i16)2282// ~~~~~~~~2283if (NotRegisters)2284return TypeSetByHwMode(); // Unknown.2285const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();2286return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));2287}22882289if (R->isSubClassOf("CondCode")) {2290assert(ResNo == 0 && "This node only has one result!");2291// Using a CondCodeSDNode.2292return TypeSetByHwMode(MVT::Other);2293}22942295if (R->isSubClassOf("ComplexPattern")) {2296assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");2297if (NotRegisters)2298return TypeSetByHwMode(); // Unknown.2299Record *T = CDP.getComplexPattern(R).getValueType();2300const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();2301return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));2302}2303if (R->isSubClassOf("PointerLikeRegClass")) {2304assert(ResNo == 0 && "Regclass can only have one result!");2305TypeSetByHwMode VTS(MVT::iPTR);2306TP.getInfer().expandOverloads(VTS);2307return VTS;2308}23092310if (R->getName() == "node" || R->getName() == "srcvalue" ||2311R->getName() == "zero_reg" || R->getName() == "immAllOnesV" ||2312R->getName() == "immAllZerosV" || R->getName() == "undef_tied_input") {2313// Placeholder.2314return TypeSetByHwMode(); // Unknown.2315}23162317if (R->isSubClassOf("Operand")) {2318const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();2319Record *T = R->getValueAsDef("Type");2320return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));2321}23222323TP.error("Unknown node flavor used in pattern: " + R->getName());2324return TypeSetByHwMode(MVT::Other);2325}23262327/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the2328/// CodeGenIntrinsic information for it, otherwise return a null pointer.2329const CodeGenIntrinsic *2330TreePatternNode::getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {2331if (getOperator() != CDP.get_intrinsic_void_sdnode() &&2332getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&2333getOperator() != CDP.get_intrinsic_wo_chain_sdnode())2334return nullptr;23352336unsigned IID = cast<IntInit>(getChild(0).getLeafValue())->getValue();2337return &CDP.getIntrinsicInfo(IID);2338}23392340/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,2341/// return the ComplexPattern information, otherwise return null.2342const ComplexPattern *2343TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {2344Record *Rec;2345if (isLeaf()) {2346DefInit *DI = dyn_cast<DefInit>(getLeafValue());2347if (!DI)2348return nullptr;2349Rec = DI->getDef();2350} else2351Rec = getOperator();23522353if (!Rec->isSubClassOf("ComplexPattern"))2354return nullptr;2355return &CGP.getComplexPattern(Rec);2356}23572358unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {2359// A ComplexPattern specifically declares how many results it fills in.2360if (const ComplexPattern *CP = getComplexPatternInfo(CGP))2361return CP->getNumOperands();23622363// If MIOperandInfo is specified, that gives the count.2364if (isLeaf()) {2365DefInit *DI = dyn_cast<DefInit>(getLeafValue());2366if (DI && DI->getDef()->isSubClassOf("Operand")) {2367DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");2368if (MIOps->getNumArgs())2369return MIOps->getNumArgs();2370}2371}23722373// Otherwise there is just one result.2374return 1;2375}23762377/// NodeHasProperty - Return true if this node has the specified property.2378bool TreePatternNode::NodeHasProperty(SDNP Property,2379const CodeGenDAGPatterns &CGP) const {2380if (isLeaf()) {2381if (const ComplexPattern *CP = getComplexPatternInfo(CGP))2382return CP->hasProperty(Property);23832384return false;2385}23862387if (Property != SDNPHasChain) {2388// The chain proprety is already present on the different intrinsic node2389// types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed2390// on the intrinsic. Anything else is specific to the individual intrinsic.2391if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))2392return Int->hasProperty(Property);2393}23942395if (!getOperator()->isSubClassOf("SDPatternOperator"))2396return false;23972398return CGP.getSDNodeInfo(getOperator()).hasProperty(Property);2399}24002401/// TreeHasProperty - Return true if any node in this tree has the specified2402/// property.2403bool TreePatternNode::TreeHasProperty(SDNP Property,2404const CodeGenDAGPatterns &CGP) const {2405if (NodeHasProperty(Property, CGP))2406return true;2407for (unsigned i = 0, e = getNumChildren(); i != e; ++i)2408if (getChild(i).TreeHasProperty(Property, CGP))2409return true;2410return false;2411}24122413/// isCommutativeIntrinsic - Return true if the node corresponds to a2414/// commutative intrinsic.2415bool TreePatternNode::isCommutativeIntrinsic(2416const CodeGenDAGPatterns &CDP) const {2417if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))2418return Int->isCommutative;2419return false;2420}24212422static bool isOperandClass(const TreePatternNode &N, StringRef Class) {2423if (!N.isLeaf())2424return N.getOperator()->isSubClassOf(Class);24252426DefInit *DI = dyn_cast<DefInit>(N.getLeafValue());2427if (DI && DI->getDef()->isSubClassOf(Class))2428return true;24292430return false;2431}24322433static void emitTooManyOperandsError(TreePattern &TP, StringRef InstName,2434unsigned Expected, unsigned Actual) {2435TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +2436" operands but expected only " + Twine(Expected) + "!");2437}24382439static void emitTooFewOperandsError(TreePattern &TP, StringRef InstName,2440unsigned Actual) {2441TP.error("Instruction '" + InstName + "' expects more than the provided " +2442Twine(Actual) + " operands!");2443}24442445/// ApplyTypeConstraints - Apply all of the type constraints relevant to2446/// this node and its children in the tree. This returns true if it makes a2447/// change, false otherwise. If a type contradiction is found, flag an error.2448bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {2449if (TP.hasError())2450return false;24512452CodeGenDAGPatterns &CDP = TP.getDAGPatterns();2453if (isLeaf()) {2454if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {2455// If it's a regclass or something else known, include the type.2456bool MadeChange = false;2457for (unsigned i = 0, e = Types.size(); i != e; ++i)2458MadeChange |= UpdateNodeType(2459i, getImplicitType(DI->getDef(), i, NotRegisters, !hasName(), TP),2460TP);2461return MadeChange;2462}24632464if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {2465assert(Types.size() == 1 && "Invalid IntInit");24662467// Int inits are always integers. :)2468bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);24692470if (!TP.getInfer().isConcrete(Types[0], false))2471return MadeChange;24722473ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);2474for (auto &P : VVT) {2475MVT::SimpleValueType VT = P.second.SimpleTy;2476if (VT == MVT::iPTR || VT == MVT::iPTRAny)2477continue;2478unsigned Size = MVT(VT).getFixedSizeInBits();2479// Make sure that the value is representable for this type.2480if (Size >= 32)2481continue;2482// Check that the value doesn't use more bits than we have. It must2483// either be a sign- or zero-extended equivalent of the original.2484int64_t SignBitAndAbove = II->getValue() >> (Size - 1);2485if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||2486SignBitAndAbove == 1)2487continue;24882489TP.error("Integer value '" + Twine(II->getValue()) +2490"' is out of range for type '" + getEnumName(VT) + "'!");2491break;2492}2493return MadeChange;2494}24952496return false;2497}24982499if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {2500bool MadeChange = false;25012502// Apply the result type to the node.2503unsigned NumRetVTs = Int->IS.RetTys.size();2504unsigned NumParamVTs = Int->IS.ParamTys.size();25052506for (unsigned i = 0, e = NumRetVTs; i != e; ++i)2507MadeChange |= UpdateNodeType(2508i, getValueType(Int->IS.RetTys[i]->getValueAsDef("VT")), TP);25092510if (getNumChildren() != NumParamVTs + 1) {2511TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +2512" operands, not " + Twine(getNumChildren() - 1) + " operands!");2513return false;2514}25152516// Apply type info to the intrinsic ID.2517MadeChange |= getChild(0).UpdateNodeType(0, MVT::iPTR, TP);25182519for (unsigned i = 0, e = getNumChildren() - 1; i != e; ++i) {2520MadeChange |= getChild(i + 1).ApplyTypeConstraints(TP, NotRegisters);25212522MVT::SimpleValueType OpVT =2523getValueType(Int->IS.ParamTys[i]->getValueAsDef("VT"));2524assert(getChild(i + 1).getNumTypes() == 1 && "Unhandled case");2525MadeChange |= getChild(i + 1).UpdateNodeType(0, OpVT, TP);2526}2527return MadeChange;2528}25292530if (getOperator()->isSubClassOf("SDNode")) {2531const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());25322533// Check that the number of operands is sane. Negative operands -> varargs.2534if (NI.getNumOperands() >= 0 &&2535getNumChildren() != (unsigned)NI.getNumOperands()) {2536TP.error(getOperator()->getName() + " node requires exactly " +2537Twine(NI.getNumOperands()) + " operands!");2538return false;2539}25402541bool MadeChange = false;2542for (unsigned i = 0, e = getNumChildren(); i != e; ++i)2543MadeChange |= getChild(i).ApplyTypeConstraints(TP, NotRegisters);2544MadeChange |= NI.ApplyTypeConstraints(*this, TP);2545return MadeChange;2546}25472548if (getOperator()->isSubClassOf("Instruction")) {2549const DAGInstruction &Inst = CDP.getInstruction(getOperator());2550CodeGenInstruction &InstInfo =2551CDP.getTargetInfo().getInstruction(getOperator());25522553bool MadeChange = false;25542555// Apply the result types to the node, these come from the things in the2556// (outs) list of the instruction.2557unsigned NumResultsToAdd =2558std::min(InstInfo.Operands.NumDefs, Inst.getNumResults());2559for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)2560MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);25612562// If the instruction has implicit defs, we apply the first one as a result.2563// FIXME: This sucks, it should apply all implicit defs.2564if (!InstInfo.ImplicitDefs.empty()) {2565unsigned ResNo = NumResultsToAdd;25662567// FIXME: Generalize to multiple possible types and multiple possible2568// ImplicitDefs.2569MVT::SimpleValueType VT =2570InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());25712572if (VT != MVT::Other)2573MadeChange |= UpdateNodeType(ResNo, VT, TP);2574}25752576// If this is an INSERT_SUBREG, constrain the source and destination VTs to2577// be the same.2578if (getOperator()->getName() == "INSERT_SUBREG") {2579assert(getChild(0).getNumTypes() == 1 && "FIXME: Unhandled");2580MadeChange |= UpdateNodeType(0, getChild(0).getExtType(0), TP);2581MadeChange |= getChild(0).UpdateNodeType(0, getExtType(0), TP);2582} else if (getOperator()->getName() == "REG_SEQUENCE") {2583// We need to do extra, custom typechecking for REG_SEQUENCE since it is2584// variadic.25852586unsigned NChild = getNumChildren();2587if (NChild < 3) {2588TP.error("REG_SEQUENCE requires at least 3 operands!");2589return false;2590}25912592if (NChild % 2 == 0) {2593TP.error("REG_SEQUENCE requires an odd number of operands!");2594return false;2595}25962597if (!isOperandClass(getChild(0), "RegisterClass")) {2598TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");2599return false;2600}26012602for (unsigned I = 1; I < NChild; I += 2) {2603TreePatternNode &SubIdxChild = getChild(I + 1);2604if (!isOperandClass(SubIdxChild, "SubRegIndex")) {2605TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +2606Twine(I + 1) + "!");2607return false;2608}2609}2610}26112612unsigned NumResults = Inst.getNumResults();2613unsigned NumFixedOperands = InstInfo.Operands.size();26142615// If one or more operands with a default value appear at the end of the2616// formal operand list for an instruction, we allow them to be overridden2617// by optional operands provided in the pattern.2618//2619// But if an operand B without a default appears at any point after an2620// operand A with a default, then we don't allow A to be overridden,2621// because there would be no way to specify whether the next operand in2622// the pattern was intended to override A or skip it.2623unsigned NonOverridableOperands = NumFixedOperands;2624while (NonOverridableOperands > NumResults &&2625CDP.operandHasDefault(2626InstInfo.Operands[NonOverridableOperands - 1].Rec))2627--NonOverridableOperands;26282629unsigned ChildNo = 0;2630assert(NumResults <= NumFixedOperands);2631for (unsigned i = NumResults, e = NumFixedOperands; i != e; ++i) {2632Record *OperandNode = InstInfo.Operands[i].Rec;26332634// If the operand has a default value, do we use it? We must use the2635// default if we've run out of children of the pattern DAG to consume,2636// or if the operand is followed by a non-defaulted one.2637if (CDP.operandHasDefault(OperandNode) &&2638(i < NonOverridableOperands || ChildNo >= getNumChildren()))2639continue;26402641// If we have run out of child nodes and there _isn't_ a default2642// value we can use for the next operand, give an error.2643if (ChildNo >= getNumChildren()) {2644emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());2645return false;2646}26472648TreePatternNode *Child = &getChild(ChildNo++);2649unsigned ChildResNo = 0; // Instructions always use res #0 of their op.26502651// If the operand has sub-operands, they may be provided by distinct2652// child patterns, so attempt to match each sub-operand separately.2653if (OperandNode->isSubClassOf("Operand")) {2654DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");2655if (unsigned NumArgs = MIOpInfo->getNumArgs()) {2656// But don't do that if the whole operand is being provided by2657// a single ComplexPattern-related Operand.26582659if (Child->getNumMIResults(CDP) < NumArgs) {2660// Match first sub-operand against the child we already have.2661Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();2662MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);26632664// And the remaining sub-operands against subsequent children.2665for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {2666if (ChildNo >= getNumChildren()) {2667emitTooFewOperandsError(TP, getOperator()->getName(),2668getNumChildren());2669return false;2670}2671Child = &getChild(ChildNo++);26722673SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();2674MadeChange |=2675Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);2676}2677continue;2678}2679}2680}26812682// If we didn't match by pieces above, attempt to match the whole2683// operand now.2684MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);2685}26862687if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {2688emitTooManyOperandsError(TP, getOperator()->getName(), ChildNo,2689getNumChildren());2690return false;2691}26922693for (unsigned i = 0, e = getNumChildren(); i != e; ++i)2694MadeChange |= getChild(i).ApplyTypeConstraints(TP, NotRegisters);2695return MadeChange;2696}26972698if (getOperator()->isSubClassOf("ComplexPattern")) {2699bool MadeChange = false;27002701if (!NotRegisters) {2702assert(Types.size() == 1 && "ComplexPatterns only produce one result!");2703Record *T = CDP.getComplexPattern(getOperator()).getValueType();2704const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();2705const ValueTypeByHwMode VVT = getValueTypeByHwMode(T, CGH);2706// TODO: AArch64 and AMDGPU use ComplexPattern<untyped, ...> and then2707// exclusively use those as non-leaf nodes with explicit type casts, so2708// for backwards compatibility we do no inference in that case. This is2709// not supported when the ComplexPattern is used as a leaf value,2710// however; this inconsistency should be resolved, either by adding this2711// case there or by altering the backends to not do this (e.g. using Any2712// instead may work).2713if (!VVT.isSimple() || VVT.getSimple() != MVT::Untyped)2714MadeChange |= UpdateNodeType(0, VVT, TP);2715}27162717for (unsigned i = 0; i < getNumChildren(); ++i)2718MadeChange |= getChild(i).ApplyTypeConstraints(TP, NotRegisters);27192720return MadeChange;2721}27222723assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");27242725// Node transforms always take one operand.2726if (getNumChildren() != 1) {2727TP.error("Node transform '" + getOperator()->getName() +2728"' requires one operand!");2729return false;2730}27312732bool MadeChange = getChild(0).ApplyTypeConstraints(TP, NotRegisters);2733return MadeChange;2734}27352736/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the2737/// RHS of a commutative operation, not the on LHS.2738static bool OnlyOnRHSOfCommutative(TreePatternNode &N) {2739if (!N.isLeaf() && N.getOperator()->getName() == "imm")2740return true;2741if (N.isLeaf() && isa<IntInit>(N.getLeafValue()))2742return true;2743if (isImmAllOnesAllZerosMatch(N))2744return true;2745return false;2746}27472748/// canPatternMatch - If it is impossible for this pattern to match on this2749/// target, fill in Reason and return false. Otherwise, return true. This is2750/// used as a sanity check for .td files (to prevent people from writing stuff2751/// that can never possibly work), and to prevent the pattern permuter from2752/// generating stuff that is useless.2753bool TreePatternNode::canPatternMatch(std::string &Reason,2754const CodeGenDAGPatterns &CDP) {2755if (isLeaf())2756return true;27572758for (unsigned i = 0, e = getNumChildren(); i != e; ++i)2759if (!getChild(i).canPatternMatch(Reason, CDP))2760return false;27612762// If this is an intrinsic, handle cases that would make it not match. For2763// example, if an operand is required to be an immediate.2764if (getOperator()->isSubClassOf("Intrinsic")) {2765// TODO:2766return true;2767}27682769if (getOperator()->isSubClassOf("ComplexPattern"))2770return true;27712772// If this node is a commutative operator, check that the LHS isn't an2773// immediate.2774const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());2775bool isCommIntrinsic = isCommutativeIntrinsic(CDP);2776if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {2777// Scan all of the operands of the node and make sure that only the last one2778// is a constant node, unless the RHS also is.2779if (!OnlyOnRHSOfCommutative(getChild(getNumChildren() - 1))) {2780unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.2781for (unsigned i = Skip, e = getNumChildren() - 1; i != e; ++i)2782if (OnlyOnRHSOfCommutative(getChild(i))) {2783Reason =2784"Immediate value must be on the RHS of commutative operators!";2785return false;2786}2787}2788}27892790return true;2791}27922793//===----------------------------------------------------------------------===//2794// TreePattern implementation2795//27962797TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,2798CodeGenDAGPatterns &cdp)2799: TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),2800Infer(*this) {2801for (Init *I : RawPat->getValues())2802Trees.push_back(ParseTreePattern(I, ""));2803}28042805TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,2806CodeGenDAGPatterns &cdp)2807: TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),2808Infer(*this) {2809Trees.push_back(ParseTreePattern(Pat, ""));2810}28112812TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,2813CodeGenDAGPatterns &cdp)2814: TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),2815Infer(*this) {2816Trees.push_back(Pat);2817}28182819void TreePattern::error(const Twine &Msg) {2820if (HasError)2821return;2822dump();2823PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);2824HasError = true;2825}28262827void TreePattern::ComputeNamedNodes() {2828for (TreePatternNodePtr &Tree : Trees)2829ComputeNamedNodes(*Tree);2830}28312832void TreePattern::ComputeNamedNodes(TreePatternNode &N) {2833if (!N.getName().empty())2834NamedNodes[N.getName()].push_back(&N);28352836for (unsigned i = 0, e = N.getNumChildren(); i != e; ++i)2837ComputeNamedNodes(N.getChild(i));2838}28392840TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,2841StringRef OpName) {2842RecordKeeper &RK = TheInit->getRecordKeeper();2843if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {2844Record *R = DI->getDef();28452846// Direct reference to a leaf DagNode or PatFrag? Turn it into a2847// TreePatternNode of its own. For example:2848/// (foo GPR, imm) -> (foo GPR, (imm))2849if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))2850return ParseTreePattern(2851DagInit::get(DI, nullptr,2852std::vector<std::pair<Init *, StringInit *>>()),2853OpName);28542855// Input argument?2856TreePatternNodePtr Res = makeIntrusiveRefCnt<TreePatternNode>(DI, 1);2857if (R->getName() == "node" && !OpName.empty()) {2858if (OpName.empty())2859error("'node' argument requires a name to match with operand list");2860Args.push_back(std::string(OpName));2861}28622863Res->setName(OpName);2864return Res;2865}28662867// ?:$name or just $name.2868if (isa<UnsetInit>(TheInit)) {2869if (OpName.empty())2870error("'?' argument requires a name to match with operand list");2871TreePatternNodePtr Res = makeIntrusiveRefCnt<TreePatternNode>(TheInit, 1);2872Args.push_back(std::string(OpName));2873Res->setName(OpName);2874return Res;2875}28762877if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {2878if (!OpName.empty())2879error("Constant int or bit argument should not have a name!");2880if (isa<BitInit>(TheInit))2881TheInit = TheInit->convertInitializerTo(IntRecTy::get(RK));2882return makeIntrusiveRefCnt<TreePatternNode>(TheInit, 1);2883}28842885if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {2886// Turn this into an IntInit.2887Init *II = BI->convertInitializerTo(IntRecTy::get(RK));2888if (!II || !isa<IntInit>(II))2889error("Bits value must be constants!");2890return II ? ParseTreePattern(II, OpName) : nullptr;2891}28922893DagInit *Dag = dyn_cast<DagInit>(TheInit);2894if (!Dag) {2895TheInit->print(errs());2896error("Pattern has unexpected init kind!");2897return nullptr;2898}2899DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());2900if (!OpDef) {2901error("Pattern has unexpected operator type!");2902return nullptr;2903}2904Record *Operator = OpDef->getDef();29052906if (Operator->isSubClassOf("ValueType")) {2907// If the operator is a ValueType, then this must be "type cast" of a leaf2908// node.2909if (Dag->getNumArgs() != 1)2910error("Type cast only takes one operand!");29112912TreePatternNodePtr New =2913ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));29142915// Apply the type cast.2916if (New->getNumTypes() != 1)2917error("Type cast can only have one type!");2918const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();2919New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);29202921if (!OpName.empty())2922error("ValueType cast should not have a name!");2923return New;2924}29252926// Verify that this is something that makes sense for an operator.2927if (!Operator->isSubClassOf("PatFrags") &&2928!Operator->isSubClassOf("SDNode") &&2929!Operator->isSubClassOf("Instruction") &&2930!Operator->isSubClassOf("SDNodeXForm") &&2931!Operator->isSubClassOf("Intrinsic") &&2932!Operator->isSubClassOf("ComplexPattern") &&2933Operator->getName() != "set" && Operator->getName() != "implicit")2934error("Unrecognized node '" + Operator->getName() + "'!");29352936// Check to see if this is something that is illegal in an input pattern.2937if (isInputPattern) {2938if (Operator->isSubClassOf("Instruction") ||2939Operator->isSubClassOf("SDNodeXForm"))2940error("Cannot use '" + Operator->getName() + "' in an input pattern!");2941} else {2942if (Operator->isSubClassOf("Intrinsic"))2943error("Cannot use '" + Operator->getName() + "' in an output pattern!");29442945if (Operator->isSubClassOf("SDNode") && Operator->getName() != "imm" &&2946Operator->getName() != "timm" && Operator->getName() != "fpimm" &&2947Operator->getName() != "tglobaltlsaddr" &&2948Operator->getName() != "tconstpool" &&2949Operator->getName() != "tjumptable" &&2950Operator->getName() != "tframeindex" &&2951Operator->getName() != "texternalsym" &&2952Operator->getName() != "tblockaddress" &&2953Operator->getName() != "tglobaladdr" && Operator->getName() != "bb" &&2954Operator->getName() != "vt" && Operator->getName() != "mcsym")2955error("Cannot use '" + Operator->getName() + "' in an output pattern!");2956}29572958std::vector<TreePatternNodePtr> Children;29592960// Parse all the operands.2961for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)2962Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));29632964// Get the actual number of results before Operator is converted to an2965// intrinsic node (which is hard-coded to have either zero or one result).2966unsigned NumResults = GetNumNodeResults(Operator, CDP);29672968// If the operator is an intrinsic, then this is just syntactic sugar for2969// (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and2970// convert the intrinsic name to a number.2971if (Operator->isSubClassOf("Intrinsic")) {2972const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);2973unsigned IID = getDAGPatterns().getIntrinsicID(Operator) + 1;29742975// If this intrinsic returns void, it must have side-effects and thus a2976// chain.2977if (Int.IS.RetTys.empty())2978Operator = getDAGPatterns().get_intrinsic_void_sdnode();2979else if (!Int.ME.doesNotAccessMemory() || Int.hasSideEffects)2980// Has side-effects, requires chain.2981Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();2982else // Otherwise, no chain.2983Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();29842985Children.insert(Children.begin(), makeIntrusiveRefCnt<TreePatternNode>(2986IntInit::get(RK, IID), 1));2987}29882989if (Operator->isSubClassOf("ComplexPattern")) {2990for (unsigned i = 0; i < Children.size(); ++i) {2991TreePatternNodePtr Child = Children[i];29922993if (Child->getName().empty())2994error("All arguments to a ComplexPattern must be named");29952996// Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"2997// and "(MY_PAT $b, $a)" should not be allowed in the same pattern;2998// neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".2999auto OperandId = std::pair(Operator, i);3000auto PrevOp = ComplexPatternOperands.find(Child->getName());3001if (PrevOp != ComplexPatternOperands.end()) {3002if (PrevOp->getValue() != OperandId)3003error("All ComplexPattern operands must appear consistently: "3004"in the same order in just one ComplexPattern instance.");3005} else3006ComplexPatternOperands[Child->getName()] = OperandId;3007}3008}30093010TreePatternNodePtr Result = makeIntrusiveRefCnt<TreePatternNode>(3011Operator, std::move(Children), NumResults);3012Result->setName(OpName);30133014if (Dag->getName()) {3015assert(Result->getName().empty());3016Result->setName(Dag->getNameStr());3017}3018return Result;3019}30203021/// SimplifyTree - See if we can simplify this tree to eliminate something that3022/// will never match in favor of something obvious that will. This is here3023/// strictly as a convenience to target authors because it allows them to write3024/// more type generic things and have useless type casts fold away.3025///3026/// This returns true if any change is made.3027static bool SimplifyTree(TreePatternNodePtr &N) {3028if (N->isLeaf())3029return false;30303031// If we have a bitconvert with a resolved type and if the source and3032// destination types are the same, then the bitconvert is useless, remove it.3033//3034// We make an exception if the types are completely empty. This can come up3035// when the pattern being simplified is in the Fragments list of a PatFrags,3036// so that the operand is just an untyped "node". In that situation we leave3037// bitconverts unsimplified, and simplify them later once the fragment is3038// expanded into its true context.3039if (N->getOperator()->getName() == "bitconvert" &&3040N->getExtType(0).isValueTypeByHwMode(false) &&3041!N->getExtType(0).empty() &&3042N->getExtType(0) == N->getChild(0).getExtType(0) &&3043N->getName().empty()) {3044if (!N->getPredicateCalls().empty()) {3045std::string Str;3046raw_string_ostream OS(Str);3047OS << *N3048<< "\n trivial bitconvert node should not have predicate calls\n";3049PrintFatalError(Str);3050return false;3051}3052N = N->getChildShared(0);3053SimplifyTree(N);3054return true;3055}30563057// Walk all children.3058bool MadeChange = false;3059for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)3060MadeChange |= SimplifyTree(N->getChildSharedPtr(i));30613062return MadeChange;3063}30643065/// InferAllTypes - Infer/propagate as many types throughout the expression3066/// patterns as possible. Return true if all types are inferred, false3067/// otherwise. Flags an error if a type contradiction is found.3068bool TreePattern::InferAllTypes(3069const StringMap<SmallVector<TreePatternNode *, 1>> *InNamedTypes) {3070if (NamedNodes.empty())3071ComputeNamedNodes();30723073bool MadeChange = true;3074while (MadeChange) {3075MadeChange = false;3076for (TreePatternNodePtr &Tree : Trees) {3077MadeChange |= Tree->ApplyTypeConstraints(*this, false);3078MadeChange |= SimplifyTree(Tree);3079}30803081// If there are constraints on our named nodes, apply them.3082for (auto &Entry : NamedNodes) {3083SmallVectorImpl<TreePatternNode *> &Nodes = Entry.second;30843085// If we have input named node types, propagate their types to the named3086// values here.3087if (InNamedTypes) {3088if (!InNamedTypes->count(Entry.getKey())) {3089error("Node '" + std::string(Entry.getKey()) +3090"' in output pattern but not input pattern");3091return true;3092}30933094const SmallVectorImpl<TreePatternNode *> &InNodes =3095InNamedTypes->find(Entry.getKey())->second;30963097// The input types should be fully resolved by now.3098for (TreePatternNode *Node : Nodes) {3099// If this node is a register class, and it is the root of the pattern3100// then we're mapping something onto an input register. We allow3101// changing the type of the input register in this case. This allows3102// us to match things like:3103// def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;3104if (Node == Trees[0].get() && Node->isLeaf()) {3105DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());3106if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||3107DI->getDef()->isSubClassOf("RegisterOperand")))3108continue;3109}31103111assert(Node->getNumTypes() == 1 && InNodes[0]->getNumTypes() == 1 &&3112"FIXME: cannot name multiple result nodes yet");3113MadeChange |=3114Node->UpdateNodeType(0, InNodes[0]->getExtType(0), *this);3115}3116}31173118// If there are multiple nodes with the same name, they must all have the3119// same type.3120if (Entry.second.size() > 1) {3121for (unsigned i = 0, e = Nodes.size() - 1; i != e; ++i) {3122TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i + 1];3123assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&3124"FIXME: cannot name multiple result nodes yet");31253126MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);3127MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);3128}3129}3130}3131}31323133bool HasUnresolvedTypes = false;3134for (const TreePatternNodePtr &Tree : Trees)3135HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);3136return !HasUnresolvedTypes;3137}31383139void TreePattern::print(raw_ostream &OS) const {3140OS << getRecord()->getName();3141if (!Args.empty()) {3142OS << "(";3143ListSeparator LS;3144for (const std::string &Arg : Args)3145OS << LS << Arg;3146OS << ")";3147}3148OS << ": ";31493150if (Trees.size() > 1)3151OS << "[\n";3152for (const TreePatternNodePtr &Tree : Trees) {3153OS << "\t";3154Tree->print(OS);3155OS << "\n";3156}31573158if (Trees.size() > 1)3159OS << "]\n";3160}31613162void TreePattern::dump() const { print(errs()); }31633164//===----------------------------------------------------------------------===//3165// CodeGenDAGPatterns implementation3166//31673168CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,3169PatternRewriterFn PatternRewriter)3170: Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),3171PatternRewriter(PatternRewriter) {31723173Intrinsics = CodeGenIntrinsicTable(Records);3174ParseNodeInfo();3175ParseNodeTransforms();3176ParseComplexPatterns();3177ParsePatternFragments();3178ParseDefaultOperands();3179ParseInstructions();3180ParsePatternFragments(/*OutFrags*/ true);3181ParsePatterns();31823183// Generate variants. For example, commutative patterns can match3184// multiple ways. Add them to PatternsToMatch as well.3185GenerateVariants();31863187// Break patterns with parameterized types into a series of patterns,3188// where each one has a fixed type and is predicated on the conditions3189// of the associated HW mode.3190ExpandHwModeBasedTypes();31913192// Infer instruction flags. For example, we can detect loads,3193// stores, and side effects in many cases by examining an3194// instruction's pattern.3195InferInstructionFlags();31963197// Verify that instruction flags match the patterns.3198VerifyInstructionFlags();3199}32003201Record *CodeGenDAGPatterns::getSDNodeNamed(StringRef Name) const {3202Record *N = Records.getDef(Name);3203if (!N || !N->isSubClassOf("SDNode"))3204PrintFatalError("Error getting SDNode '" + Name + "'!");32053206return N;3207}32083209// Parse all of the SDNode definitions for the target, populating SDNodes.3210void CodeGenDAGPatterns::ParseNodeInfo() {3211std::vector<Record *> Nodes = Records.getAllDerivedDefinitions("SDNode");3212const CodeGenHwModes &CGH = getTargetInfo().getHwModes();32133214while (!Nodes.empty()) {3215Record *R = Nodes.back();3216SDNodes.insert(std::pair(R, SDNodeInfo(R, CGH)));3217Nodes.pop_back();3218}32193220// Get the builtin intrinsic nodes.3221intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");3222intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");3223intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");3224}32253226/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms3227/// map, and emit them to the file as functions.3228void CodeGenDAGPatterns::ParseNodeTransforms() {3229std::vector<Record *> Xforms =3230Records.getAllDerivedDefinitions("SDNodeXForm");3231while (!Xforms.empty()) {3232Record *XFormNode = Xforms.back();3233Record *SDNode = XFormNode->getValueAsDef("Opcode");3234StringRef Code = XFormNode->getValueAsString("XFormFunction");3235SDNodeXForms.insert(3236std::pair(XFormNode, NodeXForm(SDNode, std::string(Code))));32373238Xforms.pop_back();3239}3240}32413242void CodeGenDAGPatterns::ParseComplexPatterns() {3243std::vector<Record *> AMs =3244Records.getAllDerivedDefinitions("ComplexPattern");3245while (!AMs.empty()) {3246ComplexPatterns.insert(std::pair(AMs.back(), AMs.back()));3247AMs.pop_back();3248}3249}32503251/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td3252/// file, building up the PatternFragments map. After we've collected them all,3253/// inline fragments together as necessary, so that there are no references left3254/// inside a pattern fragment to a pattern fragment.3255///3256void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {3257std::vector<Record *> Fragments =3258Records.getAllDerivedDefinitions("PatFrags");32593260// First step, parse all of the fragments.3261for (Record *Frag : Fragments) {3262if (OutFrags != Frag->isSubClassOf("OutPatFrag"))3263continue;32643265ListInit *LI = Frag->getValueAsListInit("Fragments");3266TreePattern *P = (PatternFragments[Frag] = std::make_unique<TreePattern>(3267Frag, LI, !Frag->isSubClassOf("OutPatFrag"), *this))3268.get();32693270// Validate the argument list, converting it to set, to discard duplicates.3271std::vector<std::string> &Args = P->getArgList();3272// Copy the args so we can take StringRefs to them.3273auto ArgsCopy = Args;3274SmallDenseSet<StringRef, 4> OperandsSet;3275OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());32763277if (OperandsSet.count(""))3278P->error("Cannot have unnamed 'node' values in pattern fragment!");32793280// Parse the operands list.3281DagInit *OpsList = Frag->getValueAsDag("Operands");3282DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());3283// Special cases: ops == outs == ins. Different names are used to3284// improve readability.3285if (!OpsOp || (OpsOp->getDef()->getName() != "ops" &&3286OpsOp->getDef()->getName() != "outs" &&3287OpsOp->getDef()->getName() != "ins"))3288P->error("Operands list should start with '(ops ... '!");32893290// Copy over the arguments.3291Args.clear();3292for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {3293if (!isa<DefInit>(OpsList->getArg(j)) ||3294cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")3295P->error("Operands list should all be 'node' values.");3296if (!OpsList->getArgName(j))3297P->error("Operands list should have names for each operand!");3298StringRef ArgNameStr = OpsList->getArgNameStr(j);3299if (!OperandsSet.count(ArgNameStr))3300P->error("'" + ArgNameStr +3301"' does not occur in pattern or was multiply specified!");3302OperandsSet.erase(ArgNameStr);3303Args.push_back(std::string(ArgNameStr));3304}33053306if (!OperandsSet.empty())3307P->error("Operands list does not contain an entry for operand '" +3308*OperandsSet.begin() + "'!");33093310// If there is a node transformation corresponding to this, keep track of3311// it.3312Record *Transform = Frag->getValueAsDef("OperandTransform");3313if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?3314for (const auto &T : P->getTrees())3315T->setTransformFn(Transform);3316}33173318// Now that we've parsed all of the tree fragments, do a closure on them so3319// that there are not references to PatFrags left inside of them.3320for (Record *Frag : Fragments) {3321if (OutFrags != Frag->isSubClassOf("OutPatFrag"))3322continue;33233324TreePattern &ThePat = *PatternFragments[Frag];3325ThePat.InlinePatternFragments();33263327// Infer as many types as possible. Don't worry about it if we don't infer3328// all of them, some may depend on the inputs of the pattern. Also, don't3329// validate type sets; validation may cause spurious failures e.g. if a3330// fragment needs floating-point types but the current target does not have3331// any (this is only an error if that fragment is ever used!).3332{3333TypeInfer::SuppressValidation SV(ThePat.getInfer());3334ThePat.InferAllTypes();3335ThePat.resetError();3336}33373338// If debugging, print out the pattern fragment result.3339LLVM_DEBUG(ThePat.dump());3340}3341}33423343void CodeGenDAGPatterns::ParseDefaultOperands() {3344std::vector<Record *> DefaultOps;3345DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");33463347// Find some SDNode.3348assert(!SDNodes.empty() && "No SDNodes parsed?");3349Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);33503351for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {3352DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");33533354// Clone the DefaultInfo dag node, changing the operator from 'ops' to3355// SomeSDnode so that we can parse this.3356std::vector<std::pair<Init *, StringInit *>> Ops;3357for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)3358Ops.push_back(3359std::pair(DefaultInfo->getArg(op), DefaultInfo->getArgName(op)));3360DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);33613362// Create a TreePattern to parse this.3363TreePattern P(DefaultOps[i], DI, false, *this);3364assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");33653366// Copy the operands over into a DAGDefaultOperand.3367DAGDefaultOperand DefaultOpInfo;33683369const TreePatternNodePtr &T = P.getTree(0);3370for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {3371TreePatternNodePtr TPN = T->getChildShared(op);3372while (TPN->ApplyTypeConstraints(P, false))3373/* Resolve all types */;33743375if (TPN->ContainsUnresolvedType(P)) {3376PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +3377DefaultOps[i]->getName() +3378"' doesn't have a concrete type!");3379}3380DefaultOpInfo.DefaultOps.push_back(std::move(TPN));3381}33823383// Insert it into the DefaultOperands map so we can find it later.3384DefaultOperands[DefaultOps[i]] = DefaultOpInfo;3385}3386}33873388/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an3389/// instruction input. Return true if this is a real use.3390static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,3391std::map<std::string, TreePatternNodePtr> &InstInputs) {3392// No name -> not interesting.3393if (Pat->getName().empty()) {3394if (Pat->isLeaf()) {3395DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());3396if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||3397DI->getDef()->isSubClassOf("RegisterOperand")))3398I.error("Input " + DI->getDef()->getName() + " must be named!");3399}3400return false;3401}34023403Record *Rec;3404if (Pat->isLeaf()) {3405DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());3406if (!DI)3407I.error("Input $" + Pat->getName() + " must be an identifier!");3408Rec = DI->getDef();3409} else {3410Rec = Pat->getOperator();3411}34123413// SRCVALUE nodes are ignored.3414if (Rec->getName() == "srcvalue")3415return false;34163417TreePatternNodePtr &Slot = InstInputs[Pat->getName()];3418if (!Slot) {3419Slot = Pat;3420return true;3421}3422Record *SlotRec;3423if (Slot->isLeaf()) {3424SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();3425} else {3426assert(Slot->getNumChildren() == 0 && "can't be a use with children!");3427SlotRec = Slot->getOperator();3428}34293430// Ensure that the inputs agree if we've already seen this input.3431if (Rec != SlotRec)3432I.error("All $" + Pat->getName() + " inputs must agree with each other");3433// Ensure that the types can agree as well.3434Slot->UpdateNodeType(0, Pat->getExtType(0), I);3435Pat->UpdateNodeType(0, Slot->getExtType(0), I);3436if (Slot->getExtTypes() != Pat->getExtTypes())3437I.error("All $" + Pat->getName() + " inputs must agree with each other");3438return true;3439}34403441/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is3442/// part of "I", the instruction), computing the set of inputs and outputs of3443/// the pattern. Report errors if we see anything naughty.3444void CodeGenDAGPatterns::FindPatternInputsAndOutputs(3445TreePattern &I, TreePatternNodePtr Pat,3446std::map<std::string, TreePatternNodePtr> &InstInputs,3447MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>3448&InstResults,3449std::vector<Record *> &InstImpResults) {34503451// The instruction pattern still has unresolved fragments. For *named*3452// nodes we must resolve those here. This may not result in multiple3453// alternatives.3454if (!Pat->getName().empty()) {3455TreePattern SrcPattern(I.getRecord(), Pat, true, *this);3456SrcPattern.InlinePatternFragments();3457SrcPattern.InferAllTypes();3458Pat = SrcPattern.getOnlyTree();3459}34603461if (Pat->isLeaf()) {3462bool isUse = HandleUse(I, Pat, InstInputs);3463if (!isUse && Pat->getTransformFn())3464I.error("Cannot specify a transform function for a non-input value!");3465return;3466}34673468if (Pat->getOperator()->getName() == "implicit") {3469for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {3470TreePatternNode &Dest = Pat->getChild(i);3471if (!Dest.isLeaf())3472I.error("implicitly defined value should be a register!");34733474DefInit *Val = dyn_cast<DefInit>(Dest.getLeafValue());3475if (!Val || !Val->getDef()->isSubClassOf("Register"))3476I.error("implicitly defined value should be a register!");3477if (Val)3478InstImpResults.push_back(Val->getDef());3479}3480return;3481}34823483if (Pat->getOperator()->getName() != "set") {3484// If this is not a set, verify that the children nodes are not void typed,3485// and recurse.3486for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {3487if (Pat->getChild(i).getNumTypes() == 0)3488I.error("Cannot have void nodes inside of patterns!");3489FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,3490InstResults, InstImpResults);3491}34923493// If this is a non-leaf node with no children, treat it basically as if3494// it were a leaf. This handles nodes like (imm).3495bool isUse = HandleUse(I, Pat, InstInputs);34963497if (!isUse && Pat->getTransformFn())3498I.error("Cannot specify a transform function for a non-input value!");3499return;3500}35013502// Otherwise, this is a set, validate and collect instruction results.3503if (Pat->getNumChildren() == 0)3504I.error("set requires operands!");35053506if (Pat->getTransformFn())3507I.error("Cannot specify a transform function on a set node!");35083509// Check the set destinations.3510unsigned NumDests = Pat->getNumChildren() - 1;3511for (unsigned i = 0; i != NumDests; ++i) {3512TreePatternNodePtr Dest = Pat->getChildShared(i);3513// For set destinations we also must resolve fragments here.3514TreePattern DestPattern(I.getRecord(), Dest, false, *this);3515DestPattern.InlinePatternFragments();3516DestPattern.InferAllTypes();3517Dest = DestPattern.getOnlyTree();35183519if (!Dest->isLeaf())3520I.error("set destination should be a register!");35213522DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());3523if (!Val) {3524I.error("set destination should be a register!");3525continue;3526}35273528if (Val->getDef()->isSubClassOf("RegisterClass") ||3529Val->getDef()->isSubClassOf("ValueType") ||3530Val->getDef()->isSubClassOf("RegisterOperand") ||3531Val->getDef()->isSubClassOf("PointerLikeRegClass")) {3532if (Dest->getName().empty())3533I.error("set destination must have a name!");3534if (InstResults.count(Dest->getName()))3535I.error("cannot set '" + Dest->getName() + "' multiple times");3536InstResults[Dest->getName()] = Dest;3537} else if (Val->getDef()->isSubClassOf("Register")) {3538InstImpResults.push_back(Val->getDef());3539} else {3540I.error("set destination should be a register!");3541}3542}35433544// Verify and collect info from the computation.3545FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,3546InstResults, InstImpResults);3547}35483549//===----------------------------------------------------------------------===//3550// Instruction Analysis3551//===----------------------------------------------------------------------===//35523553class InstAnalyzer {3554const CodeGenDAGPatterns &CDP;35553556public:3557bool hasSideEffects;3558bool mayStore;3559bool mayLoad;3560bool isBitcast;3561bool isVariadic;3562bool hasChain;35633564InstAnalyzer(const CodeGenDAGPatterns &cdp)3565: CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),3566isBitcast(false), isVariadic(false), hasChain(false) {}35673568void Analyze(const PatternToMatch &Pat) {3569const TreePatternNode &N = Pat.getSrcPattern();3570AnalyzeNode(N);3571// These properties are detected only on the root node.3572isBitcast = IsNodeBitcast(N);3573}35743575private:3576bool IsNodeBitcast(const TreePatternNode &N) const {3577if (hasSideEffects || mayLoad || mayStore || isVariadic)3578return false;35793580if (N.isLeaf())3581return false;3582if (N.getNumChildren() != 1 || !N.getChild(0).isLeaf())3583return false;35843585if (N.getOperator()->isSubClassOf("ComplexPattern"))3586return false;35873588const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N.getOperator());3589if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)3590return false;3591return OpInfo.getEnumName() == "ISD::BITCAST";3592}35933594public:3595void AnalyzeNode(const TreePatternNode &N) {3596if (N.isLeaf()) {3597if (DefInit *DI = dyn_cast<DefInit>(N.getLeafValue())) {3598Record *LeafRec = DI->getDef();3599// Handle ComplexPattern leaves.3600if (LeafRec->isSubClassOf("ComplexPattern")) {3601const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);3602if (CP.hasProperty(SDNPMayStore))3603mayStore = true;3604if (CP.hasProperty(SDNPMayLoad))3605mayLoad = true;3606if (CP.hasProperty(SDNPSideEffect))3607hasSideEffects = true;3608}3609}3610return;3611}36123613// Analyze children.3614for (unsigned i = 0, e = N.getNumChildren(); i != e; ++i)3615AnalyzeNode(N.getChild(i));36163617// Notice properties of the node.3618if (N.NodeHasProperty(SDNPMayStore, CDP))3619mayStore = true;3620if (N.NodeHasProperty(SDNPMayLoad, CDP))3621mayLoad = true;3622if (N.NodeHasProperty(SDNPSideEffect, CDP))3623hasSideEffects = true;3624if (N.NodeHasProperty(SDNPVariadic, CDP))3625isVariadic = true;3626if (N.NodeHasProperty(SDNPHasChain, CDP))3627hasChain = true;36283629if (const CodeGenIntrinsic *IntInfo = N.getIntrinsicInfo(CDP)) {3630ModRefInfo MR = IntInfo->ME.getModRef();3631// If this is an intrinsic, analyze it.3632if (isRefSet(MR))3633mayLoad = true; // These may load memory.36343635if (isModSet(MR))3636mayStore = true; // Intrinsics that can write to memory are 'mayStore'.36373638// Consider intrinsics that don't specify any restrictions on memory3639// effects as having a side-effect.3640if (IntInfo->ME == MemoryEffects::unknown() || IntInfo->hasSideEffects)3641hasSideEffects = true;3642}3643}3644};36453646static bool InferFromPattern(CodeGenInstruction &InstInfo,3647const InstAnalyzer &PatInfo, Record *PatDef) {3648bool Error = false;36493650// Remember where InstInfo got its flags.3651if (InstInfo.hasUndefFlags())3652InstInfo.InferredFrom = PatDef;36533654// Check explicitly set flags for consistency.3655if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&3656!InstInfo.hasSideEffects_Unset) {3657// Allow explicitly setting hasSideEffects = 1 on instructions, even when3658// the pattern has no side effects. That could be useful for div/rem3659// instructions that may trap.3660if (!InstInfo.hasSideEffects) {3661Error = true;3662PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +3663Twine(InstInfo.hasSideEffects));3664}3665}36663667if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {3668Error = true;3669PrintError(PatDef->getLoc(),3670"Pattern doesn't match mayStore = " + Twine(InstInfo.mayStore));3671}36723673if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {3674// Allow explicitly setting mayLoad = 1, even when the pattern has no loads.3675// Some targets translate immediates to loads.3676if (!InstInfo.mayLoad) {3677Error = true;3678PrintError(PatDef->getLoc(),3679"Pattern doesn't match mayLoad = " + Twine(InstInfo.mayLoad));3680}3681}36823683// Transfer inferred flags.3684InstInfo.hasSideEffects |= PatInfo.hasSideEffects;3685InstInfo.mayStore |= PatInfo.mayStore;3686InstInfo.mayLoad |= PatInfo.mayLoad;36873688// These flags are silently added without any verification.3689// FIXME: To match historical behavior of TableGen, for now add those flags3690// only when we're inferring from the primary instruction pattern.3691if (PatDef->isSubClassOf("Instruction")) {3692InstInfo.isBitcast |= PatInfo.isBitcast;3693InstInfo.hasChain |= PatInfo.hasChain;3694InstInfo.hasChain_Inferred = true;3695}36963697// Don't infer isVariadic. This flag means something different on SDNodes and3698// instructions. For example, a CALL SDNode is variadic because it has the3699// call arguments as operands, but a CALL instruction is not variadic - it3700// has argument registers as implicit, not explicit uses.37013702return Error;3703}37043705/// hasNullFragReference - Return true if the DAG has any reference to the3706/// null_frag operator.3707static bool hasNullFragReference(DagInit *DI) {3708DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());3709if (!OpDef)3710return false;3711Record *Operator = OpDef->getDef();37123713// If this is the null fragment, return true.3714if (Operator->getName() == "null_frag")3715return true;3716// If any of the arguments reference the null fragment, return true.3717for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {3718if (auto Arg = dyn_cast<DefInit>(DI->getArg(i)))3719if (Arg->getDef()->getName() == "null_frag")3720return true;3721DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));3722if (Arg && hasNullFragReference(Arg))3723return true;3724}37253726return false;3727}37283729/// hasNullFragReference - Return true if any DAG in the list references3730/// the null_frag operator.3731static bool hasNullFragReference(ListInit *LI) {3732for (Init *I : LI->getValues()) {3733DagInit *DI = dyn_cast<DagInit>(I);3734assert(DI && "non-dag in an instruction Pattern list?!");3735if (hasNullFragReference(DI))3736return true;3737}3738return false;3739}37403741/// Get all the instructions in a tree.3742static void getInstructionsInTree(TreePatternNode &Tree,3743SmallVectorImpl<Record *> &Instrs) {3744if (Tree.isLeaf())3745return;3746if (Tree.getOperator()->isSubClassOf("Instruction"))3747Instrs.push_back(Tree.getOperator());3748for (unsigned i = 0, e = Tree.getNumChildren(); i != e; ++i)3749getInstructionsInTree(Tree.getChild(i), Instrs);3750}37513752/// Check the class of a pattern leaf node against the instruction operand it3753/// represents.3754static bool checkOperandClass(CGIOperandList::OperandInfo &OI, Record *Leaf) {3755if (OI.Rec == Leaf)3756return true;37573758// Allow direct value types to be used in instruction set patterns.3759// The type will be checked later.3760if (Leaf->isSubClassOf("ValueType"))3761return true;37623763// Patterns can also be ComplexPattern instances.3764if (Leaf->isSubClassOf("ComplexPattern"))3765return true;37663767return false;3768}37693770void CodeGenDAGPatterns::parseInstructionPattern(CodeGenInstruction &CGI,3771ListInit *Pat,3772DAGInstMap &DAGInsts) {37733774assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");37753776// Parse the instruction.3777TreePattern I(CGI.TheDef, Pat, true, *this);37783779// InstInputs - Keep track of all of the inputs of the instruction, along3780// with the record they are declared as.3781std::map<std::string, TreePatternNodePtr> InstInputs;37823783// InstResults - Keep track of all the virtual registers that are 'set'3784// in the instruction, including what reg class they are.3785MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>3786InstResults;37873788std::vector<Record *> InstImpResults;37893790// Verify that the top-level forms in the instruction are of void type, and3791// fill in the InstResults map.3792SmallString<32> TypesString;3793for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {3794TypesString.clear();3795TreePatternNodePtr Pat = I.getTree(j);3796if (Pat->getNumTypes() != 0) {3797raw_svector_ostream OS(TypesString);3798ListSeparator LS;3799for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {3800OS << LS;3801Pat->getExtType(k).writeToStream(OS);3802}3803I.error("Top-level forms in instruction pattern should have"3804" void types, has types " +3805OS.str());3806}38073808// Find inputs and outputs, and verify the structure of the uses/defs.3809FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,3810InstImpResults);3811}38123813// Now that we have inputs and outputs of the pattern, inspect the operands3814// list for the instruction. This determines the order that operands are3815// added to the machine instruction the node corresponds to.3816unsigned NumResults = InstResults.size();38173818// Parse the operands list from the (ops) list, validating it.3819assert(I.getArgList().empty() && "Args list should still be empty here!");38203821// Check that all of the results occur first in the list.3822std::vector<Record *> Results;3823std::vector<unsigned> ResultIndices;3824SmallVector<TreePatternNodePtr, 2> ResNodes;3825for (unsigned i = 0; i != NumResults; ++i) {3826if (i == CGI.Operands.size()) {3827const std::string &OpName =3828llvm::find_if(3829InstResults,3830[](const std::pair<std::string, TreePatternNodePtr> &P) {3831return P.second;3832})3833->first;38343835I.error("'" + OpName + "' set but does not appear in operand list!");3836}38373838const std::string &OpName = CGI.Operands[i].Name;38393840// Check that it exists in InstResults.3841auto InstResultIter = InstResults.find(OpName);3842if (InstResultIter == InstResults.end() || !InstResultIter->second)3843I.error("Operand $" + OpName + " does not exist in operand list!");38443845TreePatternNodePtr RNode = InstResultIter->second;3846Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();3847ResNodes.push_back(std::move(RNode));3848if (!R)3849I.error("Operand $" + OpName +3850" should be a set destination: all "3851"outputs must occur before inputs in operand list!");38523853if (!checkOperandClass(CGI.Operands[i], R))3854I.error("Operand $" + OpName + " class mismatch!");38553856// Remember the return type.3857Results.push_back(CGI.Operands[i].Rec);38583859// Remember the result index.3860ResultIndices.push_back(std::distance(InstResults.begin(), InstResultIter));38613862// Okay, this one checks out.3863InstResultIter->second = nullptr;3864}38653866// Loop over the inputs next.3867std::vector<TreePatternNodePtr> ResultNodeOperands;3868std::vector<Record *> Operands;3869for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {3870CGIOperandList::OperandInfo &Op = CGI.Operands[i];3871const std::string &OpName = Op.Name;3872if (OpName.empty()) {3873I.error("Operand #" + Twine(i) + " in operands list has no name!");3874continue;3875}38763877if (!InstInputs.count(OpName)) {3878// If this is an operand with a DefaultOps set filled in, we can ignore3879// this. When we codegen it, we will do so as always executed.3880if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {3881// Does it have a non-empty DefaultOps field? If so, ignore this3882// operand.3883if (!getDefaultOperand(Op.Rec).DefaultOps.empty())3884continue;3885}3886I.error("Operand $" + OpName +3887" does not appear in the instruction pattern");3888continue;3889}3890TreePatternNodePtr InVal = InstInputs[OpName];3891InstInputs.erase(OpName); // It occurred, remove from map.38923893if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {3894Record *InRec = cast<DefInit>(InVal->getLeafValue())->getDef();3895if (!checkOperandClass(Op, InRec)) {3896I.error("Operand $" + OpName +3897"'s register class disagrees"3898" between the operand and pattern");3899continue;3900}3901}3902Operands.push_back(Op.Rec);39033904// Construct the result for the dest-pattern operand list.3905TreePatternNodePtr OpNode = InVal->clone();39063907// No predicate is useful on the result.3908OpNode->clearPredicateCalls();39093910// Promote the xform function to be an explicit node if set.3911if (Record *Xform = OpNode->getTransformFn()) {3912OpNode->setTransformFn(nullptr);3913std::vector<TreePatternNodePtr> Children;3914Children.push_back(OpNode);3915OpNode = makeIntrusiveRefCnt<TreePatternNode>(Xform, std::move(Children),3916OpNode->getNumTypes());3917}39183919ResultNodeOperands.push_back(std::move(OpNode));3920}39213922if (!InstInputs.empty())3923I.error("Input operand $" + InstInputs.begin()->first +3924" occurs in pattern but not in operands list!");39253926TreePatternNodePtr ResultPattern = makeIntrusiveRefCnt<TreePatternNode>(3927I.getRecord(), std::move(ResultNodeOperands),3928GetNumNodeResults(I.getRecord(), *this));3929// Copy fully inferred output node types to instruction result pattern.3930for (unsigned i = 0; i != NumResults; ++i) {3931assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");3932ResultPattern->setType(i, ResNodes[i]->getExtType(0));3933ResultPattern->setResultIndex(i, ResultIndices[i]);3934}39353936// FIXME: Assume only the first tree is the pattern. The others are clobber3937// nodes.3938TreePatternNodePtr Pattern = I.getTree(0);3939TreePatternNodePtr SrcPattern;3940if (Pattern->getOperator()->getName() == "set") {3941SrcPattern = Pattern->getChild(Pattern->getNumChildren() - 1).clone();3942} else {3943// Not a set (store or something?)3944SrcPattern = Pattern;3945}39463947// Create and insert the instruction.3948// FIXME: InstImpResults should not be part of DAGInstruction.3949Record *R = I.getRecord();3950DAGInsts.try_emplace(R, std::move(Results), std::move(Operands),3951std::move(InstImpResults), SrcPattern, ResultPattern);39523953LLVM_DEBUG(I.dump());3954}39553956/// ParseInstructions - Parse all of the instructions, inlining and resolving3957/// any fragments involved. This populates the Instructions list with fully3958/// resolved instructions.3959void CodeGenDAGPatterns::ParseInstructions() {3960std::vector<Record *> Instrs =3961Records.getAllDerivedDefinitions("Instruction");39623963for (Record *Instr : Instrs) {3964ListInit *LI = nullptr;39653966if (isa<ListInit>(Instr->getValueInit("Pattern")))3967LI = Instr->getValueAsListInit("Pattern");39683969// If there is no pattern, only collect minimal information about the3970// instruction for its operand list. We have to assume that there is one3971// result, as we have no detailed info. A pattern which references the3972// null_frag operator is as-if no pattern were specified. Normally this3973// is from a multiclass expansion w/ a SDPatternOperator passed in as3974// null_frag.3975if (!LI || LI->empty() || hasNullFragReference(LI)) {3976std::vector<Record *> Results;3977std::vector<Record *> Operands;39783979CodeGenInstruction &InstInfo = Target.getInstruction(Instr);39803981if (InstInfo.Operands.size() != 0) {3982for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)3983Results.push_back(InstInfo.Operands[j].Rec);39843985// The rest are inputs.3986for (unsigned j = InstInfo.Operands.NumDefs,3987e = InstInfo.Operands.size();3988j < e; ++j)3989Operands.push_back(InstInfo.Operands[j].Rec);3990}39913992// Create and insert the instruction.3993Instructions.try_emplace(Instr, std::move(Results), std::move(Operands),3994std::vector<Record *>());3995continue; // no pattern.3996}39973998CodeGenInstruction &CGI = Target.getInstruction(Instr);3999parseInstructionPattern(CGI, LI, Instructions);4000}40014002// If we can, convert the instructions to be patterns that are matched!4003for (auto &Entry : Instructions) {4004Record *Instr = Entry.first;4005DAGInstruction &TheInst = Entry.second;4006TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();4007TreePatternNodePtr ResultPattern = TheInst.getResultPattern();40084009if (SrcPattern && ResultPattern) {4010TreePattern Pattern(Instr, SrcPattern, true, *this);4011TreePattern Result(Instr, ResultPattern, false, *this);4012ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());4013}4014}4015}40164017typedef std::pair<TreePatternNode *, unsigned> NameRecord;40184019static void FindNames(TreePatternNode &P,4020std::map<std::string, NameRecord> &Names,4021TreePattern *PatternTop) {4022if (!P.getName().empty()) {4023NameRecord &Rec = Names[P.getName()];4024// If this is the first instance of the name, remember the node.4025if (Rec.second++ == 0)4026Rec.first = &P;4027else if (Rec.first->getExtTypes() != P.getExtTypes())4028PatternTop->error("repetition of value: $" + P.getName() +4029" where different uses have different types!");4030}40314032if (!P.isLeaf()) {4033for (unsigned i = 0, e = P.getNumChildren(); i != e; ++i)4034FindNames(P.getChild(i), Names, PatternTop);4035}4036}40374038void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,4039PatternToMatch &&PTM) {4040// Do some sanity checking on the pattern we're about to match.4041std::string Reason;4042if (!PTM.getSrcPattern().canPatternMatch(Reason, *this)) {4043PrintWarning(Pattern->getRecord()->getLoc(),4044Twine("Pattern can never match: ") + Reason);4045return;4046}40474048// If the source pattern's root is a complex pattern, that complex pattern4049// must specify the nodes it can potentially match.4050if (const ComplexPattern *CP =4051PTM.getSrcPattern().getComplexPatternInfo(*this))4052if (CP->getRootNodes().empty())4053Pattern->error("ComplexPattern at root must specify list of opcodes it"4054" could match");40554056// Find all of the named values in the input and output, ensure they have the4057// same type.4058std::map<std::string, NameRecord> SrcNames, DstNames;4059FindNames(PTM.getSrcPattern(), SrcNames, Pattern);4060FindNames(PTM.getDstPattern(), DstNames, Pattern);40614062// Scan all of the named values in the destination pattern, rejecting them if4063// they don't exist in the input pattern.4064for (const auto &Entry : DstNames) {4065if (SrcNames[Entry.first].first == nullptr)4066Pattern->error("Pattern has input without matching name in output: $" +4067Entry.first);4068}40694070// Scan all of the named values in the source pattern, rejecting them if the4071// name isn't used in the dest, and isn't used to tie two values together.4072for (const auto &Entry : SrcNames)4073if (DstNames[Entry.first].first == nullptr &&4074SrcNames[Entry.first].second == 1)4075Pattern->error("Pattern has dead named input: $" + Entry.first);40764077PatternsToMatch.push_back(std::move(PTM));4078}40794080void CodeGenDAGPatterns::InferInstructionFlags() {4081ArrayRef<const CodeGenInstruction *> Instructions =4082Target.getInstructionsByEnumValue();40834084unsigned Errors = 0;40854086// Try to infer flags from all patterns in PatternToMatch. These include4087// both the primary instruction patterns (which always come first) and4088// patterns defined outside the instruction.4089for (const PatternToMatch &PTM : ptms()) {4090// We can only infer from single-instruction patterns, otherwise we won't4091// know which instruction should get the flags.4092SmallVector<Record *, 8> PatInstrs;4093getInstructionsInTree(PTM.getDstPattern(), PatInstrs);4094if (PatInstrs.size() != 1)4095continue;40964097// Get the single instruction.4098CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());40994100// Only infer properties from the first pattern. We'll verify the others.4101if (InstInfo.InferredFrom)4102continue;41034104InstAnalyzer PatInfo(*this);4105PatInfo.Analyze(PTM);4106Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());4107}41084109if (Errors)4110PrintFatalError("pattern conflicts");41114112// If requested by the target, guess any undefined properties.4113if (Target.guessInstructionProperties()) {4114for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {4115CodeGenInstruction *InstInfo =4116const_cast<CodeGenInstruction *>(Instructions[i]);4117if (InstInfo->InferredFrom)4118continue;4119// The mayLoad and mayStore flags default to false.4120// Conservatively assume hasSideEffects if it wasn't explicit.4121if (InstInfo->hasSideEffects_Unset)4122InstInfo->hasSideEffects = true;4123}4124return;4125}41264127// Complain about any flags that are still undefined.4128for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {4129CodeGenInstruction *InstInfo =4130const_cast<CodeGenInstruction *>(Instructions[i]);4131if (InstInfo->InferredFrom)4132continue;4133if (InstInfo->hasSideEffects_Unset)4134PrintError(InstInfo->TheDef->getLoc(),4135"Can't infer hasSideEffects from patterns");4136if (InstInfo->mayStore_Unset)4137PrintError(InstInfo->TheDef->getLoc(),4138"Can't infer mayStore from patterns");4139if (InstInfo->mayLoad_Unset)4140PrintError(InstInfo->TheDef->getLoc(),4141"Can't infer mayLoad from patterns");4142}4143}41444145/// Verify instruction flags against pattern node properties.4146void CodeGenDAGPatterns::VerifyInstructionFlags() {4147unsigned Errors = 0;4148for (const PatternToMatch &PTM : ptms()) {4149SmallVector<Record *, 8> Instrs;4150getInstructionsInTree(PTM.getDstPattern(), Instrs);4151if (Instrs.empty())4152continue;41534154// Count the number of instructions with each flag set.4155unsigned NumSideEffects = 0;4156unsigned NumStores = 0;4157unsigned NumLoads = 0;4158for (const Record *Instr : Instrs) {4159const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);4160NumSideEffects += InstInfo.hasSideEffects;4161NumStores += InstInfo.mayStore;4162NumLoads += InstInfo.mayLoad;4163}41644165// Analyze the source pattern.4166InstAnalyzer PatInfo(*this);4167PatInfo.Analyze(PTM);41684169// Collect error messages.4170SmallVector<std::string, 4> Msgs;41714172// Check for missing flags in the output.4173// Permit extra flags for now at least.4174if (PatInfo.hasSideEffects && !NumSideEffects)4175Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");41764177// Don't verify store flags on instructions with side effects. At least for4178// intrinsics, side effects implies mayStore.4179if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)4180Msgs.push_back("pattern may store, but mayStore isn't set");41814182// Similarly, mayStore implies mayLoad on intrinsics.4183if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)4184Msgs.push_back("pattern may load, but mayLoad isn't set");41854186// Print error messages.4187if (Msgs.empty())4188continue;4189++Errors;41904191for (const std::string &Msg : Msgs)4192PrintError(4193PTM.getSrcRecord()->getLoc(),4194Twine(Msg) + " on the " +4195(Instrs.size() == 1 ? "instruction" : "output instructions"));4196// Provide the location of the relevant instruction definitions.4197for (const Record *Instr : Instrs) {4198if (Instr != PTM.getSrcRecord())4199PrintError(Instr->getLoc(), "defined here");4200const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);4201if (InstInfo.InferredFrom && InstInfo.InferredFrom != InstInfo.TheDef &&4202InstInfo.InferredFrom != PTM.getSrcRecord())4203PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");4204}4205}4206if (Errors)4207PrintFatalError("Errors in DAG patterns");4208}42094210/// Given a pattern result with an unresolved type, see if we can find one4211/// instruction with an unresolved result type. Force this result type to an4212/// arbitrary element if it's possible types to converge results.4213static bool ForceArbitraryInstResultType(TreePatternNode &N, TreePattern &TP) {4214if (N.isLeaf())4215return false;42164217// Analyze children.4218for (unsigned i = 0, e = N.getNumChildren(); i != e; ++i)4219if (ForceArbitraryInstResultType(N.getChild(i), TP))4220return true;42214222if (!N.getOperator()->isSubClassOf("Instruction"))4223return false;42244225// If this type is already concrete or completely unknown we can't do4226// anything.4227TypeInfer &TI = TP.getInfer();4228for (unsigned i = 0, e = N.getNumTypes(); i != e; ++i) {4229if (N.getExtType(i).empty() || TI.isConcrete(N.getExtType(i), false))4230continue;42314232// Otherwise, force its type to an arbitrary choice.4233if (TI.forceArbitrary(N.getExtType(i)))4234return true;4235}42364237return false;4238}42394240// Promote xform function to be an explicit node wherever set.4241static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {4242if (Record *Xform = N->getTransformFn()) {4243N->setTransformFn(nullptr);4244std::vector<TreePatternNodePtr> Children;4245Children.push_back(PromoteXForms(N));4246return makeIntrusiveRefCnt<TreePatternNode>(Xform, std::move(Children),4247N->getNumTypes());4248}42494250if (!N->isLeaf())4251for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {4252TreePatternNodePtr Child = N->getChildShared(i);4253N->setChild(i, PromoteXForms(Child));4254}4255return N;4256}42574258void CodeGenDAGPatterns::ParseOnePattern(4259Record *TheDef, TreePattern &Pattern, TreePattern &Result,4260const std::vector<Record *> &InstImpResults, bool ShouldIgnore) {42614262// Inline pattern fragments and expand multiple alternatives.4263Pattern.InlinePatternFragments();4264Result.InlinePatternFragments();42654266if (Result.getNumTrees() != 1)4267Result.error("Cannot use multi-alternative fragments in result pattern!");42684269// Infer types.4270bool IterateInference;4271bool InferredAllPatternTypes, InferredAllResultTypes;4272do {4273// Infer as many types as possible. If we cannot infer all of them, we4274// can never do anything with this pattern: report it to the user.4275InferredAllPatternTypes =4276Pattern.InferAllTypes(&Pattern.getNamedNodesMap());42774278// Infer as many types as possible. If we cannot infer all of them, we4279// can never do anything with this pattern: report it to the user.4280InferredAllResultTypes = Result.InferAllTypes(&Pattern.getNamedNodesMap());42814282IterateInference = false;42834284// Apply the type of the result to the source pattern. This helps us4285// resolve cases where the input type is known to be a pointer type (which4286// is considered resolved), but the result knows it needs to be 32- or4287// 64-bits. Infer the other way for good measure.4288for (const auto &T : Pattern.getTrees())4289for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),4290T->getNumTypes());4291i != e; ++i) {4292IterateInference |=4293T->UpdateNodeType(i, Result.getOnlyTree()->getExtType(i), Result);4294IterateInference |=4295Result.getOnlyTree()->UpdateNodeType(i, T->getExtType(i), Result);4296}42974298// If our iteration has converged and the input pattern's types are fully4299// resolved but the result pattern is not fully resolved, we may have a4300// situation where we have two instructions in the result pattern and4301// the instructions require a common register class, but don't care about4302// what actual MVT is used. This is actually a bug in our modelling:4303// output patterns should have register classes, not MVTs.4304//4305// In any case, to handle this, we just go through and disambiguate some4306// arbitrary types to the result pattern's nodes.4307if (!IterateInference && InferredAllPatternTypes && !InferredAllResultTypes)4308IterateInference =4309ForceArbitraryInstResultType(*Result.getTree(0), Result);4310} while (IterateInference);43114312// Verify that we inferred enough types that we can do something with the4313// pattern and result. If these fire the user has to add type casts.4314if (!InferredAllPatternTypes)4315Pattern.error("Could not infer all types in pattern!");4316if (!InferredAllResultTypes) {4317Pattern.dump();4318Result.error("Could not infer all types in pattern result!");4319}43204321// Promote xform function to be an explicit node wherever set.4322TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());43234324TreePattern Temp(Result.getRecord(), DstShared, false, *this);4325Temp.InferAllTypes();43264327ListInit *Preds = TheDef->getValueAsListInit("Predicates");4328int Complexity = TheDef->getValueAsInt("AddedComplexity");43294330if (PatternRewriter)4331PatternRewriter(&Pattern);43324333// A pattern may end up with an "impossible" type, i.e. a situation4334// where all types have been eliminated for some node in this pattern.4335// This could occur for intrinsics that only make sense for a specific4336// value type, and use a specific register class. If, for some mode,4337// that register class does not accept that type, the type inference4338// will lead to a contradiction, which is not an error however, but4339// a sign that this pattern will simply never match.4340if (Temp.getOnlyTree()->hasPossibleType()) {4341for (const auto &T : Pattern.getTrees()) {4342if (T->hasPossibleType())4343AddPatternToMatch(&Pattern,4344PatternToMatch(TheDef, Preds, T, Temp.getOnlyTree(),4345InstImpResults, Complexity,4346TheDef->getID(), ShouldIgnore));4347}4348} else {4349// Show a message about a dropped pattern with some info to make it4350// easier to identify it in the .td files.4351LLVM_DEBUG({4352dbgs() << "Dropping: ";4353Pattern.dump();4354Temp.getOnlyTree()->dump();4355dbgs() << "\n";4356});4357}4358}43594360void CodeGenDAGPatterns::ParsePatterns() {4361std::vector<Record *> Patterns = Records.getAllDerivedDefinitions("Pattern");43624363for (Record *CurPattern : Patterns) {4364DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");43654366// If the pattern references the null_frag, there's nothing to do.4367if (hasNullFragReference(Tree))4368continue;43694370TreePattern Pattern(CurPattern, Tree, true, *this);43714372ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");4373if (LI->empty())4374continue; // no pattern.43754376// Parse the instruction.4377TreePattern Result(CurPattern, LI, false, *this);43784379if (Result.getNumTrees() != 1)4380Result.error("Cannot handle instructions producing instructions "4381"with temporaries yet!");43824383// Validate that the input pattern is correct.4384std::map<std::string, TreePatternNodePtr> InstInputs;4385MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>4386InstResults;4387std::vector<Record *> InstImpResults;4388for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)4389FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,4390InstResults, InstImpResults);43914392ParseOnePattern(CurPattern, Pattern, Result, InstImpResults,4393CurPattern->getValueAsBit("GISelShouldIgnore"));4394}4395}43964397static void collectModes(std::set<unsigned> &Modes, const TreePatternNode &N) {4398for (const TypeSetByHwMode &VTS : N.getExtTypes())4399for (const auto &I : VTS)4400Modes.insert(I.first);44014402for (unsigned i = 0, e = N.getNumChildren(); i != e; ++i)4403collectModes(Modes, N.getChild(i));4404}44054406void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {4407const CodeGenHwModes &CGH = getTargetInfo().getHwModes();4408if (CGH.getNumModeIds() == 1)4409return;44104411std::vector<PatternToMatch> Copy;4412PatternsToMatch.swap(Copy);44134414auto AppendPattern = [this](PatternToMatch &P, unsigned Mode,4415StringRef Check) {4416TreePatternNodePtr NewSrc = P.getSrcPattern().clone();4417TreePatternNodePtr NewDst = P.getDstPattern().clone();4418if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {4419return;4420}44214422PatternsToMatch.emplace_back(4423P.getSrcRecord(), P.getPredicates(), std::move(NewSrc),4424std::move(NewDst), P.getDstRegs(), P.getAddedComplexity(),4425Record::getNewUID(Records), P.getGISelShouldIgnore(), Check);4426};44274428for (PatternToMatch &P : Copy) {4429const TreePatternNode *SrcP = nullptr, *DstP = nullptr;4430if (P.getSrcPattern().hasProperTypeByHwMode())4431SrcP = &P.getSrcPattern();4432if (P.getDstPattern().hasProperTypeByHwMode())4433DstP = &P.getDstPattern();4434if (!SrcP && !DstP) {4435PatternsToMatch.push_back(P);4436continue;4437}44384439std::set<unsigned> Modes;4440if (SrcP)4441collectModes(Modes, *SrcP);4442if (DstP)4443collectModes(Modes, *DstP);44444445// The predicate for the default mode needs to be constructed for each4446// pattern separately.4447// Since not all modes must be present in each pattern, if a mode m is4448// absent, then there is no point in constructing a check for m. If such4449// a check was created, it would be equivalent to checking the default4450// mode, except not all modes' predicates would be a part of the checking4451// code. The subsequently generated check for the default mode would then4452// have the exact same patterns, but a different predicate code. To avoid4453// duplicated patterns with different predicate checks, construct the4454// default check as a negation of all predicates that are actually present4455// in the source/destination patterns.4456SmallString<128> DefaultCheck;44574458for (unsigned M : Modes) {4459if (M == DefaultMode)4460continue;44614462// Fill the map entry for this mode.4463const HwMode &HM = CGH.getMode(M);4464AppendPattern(P, M, HM.Predicates);44654466// Add negations of the HM's predicates to the default predicate.4467if (!DefaultCheck.empty())4468DefaultCheck += " && ";4469DefaultCheck += "!(";4470DefaultCheck += HM.Predicates;4471DefaultCheck += ")";4472}44734474bool HasDefault = Modes.count(DefaultMode);4475if (HasDefault)4476AppendPattern(P, DefaultMode, DefaultCheck);4477}4478}44794480/// Dependent variable map for CodeGenDAGPattern variant generation4481typedef StringMap<int> DepVarMap;44824483static void FindDepVarsOf(TreePatternNode &N, DepVarMap &DepMap) {4484if (N.isLeaf()) {4485if (N.hasName() && isa<DefInit>(N.getLeafValue()))4486DepMap[N.getName()]++;4487} else {4488for (size_t i = 0, e = N.getNumChildren(); i != e; ++i)4489FindDepVarsOf(N.getChild(i), DepMap);4490}4491}44924493/// Find dependent variables within child patterns4494static void FindDepVars(TreePatternNode &N, MultipleUseVarSet &DepVars) {4495DepVarMap depcounts;4496FindDepVarsOf(N, depcounts);4497for (const auto &Pair : depcounts) {4498if (Pair.getValue() > 1)4499DepVars.insert(Pair.getKey());4500}4501}45024503#ifndef NDEBUG4504/// Dump the dependent variable set:4505static void DumpDepVars(MultipleUseVarSet &DepVars) {4506if (DepVars.empty()) {4507LLVM_DEBUG(errs() << "<empty set>");4508} else {4509LLVM_DEBUG(errs() << "[ ");4510for (const auto &DepVar : DepVars) {4511LLVM_DEBUG(errs() << DepVar.getKey() << " ");4512}4513LLVM_DEBUG(errs() << "]");4514}4515}4516#endif45174518/// CombineChildVariants - Given a bunch of permutations of each child of the4519/// 'operator' node, put them together in all possible ways.4520static void CombineChildVariants(4521TreePatternNodePtr Orig,4522const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,4523std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,4524const MultipleUseVarSet &DepVars) {4525// Make sure that each operand has at least one variant to choose from.4526for (const auto &Variants : ChildVariants)4527if (Variants.empty())4528return;45294530// The end result is an all-pairs construction of the resultant pattern.4531std::vector<unsigned> Idxs(ChildVariants.size());4532bool NotDone;4533do {4534#ifndef NDEBUG4535LLVM_DEBUG(if (!Idxs.empty()) {4536errs() << Orig->getOperator()->getName() << ": Idxs = [ ";4537for (unsigned Idx : Idxs) {4538errs() << Idx << " ";4539}4540errs() << "]\n";4541});4542#endif4543// Create the variant and add it to the output list.4544std::vector<TreePatternNodePtr> NewChildren;4545NewChildren.reserve(ChildVariants.size());4546for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)4547NewChildren.push_back(ChildVariants[i][Idxs[i]]);4548TreePatternNodePtr R = makeIntrusiveRefCnt<TreePatternNode>(4549Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());45504551// Copy over properties.4552R->setName(Orig->getName());4553R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());4554R->setPredicateCalls(Orig->getPredicateCalls());4555R->setGISelFlagsRecord(Orig->getGISelFlagsRecord());4556R->setTransformFn(Orig->getTransformFn());4557for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)4558R->setType(i, Orig->getExtType(i));45594560// If this pattern cannot match, do not include it as a variant.4561std::string ErrString;4562// Scan to see if this pattern has already been emitted. We can get4563// duplication due to things like commuting:4564// (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)4565// which are the same pattern. Ignore the dups.4566if (R->canPatternMatch(ErrString, CDP) &&4567none_of(OutVariants, [&](TreePatternNodePtr Variant) {4568return R->isIsomorphicTo(*Variant, DepVars);4569}))4570OutVariants.push_back(R);45714572// Increment indices to the next permutation by incrementing the4573// indices from last index backward, e.g., generate the sequence4574// [0, 0], [0, 1], [1, 0], [1, 1].4575int IdxsIdx;4576for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {4577if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())4578Idxs[IdxsIdx] = 0;4579else4580break;4581}4582NotDone = (IdxsIdx >= 0);4583} while (NotDone);4584}45854586/// CombineChildVariants - A helper function for binary operators.4587///4588static void CombineChildVariants(TreePatternNodePtr Orig,4589const std::vector<TreePatternNodePtr> &LHS,4590const std::vector<TreePatternNodePtr> &RHS,4591std::vector<TreePatternNodePtr> &OutVariants,4592CodeGenDAGPatterns &CDP,4593const MultipleUseVarSet &DepVars) {4594std::vector<std::vector<TreePatternNodePtr>> ChildVariants;4595ChildVariants.push_back(LHS);4596ChildVariants.push_back(RHS);4597CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);4598}45994600static void4601GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,4602std::vector<TreePatternNodePtr> &Children) {4603assert(N->getNumChildren() == 2 &&4604"Associative but doesn't have 2 children!");4605Record *Operator = N->getOperator();46064607// Only permit raw nodes.4608if (!N->getName().empty() || !N->getPredicateCalls().empty() ||4609N->getTransformFn()) {4610Children.push_back(N);4611return;4612}46134614if (N->getChild(0).isLeaf() || N->getChild(0).getOperator() != Operator)4615Children.push_back(N->getChildShared(0));4616else4617GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);46184619if (N->getChild(1).isLeaf() || N->getChild(1).getOperator() != Operator)4620Children.push_back(N->getChildShared(1));4621else4622GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);4623}46244625/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of4626/// the (potentially recursive) pattern by using algebraic laws.4627///4628static void GenerateVariantsOf(TreePatternNodePtr N,4629std::vector<TreePatternNodePtr> &OutVariants,4630CodeGenDAGPatterns &CDP,4631const MultipleUseVarSet &DepVars) {4632// We cannot permute leaves or ComplexPattern uses.4633if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {4634OutVariants.push_back(N);4635return;4636}46374638// Look up interesting info about the node.4639const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());46404641// If this node is associative, re-associate.4642if (NodeInfo.hasProperty(SDNPAssociative)) {4643// Re-associate by pulling together all of the linked operators4644std::vector<TreePatternNodePtr> MaximalChildren;4645GatherChildrenOfAssociativeOpcode(N, MaximalChildren);46464647// Only handle child sizes of 3. Otherwise we'll end up trying too many4648// permutations.4649if (MaximalChildren.size() == 3) {4650// Find the variants of all of our maximal children.4651std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;4652GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);4653GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);4654GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);46554656// There are only two ways we can permute the tree:4657// (A op B) op C and A op (B op C)4658// Within these forms, we can also permute A/B/C.46594660// Generate legal pair permutations of A/B/C.4661std::vector<TreePatternNodePtr> ABVariants;4662std::vector<TreePatternNodePtr> BAVariants;4663std::vector<TreePatternNodePtr> ACVariants;4664std::vector<TreePatternNodePtr> CAVariants;4665std::vector<TreePatternNodePtr> BCVariants;4666std::vector<TreePatternNodePtr> CBVariants;4667CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);4668CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);4669CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);4670CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);4671CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);4672CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);46734674// Combine those into the result: (x op x) op x4675CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);4676CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);4677CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);4678CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);4679CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);4680CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);46814682// Combine those into the result: x op (x op x)4683CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);4684CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);4685CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);4686CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);4687CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);4688CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);4689return;4690}4691}46924693// Compute permutations of all children.4694std::vector<std::vector<TreePatternNodePtr>> ChildVariants(4695N->getNumChildren());4696for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)4697GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);46984699// Build all permutations based on how the children were formed.4700CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);47014702// If this node is commutative, consider the commuted order.4703bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);4704if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {4705unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.4706assert(N->getNumChildren() >= (2 + Skip) &&4707"Commutative but doesn't have 2 children!");4708// Don't allow commuting children which are actually register references.4709bool NoRegisters = true;4710unsigned i = 0 + Skip;4711unsigned e = 2 + Skip;4712for (; i != e; ++i) {4713TreePatternNode &Child = N->getChild(i);4714if (Child.isLeaf())4715if (DefInit *DI = dyn_cast<DefInit>(Child.getLeafValue())) {4716Record *RR = DI->getDef();4717if (RR->isSubClassOf("Register"))4718NoRegisters = false;4719}4720}4721// Consider the commuted order.4722if (NoRegisters) {4723// Swap the first two operands after the intrinsic id, if present.4724unsigned i = isCommIntrinsic ? 1 : 0;4725std::swap(ChildVariants[i], ChildVariants[i + 1]);4726CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);4727}4728}4729}47304731// GenerateVariants - Generate variants. For example, commutative patterns can4732// match multiple ways. Add them to PatternsToMatch as well.4733void CodeGenDAGPatterns::GenerateVariants() {4734LLVM_DEBUG(errs() << "Generating instruction variants.\n");47354736// Loop over all of the patterns we've collected, checking to see if we can4737// generate variants of the instruction, through the exploitation of4738// identities. This permits the target to provide aggressive matching without4739// the .td file having to contain tons of variants of instructions.4740//4741// Note that this loop adds new patterns to the PatternsToMatch list, but we4742// intentionally do not reconsider these. Any variants of added patterns have4743// already been added.4744//4745for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {4746MultipleUseVarSet DepVars;4747std::vector<TreePatternNodePtr> Variants;4748FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);4749LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");4750LLVM_DEBUG(DumpDepVars(DepVars));4751LLVM_DEBUG(errs() << "\n");4752GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,4753*this, DepVars);47544755assert(PatternsToMatch[i].getHwModeFeatures().empty() &&4756"HwModes should not have been expanded yet!");47574758assert(!Variants.empty() && "Must create at least original variant!");4759if (Variants.size() == 1) // No additional variants for this pattern.4760continue;47614762LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";4763PatternsToMatch[i].getSrcPattern().dump(); errs() << "\n");47644765for (unsigned v = 0, e = Variants.size(); v != e; ++v) {4766TreePatternNodePtr Variant = Variants[v];47674768LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump();4769errs() << "\n");47704771// Scan to see if an instruction or explicit pattern already matches this.4772bool AlreadyExists = false;4773for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {4774// Skip if the top level predicates do not match.4775if ((i != p) && (PatternsToMatch[i].getPredicates() !=4776PatternsToMatch[p].getPredicates()))4777continue;4778// Check to see if this variant already exists.4779if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),4780DepVars)) {4781LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");4782AlreadyExists = true;4783break;4784}4785}4786// If we already have it, ignore the variant.4787if (AlreadyExists)4788continue;47894790// Otherwise, add it to the list of patterns we have.4791PatternsToMatch.emplace_back(4792PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),4793Variant, PatternsToMatch[i].getDstPatternShared(),4794PatternsToMatch[i].getDstRegs(),4795PatternsToMatch[i].getAddedComplexity(), Record::getNewUID(Records),4796PatternsToMatch[i].getGISelShouldIgnore(),4797PatternsToMatch[i].getHwModeFeatures());4798}47994800LLVM_DEBUG(errs() << "\n");4801}4802}480348044805