#include "CodeGenInstruction.h"
#include "CodeGenTarget.h"
#include "InfoByHwMode.h"
#include "VarLenCodeEmitterGen.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/CachedHashString.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/MC/MCDecoderOps.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/Record.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "decoder-emitter"
namespace {
STATISTIC(NumEncodings, "Number of encodings considered");
STATISTIC(NumEncodingsLackingDisasm, "Number of encodings without disassembler info");
STATISTIC(NumInstructions, "Number of instructions considered");
STATISTIC(NumEncodingsSupported, "Number of encodings supported");
STATISTIC(NumEncodingsOmitted, "Number of encodings omitted");
struct EncodingField {
unsigned Base, Width, Offset;
EncodingField(unsigned B, unsigned W, unsigned O)
: Base(B), Width(W), Offset(O) { }
};
struct OperandInfo {
std::vector<EncodingField> Fields;
std::string Decoder;
bool HasCompleteDecoder;
uint64_t InitValue;
OperandInfo(std::string D, bool HCD)
: Decoder(std::move(D)), HasCompleteDecoder(HCD), InitValue(0) {}
void addField(unsigned Base, unsigned Width, unsigned Offset) {
Fields.push_back(EncodingField(Base, Width, Offset));
}
unsigned numFields() const { return Fields.size(); }
typedef std::vector<EncodingField>::const_iterator const_iterator;
const_iterator begin() const { return Fields.begin(); }
const_iterator end() const { return Fields.end(); }
};
typedef std::vector<uint8_t> DecoderTable;
typedef uint32_t DecoderFixup;
typedef std::vector<DecoderFixup> FixupList;
typedef std::vector<FixupList> FixupScopeList;
typedef SmallSetVector<CachedHashString, 16> PredicateSet;
typedef SmallSetVector<CachedHashString, 16> DecoderSet;
struct DecoderTableInfo {
DecoderTable Table;
FixupScopeList FixupStack;
PredicateSet Predicates;
DecoderSet Decoders;
};
struct EncodingAndInst {
const Record *EncodingDef;
const CodeGenInstruction *Inst;
StringRef HwModeName;
EncodingAndInst(const Record *EncodingDef, const CodeGenInstruction *Inst,
StringRef HwModeName = "")
: EncodingDef(EncodingDef), Inst(Inst), HwModeName(HwModeName) {}
};
struct EncodingIDAndOpcode {
unsigned EncodingID;
unsigned Opcode;
EncodingIDAndOpcode() : EncodingID(0), Opcode(0) {}
EncodingIDAndOpcode(unsigned EncodingID, unsigned Opcode)
: EncodingID(EncodingID), Opcode(Opcode) {}
};
raw_ostream &operator<<(raw_ostream &OS, const EncodingAndInst &Value) {
if (Value.EncodingDef != Value.Inst->TheDef)
OS << Value.EncodingDef->getName() << ":";
OS << Value.Inst->TheDef->getName();
return OS;
}
class DecoderEmitter {
RecordKeeper &RK;
std::vector<EncodingAndInst> NumberedEncodings;
public:
DecoderEmitter(RecordKeeper &R, std::string PredicateNamespace,
std::string GPrefix = "if (",
std::string GPostfix = " == MCDisassembler::Fail)",
std::string ROK = "MCDisassembler::Success",
std::string RFail = "MCDisassembler::Fail", std::string L = "")
: RK(R), Target(R), PredicateNamespace(std::move(PredicateNamespace)),
GuardPrefix(std::move(GPrefix)), GuardPostfix(std::move(GPostfix)),
ReturnOK(std::move(ROK)), ReturnFail(std::move(RFail)),
Locals(std::move(L)) {}
void emitTable(formatted_raw_ostream &o, DecoderTable &Table,
unsigned Indentation, unsigned BitWidth,
StringRef Namespace) const;
void emitInstrLenTable(formatted_raw_ostream &OS,
std::vector<unsigned> &InstrLen) const;
void emitPredicateFunction(formatted_raw_ostream &OS,
PredicateSet &Predicates,
unsigned Indentation) const;
void emitDecoderFunction(formatted_raw_ostream &OS,
DecoderSet &Decoders,
unsigned Indentation) const;
void run(raw_ostream &o);
private:
CodeGenTarget Target;
public:
std::string PredicateNamespace;
std::string GuardPrefix, GuardPostfix;
std::string ReturnOK, ReturnFail;
std::string Locals;
};
}
typedef enum {
BIT_TRUE, BIT_FALSE, BIT_UNSET, BIT_UNFILTERED } bit_value_t;
static bool ValueSet(bit_value_t V) {
return (V == BIT_TRUE || V == BIT_FALSE);
}
static bool ValueNotSet(bit_value_t V) {
return (V == BIT_UNSET);
}
static int Value(bit_value_t V) {
return ValueNotSet(V) ? -1 : (V == BIT_FALSE ? 0 : 1);
}
static bit_value_t bitFromBits(const BitsInit &bits, unsigned index) {
if (BitInit *bit = dyn_cast<BitInit>(bits.getBit(index)))
return bit->getValue() ? BIT_TRUE : BIT_FALSE;
return BIT_UNSET;
}
static void dumpBits(raw_ostream &o, const BitsInit &bits) {
for (unsigned index = bits.getNumBits(); index > 0; --index) {
switch (bitFromBits(bits, index - 1)) {
case BIT_TRUE:
o << "1";
break;
case BIT_FALSE:
o << "0";
break;
case BIT_UNSET:
o << "_";
break;
default:
llvm_unreachable("unexpected return value from bitFromBits");
}
}
}
static BitsInit &getBitsField(const Record &def, StringRef str) {
const RecordVal *RV = def.getValue(str);
if (BitsInit *Bits = dyn_cast<BitsInit>(RV->getValue()))
return *Bits;
VarLenInst VLI = VarLenInst(cast<DagInit>(RV->getValue()), RV);
SmallVector<Init *, 16> Bits;
for (auto &SI : VLI) {
if (const BitsInit *BI = dyn_cast<BitsInit>(SI.Value)) {
for (unsigned Idx = 0U; Idx < BI->getNumBits(); ++Idx) {
Bits.push_back(BI->getBit(Idx));
}
} else if (const BitInit *BI = dyn_cast<BitInit>(SI.Value)) {
Bits.push_back(const_cast<BitInit *>(BI));
} else {
for (unsigned Idx = 0U; Idx < SI.BitWidth; ++Idx)
Bits.push_back(UnsetInit::get(def.getRecords()));
}
}
return *BitsInit::get(def.getRecords(), Bits);
}
typedef std::vector<bit_value_t> insn_t;
namespace {
static const uint64_t NO_FIXED_SEGMENTS_SENTINEL = -1ULL;
class FilterChooser;
class Filter {
protected:
const FilterChooser *Owner; unsigned StartBit; unsigned NumBits; bool Mixed;
std::map<uint64_t, std::vector<EncodingIDAndOpcode>>
FilteredInstructions;
std::vector<EncodingIDAndOpcode> VariableInstructions;
std::map<uint64_t, std::unique_ptr<const FilterChooser>> FilterChooserMap;
unsigned NumFiltered;
EncodingIDAndOpcode LastOpcFiltered;
public:
Filter(Filter &&f);
Filter(FilterChooser &owner, unsigned startBit, unsigned numBits, bool mixed);
~Filter() = default;
unsigned getNumFiltered() const { return NumFiltered; }
EncodingIDAndOpcode getSingletonOpc() const {
assert(NumFiltered == 1);
return LastOpcFiltered;
}
const FilterChooser &getVariableFC() const {
assert(NumFiltered == 1);
assert(FilterChooserMap.size() == 1);
return *(FilterChooserMap.find(NO_FIXED_SEGMENTS_SENTINEL)->second);
}
void recurse();
void emitTableEntry(DecoderTableInfo &TableInfo) const;
unsigned usefulness() const;
};
}
typedef enum {
ATTR_NONE,
ATTR_FILTERED,
ATTR_ALL_SET,
ATTR_ALL_UNSET,
ATTR_MIXED
} bitAttr_t;
namespace {
class FilterChooser {
protected:
friend class Filter;
ArrayRef<EncodingAndInst> AllInstructions;
const std::vector<EncodingIDAndOpcode> &Opcodes;
const std::map<unsigned, std::vector<OperandInfo>> &Operands;
std::vector<Filter> Filters;
std::vector<bit_value_t> FilterBitValues;
const FilterChooser *Parent;
int BestIndex;
unsigned BitWidth;
const DecoderEmitter *Emitter;
public:
FilterChooser(ArrayRef<EncodingAndInst> Insts,
const std::vector<EncodingIDAndOpcode> &IDs,
const std::map<unsigned, std::vector<OperandInfo>> &Ops,
unsigned BW, const DecoderEmitter *E)
: AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
FilterBitValues(BW, BIT_UNFILTERED), Parent(nullptr), BestIndex(-1),
BitWidth(BW), Emitter(E) {
doFilter();
}
FilterChooser(ArrayRef<EncodingAndInst> Insts,
const std::vector<EncodingIDAndOpcode> &IDs,
const std::map<unsigned, std::vector<OperandInfo>> &Ops,
const std::vector<bit_value_t> &ParentFilterBitValues,
const FilterChooser &parent)
: AllInstructions(Insts), Opcodes(IDs), Operands(Ops),
FilterBitValues(ParentFilterBitValues), Parent(&parent), BestIndex(-1),
BitWidth(parent.BitWidth), Emitter(parent.Emitter) {
doFilter();
}
FilterChooser(const FilterChooser &) = delete;
void operator=(const FilterChooser &) = delete;
unsigned getBitWidth() const { return BitWidth; }
protected:
void insnWithID(insn_t &Insn, unsigned Opcode) const {
BitsInit &Bits = getBitsField(*AllInstructions[Opcode].EncodingDef, "Inst");
Insn.resize(BitWidth > Bits.getNumBits() ? BitWidth : Bits.getNumBits(),
BIT_UNSET);
const RecordVal *RV =
AllInstructions[Opcode].EncodingDef->getValue("SoftFail");
const BitsInit *SFBits = RV ? dyn_cast<BitsInit>(RV->getValue()) : nullptr;
for (unsigned i = 0; i < Bits.getNumBits(); ++i) {
if (SFBits && bitFromBits(*SFBits, i) == BIT_TRUE)
Insn[i] = BIT_UNSET;
else
Insn[i] = bitFromBits(Bits, i);
}
}
void emitNameWithID(raw_ostream &OS, unsigned Opcode) const {
const Record *EncodingDef = AllInstructions[Opcode].EncodingDef;
const Record *InstDef = AllInstructions[Opcode].Inst->TheDef;
if (EncodingDef != InstDef)
OS << EncodingDef->getName() << ":";
OS << InstDef->getName();
}
bool fieldFromInsn(uint64_t &Field, insn_t &Insn, unsigned StartBit,
unsigned NumBits) const;
void dumpFilterArray(raw_ostream &o,
const std::vector<bit_value_t> & filter) const;
void dumpStack(raw_ostream &o, const char *prefix) const;
Filter &bestFilter() {
assert(BestIndex != -1 && "BestIndex not set");
return Filters[BestIndex];
}
bool PositionFiltered(unsigned i) const {
return ValueSet(FilterBitValues[i]);
}
unsigned getIslands(std::vector<unsigned> &StartBits,
std::vector<unsigned> &EndBits,
std::vector<uint64_t> &FieldVals,
const insn_t &Insn) const;
bool emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
unsigned Opc) const;
bool emitPredicateMatchAux(const Init &Val, bool ParenIfBinOp,
raw_ostream &OS) const;
bool doesOpcodeNeedPredicate(unsigned Opc) const;
unsigned getPredicateIndex(DecoderTableInfo &TableInfo, StringRef P) const;
void emitPredicateTableEntry(DecoderTableInfo &TableInfo,
unsigned Opc) const;
void emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
unsigned Opc) const;
void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
EncodingIDAndOpcode Opc) const;
void emitSingletonTableEntry(DecoderTableInfo &TableInfo,
const Filter &Best) const;
void emitBinaryParser(raw_ostream &o, unsigned &Indentation,
const OperandInfo &OpInfo,
bool &OpHasCompleteDecoder) const;
void emitDecoder(raw_ostream &OS, unsigned Indentation, unsigned Opc,
bool &HasCompleteDecoder) const;
unsigned getDecoderIndex(DecoderSet &Decoders, unsigned Opc,
bool &HasCompleteDecoder) const;
void runSingleFilter(unsigned startBit, unsigned numBit, bool mixed);
void reportRegion(bitAttr_t RA, unsigned StartBit, unsigned BitIndex,
bool AllowMixed);
bool filterProcessor(bool AllowMixed, bool Greedy = true);
void doFilter();
public:
void emitTableEntries(DecoderTableInfo &TableInfo) const;
};
}
Filter::Filter(Filter &&f)
: Owner(f.Owner), StartBit(f.StartBit), NumBits(f.NumBits), Mixed(f.Mixed),
FilteredInstructions(std::move(f.FilteredInstructions)),
VariableInstructions(std::move(f.VariableInstructions)),
FilterChooserMap(std::move(f.FilterChooserMap)), NumFiltered(f.NumFiltered),
LastOpcFiltered(f.LastOpcFiltered) {
}
Filter::Filter(FilterChooser &owner, unsigned startBit, unsigned numBits,
bool mixed)
: Owner(&owner), StartBit(startBit), NumBits(numBits), Mixed(mixed) {
assert(StartBit + NumBits - 1 < Owner->BitWidth);
NumFiltered = 0;
LastOpcFiltered = {0, 0};
for (unsigned i = 0, e = Owner->Opcodes.size(); i != e; ++i) {
insn_t Insn;
Owner->insnWithID(Insn, Owner->Opcodes[i].EncodingID);
uint64_t Field;
bool ok = Owner->fieldFromInsn(Field, Insn, StartBit, NumBits);
if (ok) {
LastOpcFiltered = Owner->Opcodes[i];
FilteredInstructions[Field].push_back(LastOpcFiltered);
++NumFiltered;
} else {
VariableInstructions.push_back(Owner->Opcodes[i]);
}
}
assert((FilteredInstructions.size() + VariableInstructions.size() > 0)
&& "Filter returns no instruction categories");
}
void Filter::recurse() {
std::vector<bit_value_t> BitValueArray(Owner->FilterBitValues);
if (!VariableInstructions.empty()) {
for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex)
BitValueArray[StartBit + bitIndex] = BIT_UNSET;
FilterChooserMap.insert(std::make_pair(NO_FIXED_SEGMENTS_SENTINEL,
std::make_unique<FilterChooser>(Owner->AllInstructions,
VariableInstructions, Owner->Operands, BitValueArray, *Owner)));
}
if (getNumFiltered() == 1) {
assert(FilterChooserMap.size() == 1);
return;
}
for (const auto &Inst : FilteredInstructions) {
for (unsigned bitIndex = 0; bitIndex < NumBits; ++bitIndex) {
if (Inst.first & (1ULL << bitIndex))
BitValueArray[StartBit + bitIndex] = BIT_TRUE;
else
BitValueArray[StartBit + bitIndex] = BIT_FALSE;
}
FilterChooserMap.insert(std::make_pair(
Inst.first, std::make_unique<FilterChooser>(
Owner->AllInstructions, Inst.second,
Owner->Operands, BitValueArray, *Owner)));
}
}
static void resolveTableFixups(DecoderTable &Table, const FixupList &Fixups,
uint32_t DestIdx) {
for (FixupList::const_reverse_iterator I = Fixups.rbegin(),
E = Fixups.rend();
I != E; ++I) {
uint32_t FixupIdx = *I;
uint32_t Delta = DestIdx - FixupIdx - 3;
assert(Delta < (1u << 24));
Table[FixupIdx] = (uint8_t)Delta;
Table[FixupIdx + 1] = (uint8_t)(Delta >> 8);
Table[FixupIdx + 2] = (uint8_t)(Delta >> 16);
}
}
void Filter::emitTableEntry(DecoderTableInfo &TableInfo) const {
TableInfo.Table.push_back(MCD::OPC_ExtractField);
TableInfo.Table.push_back(StartBit);
TableInfo.Table.push_back(NumBits);
TableInfo.FixupStack.emplace_back();
DecoderTable &Table = TableInfo.Table;
size_t PrevFilter = 0;
bool HasFallthrough = false;
for (auto &Filter : FilterChooserMap) {
if (Filter.first == NO_FIXED_SEGMENTS_SENTINEL) {
HasFallthrough = true;
assert(PrevFilter != 0 && "empty filter set!");
FixupList &CurScope = TableInfo.FixupStack.back();
resolveTableFixups(Table, CurScope, Table.size());
CurScope.clear();
PrevFilter = 0; } else {
Table.push_back(MCD::OPC_FilterValue);
uint8_t Buffer[16];
unsigned Len = encodeULEB128(Filter.first, Buffer);
Table.insert(Table.end(), Buffer, Buffer + Len);
PrevFilter = Table.size();
Table.push_back(0);
Table.push_back(0);
Table.push_back(0);
}
Filter.second->emitTableEntries(TableInfo);
if (PrevFilter) {
uint32_t NumToSkip = Table.size() - PrevFilter - 3;
assert(NumToSkip < (1u << 24) && "disassembler decoding table too large!");
Table[PrevFilter] = (uint8_t)NumToSkip;
Table[PrevFilter + 1] = (uint8_t)(NumToSkip >> 8);
Table[PrevFilter + 2] = (uint8_t)(NumToSkip >> 16);
}
}
assert(TableInfo.FixupStack.size() > 1 && "fixup stack underflow!");
FixupScopeList::iterator Source = TableInfo.FixupStack.end() - 1;
FixupScopeList::iterator Dest = Source - 1;
llvm::append_range(*Dest, *Source);
TableInfo.FixupStack.pop_back();
if (!HasFallthrough)
TableInfo.FixupStack.back().push_back(PrevFilter);
}
unsigned Filter::usefulness() const {
if (!VariableInstructions.empty())
return FilteredInstructions.size();
else
return FilteredInstructions.size() + 1;
}
void DecoderEmitter::emitTable(formatted_raw_ostream &OS, DecoderTable &Table,
unsigned Indentation, unsigned BitWidth,
StringRef Namespace) const {
OS.indent(Indentation) << "static const uint8_t DecoderTable" << Namespace
<< BitWidth << "[] = {\n";
Indentation += 2;
DecoderTable::const_iterator I = Table.begin();
DecoderTable::const_iterator E = Table.end();
while (I != E) {
assert (I < E && "incomplete decode table entry!");
uint64_t Pos = I - Table.begin();
OS << "/* " << Pos << " */";
OS.PadToColumn(12);
switch (*I) {
default:
PrintFatalError("invalid decode table opcode");
case MCD::OPC_ExtractField: {
++I;
unsigned Start = *I++;
unsigned Len = *I++;
OS.indent(Indentation) << "MCD::OPC_ExtractField, " << Start << ", "
<< Len << ", // Inst{";
if (Len > 1)
OS << (Start + Len - 1) << "-";
OS << Start << "} ...\n";
break;
}
case MCD::OPC_FilterValue: {
++I;
OS.indent(Indentation) << "MCD::OPC_FilterValue, ";
while (*I >= 128)
OS << (unsigned)*I++ << ", ";
OS << (unsigned)*I++ << ", ";
uint8_t Byte = *I++;
uint32_t NumToSkip = Byte;
OS << (unsigned)Byte << ", ";
Byte = *I++;
OS << (unsigned)Byte << ", ";
NumToSkip |= Byte << 8;
Byte = *I++;
OS << utostr(Byte) << ", ";
NumToSkip |= Byte << 16;
OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
break;
}
case MCD::OPC_CheckField: {
++I;
unsigned Start = *I++;
unsigned Len = *I++;
OS.indent(Indentation) << "MCD::OPC_CheckField, " << Start << ", "
<< Len << ", "; for (; *I >= 128; ++I)
OS << (unsigned)*I << ", ";
OS << (unsigned)*I++ << ", ";
uint8_t Byte = *I++;
uint32_t NumToSkip = Byte;
OS << (unsigned)Byte << ", ";
Byte = *I++;
OS << (unsigned)Byte << ", ";
NumToSkip |= Byte << 8;
Byte = *I++;
OS << utostr(Byte) << ", ";
NumToSkip |= Byte << 16;
OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
break;
}
case MCD::OPC_CheckPredicate: {
++I;
OS.indent(Indentation) << "MCD::OPC_CheckPredicate, ";
for (; *I >= 128; ++I)
OS << (unsigned)*I << ", ";
OS << (unsigned)*I++ << ", ";
uint8_t Byte = *I++;
uint32_t NumToSkip = Byte;
OS << (unsigned)Byte << ", ";
Byte = *I++;
OS << (unsigned)Byte << ", ";
NumToSkip |= Byte << 8;
Byte = *I++;
OS << utostr(Byte) << ", ";
NumToSkip |= Byte << 16;
OS << "// Skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
break;
}
case MCD::OPC_Decode:
case MCD::OPC_TryDecode: {
bool IsTry = *I == MCD::OPC_TryDecode;
++I;
uint8_t Buffer[16], *p = Buffer;
while ((*p++ = *I++) >= 128)
assert((p - Buffer) <= (ptrdiff_t)sizeof(Buffer)
&& "ULEB128 value too large!");
unsigned Opc = decodeULEB128(Buffer);
OS.indent(Indentation) << "MCD::OPC_" << (IsTry ? "Try" : "")
<< "Decode, ";
for (p = Buffer; *p >= 128; ++p)
OS << (unsigned)*p << ", ";
OS << (unsigned)*p << ", ";
for (; *I >= 128; ++I)
OS << (unsigned)*I << ", ";
OS << (unsigned)*I++ << ", ";
if (!IsTry) {
OS << "// Opcode: " << NumberedEncodings[Opc] << "\n";
break;
}
uint8_t Byte = *I++;
uint32_t NumToSkip = Byte;
OS << (unsigned)Byte << ", ";
Byte = *I++;
OS << (unsigned)Byte << ", ";
NumToSkip |= Byte << 8;
Byte = *I++;
OS << utostr(Byte) << ", ";
NumToSkip |= Byte << 16;
OS << "// Opcode: " << NumberedEncodings[Opc]
<< ", skip to: " << ((I - Table.begin()) + NumToSkip) << "\n";
break;
}
case MCD::OPC_SoftFail: {
++I;
OS.indent(Indentation) << "MCD::OPC_SoftFail";
uint64_t Value = 0;
unsigned Shift = 0;
do {
OS << ", " << (unsigned)*I;
Value += (*I & 0x7f) << Shift;
Shift += 7;
} while (*I++ >= 128);
if (Value > 127) {
OS << " /* 0x";
OS.write_hex(Value);
OS << " */";
}
Value = 0;
Shift = 0;
do {
OS << ", " << (unsigned)*I;
Value += (*I & 0x7f) << Shift;
Shift += 7;
} while (*I++ >= 128);
if (Value > 127) {
OS << " /* 0x";
OS.write_hex(Value);
OS << " */";
}
OS << ",\n";
break;
}
case MCD::OPC_Fail: {
++I;
OS.indent(Indentation) << "MCD::OPC_Fail,\n";
break;
}
}
}
OS.indent(Indentation) << "0\n";
Indentation -= 2;
OS.indent(Indentation) << "};\n\n";
}
void DecoderEmitter::emitInstrLenTable(formatted_raw_ostream &OS,
std::vector<unsigned> &InstrLen) const {
OS << "static const uint8_t InstrLenTable[] = {\n";
for (unsigned &Len : InstrLen) {
OS << Len << ",\n";
}
OS << "};\n\n";
}
void DecoderEmitter::emitPredicateFunction(formatted_raw_ostream &OS,
PredicateSet &Predicates,
unsigned Indentation) const {
OS.indent(Indentation) << "static bool checkDecoderPredicate(unsigned Idx, "
<< "const FeatureBitset &Bits) {\n";
Indentation += 2;
if (!Predicates.empty()) {
OS.indent(Indentation) << "switch (Idx) {\n";
OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
unsigned Index = 0;
for (const auto &Predicate : Predicates) {
OS.indent(Indentation) << "case " << Index++ << ":\n";
OS.indent(Indentation+2) << "return (" << Predicate << ");\n";
}
OS.indent(Indentation) << "}\n";
} else {
OS.indent(Indentation) << "llvm_unreachable(\"Invalid index!\");\n";
}
Indentation -= 2;
OS.indent(Indentation) << "}\n\n";
}
void DecoderEmitter::emitDecoderFunction(formatted_raw_ostream &OS,
DecoderSet &Decoders,
unsigned Indentation) const {
OS.indent(Indentation) << "template <typename InsnType>\n";
OS.indent(Indentation) << "static DecodeStatus decodeToMCInst(DecodeStatus S,"
<< " unsigned Idx, InsnType insn, MCInst &MI,\n";
OS.indent(Indentation)
<< " uint64_t "
<< "Address, const MCDisassembler *Decoder, bool &DecodeComplete) {\n";
Indentation += 2;
OS.indent(Indentation) << "DecodeComplete = true;\n";
OS.indent(Indentation) << "using TmpType = "
"std::conditional_t<std::is_integral<InsnType>::"
"value, InsnType, uint64_t>;\n";
OS.indent(Indentation) << "TmpType tmp;\n";
OS.indent(Indentation) << "switch (Idx) {\n";
OS.indent(Indentation) << "default: llvm_unreachable(\"Invalid index!\");\n";
unsigned Index = 0;
for (const auto &Decoder : Decoders) {
OS.indent(Indentation) << "case " << Index++ << ":\n";
OS << Decoder;
OS.indent(Indentation+2) << "return S;\n";
}
OS.indent(Indentation) << "}\n";
Indentation -= 2;
OS.indent(Indentation) << "}\n\n";
}
bool FilterChooser::fieldFromInsn(uint64_t &Field, insn_t &Insn,
unsigned StartBit, unsigned NumBits) const {
Field = 0;
for (unsigned i = 0; i < NumBits; ++i) {
if (Insn[StartBit + i] == BIT_UNSET)
return false;
if (Insn[StartBit + i] == BIT_TRUE)
Field = Field | (1ULL << i);
}
return true;
}
void FilterChooser::dumpFilterArray(raw_ostream &o,
const std::vector<bit_value_t> &filter) const {
for (unsigned bitIndex = BitWidth; bitIndex > 0; bitIndex--) {
switch (filter[bitIndex - 1]) {
case BIT_UNFILTERED:
o << ".";
break;
case BIT_UNSET:
o << "_";
break;
case BIT_TRUE:
o << "1";
break;
case BIT_FALSE:
o << "0";
break;
}
}
}
void FilterChooser::dumpStack(raw_ostream &o, const char *prefix) const {
const FilterChooser *current = this;
while (current) {
o << prefix;
dumpFilterArray(o, current->FilterBitValues);
o << '\n';
current = current->Parent;
}
}
unsigned FilterChooser::getIslands(std::vector<unsigned> &StartBits,
std::vector<unsigned> &EndBits,
std::vector<uint64_t> &FieldVals,
const insn_t &Insn) const {
unsigned Num, BitNo;
Num = BitNo = 0;
uint64_t FieldVal = 0;
int State = 0;
for (unsigned i = 0; i < BitWidth; ++i) {
int64_t Val = Value(Insn[i]);
bool Filtered = PositionFiltered(i);
switch (State) {
default: llvm_unreachable("Unreachable code!");
case 0:
case 1:
if (Filtered || Val == -1)
State = 1; else {
State = 2; BitNo = 0;
StartBits.push_back(i);
FieldVal = Val;
}
break;
case 2:
if (Filtered || Val == -1) {
State = 1; EndBits.push_back(i - 1);
FieldVals.push_back(FieldVal);
++Num;
} else {
State = 2; ++BitNo;
FieldVal = FieldVal | Val << BitNo;
}
break;
}
}
if (State == 2) {
EndBits.push_back(BitWidth - 1);
FieldVals.push_back(FieldVal);
++Num;
}
assert(StartBits.size() == Num && EndBits.size() == Num &&
FieldVals.size() == Num);
return Num;
}
void FilterChooser::emitBinaryParser(raw_ostream &o, unsigned &Indentation,
const OperandInfo &OpInfo,
bool &OpHasCompleteDecoder) const {
const std::string &Decoder = OpInfo.Decoder;
bool UseInsertBits = OpInfo.numFields() != 1 || OpInfo.InitValue != 0;
if (UseInsertBits) {
o.indent(Indentation) << "tmp = 0x";
o.write_hex(OpInfo.InitValue);
o << ";\n";
}
for (const EncodingField &EF : OpInfo) {
o.indent(Indentation);
if (UseInsertBits)
o << "insertBits(tmp, ";
else
o << "tmp = ";
o << "fieldFromInstruction(insn, " << EF.Base << ", " << EF.Width << ')';
if (UseInsertBits)
o << ", " << EF.Offset << ", " << EF.Width << ')';
else if (EF.Offset != 0)
o << " << " << EF.Offset;
o << ";\n";
}
if (Decoder != "") {
OpHasCompleteDecoder = OpInfo.HasCompleteDecoder;
o.indent(Indentation) << Emitter->GuardPrefix << Decoder
<< "(MI, tmp, Address, Decoder)"
<< Emitter->GuardPostfix
<< " { " << (OpHasCompleteDecoder ? "" : "DecodeComplete = false; ")
<< "return MCDisassembler::Fail; }\n";
} else {
OpHasCompleteDecoder = true;
o.indent(Indentation) << "MI.addOperand(MCOperand::createImm(tmp));\n";
}
}
void FilterChooser::emitDecoder(raw_ostream &OS, unsigned Indentation,
unsigned Opc, bool &HasCompleteDecoder) const {
HasCompleteDecoder = true;
for (const auto &Op : Operands.find(Opc)->second) {
if (Op.numFields() == 0 && !Op.Decoder.empty()) {
HasCompleteDecoder = Op.HasCompleteDecoder;
OS.indent(Indentation) << Emitter->GuardPrefix << Op.Decoder
<< "(MI, insn, Address, Decoder)"
<< Emitter->GuardPostfix
<< " { " << (HasCompleteDecoder ? "" : "DecodeComplete = false; ")
<< "return MCDisassembler::Fail; }\n";
break;
}
bool OpHasCompleteDecoder;
emitBinaryParser(OS, Indentation, Op, OpHasCompleteDecoder);
if (!OpHasCompleteDecoder)
HasCompleteDecoder = false;
}
}
unsigned FilterChooser::getDecoderIndex(DecoderSet &Decoders,
unsigned Opc,
bool &HasCompleteDecoder) const {
SmallString<256> Decoder;
raw_svector_ostream S(Decoder);
unsigned I = 4;
emitDecoder(S, I, Opc, HasCompleteDecoder);
Decoders.insert(CachedHashString(Decoder));
DecoderSet::const_iterator P = find(Decoders, Decoder.str());
return (unsigned)(P - Decoders.begin());
}
bool FilterChooser::emitPredicateMatchAux(const Init &Val, bool ParenIfBinOp,
raw_ostream &OS) const {
if (auto *D = dyn_cast<DefInit>(&Val)) {
if (!D->getDef()->isSubClassOf("SubtargetFeature"))
return true;
OS << "Bits[" << Emitter->PredicateNamespace << "::" << D->getAsString()
<< "]";
return false;
}
if (auto *D = dyn_cast<DagInit>(&Val)) {
std::string Op = D->getOperator()->getAsString();
if (Op == "not" && D->getNumArgs() == 1) {
OS << '!';
return emitPredicateMatchAux(*D->getArg(0), true, OS);
}
if ((Op == "any_of" || Op == "all_of") && D->getNumArgs() > 0) {
bool Paren = D->getNumArgs() > 1 && std::exchange(ParenIfBinOp, true);
if (Paren)
OS << '(';
ListSeparator LS(Op == "any_of" ? " || " : " && ");
for (auto *Arg : D->getArgs()) {
OS << LS;
if (emitPredicateMatchAux(*Arg, ParenIfBinOp, OS))
return true;
}
if (Paren)
OS << ')';
return false;
}
}
return true;
}
bool FilterChooser::emitPredicateMatch(raw_ostream &o, unsigned &Indentation,
unsigned Opc) const {
ListInit *Predicates =
AllInstructions[Opc].EncodingDef->getValueAsListInit("Predicates");
bool IsFirstEmission = true;
for (unsigned i = 0; i < Predicates->size(); ++i) {
Record *Pred = Predicates->getElementAsRecord(i);
if (!Pred->getValue("AssemblerMatcherPredicate"))
continue;
if (!isa<DagInit>(Pred->getValue("AssemblerCondDag")->getValue()))
continue;
if (!IsFirstEmission)
o << " && ";
if (emitPredicateMatchAux(*Pred->getValueAsDag("AssemblerCondDag"),
Predicates->size() > 1, o))
PrintFatalError(Pred->getLoc(), "Invalid AssemblerCondDag!");
IsFirstEmission = false;
}
return !Predicates->empty();
}
bool FilterChooser::doesOpcodeNeedPredicate(unsigned Opc) const {
ListInit *Predicates =
AllInstructions[Opc].EncodingDef->getValueAsListInit("Predicates");
for (unsigned i = 0; i < Predicates->size(); ++i) {
Record *Pred = Predicates->getElementAsRecord(i);
if (!Pred->getValue("AssemblerMatcherPredicate"))
continue;
if (isa<DagInit>(Pred->getValue("AssemblerCondDag")->getValue()))
return true;
}
return false;
}
unsigned FilterChooser::getPredicateIndex(DecoderTableInfo &TableInfo,
StringRef Predicate) const {
TableInfo.Predicates.insert(CachedHashString(Predicate));
PredicateSet::const_iterator P = find(TableInfo.Predicates, Predicate);
return (unsigned)(P - TableInfo.Predicates.begin());
}
void FilterChooser::emitPredicateTableEntry(DecoderTableInfo &TableInfo,
unsigned Opc) const {
if (!doesOpcodeNeedPredicate(Opc))
return;
SmallString<256> Predicate;
raw_svector_ostream PS(Predicate);
unsigned I = 0;
emitPredicateMatch(PS, I, Opc);
unsigned PIdx = getPredicateIndex(TableInfo, PS.str());
SmallString<16> PBytes;
raw_svector_ostream S(PBytes);
encodeULEB128(PIdx, S);
TableInfo.Table.push_back(MCD::OPC_CheckPredicate);
for (unsigned i = 0, e = PBytes.size(); i != e; ++i)
TableInfo.Table.push_back(PBytes[i]);
TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
TableInfo.Table.push_back(0);
TableInfo.Table.push_back(0);
TableInfo.Table.push_back(0);
}
void FilterChooser::emitSoftFailTableEntry(DecoderTableInfo &TableInfo,
unsigned Opc) const {
const RecordVal *RV = AllInstructions[Opc].EncodingDef->getValue("SoftFail");
BitsInit *SFBits = RV ? dyn_cast<BitsInit>(RV->getValue()) : nullptr;
if (!SFBits) return;
BitsInit *InstBits =
AllInstructions[Opc].EncodingDef->getValueAsBitsInit("Inst");
APInt PositiveMask(BitWidth, 0ULL);
APInt NegativeMask(BitWidth, 0ULL);
for (unsigned i = 0; i < BitWidth; ++i) {
bit_value_t B = bitFromBits(*SFBits, i);
bit_value_t IB = bitFromBits(*InstBits, i);
if (B != BIT_TRUE) continue;
switch (IB) {
case BIT_FALSE:
PositiveMask.setBit(i);
break;
case BIT_TRUE:
NegativeMask.setBit(i);
break;
default:
errs() << "SoftFail Conflict: bit SoftFail{" << i << "} in "
<< AllInstructions[Opc] << " is set but Inst{" << i
<< "} is unset!\n"
<< " - You can only mark a bit as SoftFail if it is fully defined"
<< " (1/0 - not '?') in Inst\n";
return;
}
}
bool NeedPositiveMask = PositiveMask.getBoolValue();
bool NeedNegativeMask = NegativeMask.getBoolValue();
if (!NeedPositiveMask && !NeedNegativeMask)
return;
TableInfo.Table.push_back(MCD::OPC_SoftFail);
SmallString<16> MaskBytes;
raw_svector_ostream S(MaskBytes);
if (NeedPositiveMask) {
encodeULEB128(PositiveMask.getZExtValue(), S);
for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
TableInfo.Table.push_back(MaskBytes[i]);
} else
TableInfo.Table.push_back(0);
if (NeedNegativeMask) {
MaskBytes.clear();
encodeULEB128(NegativeMask.getZExtValue(), S);
for (unsigned i = 0, e = MaskBytes.size(); i != e; ++i)
TableInfo.Table.push_back(MaskBytes[i]);
} else
TableInfo.Table.push_back(0);
}
void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
EncodingIDAndOpcode Opc) const {
std::vector<unsigned> StartBits;
std::vector<unsigned> EndBits;
std::vector<uint64_t> FieldVals;
insn_t Insn;
insnWithID(Insn, Opc.EncodingID);
getIslands(StartBits, EndBits, FieldVals, Insn);
unsigned Size = StartBits.size();
emitPredicateTableEntry(TableInfo, Opc.EncodingID);
for (unsigned I = Size; I != 0; --I) {
unsigned NumBits = EndBits[I-1] - StartBits[I-1] + 1;
TableInfo.Table.push_back(MCD::OPC_CheckField);
TableInfo.Table.push_back(StartBits[I-1]);
TableInfo.Table.push_back(NumBits);
uint8_t Buffer[16], *p;
encodeULEB128(FieldVals[I-1], Buffer);
for (p = Buffer; *p >= 128 ; ++p)
TableInfo.Table.push_back(*p);
TableInfo.Table.push_back(*p);
TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
TableInfo.Table.push_back(0);
TableInfo.Table.push_back(0);
TableInfo.Table.push_back(0);
}
emitSoftFailTableEntry(TableInfo, Opc.EncodingID);
bool HasCompleteDecoder;
unsigned DIdx =
getDecoderIndex(TableInfo.Decoders, Opc.EncodingID, HasCompleteDecoder);
TableInfo.Table.push_back(HasCompleteDecoder ? MCD::OPC_Decode :
MCD::OPC_TryDecode);
NumEncodingsSupported++;
uint8_t Buffer[16], *p;
encodeULEB128(Opc.Opcode, Buffer);
for (p = Buffer; *p >= 128 ; ++p)
TableInfo.Table.push_back(*p);
TableInfo.Table.push_back(*p);
SmallString<16> Bytes;
raw_svector_ostream S(Bytes);
encodeULEB128(DIdx, S);
for (unsigned i = 0, e = Bytes.size(); i != e; ++i)
TableInfo.Table.push_back(Bytes[i]);
if (!HasCompleteDecoder) {
TableInfo.FixupStack.back().push_back(TableInfo.Table.size());
TableInfo.Table.push_back(0);
TableInfo.Table.push_back(0);
TableInfo.Table.push_back(0);
}
}
void FilterChooser::emitSingletonTableEntry(DecoderTableInfo &TableInfo,
const Filter &Best) const {
EncodingIDAndOpcode Opc = Best.getSingletonOpc();
TableInfo.FixupStack.emplace_back();
emitSingletonTableEntry(TableInfo, Opc);
resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
TableInfo.Table.size());
TableInfo.FixupStack.pop_back();
Best.getVariableFC().emitTableEntries(TableInfo);
}
void FilterChooser::runSingleFilter(unsigned startBit, unsigned numBit,
bool mixed) {
Filters.clear();
Filters.emplace_back(*this, startBit, numBit, true);
BestIndex = 0; bestFilter().recurse();
}
void FilterChooser::reportRegion(bitAttr_t RA, unsigned StartBit,
unsigned BitIndex, bool AllowMixed) {
if (RA == ATTR_MIXED && AllowMixed)
Filters.emplace_back(*this, StartBit, BitIndex - StartBit, true);
else if (RA == ATTR_ALL_SET && !AllowMixed)
Filters.emplace_back(*this, StartBit, BitIndex - StartBit, false);
}
bool FilterChooser::filterProcessor(bool AllowMixed, bool Greedy) {
Filters.clear();
BestIndex = -1;
unsigned numInstructions = Opcodes.size();
assert(numInstructions && "Filter created with no instructions");
if (numInstructions == 1)
return true;
if (AllowMixed && !Greedy) {
assert(numInstructions == 3);
for (auto Opcode : Opcodes) {
std::vector<unsigned> StartBits;
std::vector<unsigned> EndBits;
std::vector<uint64_t> FieldVals;
insn_t Insn;
insnWithID(Insn, Opcode.EncodingID);
if (getIslands(StartBits, EndBits, FieldVals, Insn) > 0) {
runSingleFilter(StartBits[0], EndBits[0] - StartBits[0] + 1, true);
return true;
}
}
}
unsigned BitIndex;
std::vector<bitAttr_t> bitAttrs;
for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex)
if (FilterBitValues[BitIndex] == BIT_TRUE ||
FilterBitValues[BitIndex] == BIT_FALSE)
bitAttrs.push_back(ATTR_FILTERED);
else
bitAttrs.push_back(ATTR_NONE);
for (unsigned InsnIndex = 0; InsnIndex < numInstructions; ++InsnIndex) {
insn_t insn;
insnWithID(insn, Opcodes[InsnIndex].EncodingID);
for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
switch (bitAttrs[BitIndex]) {
case ATTR_NONE:
if (insn[BitIndex] == BIT_UNSET)
bitAttrs[BitIndex] = ATTR_ALL_UNSET;
else
bitAttrs[BitIndex] = ATTR_ALL_SET;
break;
case ATTR_ALL_SET:
if (insn[BitIndex] == BIT_UNSET)
bitAttrs[BitIndex] = ATTR_MIXED;
break;
case ATTR_ALL_UNSET:
if (insn[BitIndex] != BIT_UNSET)
bitAttrs[BitIndex] = ATTR_MIXED;
break;
case ATTR_MIXED:
case ATTR_FILTERED:
break;
}
}
}
bitAttr_t RA = ATTR_NONE;
unsigned StartBit = 0;
for (BitIndex = 0; BitIndex < BitWidth; ++BitIndex) {
bitAttr_t bitAttr = bitAttrs[BitIndex];
assert(bitAttr != ATTR_NONE && "Bit without attributes");
switch (RA) {
case ATTR_NONE:
switch (bitAttr) {
case ATTR_FILTERED:
break;
case ATTR_ALL_SET:
StartBit = BitIndex;
RA = ATTR_ALL_SET;
break;
case ATTR_ALL_UNSET:
break;
case ATTR_MIXED:
StartBit = BitIndex;
RA = ATTR_MIXED;
break;
default:
llvm_unreachable("Unexpected bitAttr!");
}
break;
case ATTR_ALL_SET:
switch (bitAttr) {
case ATTR_FILTERED:
reportRegion(RA, StartBit, BitIndex, AllowMixed);
RA = ATTR_NONE;
break;
case ATTR_ALL_SET:
break;
case ATTR_ALL_UNSET:
reportRegion(RA, StartBit, BitIndex, AllowMixed);
RA = ATTR_NONE;
break;
case ATTR_MIXED:
reportRegion(RA, StartBit, BitIndex, AllowMixed);
StartBit = BitIndex;
RA = ATTR_MIXED;
break;
default:
llvm_unreachable("Unexpected bitAttr!");
}
break;
case ATTR_MIXED:
switch (bitAttr) {
case ATTR_FILTERED:
reportRegion(RA, StartBit, BitIndex, AllowMixed);
StartBit = BitIndex;
RA = ATTR_NONE;
break;
case ATTR_ALL_SET:
reportRegion(RA, StartBit, BitIndex, AllowMixed);
StartBit = BitIndex;
RA = ATTR_ALL_SET;
break;
case ATTR_ALL_UNSET:
reportRegion(RA, StartBit, BitIndex, AllowMixed);
RA = ATTR_NONE;
break;
case ATTR_MIXED:
break;
default:
llvm_unreachable("Unexpected bitAttr!");
}
break;
case ATTR_ALL_UNSET:
llvm_unreachable("regionAttr state machine has no ATTR_UNSET state");
case ATTR_FILTERED:
llvm_unreachable("regionAttr state machine has no ATTR_FILTERED state");
}
}
switch (RA) {
case ATTR_NONE:
break;
case ATTR_FILTERED:
break;
case ATTR_ALL_SET:
reportRegion(RA, StartBit, BitIndex, AllowMixed);
break;
case ATTR_ALL_UNSET:
break;
case ATTR_MIXED:
reportRegion(RA, StartBit, BitIndex, AllowMixed);
break;
}
BestIndex = 0;
bool AllUseless = true;
unsigned BestScore = 0;
for (unsigned i = 0, e = Filters.size(); i != e; ++i) {
unsigned Usefulness = Filters[i].usefulness();
if (Usefulness)
AllUseless = false;
if (Usefulness > BestScore) {
BestIndex = i;
BestScore = Usefulness;
}
}
if (!AllUseless)
bestFilter().recurse();
return !AllUseless;
}
void FilterChooser::doFilter() {
unsigned Num = Opcodes.size();
assert(Num && "FilterChooser created with no instructions");
if (filterProcessor(false))
return;
if (filterProcessor(true))
return;
if (Num == 3 && filterProcessor(true, false))
return;
BestIndex = -1;
}
void FilterChooser::emitTableEntries(DecoderTableInfo &TableInfo) const {
if (Opcodes.size() == 1) {
emitSingletonTableEntry(TableInfo, Opcodes[0]);
return;
}
if (BestIndex != -1) {
const Filter &Best = Filters[BestIndex];
if (Best.getNumFiltered() == 1)
emitSingletonTableEntry(TableInfo, Best);
else
Best.emitTableEntry(TableInfo);
return;
}
errs() << "Decoding Conflict:\n";
dumpStack(errs(), "\t\t");
for (auto Opcode : Opcodes) {
errs() << '\t';
emitNameWithID(errs(), Opcode.EncodingID);
errs() << " ";
dumpBits(
errs(),
getBitsField(*AllInstructions[Opcode.EncodingID].EncodingDef, "Inst"));
errs() << '\n';
}
}
static std::string findOperandDecoderMethod(Record *Record) {
std::string Decoder;
RecordVal *DecoderString = Record->getValue("DecoderMethod");
StringInit *String = DecoderString ?
dyn_cast<StringInit>(DecoderString->getValue()) : nullptr;
if (String) {
Decoder = std::string(String->getValue());
if (!Decoder.empty())
return Decoder;
}
if (Record->isSubClassOf("RegisterOperand"))
Record = Record->getValueAsDef("RegClass");
if (Record->isSubClassOf("RegisterClass")) {
Decoder = "Decode" + Record->getName().str() + "RegisterClass";
} else if (Record->isSubClassOf("PointerLikeRegClass")) {
Decoder = "DecodePointerLikeRegClass" +
utostr(Record->getValueAsInt("RegClassKind"));
}
return Decoder;
}
OperandInfo getOpInfo(Record *TypeRecord) {
std::string Decoder = findOperandDecoderMethod(TypeRecord);
RecordVal *HasCompleteDecoderVal = TypeRecord->getValue("hasCompleteDecoder");
BitInit *HasCompleteDecoderBit =
HasCompleteDecoderVal
? dyn_cast<BitInit>(HasCompleteDecoderVal->getValue())
: nullptr;
bool HasCompleteDecoder =
HasCompleteDecoderBit ? HasCompleteDecoderBit->getValue() : true;
return OperandInfo(Decoder, HasCompleteDecoder);
}
void parseVarLenInstOperand(const Record &Def,
std::vector<OperandInfo> &Operands,
const CodeGenInstruction &CGI) {
const RecordVal *RV = Def.getValue("Inst");
VarLenInst VLI(cast<DagInit>(RV->getValue()), RV);
SmallVector<int> TiedTo;
for (unsigned Idx = 0; Idx < CGI.Operands.size(); ++Idx) {
auto &Op = CGI.Operands[Idx];
if (Op.MIOperandInfo && Op.MIOperandInfo->getNumArgs() > 0)
for (auto *Arg : Op.MIOperandInfo->getArgs())
Operands.push_back(getOpInfo(cast<DefInit>(Arg)->getDef()));
else
Operands.push_back(getOpInfo(Op.Rec));
int TiedReg = Op.getTiedRegister();
TiedTo.push_back(-1);
if (TiedReg != -1) {
TiedTo[Idx] = TiedReg;
TiedTo[TiedReg] = Idx;
}
}
unsigned CurrBitPos = 0;
for (auto &EncodingSegment : VLI) {
unsigned Offset = 0;
StringRef OpName;
if (const StringInit *SI = dyn_cast<StringInit>(EncodingSegment.Value)) {
OpName = SI->getValue();
} else if (const DagInit *DI = dyn_cast<DagInit>(EncodingSegment.Value)) {
OpName = cast<StringInit>(DI->getArg(0))->getValue();
Offset = cast<IntInit>(DI->getArg(2))->getValue();
}
if (!OpName.empty()) {
auto OpSubOpPair =
const_cast<CodeGenInstruction &>(CGI).Operands.ParseOperandName(
OpName);
unsigned OpIdx = CGI.Operands.getFlattenedOperandNumber(OpSubOpPair);
Operands[OpIdx].addField(CurrBitPos, EncodingSegment.BitWidth, Offset);
int TiedReg = TiedTo[OpSubOpPair.first];
if (TiedReg != -1) {
unsigned OpIdx = CGI.Operands.getFlattenedOperandNumber(
std::make_pair(TiedReg, OpSubOpPair.second));
Operands[OpIdx].addField(CurrBitPos, EncodingSegment.BitWidth, Offset);
}
}
CurrBitPos += EncodingSegment.BitWidth;
}
}
static unsigned
populateInstruction(CodeGenTarget &Target, const Record &EncodingDef,
const CodeGenInstruction &CGI, unsigned Opc,
std::map<unsigned, std::vector<OperandInfo>> &Operands,
bool IsVarLenInst) {
const Record &Def = *CGI.TheDef;
BitsInit &Bits = getBitsField(EncodingDef, "Inst");
if (Bits.allInComplete())
return 0;
std::vector<OperandInfo> InsnOperands;
StringRef InstDecoder = EncodingDef.getValueAsString("DecoderMethod");
if (InstDecoder != "") {
bool HasCompleteInstDecoder = EncodingDef.getValueAsBit("hasCompleteDecoder");
InsnOperands.push_back(
OperandInfo(std::string(InstDecoder), HasCompleteInstDecoder));
Operands[Opc] = InsnOperands;
return Bits.getNumBits();
}
std::vector<std::pair<Init*, StringRef>> InOutOperands;
DagInit *Out = Def.getValueAsDag("OutOperandList");
DagInit *In = Def.getValueAsDag("InOperandList");
for (unsigned i = 0; i < Out->getNumArgs(); ++i)
InOutOperands.push_back(
std::make_pair(Out->getArg(i), Out->getArgNameStr(i)));
for (unsigned i = 0; i < In->getNumArgs(); ++i)
InOutOperands.push_back(
std::make_pair(In->getArg(i), In->getArgNameStr(i)));
std::map<std::string, std::string> TiedNames;
for (unsigned i = 0; i < CGI.Operands.size(); ++i) {
int tiedTo = CGI.Operands[i].getTiedRegister();
if (tiedTo != -1) {
std::pair<unsigned, unsigned> SO =
CGI.Operands.getSubOperandNumber(tiedTo);
TiedNames[std::string(InOutOperands[i].second)] =
std::string(InOutOperands[SO.first].second);
TiedNames[std::string(InOutOperands[SO.first].second)] =
std::string(InOutOperands[i].second);
}
}
if (IsVarLenInst) {
parseVarLenInstOperand(EncodingDef, InsnOperands, CGI);
} else {
std::map<std::string, std::vector<OperandInfo>> NumberedInsnOperands;
std::set<std::string> NumberedInsnOperandsNoTie;
if (Target.getInstructionSet()->getValueAsBit(
"decodePositionallyEncodedOperands")) {
const std::vector<RecordVal> &Vals = Def.getValues();
unsigned NumberedOp = 0;
std::set<unsigned> NamedOpIndices;
if (Target.getInstructionSet()->getValueAsBit(
"noNamedPositionallyEncodedOperands"))
for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
unsigned OpIdx;
if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
continue;
NamedOpIndices.insert(OpIdx);
}
for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
if (Vals[i].isNonconcreteOK() || Vals[i].getValue()->isComplete())
continue;
unsigned bi = 0;
for (; bi < Bits.getNumBits(); ++bi) {
VarInit *Var = nullptr;
VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
if (BI)
Var = dyn_cast<VarInit>(BI->getBitVar());
else
Var = dyn_cast<VarInit>(Bits.getBit(bi));
if (Var && Var->getName() == Vals[i].getName())
break;
}
if (bi == Bits.getNumBits())
continue;
unsigned OpIdx;
if (CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx))
continue;
unsigned bitStart = bi++, bitWidth = 1;
for (; bi < Bits.getNumBits(); ++bi) {
VarInit *Var = nullptr;
VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
if (BI)
Var = dyn_cast<VarInit>(BI->getBitVar());
else
Var = dyn_cast<VarInit>(Bits.getBit(bi));
if (!Var)
break;
if (Var->getName() != Vals[i].getName())
break;
++bitWidth;
}
unsigned NumberOps = CGI.Operands.size();
while (NumberedOp < NumberOps &&
(CGI.Operands.isFlatOperandNotEmitted(NumberedOp) ||
(!NamedOpIndices.empty() &&
NamedOpIndices.count(
CGI.Operands.getSubOperandNumber(NumberedOp).first))))
++NumberedOp;
OpIdx = NumberedOp++;
std::pair<unsigned, unsigned> SO =
CGI.Operands.getSubOperandNumber(OpIdx);
const std::string &Name = CGI.Operands[SO.first].Name;
LLVM_DEBUG(dbgs() << "Numbered operand mapping for " << Def.getName()
<< ": " << Name << "(" << SO.first << ", "
<< SO.second << ") => " << Vals[i].getName() << "\n");
std::string Decoder;
Record *TypeRecord = CGI.Operands[SO.first].Rec;
RecordVal *DecoderString = TypeRecord->getValue("DecoderMethod");
StringInit *String =
DecoderString ? dyn_cast<StringInit>(DecoderString->getValue())
: nullptr;
if (String && String->getValue() != "")
Decoder = std::string(String->getValue());
if (Decoder == "" && CGI.Operands[SO.first].MIOperandInfo &&
CGI.Operands[SO.first].MIOperandInfo->getNumArgs()) {
Init *Arg = CGI.Operands[SO.first].MIOperandInfo->getArg(SO.second);
if (DefInit *DI = cast<DefInit>(Arg))
TypeRecord = DI->getDef();
}
bool isReg = false;
if (TypeRecord->isSubClassOf("RegisterOperand"))
TypeRecord = TypeRecord->getValueAsDef("RegClass");
if (TypeRecord->isSubClassOf("RegisterClass")) {
Decoder = "Decode" + TypeRecord->getName().str() + "RegisterClass";
isReg = true;
} else if (TypeRecord->isSubClassOf("PointerLikeRegClass")) {
Decoder = "DecodePointerLikeRegClass" +
utostr(TypeRecord->getValueAsInt("RegClassKind"));
isReg = true;
}
DecoderString = TypeRecord->getValue("DecoderMethod");
String = DecoderString ? dyn_cast<StringInit>(DecoderString->getValue())
: nullptr;
if (!isReg && String && String->getValue() != "")
Decoder = std::string(String->getValue());
RecordVal *HasCompleteDecoderVal =
TypeRecord->getValue("hasCompleteDecoder");
BitInit *HasCompleteDecoderBit =
HasCompleteDecoderVal
? dyn_cast<BitInit>(HasCompleteDecoderVal->getValue())
: nullptr;
bool HasCompleteDecoder =
HasCompleteDecoderBit ? HasCompleteDecoderBit->getValue() : true;
OperandInfo OpInfo(Decoder, HasCompleteDecoder);
OpInfo.addField(bitStart, bitWidth, 0);
NumberedInsnOperands[Name].push_back(OpInfo);
if (CGI.Operands[SO.first].MIOperandInfo &&
CGI.Operands[SO.first].MIOperandInfo->getNumArgs() > 1 && String &&
String->getValue() != "")
NumberedInsnOperandsNoTie.insert(Name);
}
}
for (const auto &Op : InOutOperands) {
if (!NumberedInsnOperands[std::string(Op.second)].empty()) {
llvm::append_range(InsnOperands,
NumberedInsnOperands[std::string(Op.second)]);
continue;
}
if (!NumberedInsnOperands[TiedNames[std::string(Op.second)]].empty()) {
if (!NumberedInsnOperandsNoTie.count(
TiedNames[std::string(Op.second)])) {
unsigned i =
CGI.Operands.getOperandNamed(TiedNames[std::string(Op.second)]);
int tiedTo = CGI.Operands[i].getTiedRegister();
if (tiedTo == -1) {
i = CGI.Operands.getOperandNamed(Op.second);
tiedTo = CGI.Operands[i].getTiedRegister();
}
if (tiedTo != -1) {
std::pair<unsigned, unsigned> SO =
CGI.Operands.getSubOperandNumber(tiedTo);
InsnOperands.push_back(
NumberedInsnOperands[TiedNames[std::string(Op.second)]]
[SO.second]);
}
}
continue;
}
OperandInfo OpInfo = getOpInfo(cast<DefInit>(Op.first)->getDef());
if (const RecordVal *EncodedValue = EncodingDef.getValue(Op.second))
if (const BitsInit *OpBits =
dyn_cast<BitsInit>(EncodedValue->getValue()))
for (unsigned I = 0; I < OpBits->getNumBits(); ++I)
if (const BitInit *OpBit = dyn_cast<BitInit>(OpBits->getBit(I)))
if (OpBit->getValue())
OpInfo.InitValue |= 1ULL << I;
unsigned Base = ~0U;
unsigned Width = 0;
unsigned Offset = 0;
for (unsigned bi = 0; bi < Bits.getNumBits(); ++bi) {
VarInit *Var = nullptr;
VarBitInit *BI = dyn_cast<VarBitInit>(Bits.getBit(bi));
if (BI)
Var = dyn_cast<VarInit>(BI->getBitVar());
else
Var = dyn_cast<VarInit>(Bits.getBit(bi));
if (!Var) {
if (Base != ~0U) {
OpInfo.addField(Base, Width, Offset);
Base = ~0U;
Width = 0;
Offset = 0;
}
continue;
}
if ((Var->getName() != Op.second &&
Var->getName() != TiedNames[std::string(Op.second)])) {
if (Base != ~0U) {
OpInfo.addField(Base, Width, Offset);
Base = ~0U;
Width = 0;
Offset = 0;
}
continue;
}
if (Base == ~0U) {
Base = bi;
Width = 1;
Offset = BI ? BI->getBitNum() : 0;
} else if (BI && BI->getBitNum() != Offset + Width) {
OpInfo.addField(Base, Width, Offset);
Base = bi;
Width = 1;
Offset = BI->getBitNum();
} else {
++Width;
}
}
if (Base != ~0U)
OpInfo.addField(Base, Width, Offset);
if (OpInfo.numFields() > 0)
InsnOperands.push_back(OpInfo);
}
}
Operands[Opc] = InsnOperands;
#if 0#endif
return Bits.getNumBits();
}
static void emitFieldFromInstruction(formatted_raw_ostream &OS) {
OS << "// Helper functions for extracting fields from encoded instructions.\n"
<< "// InsnType must either be integral or an APInt-like object that "
"must:\n"
<< "// * be default-constructible and copy-constructible\n"
<< "// * be constructible from an APInt (this can be private)\n"
<< "// * Support insertBits(bits, startBit, numBits)\n"
<< "// * Support extractBitsAsZExtValue(numBits, startBit)\n"
<< "// * Support the ~, &, ==, and != operators with other objects of "
"the same type\n"
<< "// * Support the != and bitwise & with uint64_t\n"
<< "// * Support put (<<) to raw_ostream&\n"
<< "template <typename InsnType>\n"
<< "#if defined(_MSC_VER) && !defined(__clang__)\n"
<< "__declspec(noinline)\n"
<< "#endif\n"
<< "static std::enable_if_t<std::is_integral<InsnType>::value, InsnType>\n"
<< "fieldFromInstruction(const InsnType &insn, unsigned startBit,\n"
<< " unsigned numBits) {\n"
<< " assert(startBit + numBits <= 64 && \"Cannot support >64-bit "
"extractions!\");\n"
<< " assert(startBit + numBits <= (sizeof(InsnType) * 8) &&\n"
<< " \"Instruction field out of bounds!\");\n"
<< " InsnType fieldMask;\n"
<< " if (numBits == sizeof(InsnType) * 8)\n"
<< " fieldMask = (InsnType)(-1LL);\n"
<< " else\n"
<< " fieldMask = (((InsnType)1 << numBits) - 1) << startBit;\n"
<< " return (insn & fieldMask) >> startBit;\n"
<< "}\n"
<< "\n"
<< "template <typename InsnType>\n"
<< "static std::enable_if_t<!std::is_integral<InsnType>::value, "
"uint64_t>\n"
<< "fieldFromInstruction(const InsnType &insn, unsigned startBit,\n"
<< " unsigned numBits) {\n"
<< " return insn.extractBitsAsZExtValue(numBits, startBit);\n"
<< "}\n\n";
}
static void emitInsertBits(formatted_raw_ostream &OS) {
OS << "// Helper function for inserting bits extracted from an encoded "
"instruction into\n"
<< "// a field.\n"
<< "template <typename InsnType>\n"
<< "static std::enable_if_t<std::is_integral<InsnType>::value>\n"
<< "insertBits(InsnType &field, InsnType bits, unsigned startBit, "
"unsigned numBits) {\n"
<< " assert(startBit + numBits <= sizeof field * 8);\n"
<< " field |= (InsnType)bits << startBit;\n"
<< "}\n"
<< "\n"
<< "template <typename InsnType>\n"
<< "static std::enable_if_t<!std::is_integral<InsnType>::value>\n"
<< "insertBits(InsnType &field, uint64_t bits, unsigned startBit, "
"unsigned numBits) {\n"
<< " field.insertBits(bits, startBit, numBits);\n"
<< "}\n\n";
}
static void emitDecodeInstruction(formatted_raw_ostream &OS,
bool IsVarLenInst) {
OS << "template <typename InsnType>\n"
<< "static DecodeStatus decodeInstruction(const uint8_t DecodeTable[], "
"MCInst &MI,\n"
<< " InsnType insn, uint64_t "
"Address,\n"
<< " const MCDisassembler *DisAsm,\n"
<< " const MCSubtargetInfo &STI";
if (IsVarLenInst) {
OS << ",\n"
<< " llvm::function_ref<void(APInt "
"&,"
<< " uint64_t)> makeUp";
}
OS << ") {\n"
<< " const FeatureBitset &Bits = STI.getFeatureBits();\n"
<< "\n"
<< " const uint8_t *Ptr = DecodeTable;\n"
<< " uint64_t CurFieldValue = 0;\n"
<< " DecodeStatus S = MCDisassembler::Success;\n"
<< " while (true) {\n"
<< " ptrdiff_t Loc = Ptr - DecodeTable;\n"
<< " switch (*Ptr) {\n"
<< " default:\n"
<< " errs() << Loc << \": Unexpected decode table opcode!\\n\";\n"
<< " return MCDisassembler::Fail;\n"
<< " case MCD::OPC_ExtractField: {\n"
<< " unsigned Start = *++Ptr;\n"
<< " unsigned Len = *++Ptr;\n"
<< " ++Ptr;\n";
if (IsVarLenInst)
OS << " makeUp(insn, Start + Len);\n";
OS << " CurFieldValue = fieldFromInstruction(insn, Start, Len);\n"
<< " LLVM_DEBUG(dbgs() << Loc << \": OPC_ExtractField(\" << Start << "
"\", \"\n"
<< " << Len << \"): \" << CurFieldValue << \"\\n\");\n"
<< " break;\n"
<< " }\n"
<< " case MCD::OPC_FilterValue: {\n"
<< " // Decode the field value.\n"
<< " unsigned Len;\n"
<< " uint64_t Val = decodeULEB128(++Ptr, &Len);\n"
<< " Ptr += Len;\n"
<< " // NumToSkip is a plain 24-bit integer.\n"
<< " unsigned NumToSkip = *Ptr++;\n"
<< " NumToSkip |= (*Ptr++) << 8;\n"
<< " NumToSkip |= (*Ptr++) << 16;\n"
<< "\n"
<< " // Perform the filter operation.\n"
<< " if (Val != CurFieldValue)\n"
<< " Ptr += NumToSkip;\n"
<< " LLVM_DEBUG(dbgs() << Loc << \": OPC_FilterValue(\" << Val << "
"\", \" << NumToSkip\n"
<< " << \"): \" << ((Val != CurFieldValue) ? \"FAIL:\" "
": \"PASS:\")\n"
<< " << \" continuing at \" << (Ptr - DecodeTable) << "
"\"\\n\");\n"
<< "\n"
<< " break;\n"
<< " }\n"
<< " case MCD::OPC_CheckField: {\n"
<< " unsigned Start = *++Ptr;\n"
<< " unsigned Len = *++Ptr;\n";
if (IsVarLenInst)
OS << " makeUp(insn, Start + Len);\n";
OS << " uint64_t FieldValue = fieldFromInstruction(insn, Start, Len);\n"
<< " // Decode the field value.\n"
<< " unsigned PtrLen = 0;\n"
<< " uint64_t ExpectedValue = decodeULEB128(++Ptr, &PtrLen);\n"
<< " Ptr += PtrLen;\n"
<< " // NumToSkip is a plain 24-bit integer.\n"
<< " unsigned NumToSkip = *Ptr++;\n"
<< " NumToSkip |= (*Ptr++) << 8;\n"
<< " NumToSkip |= (*Ptr++) << 16;\n"
<< "\n"
<< " // If the actual and expected values don't match, skip.\n"
<< " if (ExpectedValue != FieldValue)\n"
<< " Ptr += NumToSkip;\n"
<< " LLVM_DEBUG(dbgs() << Loc << \": OPC_CheckField(\" << Start << "
"\", \"\n"
<< " << Len << \", \" << ExpectedValue << \", \" << "
"NumToSkip\n"
<< " << \"): FieldValue = \" << FieldValue << \", "
"ExpectedValue = \"\n"
<< " << ExpectedValue << \": \"\n"
<< " << ((ExpectedValue == FieldValue) ? \"PASS\\n\" : "
"\"FAIL\\n\"));\n"
<< " break;\n"
<< " }\n"
<< " case MCD::OPC_CheckPredicate: {\n"
<< " unsigned Len;\n"
<< " // Decode the Predicate Index value.\n"
<< " unsigned PIdx = decodeULEB128(++Ptr, &Len);\n"
<< " Ptr += Len;\n"
<< " // NumToSkip is a plain 24-bit integer.\n"
<< " unsigned NumToSkip = *Ptr++;\n"
<< " NumToSkip |= (*Ptr++) << 8;\n"
<< " NumToSkip |= (*Ptr++) << 16;\n"
<< " // Check the predicate.\n"
<< " bool Pred;\n"
<< " if (!(Pred = checkDecoderPredicate(PIdx, Bits)))\n"
<< " Ptr += NumToSkip;\n"
<< " (void)Pred;\n"
<< " LLVM_DEBUG(dbgs() << Loc << \": OPC_CheckPredicate(\" << PIdx "
"<< \"): \"\n"
<< " << (Pred ? \"PASS\\n\" : \"FAIL\\n\"));\n"
<< "\n"
<< " break;\n"
<< " }\n"
<< " case MCD::OPC_Decode: {\n"
<< " unsigned Len;\n"
<< " // Decode the Opcode value.\n"
<< " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
<< " Ptr += Len;\n"
<< " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
<< " Ptr += Len;\n"
<< "\n"
<< " MI.clear();\n"
<< " MI.setOpcode(Opc);\n"
<< " bool DecodeComplete;\n";
if (IsVarLenInst) {
OS << " Len = InstrLenTable[Opc];\n"
<< " makeUp(insn, Len);\n";
}
OS << " S = decodeToMCInst(S, DecodeIdx, insn, MI, Address, DisAsm, "
"DecodeComplete);\n"
<< " assert(DecodeComplete);\n"
<< "\n"
<< " LLVM_DEBUG(dbgs() << Loc << \": OPC_Decode: opcode \" << Opc\n"
<< " << \", using decoder \" << DecodeIdx << \": \"\n"
<< " << (S != MCDisassembler::Fail ? \"PASS\" : "
"\"FAIL\") << \"\\n\");\n"
<< " return S;\n"
<< " }\n"
<< " case MCD::OPC_TryDecode: {\n"
<< " unsigned Len;\n"
<< " // Decode the Opcode value.\n"
<< " unsigned Opc = decodeULEB128(++Ptr, &Len);\n"
<< " Ptr += Len;\n"
<< " unsigned DecodeIdx = decodeULEB128(Ptr, &Len);\n"
<< " Ptr += Len;\n"
<< " // NumToSkip is a plain 24-bit integer.\n"
<< " unsigned NumToSkip = *Ptr++;\n"
<< " NumToSkip |= (*Ptr++) << 8;\n"
<< " NumToSkip |= (*Ptr++) << 16;\n"
<< "\n"
<< " // Perform the decode operation.\n"
<< " MCInst TmpMI;\n"
<< " TmpMI.setOpcode(Opc);\n"
<< " bool DecodeComplete;\n"
<< " S = decodeToMCInst(S, DecodeIdx, insn, TmpMI, Address, DisAsm, "
"DecodeComplete);\n"
<< " LLVM_DEBUG(dbgs() << Loc << \": OPC_TryDecode: opcode \" << "
"Opc\n"
<< " << \", using decoder \" << DecodeIdx << \": \");\n"
<< "\n"
<< " if (DecodeComplete) {\n"
<< " // Decoding complete.\n"
<< " LLVM_DEBUG(dbgs() << (S != MCDisassembler::Fail ? \"PASS\" : "
"\"FAIL\") << \"\\n\");\n"
<< " MI = TmpMI;\n"
<< " return S;\n"
<< " } else {\n"
<< " assert(S == MCDisassembler::Fail);\n"
<< " // If the decoding was incomplete, skip.\n"
<< " Ptr += NumToSkip;\n"
<< " LLVM_DEBUG(dbgs() << \"FAIL: continuing at \" << (Ptr - "
"DecodeTable) << \"\\n\");\n"
<< " // Reset decode status. This also drops a SoftFail status "
"that could be\n"
<< " // set before the decode attempt.\n"
<< " S = MCDisassembler::Success;\n"
<< " }\n"
<< " break;\n"
<< " }\n"
<< " case MCD::OPC_SoftFail: {\n"
<< " // Decode the mask values.\n"
<< " unsigned Len;\n"
<< " uint64_t PositiveMask = decodeULEB128(++Ptr, &Len);\n"
<< " Ptr += Len;\n"
<< " uint64_t NegativeMask = decodeULEB128(Ptr, &Len);\n"
<< " Ptr += Len;\n"
<< " bool Fail = (insn & PositiveMask) != 0 || (~insn & "
"NegativeMask) != 0;\n"
<< " if (Fail)\n"
<< " S = MCDisassembler::SoftFail;\n"
<< " LLVM_DEBUG(dbgs() << Loc << \": OPC_SoftFail: \" << (Fail ? "
"\"FAIL\\n\" : \"PASS\\n\"));\n"
<< " break;\n"
<< " }\n"
<< " case MCD::OPC_Fail: {\n"
<< " LLVM_DEBUG(dbgs() << Loc << \": OPC_Fail\\n\");\n"
<< " return MCDisassembler::Fail;\n"
<< " }\n"
<< " }\n"
<< " }\n"
<< " llvm_unreachable(\"bogosity detected in disassembler state "
"machine!\");\n"
<< "}\n\n";
}
void DecoderEmitter::run(raw_ostream &o) {
formatted_raw_ostream OS(o);
OS << "#include \"llvm/MC/MCInst.h\"\n";
OS << "#include \"llvm/MC/MCSubtargetInfo.h\"\n";
OS << "#include \"llvm/MC/SubtargetFeature.h\"\n";
OS << "#include \"llvm/Support/DataTypes.h\"\n";
OS << "#include \"llvm/Support/Debug.h\"\n";
OS << "#include \"llvm/Support/LEB128.h\"\n";
OS << "#include \"llvm/Support/raw_ostream.h\"\n";
OS << "#include <assert.h>\n";
OS << '\n';
OS << "namespace llvm {\n\n";
emitFieldFromInstruction(OS);
emitInsertBits(OS);
Target.reverseBitsForLittleEndianEncoding();
std::set<StringRef> HwModeNames;
const auto &NumberedInstructions = Target.getInstructionsByEnumValue();
NumberedEncodings.reserve(NumberedInstructions.size());
DenseMap<Record *, unsigned> IndexOfInstruction;
for (const auto &NumberedInstruction : NumberedInstructions) {
IndexOfInstruction[NumberedInstruction->TheDef] = NumberedEncodings.size();
if (const RecordVal *RV =
NumberedInstruction->TheDef->getValue("EncodingInfos")) {
if (auto *DI = dyn_cast_or_null<DefInit>(RV->getValue())) {
const CodeGenHwModes &HWM = Target.getHwModes();
EncodingInfoByHwMode EBM(DI->getDef(), HWM);
for (auto &KV : EBM)
HwModeNames.insert(HWM.getMode(KV.first).Name);
}
}
}
if (HwModeNames.empty())
HwModeNames.insert("");
for (const auto &NumberedInstruction : NumberedInstructions) {
IndexOfInstruction[NumberedInstruction->TheDef] = NumberedEncodings.size();
if (const RecordVal *RV =
NumberedInstruction->TheDef->getValue("EncodingInfos")) {
if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue())) {
const CodeGenHwModes &HWM = Target.getHwModes();
EncodingInfoByHwMode EBM(DI->getDef(), HWM);
for (auto &KV : EBM) {
NumberedEncodings.emplace_back(KV.second, NumberedInstruction,
HWM.getMode(KV.first).Name);
HwModeNames.insert(HWM.getMode(KV.first).Name);
}
continue;
}
}
for (StringRef HwModeName : HwModeNames)
NumberedEncodings.emplace_back(NumberedInstruction->TheDef,
NumberedInstruction, HwModeName);
}
for (const auto &NumberedAlias : RK.getAllDerivedDefinitions("AdditionalEncoding"))
NumberedEncodings.emplace_back(
NumberedAlias,
&Target.getInstruction(NumberedAlias->getValueAsDef("AliasOf")));
std::map<std::pair<std::string, unsigned>, std::vector<EncodingIDAndOpcode>>
OpcMap;
std::map<unsigned, std::vector<OperandInfo>> Operands;
std::vector<unsigned> InstrLen;
bool IsVarLenInst =
any_of(NumberedInstructions, [](const CodeGenInstruction *CGI) {
RecordVal *RV = CGI->TheDef->getValue("Inst");
return RV && isa<DagInit>(RV->getValue());
});
unsigned MaxInstLen = 0;
for (unsigned i = 0; i < NumberedEncodings.size(); ++i) {
const Record *EncodingDef = NumberedEncodings[i].EncodingDef;
const CodeGenInstruction *Inst = NumberedEncodings[i].Inst;
const Record *Def = Inst->TheDef;
unsigned Size = EncodingDef->getValueAsInt("Size");
if (Def->getValueAsString("Namespace") == "TargetOpcode" ||
Def->getValueAsBit("isPseudo") ||
Def->getValueAsBit("isAsmParserOnly") ||
Def->getValueAsBit("isCodeGenOnly")) {
NumEncodingsLackingDisasm++;
continue;
}
if (i < NumberedInstructions.size())
NumInstructions++;
NumEncodings++;
if (!Size && !IsVarLenInst)
continue;
if (IsVarLenInst)
InstrLen.resize(NumberedInstructions.size(), 0);
if (unsigned Len = populateInstruction(Target, *EncodingDef, *Inst, i,
Operands, IsVarLenInst)) {
if (IsVarLenInst) {
MaxInstLen = std::max(MaxInstLen, Len);
InstrLen[i] = Len;
}
std::string DecoderNamespace =
std::string(EncodingDef->getValueAsString("DecoderNamespace"));
if (!NumberedEncodings[i].HwModeName.empty())
DecoderNamespace +=
std::string("_") + NumberedEncodings[i].HwModeName.str();
OpcMap[std::make_pair(DecoderNamespace, Size)].emplace_back(
i, IndexOfInstruction.find(Def)->second);
} else {
NumEncodingsOmitted++;
}
}
DecoderTableInfo TableInfo;
for (const auto &Opc : OpcMap) {
ArrayRef<EncodingAndInst> NumberedEncodingsRef(
NumberedEncodings.data(), NumberedEncodings.size());
FilterChooser FC(NumberedEncodingsRef, Opc.second, Operands,
IsVarLenInst ? MaxInstLen : 8 * Opc.first.second, this);
TableInfo.Table.clear();
TableInfo.FixupStack.clear();
TableInfo.Table.reserve(16384);
TableInfo.FixupStack.emplace_back();
FC.emitTableEntries(TableInfo);
assert(TableInfo.FixupStack.size() == 1 && "fixup stack phasing error!");
resolveTableFixups(TableInfo.Table, TableInfo.FixupStack.back(),
TableInfo.Table.size());
TableInfo.FixupStack.clear();
TableInfo.Table.push_back(MCD::OPC_Fail);
emitTable(OS, TableInfo.Table, 0, FC.getBitWidth(), Opc.first.first);
OS.flush();
}
if (IsVarLenInst)
emitInstrLenTable(OS, InstrLen);
emitPredicateFunction(OS, TableInfo.Predicates, 0);
emitDecoderFunction(OS, TableInfo.Decoders, 0);
emitDecodeInstruction(OS, IsVarLenInst);
OS << "\n} // end namespace llvm\n";
}
namespace llvm {
void EmitDecoder(RecordKeeper &RK, raw_ostream &OS,
const std::string &PredicateNamespace,
const std::string &GPrefix, const std::string &GPostfix,
const std::string &ROK, const std::string &RFail,
const std::string &L) {
DecoderEmitter(RK, PredicateNamespace, GPrefix, GPostfix, ROK, RFail, L)
.run(OS);
}
}