#ifndef LLVM_UTILS_TABLEGEN_CODEGENDAGPATTERNS_H
#define LLVM_UTILS_TABLEGEN_CODEGENDAGPATTERNS_H
#include "CodeGenIntrinsics.h"
#include "CodeGenTarget.h"
#include "SDNodeProperties.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include <algorithm>
#include <array>
#include <functional>
#include <map>
#include <numeric>
#include <vector>
namespace llvm {
class Record;
class Init;
class ListInit;
class DagInit;
class SDNodeInfo;
class TreePattern;
class TreePatternNode;
class CodeGenDAGPatterns;
using TreePatternNodePtr = std::shared_ptr<TreePatternNode>;
struct MachineValueTypeSet {
static_assert(std::is_same<std::underlying_type<MVT::SimpleValueType>::type,
uint8_t>::value,
"Change uint8_t here to the SimpleValueType's type");
static unsigned constexpr Capacity = std::numeric_limits<uint8_t>::max()+1;
using WordType = uint64_t;
static unsigned constexpr WordWidth = CHAR_BIT*sizeof(WordType);
static unsigned constexpr NumWords = Capacity/WordWidth;
static_assert(NumWords*WordWidth == Capacity,
"Capacity should be a multiple of WordWidth");
LLVM_ATTRIBUTE_ALWAYS_INLINE
MachineValueTypeSet() {
clear();
}
LLVM_ATTRIBUTE_ALWAYS_INLINE
unsigned size() const {
unsigned Count = 0;
for (WordType W : Words)
Count += countPopulation(W);
return Count;
}
LLVM_ATTRIBUTE_ALWAYS_INLINE
void clear() {
std::memset(Words.data(), 0, NumWords*sizeof(WordType));
}
LLVM_ATTRIBUTE_ALWAYS_INLINE
bool empty() const {
for (WordType W : Words)
if (W != 0)
return false;
return true;
}
LLVM_ATTRIBUTE_ALWAYS_INLINE
unsigned count(MVT T) const {
return (Words[T.SimpleTy / WordWidth] >> (T.SimpleTy % WordWidth)) & 1;
}
std::pair<MachineValueTypeSet&,bool> insert(MVT T) {
bool V = count(T.SimpleTy);
Words[T.SimpleTy / WordWidth] |= WordType(1) << (T.SimpleTy % WordWidth);
return {*this, V};
}
MachineValueTypeSet &insert(const MachineValueTypeSet &S) {
for (unsigned i = 0; i != NumWords; ++i)
Words[i] |= S.Words[i];
return *this;
}
LLVM_ATTRIBUTE_ALWAYS_INLINE
void erase(MVT T) {
Words[T.SimpleTy / WordWidth] &= ~(WordType(1) << (T.SimpleTy % WordWidth));
}
void writeToStream(raw_ostream &OS) const;
struct const_iterator {
using iterator_category = std::forward_iterator_tag;
using value_type = MVT;
using difference_type = ptrdiff_t;
using pointer = const MVT*;
using reference = const MVT&;
LLVM_ATTRIBUTE_ALWAYS_INLINE
MVT operator*() const {
assert(Pos != Capacity);
return MVT::SimpleValueType(Pos);
}
LLVM_ATTRIBUTE_ALWAYS_INLINE
const_iterator(const MachineValueTypeSet *S, bool End) : Set(S) {
Pos = End ? Capacity : find_from_pos(0);
}
LLVM_ATTRIBUTE_ALWAYS_INLINE
const_iterator &operator++() {
assert(Pos != Capacity);
Pos = find_from_pos(Pos+1);
return *this;
}
LLVM_ATTRIBUTE_ALWAYS_INLINE
bool operator==(const const_iterator &It) const {
return Set == It.Set && Pos == It.Pos;
}
LLVM_ATTRIBUTE_ALWAYS_INLINE
bool operator!=(const const_iterator &It) const {
return !operator==(It);
}
private:
unsigned find_from_pos(unsigned P) const {
unsigned SkipWords = P / WordWidth;
unsigned SkipBits = P % WordWidth;
unsigned Count = SkipWords * WordWidth;
if (SkipBits != 0) {
WordType W = Set->Words[SkipWords];
W &= maskLeadingOnes<WordType>(WordWidth-SkipBits);
if (W != 0)
return Count + findFirstSet(W);
Count += WordWidth;
SkipWords++;
}
for (unsigned i = SkipWords; i != NumWords; ++i) {
WordType W = Set->Words[i];
if (W != 0)
return Count + findFirstSet(W);
Count += WordWidth;
}
return Capacity;
}
const MachineValueTypeSet *Set;
unsigned Pos;
};
LLVM_ATTRIBUTE_ALWAYS_INLINE
const_iterator begin() const { return const_iterator(this, false); }
LLVM_ATTRIBUTE_ALWAYS_INLINE
const_iterator end() const { return const_iterator(this, true); }
LLVM_ATTRIBUTE_ALWAYS_INLINE
bool operator==(const MachineValueTypeSet &S) const {
return Words == S.Words;
}
LLVM_ATTRIBUTE_ALWAYS_INLINE
bool operator!=(const MachineValueTypeSet &S) const {
return !operator==(S);
}
private:
friend struct const_iterator;
std::array<WordType,NumWords> Words;
};
raw_ostream &operator<<(raw_ostream &OS, const MachineValueTypeSet &T);
struct TypeSetByHwMode : public InfoByHwMode<MachineValueTypeSet> {
using SetType = MachineValueTypeSet;
SmallVector<unsigned, 16> AddrSpaces;
TypeSetByHwMode() = default;
TypeSetByHwMode(const TypeSetByHwMode &VTS) = default;
TypeSetByHwMode &operator=(const TypeSetByHwMode &) = default;
TypeSetByHwMode(MVT::SimpleValueType VT)
: TypeSetByHwMode(ValueTypeByHwMode(VT)) {}
TypeSetByHwMode(ValueTypeByHwMode VT)
: TypeSetByHwMode(ArrayRef<ValueTypeByHwMode>(&VT, 1)) {}
TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList);
SetType &getOrCreate(unsigned Mode) {
return Map[Mode];
}
bool isValueTypeByHwMode(bool AllowEmpty) const;
ValueTypeByHwMode getValueTypeByHwMode() const;
LLVM_ATTRIBUTE_ALWAYS_INLINE
bool isMachineValueType() const {
return isDefaultOnly() && Map.begin()->second.size() == 1;
}
LLVM_ATTRIBUTE_ALWAYS_INLINE
MVT getMachineValueType() const {
assert(isMachineValueType());
return *Map.begin()->second.begin();
}
bool isPossible() const;
LLVM_ATTRIBUTE_ALWAYS_INLINE
bool isDefaultOnly() const {
return Map.size() == 1 && Map.begin()->first == DefaultMode;
}
bool isPointer() const {
return getValueTypeByHwMode().isPointer();
}
unsigned getPtrAddrSpace() const {
assert(isPointer());
return getValueTypeByHwMode().PtrAddrSpace;
}
bool insert(const ValueTypeByHwMode &VVT);
bool constrain(const TypeSetByHwMode &VTS);
template <typename Predicate> bool constrain(Predicate P);
template <typename Predicate>
bool assign_if(const TypeSetByHwMode &VTS, Predicate P);
void writeToStream(raw_ostream &OS) const;
bool operator==(const TypeSetByHwMode &VTS) const;
bool operator!=(const TypeSetByHwMode &VTS) const { return !(*this == VTS); }
void dump() const;
bool validate() const;
private:
unsigned PtrAddrSpace = std::numeric_limits<unsigned>::max();
bool intersect(SetType &Out, const SetType &In);
};
raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T);
struct TypeInfer {
TypeInfer(TreePattern &T) : TP(T), ForceMode(0) {}
bool isConcrete(const TypeSetByHwMode &VTS, bool AllowEmpty) const {
return VTS.isValueTypeByHwMode(AllowEmpty);
}
ValueTypeByHwMode getConcrete(const TypeSetByHwMode &VTS,
bool AllowEmpty) const {
assert(VTS.isValueTypeByHwMode(AllowEmpty));
return VTS.getValueTypeByHwMode();
}
bool MergeInTypeInfo(TypeSetByHwMode &Out, const TypeSetByHwMode &In);
bool MergeInTypeInfo(TypeSetByHwMode &Out, MVT::SimpleValueType InVT) {
return MergeInTypeInfo(Out, TypeSetByHwMode(InVT));
}
bool MergeInTypeInfo(TypeSetByHwMode &Out, ValueTypeByHwMode InVT) {
return MergeInTypeInfo(Out, TypeSetByHwMode(InVT));
}
bool forceArbitrary(TypeSetByHwMode &Out);
bool EnforceInteger(TypeSetByHwMode &Out);
bool EnforceFloatingPoint(TypeSetByHwMode &Out);
bool EnforceScalar(TypeSetByHwMode &Out);
bool EnforceVector(TypeSetByHwMode &Out);
bool EnforceAny(TypeSetByHwMode &Out);
bool EnforceSmallerThan(TypeSetByHwMode &Small, TypeSetByHwMode &Big,
bool SmallIsVT = false);
bool EnforceVectorEltTypeIs(TypeSetByHwMode &Vec, TypeSetByHwMode &Elem);
bool EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
const ValueTypeByHwMode &VVT);
bool EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
TypeSetByHwMode &Sub);
bool EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W);
bool EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B);
void expandOverloads(TypeSetByHwMode &VTS);
void expandOverloads(TypeSetByHwMode::SetType &Out,
const TypeSetByHwMode::SetType &Legal);
struct ValidateOnExit {
ValidateOnExit(TypeSetByHwMode &T, TypeInfer &TI) : Infer(TI), VTS(T) {}
#ifndef NDEBUG
~ValidateOnExit();
#else
~ValidateOnExit() {} #endif
TypeInfer &Infer;
TypeSetByHwMode &VTS;
};
struct SuppressValidation {
SuppressValidation(TypeInfer &TI) : Infer(TI), SavedValidate(TI.Validate) {
Infer.Validate = false;
}
~SuppressValidation() {
Infer.Validate = SavedValidate;
}
TypeInfer &Infer;
bool SavedValidate;
};
TreePattern &TP;
unsigned ForceMode; bool CodeGen = false; bool Validate = true;
private:
const TypeSetByHwMode &getLegalTypes();
bool LegalTypesCached = false;
TypeSetByHwMode LegalCache;
};
typedef StringSet<> MultipleUseVarSet;
struct SDTypeConstraint {
SDTypeConstraint(Record *R, const CodeGenHwModes &CGH);
unsigned OperandNo; enum {
SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisVec, SDTCisSameAs,
SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisEltOfVec,
SDTCisSubVecOfVec, SDTCVecEltisVT, SDTCisSameNumEltsAs, SDTCisSameSizeAs
} ConstraintType;
union { struct {
unsigned OtherOperandNum;
} SDTCisSameAs_Info;
struct {
unsigned OtherOperandNum;
} SDTCisVTSmallerThanOp_Info;
struct {
unsigned BigOperandNum;
} SDTCisOpSmallerThanOp_Info;
struct {
unsigned OtherOperandNum;
} SDTCisEltOfVec_Info;
struct {
unsigned OtherOperandNum;
} SDTCisSubVecOfVec_Info;
struct {
unsigned OtherOperandNum;
} SDTCisSameNumEltsAs_Info;
struct {
unsigned OtherOperandNum;
} SDTCisSameSizeAs_Info;
} x;
ValueTypeByHwMode VVT;
bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
TreePattern &TP) const;
};
class ScopedName {
unsigned Scope;
std::string Identifier;
public:
ScopedName(unsigned Scope, StringRef Identifier)
: Scope(Scope), Identifier(std::string(Identifier)) {
assert(Scope != 0 &&
"Scope == 0 is used to indicate predicates without arguments");
}
unsigned getScope() const { return Scope; }
const std::string &getIdentifier() const { return Identifier; }
bool operator==(const ScopedName &o) const;
bool operator!=(const ScopedName &o) const;
};
class SDNodeInfo {
Record *Def;
StringRef EnumName;
StringRef SDClassName;
unsigned Properties;
unsigned NumResults;
int NumOperands;
std::vector<SDTypeConstraint> TypeConstraints;
public:
SDNodeInfo(Record *R, const CodeGenHwModes &CGH);
unsigned getNumResults() const { return NumResults; }
int getNumOperands() const { return NumOperands; }
Record *getRecord() const { return Def; }
StringRef getEnumName() const { return EnumName; }
StringRef getSDClassName() const { return SDClassName; }
const std::vector<SDTypeConstraint> &getTypeConstraints() const {
return TypeConstraints;
}
MVT::SimpleValueType getKnownType(unsigned ResNo) const;
bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const;
};
class TreePredicateFn {
TreePattern *PatFragRec;
public:
TreePredicateFn(TreePattern *N);
TreePattern *getOrigPatFragRecord() const { return PatFragRec; }
bool isAlwaysTrue() const;
bool isImmediatePattern() const { return hasImmCode(); }
std::string getImmediatePredicateCode() const {
std::string Result = getImmCode();
assert(!Result.empty() && "Isn't an immediate pattern!");
return Result;
}
bool operator==(const TreePredicateFn &RHS) const {
return PatFragRec == RHS.PatFragRec;
}
bool operator!=(const TreePredicateFn &RHS) const { return !(*this == RHS); }
std::string getFnName() const;
std::string getCodeToRunOnSDNode() const;
StringRef getImmType() const;
StringRef getImmTypeIdentifier() const;
bool usesOperands() const;
bool hasNoUse() const;
bool isLoad() const;
bool isStore() const;
bool isAtomic() const;
bool isUnindexed() const;
bool isNonExtLoad() const;
bool isAnyExtLoad() const;
bool isSignExtLoad() const;
bool isZeroExtLoad() const;
bool isNonTruncStore() const;
bool isTruncStore() const;
bool isAtomicOrderingMonotonic() const;
bool isAtomicOrderingAcquire() const;
bool isAtomicOrderingRelease() const;
bool isAtomicOrderingAcquireRelease() const;
bool isAtomicOrderingSequentiallyConsistent() const;
bool isAtomicOrderingAcquireOrStronger() const;
bool isAtomicOrderingWeakerThanAcquire() const;
bool isAtomicOrderingReleaseOrStronger() const;
bool isAtomicOrderingWeakerThanRelease() const;
Record *getMemoryVT() const;
Record *getScalarMemoryVT() const;
ListInit *getAddressSpaces() const;
int64_t getMinAlignment() const;
bool hasGISelPredicateCode() const;
std::string getGISelPredicateCode() const;
private:
bool hasPredCode() const;
bool hasImmCode() const;
std::string getPredCode() const;
std::string getImmCode() const;
bool immCodeUsesAPInt() const;
bool immCodeUsesAPFloat() const;
bool isPredefinedPredicateEqualTo(StringRef Field, bool Value) const;
};
struct TreePredicateCall {
TreePredicateFn Fn;
unsigned Scope;
TreePredicateCall(const TreePredicateFn &Fn, unsigned Scope)
: Fn(Fn), Scope(Scope) {}
bool operator==(const TreePredicateCall &o) const {
return Fn == o.Fn && Scope == o.Scope;
}
bool operator!=(const TreePredicateCall &o) const {
return !(*this == o);
}
};
class TreePatternNode {
std::vector<TypeSetByHwMode> Types;
std::vector<unsigned> ResultPerm;
Record *Operator;
Init *Val;
std::string Name;
std::vector<ScopedName> NamesAsPredicateArg;
std::vector<TreePredicateCall> PredicateCalls;
Record *TransformFn;
std::vector<TreePatternNodePtr> Children;
public:
TreePatternNode(Record *Op, std::vector<TreePatternNodePtr> Ch,
unsigned NumResults)
: Operator(Op), Val(nullptr), TransformFn(nullptr),
Children(std::move(Ch)) {
Types.resize(NumResults);
ResultPerm.resize(NumResults);
std::iota(ResultPerm.begin(), ResultPerm.end(), 0);
}
TreePatternNode(Init *val, unsigned NumResults) : Operator(nullptr), Val(val), TransformFn(nullptr) {
Types.resize(NumResults);
ResultPerm.resize(NumResults);
std::iota(ResultPerm.begin(), ResultPerm.end(), 0);
}
bool hasName() const { return !Name.empty(); }
const std::string &getName() const { return Name; }
void setName(StringRef N) { Name.assign(N.begin(), N.end()); }
const std::vector<ScopedName> &getNamesAsPredicateArg() const {
return NamesAsPredicateArg;
}
void setNamesAsPredicateArg(const std::vector<ScopedName>& Names) {
NamesAsPredicateArg = Names;
}
void addNameAsPredicateArg(const ScopedName &N) {
NamesAsPredicateArg.push_back(N);
}
bool isLeaf() const { return Val != nullptr; }
unsigned getNumTypes() const { return Types.size(); }
ValueTypeByHwMode getType(unsigned ResNo) const {
return Types[ResNo].getValueTypeByHwMode();
}
const std::vector<TypeSetByHwMode> &getExtTypes() const { return Types; }
const TypeSetByHwMode &getExtType(unsigned ResNo) const {
return Types[ResNo];
}
TypeSetByHwMode &getExtType(unsigned ResNo) { return Types[ResNo]; }
void setType(unsigned ResNo, const TypeSetByHwMode &T) { Types[ResNo] = T; }
MVT::SimpleValueType getSimpleType(unsigned ResNo) const {
return Types[ResNo].getMachineValueType().SimpleTy;
}
bool hasConcreteType(unsigned ResNo) const {
return Types[ResNo].isValueTypeByHwMode(false);
}
bool isTypeCompletelyUnknown(unsigned ResNo, TreePattern &TP) const {
return Types[ResNo].empty();
}
unsigned getNumResults() const { return ResultPerm.size(); }
unsigned getResultIndex(unsigned ResNo) const { return ResultPerm[ResNo]; }
void setResultIndex(unsigned ResNo, unsigned RI) { ResultPerm[ResNo] = RI; }
Init *getLeafValue() const { assert(isLeaf()); return Val; }
Record *getOperator() const { assert(!isLeaf()); return Operator; }
unsigned getNumChildren() const { return Children.size(); }
TreePatternNode *getChild(unsigned N) const { return Children[N].get(); }
const TreePatternNodePtr &getChildShared(unsigned N) const {
return Children[N];
}
void setChild(unsigned i, TreePatternNodePtr N) { Children[i] = N; }
bool hasChild(const TreePatternNode *N) const {
for (unsigned i = 0, e = Children.size(); i != e; ++i)
if (Children[i].get() == N)
return true;
return false;
}
bool hasProperTypeByHwMode() const;
bool hasPossibleType() const;
bool setDefaultMode(unsigned Mode);
bool hasAnyPredicate() const { return !PredicateCalls.empty(); }
const std::vector<TreePredicateCall> &getPredicateCalls() const {
return PredicateCalls;
}
void clearPredicateCalls() { PredicateCalls.clear(); }
void setPredicateCalls(const std::vector<TreePredicateCall> &Calls) {
assert(PredicateCalls.empty() && "Overwriting non-empty predicate list!");
PredicateCalls = Calls;
}
void addPredicateCall(const TreePredicateCall &Call) {
assert(!Call.Fn.isAlwaysTrue() && "Empty predicate string!");
assert(!is_contained(PredicateCalls, Call) && "predicate applied recursively");
PredicateCalls.push_back(Call);
}
void addPredicateCall(const TreePredicateFn &Fn, unsigned Scope) {
assert((Scope != 0) == Fn.usesOperands());
addPredicateCall(TreePredicateCall(Fn, Scope));
}
Record *getTransformFn() const { return TransformFn; }
void setTransformFn(Record *Fn) { TransformFn = Fn; }
const CodeGenIntrinsic *getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const;
const ComplexPattern *
getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const;
unsigned getNumMIResults(const CodeGenDAGPatterns &CGP) const;
bool NodeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const;
bool TreeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const;
bool isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const;
void print(raw_ostream &OS) const;
void dump() const;
public:
TreePatternNodePtr clone() const;
void RemoveAllTypes();
bool isIsomorphicTo(const TreePatternNode *N,
const MultipleUseVarSet &DepVars) const;
void
SubstituteFormalArguments(std::map<std::string, TreePatternNodePtr> &ArgMap);
void InlinePatternFragments(TreePatternNodePtr T,
TreePattern &TP,
std::vector<TreePatternNodePtr> &OutAlternatives);
bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
bool UpdateNodeType(unsigned ResNo, const TypeSetByHwMode &InTy,
TreePattern &TP);
bool UpdateNodeType(unsigned ResNo, MVT::SimpleValueType InTy,
TreePattern &TP);
bool UpdateNodeType(unsigned ResNo, ValueTypeByHwMode InTy,
TreePattern &TP);
bool UpdateNodeTypeFromInst(unsigned ResNo, Record *Operand, TreePattern &TP);
bool ContainsUnresolvedType(TreePattern &TP) const;
bool canPatternMatch(std::string &Reason, const CodeGenDAGPatterns &CDP);
};
inline raw_ostream &operator<<(raw_ostream &OS, const TreePatternNode &TPN) {
TPN.print(OS);
return OS;
}
class TreePattern {
std::vector<TreePatternNodePtr> Trees;
StringMap<SmallVector<TreePatternNode *, 1>> NamedNodes;
Record *TheRecord;
std::vector<std::string> Args;
CodeGenDAGPatterns &CDP;
bool isInputPattern;
bool HasError;
StringMap<std::pair<Record *, unsigned>> ComplexPatternOperands;
TypeInfer Infer;
public:
TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
CodeGenDAGPatterns &ise);
TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
CodeGenDAGPatterns &ise);
TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
CodeGenDAGPatterns &ise);
const std::vector<TreePatternNodePtr> &getTrees() const { return Trees; }
unsigned getNumTrees() const { return Trees.size(); }
const TreePatternNodePtr &getTree(unsigned i) const { return Trees[i]; }
void setTree(unsigned i, TreePatternNodePtr Tree) { Trees[i] = Tree; }
const TreePatternNodePtr &getOnlyTree() const {
assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
return Trees[0];
}
const StringMap<SmallVector<TreePatternNode *, 1>> &getNamedNodesMap() {
if (NamedNodes.empty())
ComputeNamedNodes();
return NamedNodes;
}
Record *getRecord() const { return TheRecord; }
unsigned getNumArgs() const { return Args.size(); }
const std::string &getArgName(unsigned i) const {
assert(i < Args.size() && "Argument reference out of range!");
return Args[i];
}
std::vector<std::string> &getArgList() { return Args; }
CodeGenDAGPatterns &getDAGPatterns() const { return CDP; }
void InlinePatternFragments() {
std::vector<TreePatternNodePtr> Copy = Trees;
Trees.clear();
for (unsigned i = 0, e = Copy.size(); i != e; ++i)
Copy[i]->InlinePatternFragments(Copy[i], *this, Trees);
}
bool InferAllTypes(
const StringMap<SmallVector<TreePatternNode *, 1>> *NamedTypes = nullptr);
void error(const Twine &Msg);
bool hasError() const {
return HasError;
}
void resetError() {
HasError = false;
}
TypeInfer &getInfer() { return Infer; }
void print(raw_ostream &OS) const;
void dump() const;
private:
TreePatternNodePtr ParseTreePattern(Init *DI, StringRef OpName);
void ComputeNamedNodes();
void ComputeNamedNodes(TreePatternNode *N);
};
inline bool TreePatternNode::UpdateNodeType(unsigned ResNo,
const TypeSetByHwMode &InTy,
TreePattern &TP) {
TypeSetByHwMode VTS(InTy);
TP.getInfer().expandOverloads(VTS);
return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS);
}
inline bool TreePatternNode::UpdateNodeType(unsigned ResNo,
MVT::SimpleValueType InTy,
TreePattern &TP) {
TypeSetByHwMode VTS(InTy);
TP.getInfer().expandOverloads(VTS);
return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS);
}
inline bool TreePatternNode::UpdateNodeType(unsigned ResNo,
ValueTypeByHwMode InTy,
TreePattern &TP) {
TypeSetByHwMode VTS(InTy);
TP.getInfer().expandOverloads(VTS);
return TP.getInfer().MergeInTypeInfo(Types[ResNo], VTS);
}
struct DAGDefaultOperand {
std::vector<TreePatternNodePtr> DefaultOps;
};
class DAGInstruction {
std::vector<Record*> Results;
std::vector<Record*> Operands;
std::vector<Record*> ImpResults;
TreePatternNodePtr SrcPattern;
TreePatternNodePtr ResultPattern;
public:
DAGInstruction(const std::vector<Record*> &results,
const std::vector<Record*> &operands,
const std::vector<Record*> &impresults,
TreePatternNodePtr srcpattern = nullptr,
TreePatternNodePtr resultpattern = nullptr)
: Results(results), Operands(operands), ImpResults(impresults),
SrcPattern(srcpattern), ResultPattern(resultpattern) {}
unsigned getNumResults() const { return Results.size(); }
unsigned getNumOperands() const { return Operands.size(); }
unsigned getNumImpResults() const { return ImpResults.size(); }
const std::vector<Record*>& getImpResults() const { return ImpResults; }
Record *getResult(unsigned RN) const {
assert(RN < Results.size());
return Results[RN];
}
Record *getOperand(unsigned ON) const {
assert(ON < Operands.size());
return Operands[ON];
}
Record *getImpResult(unsigned RN) const {
assert(RN < ImpResults.size());
return ImpResults[RN];
}
TreePatternNodePtr getSrcPattern() const { return SrcPattern; }
TreePatternNodePtr getResultPattern() const { return ResultPattern; }
};
class PatternToMatch {
Record *SrcRecord; ListInit *Predicates; TreePatternNodePtr SrcPattern; TreePatternNodePtr DstPattern; std::vector<Record*> Dstregs; std::string HwModeFeatures;
int AddedComplexity; unsigned ID; unsigned ForceMode;
public:
PatternToMatch(Record *srcrecord, ListInit *preds, TreePatternNodePtr src,
TreePatternNodePtr dst, std::vector<Record *> dstregs,
int complexity, unsigned uid, unsigned setmode = 0,
const Twine &hwmodefeatures = "")
: SrcRecord(srcrecord), Predicates(preds), SrcPattern(src),
DstPattern(dst), Dstregs(std::move(dstregs)),
HwModeFeatures(hwmodefeatures.str()), AddedComplexity(complexity),
ID(uid), ForceMode(setmode) {}
Record *getSrcRecord() const { return SrcRecord; }
ListInit *getPredicates() const { return Predicates; }
TreePatternNode *getSrcPattern() const { return SrcPattern.get(); }
TreePatternNodePtr getSrcPatternShared() const { return SrcPattern; }
TreePatternNode *getDstPattern() const { return DstPattern.get(); }
TreePatternNodePtr getDstPatternShared() const { return DstPattern; }
const std::vector<Record*> &getDstRegs() const { return Dstregs; }
StringRef getHwModeFeatures() const { return HwModeFeatures; }
int getAddedComplexity() const { return AddedComplexity; }
unsigned getID() const { return ID; }
unsigned getForceMode() const { return ForceMode; }
std::string getPredicateCheck() const;
void getPredicateRecords(SmallVectorImpl<Record *> &PredicateRecs) const;
int getPatternComplexity(const CodeGenDAGPatterns &CGP) const;
};
class CodeGenDAGPatterns {
RecordKeeper &Records;
CodeGenTarget Target;
CodeGenIntrinsicTable Intrinsics;
std::map<Record*, SDNodeInfo, LessRecordByID> SDNodes;
std::map<Record*, std::pair<Record*, std::string>, LessRecordByID>
SDNodeXForms;
std::map<Record*, ComplexPattern, LessRecordByID> ComplexPatterns;
std::map<Record *, std::unique_ptr<TreePattern>, LessRecordByID>
PatternFragments;
std::map<Record*, DAGDefaultOperand, LessRecordByID> DefaultOperands;
std::map<Record*, DAGInstruction, LessRecordByID> Instructions;
Record *intrinsic_void_sdnode;
Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode;
std::vector<PatternToMatch> PatternsToMatch;
TypeSetByHwMode LegalVTS;
using PatternRewriterFn = std::function<void (TreePattern *)>;
PatternRewriterFn PatternRewriter;
unsigned NumScopes = 0;
public:
CodeGenDAGPatterns(RecordKeeper &R,
PatternRewriterFn PatternRewriter = nullptr);
CodeGenTarget &getTargetInfo() { return Target; }
const CodeGenTarget &getTargetInfo() const { return Target; }
const TypeSetByHwMode &getLegalTypes() const { return LegalVTS; }
Record *getSDNodeNamed(StringRef Name) const;
const SDNodeInfo &getSDNodeInfo(Record *R) const {
auto F = SDNodes.find(R);
assert(F != SDNodes.end() && "Unknown node!");
return F->second;
}
typedef std::pair<Record*, std::string> NodeXForm;
const NodeXForm &getSDNodeTransform(Record *R) const {
auto F = SDNodeXForms.find(R);
assert(F != SDNodeXForms.end() && "Invalid transform!");
return F->second;
}
const ComplexPattern &getComplexPattern(Record *R) const {
auto F = ComplexPatterns.find(R);
assert(F != ComplexPatterns.end() && "Unknown addressing mode!");
return F->second;
}
const CodeGenIntrinsic &getIntrinsic(Record *R) const {
for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
if (Intrinsics[i].TheDef == R) return Intrinsics[i];
llvm_unreachable("Unknown intrinsic!");
}
const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const {
if (IID-1 < Intrinsics.size())
return Intrinsics[IID-1];
llvm_unreachable("Bad intrinsic ID!");
}
unsigned getIntrinsicID(Record *R) const {
for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
if (Intrinsics[i].TheDef == R) return i;
llvm_unreachable("Unknown intrinsic!");
}
const DAGDefaultOperand &getDefaultOperand(Record *R) const {
auto F = DefaultOperands.find(R);
assert(F != DefaultOperands.end() &&"Isn't an analyzed default operand!");
return F->second;
}
TreePattern *getPatternFragment(Record *R) const {
auto F = PatternFragments.find(R);
assert(F != PatternFragments.end() && "Invalid pattern fragment request!");
return F->second.get();
}
TreePattern *getPatternFragmentIfRead(Record *R) const {
auto F = PatternFragments.find(R);
if (F == PatternFragments.end())
return nullptr;
return F->second.get();
}
typedef std::map<Record *, std::unique_ptr<TreePattern>,
LessRecordByID>::const_iterator pf_iterator;
pf_iterator pf_begin() const { return PatternFragments.begin(); }
pf_iterator pf_end() const { return PatternFragments.end(); }
iterator_range<pf_iterator> ptfs() const { return PatternFragments; }
typedef std::vector<PatternToMatch>::const_iterator ptm_iterator;
ptm_iterator ptm_begin() const { return PatternsToMatch.begin(); }
ptm_iterator ptm_end() const { return PatternsToMatch.end(); }
iterator_range<ptm_iterator> ptms() const { return PatternsToMatch; }
typedef std::map<Record*, DAGInstruction, LessRecordByID> DAGInstMap;
void parseInstructionPattern(
CodeGenInstruction &CGI, ListInit *Pattern,
DAGInstMap &DAGInsts);
const DAGInstruction &getInstruction(Record *R) const {
auto F = Instructions.find(R);
assert(F != Instructions.end() && "Unknown instruction!");
return F->second;
}
Record *get_intrinsic_void_sdnode() const {
return intrinsic_void_sdnode;
}
Record *get_intrinsic_w_chain_sdnode() const {
return intrinsic_w_chain_sdnode;
}
Record *get_intrinsic_wo_chain_sdnode() const {
return intrinsic_wo_chain_sdnode;
}
unsigned allocateScope() { return ++NumScopes; }
bool operandHasDefault(Record *Op) const {
return Op->isSubClassOf("OperandWithDefaultOps") &&
!getDefaultOperand(Op).DefaultOps.empty();
}
private:
void ParseNodeInfo();
void ParseNodeTransforms();
void ParseComplexPatterns();
void ParsePatternFragments(bool OutFrags = false);
void ParseDefaultOperands();
void ParseInstructions();
void ParsePatterns();
void ExpandHwModeBasedTypes();
void InferInstructionFlags();
void GenerateVariants();
void VerifyInstructionFlags();
void ParseOnePattern(Record *TheDef,
TreePattern &Pattern, TreePattern &Result,
const std::vector<Record *> &InstImpResults);
void AddPatternToMatch(TreePattern *Pattern, PatternToMatch &&PTM);
void FindPatternInputsAndOutputs(
TreePattern &I, TreePatternNodePtr Pat,
std::map<std::string, TreePatternNodePtr> &InstInputs,
MapVector<std::string, TreePatternNodePtr,
std::map<std::string, unsigned>> &InstResults,
std::vector<Record *> &InstImpResults);
};
inline bool SDNodeInfo::ApplyTypeConstraints(TreePatternNode *N,
TreePattern &TP) const {
bool MadeChange = false;
for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
return MadeChange;
}
}
#endif