20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/DenseSet.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/ScopeExit.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/Support/Endian.h"
29#include "llvm/Support/MemoryBufferRef.h"
30#include "llvm/Support/SourceMgr.h"
40#define DEBUG_TYPE "mlir-bytecode-reader"
52 return "AttrType (2)";
54 return "AttrTypeOffset (3)";
58 return "Resource (5)";
60 return "ResourceOffset (6)";
62 return "DialectVersions (7)";
64 return "Properties (8)";
66 return (
"Unknown (" + Twine(
static_cast<unsigned>(sectionID)) +
")").str();
86 llvm_unreachable(
"unknown section ID");
97 explicit EncodingReader(ArrayRef<uint8_t> contents, Location fileLoc)
98 : buffer(contents), dataIt(buffer.begin()), fileLoc(fileLoc) {}
99 explicit EncodingReader(StringRef contents, Location fileLoc)
100 : EncodingReader({
reinterpret_cast<const uint8_t *
>(contents.data()),
105 bool empty()
const {
return dataIt == buffer.end(); }
108 size_t size()
const {
return buffer.end() - dataIt; }
111 LogicalResult alignTo(
unsigned alignment) {
112 if (!llvm::isPowerOf2_32(alignment))
113 return emitError(
"expected alignment to be a power-of-two");
115 auto isUnaligned = [&](
const uint8_t *ptr) {
116 return ((uintptr_t)ptr & (alignment - 1)) != 0;
123 while (isUnaligned(dataIt)) {
125 if (
failed(parseByte(padding)))
128 return emitError(
"expected alignment byte (0xCB), but got: '0x" +
129 llvm::utohexstr(padding) +
"'");
135 if (LLVM_UNLIKELY(isUnaligned(dataIt))) {
136 return emitError(
"expected data iterator aligned to ", alignment,
137 ", but got pointer: '0x" +
138 llvm::utohexstr((uintptr_t)dataIt) +
"'");
145 template <
typename... Args>
146 InFlightDiagnostic
emitError(Args &&...args)
const {
147 return ::emitError(fileLoc).
append(std::forward<Args>(args)...);
149 InFlightDiagnostic
emitError()
const { return ::emitError(fileLoc); }
152 template <
typename... Args>
153 InFlightDiagnostic
emitWarning(Args &&...args)
const {
154 return ::emitWarning(fileLoc).
append(std::forward<Args>(args)...);
156 InFlightDiagnostic
emitWarning()
const { return ::emitWarning(fileLoc); }
159 template <
typename T>
160 LogicalResult parseByte(T &value) {
162 return emitError(
"attempting to parse a byte at the end of the bytecode");
163 value =
static_cast<T
>(*dataIt++);
167 LogicalResult parseBytes(
size_t length, ArrayRef<uint8_t> &
result) {
168 if (length > size()) {
169 return emitError(
"attempting to parse ", length,
" bytes when only ",
172 result = {dataIt, length};
178 LogicalResult parseBytes(
size_t length, uint8_t *
result) {
179 if (length > size()) {
180 return emitError(
"attempting to parse ", length,
" bytes when only ",
183 memcpy(
result, dataIt, length);
190 LogicalResult parseBlobAndAlignment(ArrayRef<uint8_t> &data,
191 uint64_t &alignment) {
193 if (
failed(parseVarInt(alignment)) ||
failed(parseVarInt(dataSize)) ||
194 failed(alignTo(alignment)))
196 return parseBytes(dataSize, data);
206 LogicalResult parseVarInt(uint64_t &
result) {
213 if (LLVM_LIKELY(
result & 1)) {
221 if (LLVM_UNLIKELY(
result == 0)) {
222 llvm::support::ulittle64_t resultLE;
223 if (
failed(parseBytes(
sizeof(resultLE),
224 reinterpret_cast<uint8_t *
>(&resultLE))))
229 return parseMultiByteVarInt(
result);
235 LogicalResult parseSignedVarInt(uint64_t &
result) {
245 LogicalResult parseVarIntWithFlag(uint64_t &
result,
bool &flag) {
254 LogicalResult skipBytes(
size_t length) {
255 if (length > size()) {
256 return emitError(
"attempting to skip ", length,
" bytes when only ",
265 LogicalResult parseNullTerminatedString(StringRef &
result) {
266 const char *startIt = (
const char *)dataIt;
267 const char *nulIt = (
const char *)memchr(startIt, 0, size());
270 "malformed null-terminated string, no null character found");
272 result = StringRef(startIt, nulIt - startIt);
273 dataIt = (
const uint8_t *)nulIt + 1;
278 using ValidateAlignmentFn =
function_ref<LogicalResult(
unsigned alignment)>;
283 ValidateAlignmentFn alignmentValidator,
284 ArrayRef<uint8_t> §ionData) {
285 uint8_t sectionIDAndHasAlignment;
287 if (
failed(parseByte(sectionIDAndHasAlignment)) ||
288 failed(parseVarInt(length)))
295 bool hasAlignment = sectionIDAndHasAlignment & 0b10000000;
300 return emitError(
"invalid section ID: ",
unsigned(sectionID));
306 if (
failed(parseVarInt(alignment)))
341 if (
failed(alignmentValidator(alignment)))
342 return emitError(
"failed to align section ID: ",
unsigned(sectionID));
345 if (
failed(alignTo(alignment)))
350 return parseBytes(
static_cast<size_t>(length), sectionData);
353 Location getLoc()
const {
return fileLoc; }
362 LLVM_ATTRIBUTE_NOINLINE LogicalResult parseMultiByteVarInt(uint64_t &
result) {
368 uint32_t numBytes = llvm::countr_zero<uint32_t>(
result);
369 assert(numBytes > 0 && numBytes <= 7 &&
370 "unexpected number of trailing zeros in varint encoding");
373 llvm::support::ulittle64_t resultLE(
result);
375 parseBytes(numBytes,
reinterpret_cast<uint8_t *
>(&resultLE) + 1)))
380 result = resultLE >> (numBytes + 1);
385 ArrayRef<uint8_t> buffer;
388 const uint8_t *dataIt;
399template <
typename RangeT,
typename T>
400static LogicalResult
resolveEntry(EncodingReader &reader, RangeT &entries,
401 uint64_t
index, T &entry,
402 StringRef entryStr) {
403 if (
index >= entries.size())
404 return reader.emitError(
"invalid ", entryStr,
" index: ",
index);
407 if constexpr (std::is_convertible_v<llvm::detail::ValueOfRange<RangeT>, T>)
408 entry = entries[
index];
410 entry = &entries[
index];
415template <
typename RangeT,
typename T>
416static LogicalResult
parseEntry(EncodingReader &reader, RangeT &entries,
417 T &entry, StringRef entryStr) {
419 if (failed(reader.parseVarInt(entryIdx)))
421 return resolveEntry(reader, entries, entryIdx, entry, entryStr);
431class StringSectionReader {
434 LogicalResult
initialize(Location fileLoc, ArrayRef<uint8_t> sectionData);
438 LogicalResult parseString(EncodingReader &reader, StringRef &
result)
const {
445 LogicalResult parseStringWithFlag(EncodingReader &reader, StringRef &
result,
448 if (
failed(reader.parseVarIntWithFlag(entryIdx, flag)))
450 return parseStringAtIndex(reader, entryIdx,
result);
455 LogicalResult parseStringAtIndex(EncodingReader &reader, uint64_t index,
456 StringRef &
result)
const {
462 SmallVector<StringRef> strings;
466LogicalResult StringSectionReader::initialize(
Location fileLoc,
468 EncodingReader stringReader(sectionData, fileLoc);
472 if (
failed(stringReader.parseVarInt(numStrings)))
474 strings.resize(numStrings);
478 size_t stringDataEndOffset = sectionData.size();
479 for (StringRef &
string : llvm::reverse(strings)) {
481 if (
failed(stringReader.parseVarInt(stringSize)))
483 if (stringDataEndOffset < stringSize) {
484 return stringReader.emitError(
485 "string size exceeds the available data size");
489 size_t stringOffset = stringDataEndOffset - stringSize;
491 reinterpret_cast<const char *
>(sectionData.data() + stringOffset),
493 stringDataEndOffset = stringOffset;
498 if ((sectionData.size() - stringReader.size()) != stringDataEndOffset) {
499 return stringReader.emitError(
"unexpected trailing data between the "
500 "offsets for strings and their data");
513struct BytecodeDialect {
518 LogicalResult
load(
const DialectReader &reader, MLIRContext *ctx);
522 Dialect *getLoadedDialect()
const {
524 "expected `load` to be invoked before `getLoadedDialect`");
531 std::optional<Dialect *> dialect;
536 const BytecodeDialectInterface *
interface =
nullptr;
542 ArrayRef<uint8_t> versionBuffer;
545 std::unique_ptr<DialectVersion> loadedVersion;
549struct BytecodeOperationName {
550 BytecodeOperationName(BytecodeDialect *dialect, StringRef name,
551 std::optional<bool> wasRegistered)
552 : dialect(dialect), name(name), wasRegistered(wasRegistered) {}
556 std::optional<OperationName> opName;
559 BytecodeDialect *dialect;
566 std::optional<bool> wasRegistered;
572 EncodingReader &reader,
574 function_ref<LogicalResult(BytecodeDialect *)> entryCallback) {
576 std::unique_ptr<BytecodeDialect> *dialect;
577 if (failed(
parseEntry(reader, dialects, dialect,
"dialect")))
580 if (failed(reader.parseVarInt(numEntries)))
583 for (uint64_t i = 0; i < numEntries; ++i)
584 if (failed(entryCallback(dialect->get())))
595class ResourceSectionReader {
599 initialize(Location fileLoc,
const ParserConfig &config,
600 MutableArrayRef<std::unique_ptr<BytecodeDialect>> dialects,
601 StringSectionReader &stringReader, ArrayRef<uint8_t> sectionData,
602 ArrayRef<uint8_t> offsetSectionData, DialectReader &dialectReader,
603 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef);
606 LogicalResult parseResourceHandle(EncodingReader &reader,
607 AsmDialectResourceHandle &
result)
const {
613 SmallVector<AsmDialectResourceHandle> dialectResources;
614 llvm::StringMap<std::string> dialectResourceHandleRenamingMap;
617class ParsedResourceEntry :
public AsmParsedResourceEntry {
620 EncodingReader &reader, StringSectionReader &stringReader,
621 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef)
622 : key(key), kind(kind), reader(reader), stringReader(stringReader),
623 bufferOwnerRef(bufferOwnerRef) {}
624 ~ParsedResourceEntry()
override =
default;
626 StringRef getKey() const final {
return key; }
628 InFlightDiagnostic
emitError() const final {
return reader.emitError(); }
632 FailureOr<bool> parseAsBool() const final {
633 if (kind != AsmResourceEntryKind::Bool)
634 return emitError() <<
"expected a bool resource entry, but found a "
635 <<
toString(kind) <<
" entry instead";
638 if (
failed(reader.parseByte(value)))
642 FailureOr<std::string> parseAsString() const final {
643 if (kind != AsmResourceEntryKind::String)
644 return emitError() <<
"expected a string resource entry, but found a "
645 <<
toString(kind) <<
" entry instead";
648 if (
failed(stringReader.parseString(reader,
string)))
653 FailureOr<AsmResourceBlob>
654 parseAsBlob(BlobAllocatorFn allocator)
const final {
655 if (kind != AsmResourceEntryKind::Blob)
656 return emitError() <<
"expected a blob resource entry, but found a "
657 <<
toString(kind) <<
" entry instead";
659 ArrayRef<uint8_t> data;
661 if (
failed(reader.parseBlobAndAlignment(data, alignment)))
666 if (bufferOwnerRef) {
667 ArrayRef<char> charData(
reinterpret_cast<const char *
>(data.data()),
675 [bufferOwnerRef = bufferOwnerRef](
void *,
size_t,
size_t) {});
680 AsmResourceBlob blob = allocator(data.size(), alignment);
681 assert(llvm::isAddrAligned(llvm::Align(alignment), blob.
getData().data()) &&
683 "blob allocator did not return a properly aligned address");
691 EncodingReader &reader;
692 StringSectionReader &stringReader;
693 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef;
700 EncodingReader &offsetReader, EncodingReader &resourceReader,
701 StringSectionReader &stringReader, T *handler,
702 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef,
704 function_ref<LogicalResult(StringRef)> processKeyFn = {}) {
705 uint64_t numResources;
706 if (
failed(offsetReader.parseVarInt(numResources)))
709 for (uint64_t i = 0; i < numResources; ++i) {
712 uint64_t resourceOffset;
713 ArrayRef<uint8_t> data;
714 if (
failed(stringReader.parseString(offsetReader, key)) ||
715 failed(offsetReader.parseVarInt(resourceOffset)) ||
716 failed(offsetReader.parseByte(kind)) ||
717 failed(resourceReader.parseBytes(resourceOffset, data)))
721 if ((processKeyFn &&
failed(processKeyFn(key))))
726 if (allowEmpty && data.empty())
734 EncodingReader entryReader(data, fileLoc);
736 ParsedResourceEntry entry(key, kind, entryReader, stringReader,
738 if (
failed(handler->parseResource(entry)))
740 if (!entryReader.empty()) {
741 return entryReader.emitError(
742 "unexpected trailing bytes in resource entry '", key,
"'");
748LogicalResult ResourceSectionReader::initialize(
749 Location fileLoc,
const ParserConfig &config,
750 MutableArrayRef<std::unique_ptr<BytecodeDialect>> dialects,
751 StringSectionReader &stringReader, ArrayRef<uint8_t> sectionData,
752 ArrayRef<uint8_t> offsetSectionData, DialectReader &dialectReader,
753 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef) {
754 EncodingReader resourceReader(sectionData, fileLoc);
755 EncodingReader offsetReader(offsetSectionData, fileLoc);
758 uint64_t numExternalResourceGroups;
759 if (
failed(offsetReader.parseVarInt(numExternalResourceGroups)))
764 auto parseGroup = [&](
auto *handler,
bool allowEmpty =
false,
766 auto resolveKey = [&](StringRef key) -> StringRef {
767 auto it = dialectResourceHandleRenamingMap.find(key);
768 if (it == dialectResourceHandleRenamingMap.end())
774 stringReader, handler, bufferOwnerRef, resolveKey,
779 for (uint64_t i = 0; i < numExternalResourceGroups; ++i) {
781 if (
failed(stringReader.parseString(offsetReader, key)))
788 emitWarning(fileLoc) <<
"ignoring unknown external resources for '" << key
792 if (
failed(parseGroup(handler)))
798 while (!offsetReader.empty()) {
799 std::unique_ptr<BytecodeDialect> *dialect;
801 failed((*dialect)->load(dialectReader, ctx)))
803 Dialect *loadedDialect = (*dialect)->getLoadedDialect();
804 if (!loadedDialect) {
805 return resourceReader.emitError()
806 <<
"dialect '" << (*dialect)->name <<
"' is unknown";
808 const auto *handler = dyn_cast<OpAsmDialectInterface>(loadedDialect);
810 return resourceReader.emitError()
811 <<
"unexpected resources for dialect '" << (*dialect)->name <<
"'";
815 auto processResourceKeyFn = [&](StringRef key) -> LogicalResult {
816 FailureOr<AsmDialectResourceHandle> handle =
817 handler->declareResource(key);
819 return resourceReader.emitError()
820 <<
"unknown 'resource' key '" << key <<
"' for dialect '"
821 << (*dialect)->name <<
"'";
823 dialectResourceHandleRenamingMap[key] = handler->getResourceKey(*handle);
824 dialectResources.push_back(*handle);
830 if (
failed(parseGroup(handler,
true, processResourceKeyFn)))
862class AttrTypeReader {
864 template <
typename T>
869 BytecodeDialect *dialect =
nullptr;
872 bool hasCustomEncoding =
false;
875 size_t nextCallbackIndex = 0;
877 ArrayRef<uint8_t> data;
879 using AttrEntry = Entry<Attribute>;
880 using TypeEntry = Entry<Type>;
883 AttrTypeReader(
const StringSectionReader &stringReader,
884 const ResourceSectionReader &resourceReader,
885 const llvm::StringMap<BytecodeDialect *> &dialectsMap,
886 uint64_t &bytecodeVersion, Location fileLoc,
887 const ParserConfig &config)
888 : stringReader(stringReader), resourceReader(resourceReader),
889 dialectsMap(dialectsMap), fileLoc(fileLoc),
890 bytecodeVersion(bytecodeVersion), parserConfig(config) {}
894 initialize(MutableArrayRef<std::unique_ptr<BytecodeDialect>> dialects,
895 ArrayRef<uint8_t> sectionData,
896 ArrayRef<uint8_t> offsetSectionData);
898 LogicalResult readAttribute(uint64_t index, Attribute &
result,
899 uint64_t depth = 0) {
900 return readEntry(attributes, index,
result,
"attribute", depth);
903 LogicalResult readType(uint64_t index, Type &
result, uint64_t depth = 0) {
904 return readEntry(types, index,
result,
"type", depth);
909 Attribute resolveAttribute(
size_t index) {
912 Type resolveType(
size_t index) {
return resolveEntry(types, index,
"Type"); }
914 Attribute getAttributeOrSentinel(
size_t index) {
915 if (index >= attributes.size())
917 return attributes[index].entry;
919 Type getTypeOrSentinel(
size_t index) {
920 if (index >= types.size())
922 return types[index].entry;
928 if (
failed(reader.parseVarInt(attrIdx)))
930 result = resolveAttribute(attrIdx);
936 if (
failed(reader.parseVarInt(typeIdx)))
938 result = resolveType(typeIdx);
942 template <
typename T>
944 Attribute baseResult;
947 if ((
result = dyn_cast<T>(baseResult)))
949 return reader.emitError(
"expected attribute of type: ",
950 llvm::getTypeName<T>(),
", but got: ", baseResult);
954 enum class EntryKind { Attribute, Type };
955 using WorklistEntry = std::pair<uint64_t, EntryKind>;
958 void addDeferredParsing(uint64_t index, EntryKind kind) {
959 deferredWorklist.emplace_back(index, kind);
963 bool isResolving()
const {
return resolving; }
970 Type publishPartialType(uint64_t index, Type type) {
971 auto [it,
inserted] = partialTypes.try_emplace(index, type);
973 partialHistory.push_back(index);
974 ++progressGeneration;
983 Type getPartialType(uint64_t index)
const {
984 return partialTypes.lookup(index);
989 struct RollbackPoint {
990 size_t deferredWorklistSize;
991 size_t partialHistorySize;
992 uint64_t resolvedCount;
997 class AttrTypeWorklist {
999 bool empty()
const {
return entries.empty(); }
1001 void pushFront(WorklistEntry entry) {
1002 auto [it,
inserted] = positions.try_emplace(entry);
1004 it->second = entries.insert(entries.begin(), entry);
1006 entries.splice(entries.begin(), entries, it->second);
1009 void pushBack(WorklistEntry entry) {
1010 auto [it,
inserted] = positions.try_emplace(entry);
1012 it->second = entries.insert(entries.end(), entry);
1015 WorklistEntry popFront() {
1016 assert(!empty() &&
"cannot pop from an empty worklist");
1017 WorklistEntry front = entries.front();
1018 positions.erase(front);
1019 entries.pop_front();
1024 std::list<WorklistEntry> entries;
1025 DenseMap<WorklistEntry, std::list<WorklistEntry>::iterator> positions;
1030 bool hasLivePartialSince(
size_t start)
const {
1031 return llvm::any_of(
1032 ArrayRef(partialHistory).drop_front(start),
1033 [&](uint64_t idx) {
return partialTypes.contains(idx); });
1036 void eraseUncommittedPartialType(uint64_t index) {
1037 if (partialTypes.erase(index))
1038 --progressGeneration;
1041 RollbackPoint saveRollbackPoint()
const {
1042 return {deferredWorklist.size(), partialHistory.size(), resolvedCount};
1045 void restoreRollbackPoint(RollbackPoint point) {
1046 deferredWorklist.resize(point.deferredWorklistSize);
1047 while (partialHistory.size() > point.partialHistorySize) {
1048 uint64_t idx = partialHistory.pop_back_val();
1049 if (!types[idx].entry)
1050 eraseUncommittedPartialType(idx);
1055 template <
typename T>
1056 T
resolveEntry(SmallVectorImpl<Entry<T>> &entries, uint64_t index,
1057 StringRef entryType);
1061 template <
typename T>
1062 LogicalResult readEntry(SmallVectorImpl<Entry<T>> &entries, uint64_t index,
1063 T &
result, StringRef entryType, uint64_t depth);
1067 template <
typename T>
1068 LogicalResult parseCustomEntry(Entry<T> &entry, EncodingReader &reader,
1069 uint64_t index, uint64_t depth, T &
result);
1073 template <
typename T>
1074 LogicalResult parseAsmEntry(T &
result, EncodingReader &reader,
1075 StringRef entryType);
1079 const StringSectionReader &stringReader;
1083 const ResourceSectionReader &resourceReader;
1087 const llvm::StringMap<BytecodeDialect *> &dialectsMap;
1090 SmallVector<AttrEntry> attributes;
1091 SmallVector<TypeEntry> types;
1096 SmallVector<uint64_t, 4> partialHistory;
1101 llvm::SmallDenseMap<WorklistEntry, size_t, 8> activeEntries;
1106 uint64_t progressGeneration = 0;
1110 uint64_t resolvedCount = 0;
1116 uint64_t &bytecodeVersion;
1119 const ParserConfig &parserConfig;
1125 std::vector<WorklistEntry> deferredWorklist;
1128 bool resolving =
false;
1131class DialectReader :
public DialectBytecodeReader {
1133 DialectReader(AttrTypeReader &attrTypeReader,
1134 const StringSectionReader &stringReader,
1135 const ResourceSectionReader &resourceReader,
1136 const llvm::StringMap<BytecodeDialect *> &dialectsMap,
1137 EncodingReader &reader, uint64_t &bytecodeVersion,
1139 std::optional<uint64_t> cyclicTypeIndex = std::nullopt)
1140 : attrTypeReader(attrTypeReader), stringReader(stringReader),
1141 resourceReader(resourceReader), dialectsMap(dialectsMap),
1142 reader(reader), bytecodeVersion(bytecodeVersion), depth(depth),
1143 cyclicTypeIndex(cyclicTypeIndex) {}
1151 LogicalResult tryStartCyclicRead(Type type)
override;
1153 InFlightDiagnostic
emitError(
const Twine &msg)
const override {
1154 return reader.emitError(msg);
1157 InFlightDiagnostic
emitWarning(
const Twine &msg)
const override {
1158 return reader.emitWarning(msg);
1161 FailureOr<const DialectVersion *>
1162 getDialectVersion(StringRef dialectName)
const override {
1164 auto dialectEntry = dialectsMap.find(dialectName);
1165 if (dialectEntry == dialectsMap.end())
1170 if (
failed(dialectEntry->getValue()->load(*
this, getLoc().
getContext())) ||
1171 dialectEntry->getValue()->loadedVersion ==
nullptr)
1173 return dialectEntry->getValue()->loadedVersion.get();
1176 MLIRContext *
getContext()
const override {
return getLoc().getContext(); }
1178 uint64_t getBytecodeVersion()
const override {
return bytecodeVersion; }
1180 DialectReader withEncodingReader(EncodingReader &encReader)
const {
1181 return DialectReader(attrTypeReader, stringReader, resourceReader,
1182 dialectsMap, encReader, bytecodeVersion);
1185 Location getLoc()
const {
return reader.getLoc(); }
1193 static constexpr uint64_t maxAttrTypeDepth = 5;
1195 LogicalResult readAttribute(Attribute &
result)
override {
1197 if (
failed(reader.parseVarInt(index)))
1199 return readEntryAtIndex(index,
result);
1201 LogicalResult readOptionalAttribute(Attribute &
result)
override {
1203 bool hasAttr =
false;
1204 if (
failed(reader.parseVarIntWithFlag(index, hasAttr)))
1208 return readEntryAtIndex(index,
result);
1210 LogicalResult readType(Type &
result)
override {
1212 if (
failed(reader.parseVarInt(index)))
1214 return readEntryAtIndex(index,
result);
1218 AsmDialectResourceHandle handle;
1219 if (
failed(resourceReader.parseResourceHandle(reader, handle)))
1228 LogicalResult readVarInt(uint64_t &
result)
override {
1229 return reader.parseVarInt(
result);
1232 LogicalResult readSignedVarInt(int64_t &
result)
override {
1233 uint64_t unsignedResult;
1234 if (
failed(reader.parseSignedVarInt(unsignedResult)))
1236 result =
static_cast<int64_t
>(unsignedResult);
1240 FailureOr<APInt> readAPIntWithKnownWidth(
unsigned bitWidth)
override {
1242 if (bitWidth <= 8) {
1244 if (
failed(reader.parseByte(value)))
1246 return APInt(bitWidth, value);
1250 if (bitWidth <= 64) {
1252 if (
failed(reader.parseSignedVarInt(value)))
1254 return APInt(bitWidth, value);
1259 uint64_t numActiveWords;
1260 if (
failed(reader.parseVarInt(numActiveWords)))
1262 SmallVector<uint64_t, 4> words(numActiveWords);
1263 for (uint64_t i = 0; i < numActiveWords; ++i)
1264 if (
failed(reader.parseSignedVarInt(words[i])))
1266 return APInt(bitWidth, words);
1270 readAPFloatWithKnownSemantics(
const llvm::fltSemantics &semantics)
override {
1271 FailureOr<APInt> intVal =
1272 readAPIntWithKnownWidth(APFloat::getSizeInBits(semantics));
1275 return APFloat(semantics, *intVal);
1278 LogicalResult readString(StringRef &
result)
override {
1279 return stringReader.parseString(reader,
result);
1282 LogicalResult readBlob(ArrayRef<char> &
result)
override {
1284 ArrayRef<uint8_t> data;
1285 if (
failed(reader.parseVarInt(dataSize)) ||
1286 failed(reader.parseBytes(dataSize, data)))
1288 result = llvm::ArrayRef(
reinterpret_cast<const char *
>(data.data()),
1293 LogicalResult readBool(
bool &
result)
override {
1294 return reader.parseByte(
result);
1298 template <
typename T>
1299 LogicalResult readEntryAtIndex(uint64_t index, T &
result) {
1303 if (!attrTypeReader.isResolving()) {
1305 if constexpr (std::is_same_v<T, Type>)
1306 resolved = attrTypeReader.resolveType(index);
1308 resolved = attrTypeReader.resolveAttribute(index);
1315 if constexpr (std::is_same_v<T, Type>) {
1316 if (Type type = attrTypeReader.getTypeOrSentinel(index)) {
1320 if (Type partial = attrTypeReader.getPartialType(index)) {
1324 if (depth > maxAttrTypeDepth) {
1325 attrTypeReader.addDeferredParsing(index,
1326 AttrTypeReader::EntryKind::Type);
1329 return attrTypeReader.readType(index,
result, depth + 1);
1331 if (Attribute attr = attrTypeReader.getAttributeOrSentinel(index)) {
1335 if (depth > maxAttrTypeDepth) {
1336 attrTypeReader.addDeferredParsing(index,
1337 AttrTypeReader::EntryKind::Attribute);
1340 return attrTypeReader.readAttribute(index,
result, depth + 1);
1344 AttrTypeReader &attrTypeReader;
1345 const StringSectionReader &stringReader;
1346 const ResourceSectionReader &resourceReader;
1347 const llvm::StringMap<BytecodeDialect *> &dialectsMap;
1348 EncodingReader &reader;
1349 uint64_t &bytecodeVersion;
1354 std::optional<uint64_t> cyclicTypeIndex;
1358class PropertiesSectionReader {
1361 LogicalResult
initialize(Location fileLoc, ArrayRef<uint8_t> sectionData) {
1362 if (sectionData.empty())
1364 EncodingReader propReader(sectionData, fileLoc);
1366 if (
failed(propReader.parseVarInt(count)))
1369 if (
failed(propReader.parseBytes(propReader.size(), propertiesBuffers)))
1372 EncodingReader offsetsReader(propertiesBuffers, fileLoc);
1373 offsetTable.reserve(count);
1374 for (
auto idx : llvm::seq<int64_t>(0, count)) {
1376 offsetTable.push_back(propertiesBuffers.size() - offsetsReader.size());
1377 ArrayRef<uint8_t> rawProperties;
1379 if (
failed(offsetsReader.parseVarInt(dataSize)) ||
1380 failed(offsetsReader.parseBytes(dataSize, rawProperties)))
1383 if (!offsetsReader.empty())
1384 return offsetsReader.emitError()
1385 <<
"Broken properties section: didn't exhaust the offsets table";
1389 LogicalResult read(Location fileLoc, DialectReader &dialectReader,
1390 OperationName *opName, OperationState &opState)
const {
1391 uint64_t propertiesIdx;
1392 if (
failed(dialectReader.readVarInt(propertiesIdx)))
1394 if (propertiesIdx >= offsetTable.size())
1395 return dialectReader.emitError(
"Properties idx out-of-bound for ")
1397 size_t propertiesOffset = offsetTable[propertiesIdx];
1398 if (propertiesIdx >= propertiesBuffers.size())
1399 return dialectReader.emitError(
"Properties offset out-of-bound for ")
1403 ArrayRef<char> rawProperties;
1407 EncodingReader reader(propertiesBuffers.drop_front(propertiesOffset),
1411 dialectReader.withEncodingReader(reader).readBlob(rawProperties)))
1415 EncodingReader reader(
1416 StringRef(rawProperties.begin(), rawProperties.size()), fileLoc);
1417 DialectReader propReader = dialectReader.withEncodingReader(reader);
1419 auto *iface = opName->
getInterface<BytecodeOpInterface>();
1421 return iface->readProperties(propReader, opState);
1423 return propReader.emitError(
1424 "has properties but missing BytecodeOpInterface for ")
1432 ArrayRef<uint8_t> propertiesBuffers;
1435 SmallVector<int64_t> offsetTable;
1439LogicalResult AttrTypeReader::initialize(
1440 MutableArrayRef<std::unique_ptr<BytecodeDialect>> dialects,
1441 ArrayRef<uint8_t> sectionData, ArrayRef<uint8_t> offsetSectionData) {
1442 EncodingReader offsetReader(offsetSectionData, fileLoc);
1445 uint64_t numAttributes, numTypes;
1446 if (
failed(offsetReader.parseVarInt(numAttributes)) ||
1447 failed(offsetReader.parseVarInt(numTypes)))
1449 attributes.resize(numAttributes);
1450 types.resize(numTypes);
1454 uint64_t currentOffset = 0;
1455 auto parseEntries = [&](
auto &&range) {
1456 size_t currentIndex = 0, endIndex = range.size();
1459 auto parseEntryFn = [&](BytecodeDialect *dialect) -> LogicalResult {
1462 if (currentIndex == endIndex) {
1463 return offsetReader.emitError(
1464 "Attribute or Type dialect group entries exceed the declared "
1465 "number of entries (",
1468 auto &entry = range[currentIndex++];
1471 if (
failed(offsetReader.parseVarIntWithFlag(entrySize,
1472 entry.hasCustomEncoding)))
1476 if (currentOffset + entrySize > sectionData.size()) {
1477 return offsetReader.emitError(
1478 "Attribute or Type entry offset points past the end of section");
1481 entry.data = sectionData.slice(currentOffset, entrySize);
1482 entry.dialect = dialect;
1483 currentOffset += entrySize;
1486 while (currentIndex != endIndex)
1493 if (
failed(parseEntries(attributes)) ||
failed(parseEntries(types)))
1497 if (!offsetReader.empty()) {
1498 return offsetReader.emitError(
1499 "unexpected trailing data in the Attribute/Type offset section");
1505template <
typename T>
1506T AttrTypeReader::resolveEntry(SmallVectorImpl<Entry<T>> &entries,
1507 uint64_t index, StringRef entryType) {
1508 assert(!resolving &&
"resolveEntry is not re-entrant");
1510 llvm::scope_exit restoreResolving([&]() {
1515 partialTypes.clear();
1516 partialHistory.clear();
1517 deferredWorklist.clear();
1520 if (index >= entries.size()) {
1521 emitError(fileLoc) <<
"invalid " << entryType <<
" index: " << index;
1527 assert(deferredWorklist.empty());
1529 if (succeeded(readEntry(entries, index,
result, entryType, 0))) {
1530 assert(deferredWorklist.empty());
1531 assert(partialTypes.empty());
1534 if (deferredWorklist.empty()) {
1541 static_assert((std::is_same_v<T, Type> || std::is_same_v<T, Attribute>) &&
1542 "Only support resolving Attributes and Types");
1543 constexpr EntryKind rootKind =
1544 std::is_same_v<T, Type> ? EntryKind::Type : EntryKind::Attribute;
1546 AttrTypeWorklist worklist;
1547 worklist.pushBack({index, rootKind});
1548 for (WorklistEntry dep : llvm::reverse(deferredWorklist))
1549 worklist.pushFront(dep);
1550 deferredWorklist.clear();
1553 uint64_t lastGeneration = progressGeneration;
1555 while (!worklist.empty()) {
1556 WorklistEntry current = worklist.popFront();
1557 auto [currentIndex, entryKind] = current;
1560 deferredWorklist.clear();
1562 LogicalResult parseStatus = failure();
1563 if (entryKind == EntryKind::Type) {
1565 parseStatus = readType(currentIndex, typeResult, 0);
1567 assert(entryKind == EntryKind::Attribute &&
"Unexpected entry kind");
1568 Attribute attrResult;
1569 parseStatus = readAttribute(currentIndex, attrResult, 0);
1572 if (succeeded(parseStatus)) {
1573 failedInEpoch.clear();
1574 lastGeneration = progressGeneration;
1578 if (deferredWorklist.empty()) {
1583 if (progressGeneration != lastGeneration) {
1584 failedInEpoch.clear();
1585 lastGeneration = progressGeneration;
1587 if (!failedInEpoch.insert(current).second) {
1588 StringRef kindStr = entryKind == EntryKind::Type ?
"type" :
"attribute";
1589 emitError(fileLoc) <<
"cyclic dependency detected in " << kindStr
1590 <<
" entry " << currentIndex;
1591 deferredWorklist.clear();
1597 worklist.pushFront(current);
1598 for (WorklistEntry dep : llvm::reverse(deferredWorklist))
1599 worklist.pushFront(dep);
1600 deferredWorklist.clear();
1603 assert(partialTypes.empty());
1604 return entries[index].entry;
1607LogicalResult DialectReader::tryStartCyclicRead(Type type) {
1608 if (!cyclicTypeIndex)
1610 "tryStartCyclicRead called while not reading a custom type entry");
1612 return emitError(
"cannot start cyclic read with null type");
1614 return emitError(
"cannot start cyclic read on immutable type: ") << type;
1615 Type published = attrTypeReader.publishPartialType(*cyclicTypeIndex, type);
1616 if (published != type) {
1618 << *cyclicTypeIndex <<
" already published a different '"
1624template <
typename T>
1625LogicalResult AttrTypeReader::readEntry(SmallVectorImpl<Entry<T>> &entries,
1626 uint64_t index, T &
result,
1627 StringRef entryType, uint64_t depth) {
1628 if (index >= entries.size()) {
1629 deferredWorklist.clear();
1630 return emitError(fileLoc) <<
"invalid " << entryType <<
" index: " << index;
1634 Entry<T> &entry = entries[index];
1640 constexpr EntryKind kind =
1641 std::is_same_v<T, Type> ? EntryKind::Type : EntryKind::Attribute;
1642 WorklistEntry activeKey(index, kind);
1643 auto [activeIt, firstActivation] =
1644 activeEntries.try_emplace(activeKey, partialHistory.size());
1645 if (!firstActivation) {
1650 if (hasLivePartialSince(activeIt->second)) {
1651 addDeferredParsing(index, kind);
1654 deferredWorklist.clear();
1655 StringRef kindStr = std::is_same_v<T, Type> ?
"type" :
"attribute";
1657 <<
"cyclic dependency detected in " << kindStr <<
" entry " << index;
1659 llvm::scope_exit eraseActive([&]() { activeEntries.erase(activeKey); });
1662 EncodingReader reader(entry.data, fileLoc);
1664 LogicalResult parseResult =
1665 entry.hasCustomEncoding
1666 ? parseCustomEntry(entry, reader, index, depth, parsedEntry)
1667 : parseAsmEntry(parsedEntry, reader, entryType);
1668 if (
failed(parseResult)) {
1669 if constexpr (std::is_same_v<T, Type>) {
1670 if (partialTypes.contains(index)) {
1673 if (!deferredWorklist.empty())
1674 addDeferredParsing(index, EntryKind::Type);
1676 eraseUncommittedPartialType(index);
1682 if (!reader.empty()) {
1683 deferredWorklist.clear();
1684 if constexpr (std::is_same_v<T, Type>)
1685 eraseUncommittedPartialType(index);
1686 return reader.emitError(
"unexpected trailing bytes after ", entryType,
1690 if constexpr (std::is_same_v<T, Type>)
1691 partialTypes.erase(index);
1692 entry.entry =
result = parsedEntry;
1693 ++progressGeneration;
1698template <
typename T>
1700AttrTypeReader::parseCustomEntry(Entry<T> &entry, EncodingReader &reader,
1701 uint64_t index, uint64_t depth, T &
result) {
1702 std::optional<uint64_t> cyclicTypeIndex;
1703 if constexpr (std::is_same_v<T, Type>)
1704 cyclicTypeIndex = index;
1705 DialectReader dialectReader(*
this, stringReader, resourceReader, dialectsMap,
1706 reader, bytecodeVersion, depth, cyclicTypeIndex);
1710 auto verifyPublishedPartial = [&](T parsed) -> LogicalResult {
1711 if constexpr (std::is_same_v<T, Type>) {
1714 if (Type partial = getPartialType(index)) {
1715 if (parsed && parsed != partial) {
1716 deferredWorklist.clear();
1717 return reader.emitError(
"custom type reader for dialect '",
1718 entry.dialect->name,
1719 "' returned a different type than the one "
1720 "published with tryStartCyclicRead");
1728 ArrayRef<std::unique_ptr<AttrTypeBytecodeReader<T>>> callbacks = [&]() {
1729 if constexpr (std::is_same_v<T, Type>)
1734 for (
size_t e = callbacks.size(); entry.nextCallbackIndex < e;
1735 ++entry.nextCallbackIndex) {
1736 const std::unique_ptr<AttrTypeBytecodeReader<T>> &callback =
1737 callbacks[entry.nextCallbackIndex];
1738 RollbackPoint rollback = saveRollbackPoint();
1739 if (
failed(callback->read(dialectReader, entry.dialect->name,
result)))
1742 return verifyPublishedPartial(
result);
1744 if (partialHistory.size() > rollback.partialHistorySize &&
1745 resolvedCount != rollback.resolvedCount) {
1746 restoreRollbackPoint(rollback);
1747 deferredWorklist.clear();
1748 return reader.emitError(
1749 "custom type reader callback published a partial type that may "
1750 "have escaped into a resolved nested entry before falling through");
1755 restoreRollbackPoint(rollback);
1756 reader = EncodingReader(entry.data, reader.getLoc());
1760 if (!entry.dialect->interface) {
1761 return reader.emitError(
"dialect '", entry.dialect->name,
1762 "' does not implement the bytecode interface");
1765 if constexpr (std::is_same_v<T, Type>)
1766 result = entry.dialect->interface->readType(dialectReader);
1768 result = entry.dialect->interface->readAttribute(dialectReader);
1776template <
typename T>
1777LogicalResult AttrTypeReader::parseAsmEntry(T &
result, EncodingReader &reader,
1778 StringRef entryType) {
1780 if (
failed(reader.parseNullTerminatedString(asmStr)))
1785 MLIRContext *context = fileLoc->
getContext();
1786 if constexpr (std::is_same_v<T, Type>)
1796 if (numRead != asmStr.size()) {
1797 return reader.emitError(
"trailing characters found after ", entryType,
1798 " assembly format: ", asmStr.drop_front(numRead));
1809 struct RegionReadState;
1810 using LazyLoadableOpsInfo =
1811 std::list<std::pair<Operation *, RegionReadState>>;
1812 using LazyLoadableOpsMap =
1817 llvm::MemoryBufferRef buffer,
1818 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef)
1819 : config(config), fileLoc(fileLoc), lazyLoading(lazyLoading),
1820 attrTypeReader(stringReader, resourceReader, dialectsMap, version,
1824 forwardRefOpState(UnknownLoc::
get(config.getContext()),
1825 "builtin.unrealized_conversion_cast",
ValueRange(),
1826 NoneType::
get(config.getContext())),
1827 buffer(buffer), bufferOwnerRef(bufferOwnerRef) {}
1830 LogicalResult read(
Block *block,
1843 this->lazyOpsCallback = lazyOpsCallback;
1844 llvm::scope_exit resetlazyOpsCallback(
1845 [&] { this->lazyOpsCallback =
nullptr; });
1846 auto it = lazyLoadableOpsMap.find(op);
1847 assert(it != lazyLoadableOpsMap.end() &&
1848 "materialize called on non-materializable op");
1854 while (!lazyLoadableOpsMap.empty()) {
1855 if (failed(
materialize(lazyLoadableOpsMap.begin())))
1866 while (!lazyLoadableOps.empty()) {
1867 Operation *op = lazyLoadableOps.begin()->first;
1868 if (shouldMaterialize(op)) {
1869 if (failed(
materialize(lazyLoadableOpsMap.find(op))))
1875 lazyLoadableOps.pop_front();
1876 lazyLoadableOpsMap.erase(op);
1882 LogicalResult
materialize(LazyLoadableOpsMap::iterator it) {
1883 assert(it != lazyLoadableOpsMap.end() &&
1884 "materialize called on non-materializable op");
1885 valueScopes.emplace_back();
1886 std::vector<RegionReadState> regionStack;
1887 regionStack.push_back(std::move(it->getSecond()->second));
1888 lazyLoadableOps.erase(it->getSecond());
1889 lazyLoadableOpsMap.erase(it);
1891 while (!regionStack.empty())
1892 if (failed(parseRegions(regionStack, regionStack.back())))
1897 LogicalResult checkSectionAlignment(
1908 const bool isGloballyAligned =
1909 ((uintptr_t)buffer.getBufferStart() & (alignment - 1)) == 0;
1911 if (!isGloballyAligned)
1912 return emitError(
"expected section alignment ")
1913 << alignment <<
" but bytecode buffer 0x"
1914 << Twine::utohexstr((uint64_t)buffer.getBufferStart())
1915 <<
" is not aligned";
1924 LogicalResult parseVersion(EncodingReader &reader);
1929 LogicalResult parseDialectSection(ArrayRef<uint8_t> sectionData);
1934 FailureOr<OperationName> parseOpName(EncodingReader &reader,
1935 std::optional<bool> &wasRegistered);
1941 template <
typename T>
1943 return attrTypeReader.parseAttribute(reader,
result);
1946 return attrTypeReader.parseType(reader,
result);
1953 parseResourceSection(EncodingReader &reader,
1954 std::optional<ArrayRef<uint8_t>> resourceData,
1955 std::optional<ArrayRef<uint8_t>> resourceOffsetData);
1962 struct RegionReadState {
1963 RegionReadState(Operation *op, EncodingReader *reader,
1964 bool isIsolatedFromAbove)
1965 : RegionReadState(op->getRegions(), reader, isIsolatedFromAbove) {}
1966 RegionReadState(MutableArrayRef<Region> regions, EncodingReader *reader,
1967 bool isIsolatedFromAbove)
1968 : curRegion(regions.begin()), endRegion(regions.end()), reader(reader),
1969 isIsolatedFromAbove(isIsolatedFromAbove) {}
1972 MutableArrayRef<Region>::iterator curRegion, endRegion;
1977 EncodingReader *reader;
1978 std::unique_ptr<EncodingReader> owningReader;
1981 unsigned numValues = 0;
1984 SmallVector<Block *> curBlocks;
1989 uint64_t numOpsRemaining = 0;
1992 bool isIsolatedFromAbove =
false;
1995 LogicalResult parseIRSection(ArrayRef<uint8_t> sectionData,
Block *block);
1996 LogicalResult parseRegions(std::vector<RegionReadState> ®ionStack,
1997 RegionReadState &readState);
1998 FailureOr<Operation *> parseOpWithoutRegions(EncodingReader &reader,
1999 RegionReadState &readState,
2000 bool &isIsolatedFromAbove);
2002 LogicalResult parseRegion(RegionReadState &readState);
2003 LogicalResult parseBlockHeader(EncodingReader &reader,
2004 RegionReadState &readState);
2005 LogicalResult parseBlockArguments(EncodingReader &reader,
Block *block);
2012 Value parseOperand(EncodingReader &reader);
2015 LogicalResult defineValues(EncodingReader &reader,
ValueRange values);
2018 Value createForwardRef();
2026 struct UseListOrderStorage {
2027 UseListOrderStorage(
bool isIndexPairEncoding,
2028 SmallVector<unsigned, 4> &&
indices)
2030 isIndexPairEncoding(isIndexPairEncoding) {};
2033 SmallVector<unsigned, 4>
indices;
2037 bool isIndexPairEncoding;
2045 using UseListMapT = DenseMap<unsigned, UseListOrderStorage>;
2046 FailureOr<UseListMapT> parseUseListOrderForRange(EncodingReader &reader,
2047 uint64_t rangeSize);
2050 LogicalResult sortUseListOrder(Value value);
2054 LogicalResult processUseLists(Operation *topLevelOp);
2064 void push(RegionReadState &readState) {
2065 nextValueIDs.push_back(values.size());
2066 values.resize(values.size() + readState.numValues);
2071 void pop(RegionReadState &readState) {
2072 values.resize(values.size() - readState.numValues);
2073 nextValueIDs.pop_back();
2077 std::vector<Value> values;
2081 SmallVector<unsigned, 4> nextValueIDs;
2085 const ParserConfig &config;
2096 LazyLoadableOpsInfo lazyLoadableOps;
2097 LazyLoadableOpsMap lazyLoadableOpsMap;
2098 llvm::function_ref<bool(Operation *)> lazyOpsCallback;
2101 AttrTypeReader attrTypeReader;
2104 uint64_t version = 0;
2110 SmallVector<std::unique_ptr<BytecodeDialect>> dialects;
2111 llvm::StringMap<BytecodeDialect *> dialectsMap;
2112 SmallVector<BytecodeOperationName> opNames;
2115 ResourceSectionReader resourceReader;
2119 DenseMap<void *, UseListOrderStorage> valueToUseListMap;
2122 StringSectionReader stringReader;
2125 PropertiesSectionReader propertiesReader;
2128 std::vector<ValueScope> valueScopes;
2135 Block forwardRefOps;
2139 Block openForwardRefOps;
2142 OperationState forwardRefOpState;
2145 llvm::MemoryBufferRef buffer;
2149 const std::shared_ptr<llvm::SourceMgr> bufferOwnerRef;
2154 EncodingReader reader(buffer.getBuffer(), fileLoc);
2155 this->lazyOpsCallback = lazyOpsCallback;
2156 llvm::scope_exit resetlazyOpsCallback(
2157 [&] { this->lazyOpsCallback =
nullptr; });
2160 if (failed(reader.skipBytes(StringRef(
"ML\xefR").size())))
2163 if (failed(parseVersion(reader)) ||
2164 failed(reader.parseNullTerminatedString(producer)))
2170 diag.attachNote() <<
"in bytecode version " << version
2171 <<
" produced by: " << producer;
2175 const auto checkSectionAlignment = [&](
unsigned alignment) {
2176 return this->checkSectionAlignment(
2177 alignment, [&](
const auto &msg) {
return reader.emitError(msg); });
2181 std::optional<ArrayRef<uint8_t>>
2183 while (!reader.empty()) {
2188 reader.parseSection(sectionID, checkSectionAlignment, sectionData)))
2192 if (sectionDatas[sectionID]) {
2193 return reader.emitError(
"duplicate top-level section: ",
2196 sectionDatas[sectionID] = sectionData;
2202 return reader.emitError(
"missing data for top-level section: ",
2208 if (failed(stringReader.initialize(
2214 failed(propertiesReader.initialize(
2223 if (failed(parseResourceSection(
2229 if (failed(attrTypeReader.initialize(
2238LogicalResult BytecodeReader::Impl::parseVersion(EncodingReader &reader) {
2239 if (failed(reader.parseVarInt(version)))
2245 if (version < minSupportedVersion) {
2246 return reader.emitError(
"bytecode version ", version,
2247 " is older than the current version of ",
2248 currentVersion,
", and upgrade is not supported");
2250 if (version > currentVersion) {
2251 return reader.emitError(
"bytecode version ", version,
2252 " is newer than the current version ",
2257 lazyLoading =
false;
2265LogicalResult BytecodeDialect::load(
const DialectReader &reader,
2271 return reader.emitError(
"dialect '")
2273 <<
"' is unknown. If this is intended, please call "
2274 "allowUnregisteredDialects() on the MLIRContext, or use "
2275 "-allow-unregistered-dialect with the MLIR tool used.";
2277 dialect = loadedDialect;
2282 interface = dyn_cast<BytecodeDialectInterface>(loadedDialect);
2283 if (!versionBuffer.empty()) {
2285 return reader.emitError(
"dialect '")
2287 <<
"' does not implement the bytecode interface, "
2288 "but found a version entry";
2289 EncodingReader encReader(versionBuffer, reader.getLoc());
2290 DialectReader versionReader = reader.withEncodingReader(encReader);
2291 loadedVersion = interface->readVersion(versionReader);
2299BytecodeReader::Impl::parseDialectSection(ArrayRef<uint8_t> sectionData) {
2300 EncodingReader sectionReader(sectionData, fileLoc);
2303 uint64_t numDialects;
2304 if (
failed(sectionReader.parseVarInt(numDialects)))
2306 dialects.resize(numDialects);
2308 const auto checkSectionAlignment = [&](
unsigned alignment) {
2309 return this->checkSectionAlignment(alignment, [&](
const auto &msg) {
2310 return sectionReader.emitError(msg);
2315 for (uint64_t i = 0; i < numDialects; ++i) {
2316 dialects[i] = std::make_unique<BytecodeDialect>();
2320 if (
failed(stringReader.parseString(sectionReader, dialects[i]->name)))
2326 uint64_t dialectNameIdx;
2327 bool versionAvailable;
2328 if (
failed(sectionReader.parseVarIntWithFlag(dialectNameIdx,
2331 if (
failed(stringReader.parseStringAtIndex(sectionReader, dialectNameIdx,
2332 dialects[i]->name)))
2334 if (versionAvailable) {
2336 if (
failed(sectionReader.parseSection(sectionID, checkSectionAlignment,
2337 dialects[i]->versionBuffer)))
2340 emitError(fileLoc,
"expected dialect version section");
2344 dialectsMap[dialects[i]->name] = dialects[i].get();
2348 auto parseOpName = [&](BytecodeDialect *dialect) {
2350 std::optional<bool> wasRegistered;
2354 if (
failed(stringReader.parseString(sectionReader, opName)))
2357 bool wasRegisteredFlag;
2358 if (
failed(stringReader.parseStringWithFlag(sectionReader, opName,
2359 wasRegisteredFlag)))
2361 wasRegistered = wasRegisteredFlag;
2363 opNames.emplace_back(dialect, opName, wasRegistered);
2370 if (
failed(sectionReader.parseVarInt(numOps)))
2372 opNames.reserve(numOps);
2374 while (!sectionReader.empty())
2380FailureOr<OperationName>
2381BytecodeReader::Impl::parseOpName(EncodingReader &reader,
2382 std::optional<bool> &wasRegistered) {
2383 BytecodeOperationName *opName =
nullptr;
2386 wasRegistered = opName->wasRegistered;
2389 if (!opName->opName) {
2394 if (opName->name.empty()) {
2395 opName->opName.emplace(opName->dialect->name,
getContext());
2398 DialectReader dialectReader(attrTypeReader, stringReader, resourceReader,
2399 dialectsMap, reader, version);
2402 opName->opName.emplace((opName->dialect->name +
"." + opName->name).str(),
2406 return *opName->opName;
2413LogicalResult BytecodeReader::Impl::parseResourceSection(
2414 EncodingReader &reader, std::optional<ArrayRef<uint8_t>> resourceData,
2415 std::optional<ArrayRef<uint8_t>> resourceOffsetData) {
2417 if (resourceData.has_value() != resourceOffsetData.has_value()) {
2418 if (resourceOffsetData)
2419 return emitError(fileLoc,
"unexpected resource offset section when "
2420 "resource section is not present");
2423 "expected resource offset section when resource section is present");
2431 DialectReader dialectReader(attrTypeReader, stringReader, resourceReader,
2432 dialectsMap, reader, version);
2433 return resourceReader.initialize(fileLoc, config, dialects, stringReader,
2434 *resourceData, *resourceOffsetData,
2435 dialectReader, bufferOwnerRef);
2442FailureOr<BytecodeReader::Impl::UseListMapT>
2443BytecodeReader::Impl::parseUseListOrderForRange(EncodingReader &reader,
2444 uint64_t numResults) {
2445 BytecodeReader::Impl::UseListMapT map;
2446 uint64_t numValuesToRead = 1;
2447 if (numResults > 1 &&
failed(reader.parseVarInt(numValuesToRead)))
2450 for (
size_t valueIdx = 0; valueIdx < numValuesToRead; valueIdx++) {
2451 uint64_t resultIdx = 0;
2452 if (numResults > 1 &&
failed(reader.parseVarInt(resultIdx)))
2456 bool indexPairEncoding;
2457 if (
failed(reader.parseVarIntWithFlag(numValues, indexPairEncoding)))
2460 SmallVector<unsigned, 4> useListOrders;
2461 for (
size_t idx = 0; idx < numValues; idx++) {
2463 if (
failed(reader.parseVarInt(index)))
2465 useListOrders.push_back(index);
2469 map.try_emplace(resultIdx, UseListOrderStorage(indexPairEncoding,
2470 std::move(useListOrders)));
2481LogicalResult BytecodeReader::Impl::sortUseListOrder(Value value) {
2486 bool hasIncomingOrder =
2491 bool alreadySorted =
true;
2495 llvm::SmallVector<std::pair<unsigned, uint64_t>> currentOrder = {{0, prevID}};
2496 for (
auto item : llvm::drop_begin(llvm::enumerate(value.
getUses()))) {
2498 item.value(), operationIDs.at(item.value().getOwner()));
2499 alreadySorted &= prevID > currentID;
2500 currentOrder.push_back({item.index(), currentID});
2506 if (alreadySorted && !hasIncomingOrder)
2513 currentOrder.begin(), currentOrder.end(),
2514 [](
auto elem1,
auto elem2) { return elem1.second > elem2.second; });
2516 if (!hasIncomingOrder) {
2520 SmallVector<unsigned> shuffle(llvm::make_first_range(currentOrder));
2526 UseListOrderStorage customOrder =
2528 SmallVector<unsigned, 4> shuffle = std::move(customOrder.indices);
2535 if (customOrder.isIndexPairEncoding) {
2537 if (shuffle.size() & 1)
2540 SmallVector<unsigned, 4> newShuffle(numUses);
2542 std::iota(newShuffle.begin(), newShuffle.end(), idx);
2543 for (idx = 0; idx < shuffle.size(); idx += 2)
2544 newShuffle[shuffle[idx]] = shuffle[idx + 1];
2546 shuffle = std::move(newShuffle);
2553 uint64_t accumulator = 0;
2554 for (
const auto &elem : shuffle) {
2555 if (!set.insert(elem).second)
2557 accumulator += elem;
2559 if (numUses != shuffle.size() ||
2560 accumulator != (((numUses - 1) * numUses) >> 1))
2579 SmallVector<unsigned, 4> finalShuffle(numUses);
2580 if (customOrder.isIndexPairEncoding) {
2581 for (
size_t writerMemIdx = 0; writerMemIdx < numUses; ++writerMemIdx)
2582 finalShuffle[currentOrder[shuffle[writerMemIdx]].first] = writerMemIdx;
2584 for (
size_t sortedPos = 0; sortedPos < numUses; ++sortedPos)
2585 finalShuffle[currentOrder[sortedPos].first] = shuffle[sortedPos];
2587 shuffle = std::move(finalShuffle);
2593LogicalResult BytecodeReader::Impl::processUseLists(Operation *topLevelOp) {
2597 unsigned operationID = 0;
2599 [&](Operation *op) { operationIDs.try_emplace(op, operationID++); });
2601 auto blockWalk = topLevelOp->
walk([
this](
Block *block) {
2603 if (
failed(sortUseListOrder(arg)))
2608 auto resultWalk = topLevelOp->
walk([
this](Operation *op) {
2615 return failure(blockWalk.wasInterrupted() || resultWalk.wasInterrupted());
2623BytecodeReader::Impl::parseIRSection(ArrayRef<uint8_t> sectionData,
2625 EncodingReader reader(sectionData, fileLoc);
2628 std::vector<RegionReadState> regionStack;
2631 OwningOpRef<ModuleOp> moduleOp = ModuleOp::create(fileLoc);
2632 regionStack.emplace_back(*moduleOp, &reader,
true);
2633 regionStack.back().curBlocks.push_back(moduleOp->getBody());
2634 regionStack.back().curBlock = regionStack.back().curRegion->begin();
2635 if (
failed(parseBlockHeader(reader, regionStack.back())))
2637 valueScopes.emplace_back();
2638 valueScopes.back().push(regionStack.back());
2641 while (!regionStack.empty())
2642 if (
failed(parseRegions(regionStack, regionStack.back())))
2644 if (!forwardRefOps.empty()) {
2645 return reader.emitError(
2646 "not all forward unresolved forward operand references");
2650 if (
failed(processUseLists(*moduleOp)))
2651 return reader.emitError(
2652 "parsed use-list orders were invalid and could not be applied");
2655 for (
const std::unique_ptr<BytecodeDialect> &byteCodeDialect : dialects) {
2658 if (!byteCodeDialect->loadedVersion)
2660 if (byteCodeDialect->interface &&
2661 failed(byteCodeDialect->interface->upgradeFromVersion(
2662 *moduleOp, *byteCodeDialect->loadedVersion)))
2671 auto &parsedOps = moduleOp->getBody()->getOperations();
2673 destOps.splice(destOps.end(), parsedOps, parsedOps.begin(), parsedOps.end());
2678BytecodeReader::Impl::parseRegions(std::vector<RegionReadState> ®ionStack,
2679 RegionReadState &readState) {
2680 const auto checkSectionAlignment = [&](
unsigned alignment) {
2681 return this->checkSectionAlignment(
2682 alignment, [&](
const auto &msg) {
return emitError(fileLoc, msg); });
2688 for (; readState.curRegion != readState.endRegion; ++readState.curRegion) {
2694 if (
failed(parseRegion(readState)))
2698 if (readState.curRegion->empty())
2703 EncodingReader &reader = *readState.reader;
2705 while (readState.numOpsRemaining--) {
2708 bool isIsolatedFromAbove =
false;
2709 FailureOr<Operation *> op =
2710 parseOpWithoutRegions(reader, readState, isIsolatedFromAbove);
2718 if ((*op)->getNumRegions()) {
2719 RegionReadState childState(*op, &reader, isIsolatedFromAbove);
2724 ArrayRef<uint8_t> sectionData;
2725 if (
failed(reader.parseSection(sectionID, checkSectionAlignment,
2729 return emitError(fileLoc,
"expected IR section for region");
2730 childState.owningReader =
2731 std::make_unique<EncodingReader>(sectionData, fileLoc);
2732 childState.reader = childState.owningReader.get();
2736 if (lazyLoading && (!lazyOpsCallback || !lazyOpsCallback(*op))) {
2737 lazyLoadableOps.emplace_back(*op, std::move(childState));
2738 lazyLoadableOpsMap.try_emplace(*op,
2739 std::prev(lazyLoadableOps.end()));
2743 regionStack.push_back(std::move(childState));
2746 if (isIsolatedFromAbove)
2747 valueScopes.emplace_back();
2753 if (++readState.curBlock == readState.curRegion->end())
2755 if (
failed(parseBlockHeader(reader, readState)))
2760 readState.curBlock = {};
2761 valueScopes.back().pop(readState);
2766 if (readState.isIsolatedFromAbove) {
2767 assert(!valueScopes.empty() &&
"Expect a valueScope after reading region");
2768 valueScopes.pop_back();
2770 assert(!regionStack.empty() &&
"Expect a regionStack after reading region");
2771 regionStack.pop_back();
2775FailureOr<Operation *>
2776BytecodeReader::Impl::parseOpWithoutRegions(EncodingReader &reader,
2777 RegionReadState &readState,
2778 bool &isIsolatedFromAbove) {
2780 std::optional<bool> wasRegistered;
2781 FailureOr<OperationName> opName = parseOpName(reader, wasRegistered);
2788 if (
failed(reader.parseByte(opMask)))
2798 OperationState opState(opLoc, *opName);
2802 DictionaryAttr dictAttr;
2813 "Unexpected missing `wasRegistered` opname flag at "
2814 "bytecode version ")
2815 << version <<
" with properties.";
2819 if (wasRegistered) {
2820 DialectReader dialectReader(attrTypeReader, stringReader, resourceReader,
2821 dialectsMap, reader, version);
2823 propertiesReader.read(fileLoc, dialectReader, &*opName, opState)))
2835 uint64_t numResults;
2836 if (
failed(reader.parseVarInt(numResults)))
2838 opState.
types.resize(numResults);
2839 for (
int i = 0, e = numResults; i < e; ++i)
2846 uint64_t numOperands;
2847 if (
failed(reader.parseVarInt(numOperands)))
2849 opState.
operands.resize(numOperands);
2850 for (
int i = 0, e = numOperands; i < e; ++i)
2851 if (!(opState.
operands[i] = parseOperand(reader)))
2858 if (
failed(reader.parseVarInt(numSuccs)))
2861 for (
int i = 0, e = numSuccs; i < e; ++i) {
2870 std::optional<UseListMapT> resultIdxToUseListMap = std::nullopt;
2873 size_t numResults = opState.
types.size();
2874 auto parseResult = parseUseListOrderForRange(reader, numResults);
2877 resultIdxToUseListMap = std::move(*parseResult);
2882 uint64_t numRegions;
2883 if (
failed(reader.parseVarIntWithFlag(numRegions, isIsolatedFromAbove)))
2886 opState.
regions.reserve(numRegions);
2887 for (
int i = 0, e = numRegions; i < e; ++i)
2888 opState.
regions.push_back(std::make_unique<Region>());
2893 readState.curBlock->push_back(op);
2904 if (resultIdxToUseListMap.has_value()) {
2906 if (resultIdxToUseListMap->contains(idx)) {
2908 resultIdxToUseListMap->at(idx));
2915LogicalResult BytecodeReader::Impl::parseRegion(RegionReadState &readState) {
2916 EncodingReader &reader = *readState.reader;
2920 if (
failed(reader.parseVarInt(numBlocks)))
2929 if (
failed(reader.parseVarInt(numValues)))
2931 readState.numValues = numValues;
2935 readState.curBlocks.clear();
2936 readState.curBlocks.reserve(numBlocks);
2937 for (uint64_t i = 0; i < numBlocks; ++i) {
2938 readState.curBlocks.push_back(
new Block());
2939 readState.curRegion->push_back(readState.curBlocks.back());
2943 valueScopes.back().push(readState);
2946 readState.curBlock = readState.curRegion->begin();
2947 return parseBlockHeader(reader, readState);
2951BytecodeReader::Impl::parseBlockHeader(EncodingReader &reader,
2952 RegionReadState &readState) {
2954 if (
failed(reader.parseVarIntWithFlag(readState.numOpsRemaining, hasArgs)))
2958 if (hasArgs &&
failed(parseBlockArguments(reader, &*readState.curBlock)))
2965 uint8_t hasUseListOrders = 0;
2966 if (hasArgs &&
failed(reader.parseByte(hasUseListOrders)))
2969 if (!hasUseListOrders)
2972 Block &blk = *readState.curBlock;
2973 auto argIdxToUseListMap =
2975 if (
failed(argIdxToUseListMap) || argIdxToUseListMap->empty())
2979 if (argIdxToUseListMap->contains(idx))
2981 argIdxToUseListMap->at(idx));
2987LogicalResult BytecodeReader::Impl::parseBlockArguments(EncodingReader &reader,
2991 if (
failed(reader.parseVarInt(numArgs)))
2994 SmallVector<Type> argTypes;
2995 SmallVector<Location> argLocs;
2996 argTypes.reserve(numArgs);
2997 argLocs.reserve(numArgs);
2999 Location unknownLoc = UnknownLoc::get(config.
getContext());
3002 LocationAttr argLoc = unknownLoc;
3007 if (
failed(reader.parseVarIntWithFlag(typeIdx, hasLoc)) ||
3008 !(argType = attrTypeReader.resolveType(typeIdx)))
3018 argTypes.push_back(argType);
3019 argLocs.push_back(argLoc);
3029Value BytecodeReader::Impl::parseOperand(EncodingReader &reader) {
3030 std::vector<Value> &values = valueScopes.back().values;
3031 Value *value =
nullptr;
3037 *value = createForwardRef();
3041LogicalResult BytecodeReader::Impl::defineValues(EncodingReader &reader,
3043 ValueScope &valueScope = valueScopes.back();
3044 std::vector<Value> &values = valueScope.values;
3046 unsigned &valueID = valueScope.nextValueIDs.back();
3047 unsigned valueIDEnd = valueID + newValues.size();
3048 if (valueIDEnd > values.size()) {
3049 return reader.emitError(
3050 "value index range was outside of the expected range for "
3051 "the parent region, got [",
3052 valueID,
", ", valueIDEnd,
"), but the maximum index was ",
3057 for (
unsigned i = 0, e = newValues.size(); i != e; ++i, ++valueID) {
3058 Value newValue = newValues[i];
3061 if (Value oldValue = std::exchange(values[valueID], newValue)) {
3062 Operation *forwardRefOp = oldValue.getDefiningOp();
3067 assert(forwardRefOp && forwardRefOp->
getBlock() == &forwardRefOps &&
3068 "value index was already defined?");
3070 oldValue.replaceAllUsesWith(newValue);
3071 forwardRefOp->
moveBefore(&openForwardRefOps, openForwardRefOps.end());
3077Value BytecodeReader::Impl::createForwardRef() {
3080 if (!openForwardRefOps.empty()) {
3081 Operation *op = &openForwardRefOps.back();
3082 op->
moveBefore(&forwardRefOps, forwardRefOps.end());
3086 return forwardRefOps.back().getResult(0);
3096 llvm::MemoryBufferRef buffer,
const ParserConfig &config,
bool lazyLoading,
3097 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef) {
3101 impl = std::make_unique<Impl>(sourceFileLoc, config, lazyLoading, buffer,
3107 return impl->read(block, lazyOpsCallback);
3111 return impl->getNumOpsToMaterialize();
3115 return impl->isMaterializable(op);
3120 return impl->materialize(op, lazyOpsCallback);
3125 return impl->finalize(shouldMaterialize);
3129 return buffer.getBuffer().starts_with(
"ML\xefR");
3138 const std::shared_ptr<llvm::SourceMgr> &bufferOwnerRef) {
3144 "input buffer is not an MLIR bytecode file");
3148 buffer, bufferOwnerRef);
3149 return reader.
read(block,
nullptr);
3160 *sourceMgr->getMemoryBuffer(sourceMgr->getMainFileID()), block, config,
static LogicalResult parseDialectGrouping(EncodingReader &reader, MutableArrayRef< std::unique_ptr< BytecodeDialect > > dialects, function_ref< LogicalResult(BytecodeDialect *)> entryCallback)
Parse a single dialect group encoded in the byte stream.
static LogicalResult readBytecodeFileImpl(llvm::MemoryBufferRef buffer, Block *block, const ParserConfig &config, const std::shared_ptr< llvm::SourceMgr > &bufferOwnerRef)
Read the bytecode from the provided memory buffer reference.
static bool isSectionOptional(bytecode::Section::ID sectionID, int version)
Returns true if the given top-level section ID is optional.
static LogicalResult parseResourceGroup(Location fileLoc, bool allowEmpty, EncodingReader &offsetReader, EncodingReader &resourceReader, StringSectionReader &stringReader, T *handler, const std::shared_ptr< llvm::SourceMgr > &bufferOwnerRef, function_ref< StringRef(StringRef)> remapKey={}, function_ref< LogicalResult(StringRef)> processKeyFn={})
static LogicalResult resolveEntry(EncodingReader &reader, RangeT &entries, uint64_t index, T &entry, StringRef entryStr)
Resolve an index into the given entry list.
static LogicalResult parseEntry(EncodingReader &reader, RangeT &entries, T &entry, StringRef entryStr)
Parse and resolve an index into the given entry list.
LogicalResult initialize(unsigned origNumLoops, ArrayRef< ReassociationIndices > foldedIterationDims)
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
StringRef getName() const
Return the unique name representing the type.
MutableArrayRef< char > getMutableData()
Return a mutable reference to the raw underlying data of this blob.
ArrayRef< char > getData() const
Return the raw underlying data of this blob.
bool isMutable() const
Return if the data of this blob is mutable.
MLIRContext * getContext() const
Return the context this attribute belongs to.
Block represents an ordered list of Operations.
BlockArgument getArgument(unsigned i)
unsigned getNumArguments()
iterator_range< args_iterator > addArguments(TypeRange types, ArrayRef< Location > locs)
Add one argument to the argument list for each type specified in the list.
OpListType & getOperations()
BlockArgListType getArguments()
ArrayRef< std::unique_ptr< AttrTypeBytecodeReader< Type > > > getTypeCallbacks() const
ArrayRef< std::unique_ptr< AttrTypeBytecodeReader< Attribute > > > getAttributeCallbacks() const
Returns the callbacks available to the parser.
This class is used to read a bytecode buffer and translate it into MLIR.
LogicalResult materializeAll()
Materialize all operations.
LogicalResult read(Block *block, llvm::function_ref< bool(Operation *)> lazyOps)
Read the bytecode defined within buffer into the given block.
bool isMaterializable(Operation *op)
Impl(Location fileLoc, const ParserConfig &config, bool lazyLoading, llvm::MemoryBufferRef buffer, const std::shared_ptr< llvm::SourceMgr > &bufferOwnerRef)
LogicalResult finalize(function_ref< bool(Operation *)> shouldMaterialize)
Finalize the lazy-loading by calling back with every op that hasn't been materialized to let the clie...
LogicalResult materialize(Operation *op, llvm::function_ref< bool(Operation *)> lazyOpsCallback)
Materialize the provided operation, invoke the lazyOpsCallback on every newly found lazy operation.
int64_t getNumOpsToMaterialize() const
Return the number of ops that haven't been materialized yet.
LogicalResult materialize(Operation *op, llvm::function_ref< bool(Operation *)> lazyOpsCallback=[](Operation *) { return false;})
Materialize the provide operation.
LogicalResult finalize(function_ref< bool(Operation *)> shouldMaterialize=[](Operation *) { return true;})
Finalize the lazy-loading by calling back with every op that hasn't been materialized to let the clie...
BytecodeReader(llvm::MemoryBufferRef buffer, const ParserConfig &config, bool lazyLoad, const std::shared_ptr< llvm::SourceMgr > &bufferOwnerRef={})
Create a bytecode reader for the given buffer.
int64_t getNumOpsToMaterialize() const
Return the number of ops that haven't been materialized yet.
bool isMaterializable(Operation *op)
Return true if the provided op is materializable.
LogicalResult readTopLevel(Block *block, llvm::function_ref< bool(Operation *)> lazyOps=[](Operation *) { return false;})
Read the operations defined within the given memory buffer, containing MLIR bytecode,...
This class contains all of the information necessary to report a diagnostic to the DiagnosticEngine.
static FileLineColLoc get(StringAttr filename, unsigned line, unsigned column)
This class represents a diagnostic that is inflight and set to be reported.
InFlightDiagnostic & append(Args &&...args) &
Append arguments to the diagnostic.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext * getContext() const
Return the context this location is uniqued in.
MLIRContext is the top-level object for a collection of MLIR operations.
T * getOrLoadDialect()
Get (or create) a dialect for the given derived dialect type.
bool allowsUnregisteredDialects()
Return true if we allow to create operation for unregistered dialects.
StringRef getStringRef() const
Return the name of this operation. This always succeeds.
bool isRegistered() const
Return if this operation is registered.
T::Concept * getInterface() const
Returns an instance of the concept object for the given interface if it was registered to this operat...
Operation is the basic unit of execution within MLIR.
void dropAllReferences()
This drops all operand uses from this operation, which is an essential step in breaking cyclic depend...
Block * getBlock()
Returns the operation block that contains this operation.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
static Operation * create(Location location, OperationName name, TypeRange resultTypes, ValueRange operands, NamedAttrList &&attributes, PropertyRef properties, BlockRange successors, unsigned numRegions)
Create a new Operation with the specific fields.
void moveBefore(Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
result_range getResults()
void erase()
Remove this operation from its parent block and delete it.
unsigned getNumResults()
Return the number of results held by this operation.
This class represents a configuration for the MLIR assembly parser.
MLIRContext * getContext() const
Return the MLIRContext to be used when parsing.
bool shouldVerifyAfterParse() const
Returns if the parser should verify the IR after parsing.
BytecodeReaderConfig & getBytecodeReaderConfig() const
Returns the parsing configurations associated to the bytecode read.
AsmResourceParser * getResourceParser(StringRef name) const
Return the resource parser registered to the given name, or nullptr if no parser with name is registe...
BlockListType::iterator iterator
This diagnostic handler is a simple RAII class that registers and erases a diagnostic handler on a gi...
const AbstractTy & getAbstractType() const
Return the abstract type descriptor for this type.
bool hasTrait()
Returns true if the type was registered with a particular trait.
static AsmResourceBlob allocateWithAlign(ArrayRef< char > data, size_t align, AsmResourceBlob::DeleterFn deleter={}, bool dataIsMutable=false)
Create a new unmanaged resource directly referencing the provided data.
This class provides an abstraction over the different types of ranges over Values.
bool use_empty() const
Returns true if this value has no uses.
void shuffleUseList(ArrayRef< unsigned > indices)
Shuffle the use list order according to the provided indices.
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
void * getAsOpaquePointer() const
Methods for supporting PointerLikeTypeTraits.
unsigned getNumUses() const
This method computes the number of uses of this Value.
bool hasOneUse() const
Returns true if this value has exactly one use.
use_iterator use_begin() const
static WalkResult advance()
static WalkResult interrupt()
detail::StorageUserTrait::IsMutable< ConcreteType > IsMutable
@ kAttrType
This section contains the attributes and types referenced within an IR module.
@ kAttrTypeOffset
This section contains the offsets for the attribute and types within the AttrType section.
@ kIR
This section contains the list of operations serialized into the bytecode, and their nested regions/o...
@ kResource
This section contains the resources of the bytecode.
@ kResourceOffset
This section contains the offsets of resources within the Resource section.
@ kDialect
This section contains the dialects referenced within an IR module.
@ kString
This section contains strings referenced within the bytecode.
@ kDialectVersions
This section contains the versions of each dialect.
@ kProperties
This section contains the properties for the operations.
@ kNumSections
The total number of section types.
static uint64_t getUseID(OperandT &val, unsigned ownerID)
Get the unique ID of a value use.
@ kUseListOrdering
Use-list ordering started to be encoded in version 3.
@ kAlignmentByte
An arbitrary value used to fill alignment padding.
@ kVersion
The current bytecode version.
@ kLazyLoading
Support for lazy-loading of isolated region was added in version 2.
@ kDialectVersioning
Dialects versioning was added in version 1.
@ kElideUnknownBlockArgLocation
Avoid recording unknown locations on block arguments (compression) started in version 4.
@ kNativePropertiesEncoding
Support for encoding properties natively in bytecode instead of merged with the discardable attribute...
@ kMinSupportedVersion
The minimum supported version of the bytecode.
Include the generated interface declarations.
InFlightDiagnostic emitWarning(Location loc)
Utility method to emit a warning message using this location.
StringRef toString(AsmResourceEntryKind kind)
bool isBytecode(llvm::MemoryBufferRef buffer)
Returns true if the given buffer starts with the magic bytes that signal MLIR bytecode.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
Attribute parseAttribute(llvm::StringRef attrStr, MLIRContext *context, Type type={}, size_t *numRead=nullptr, bool isKnownNullTerminated=false)
This parses a single MLIR attribute to an MLIR context if it was valid.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
Type parseType(llvm::StringRef typeStr, MLIRContext *context, size_t *numRead=nullptr, bool isKnownNullTerminated=false)
This parses a single MLIR type to an MLIR context if it was valid.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
AsmResourceEntryKind
This enum represents the different kinds of resource values.
LogicalResult readBytecodeFile(llvm::MemoryBufferRef buffer, Block *block, const ParserConfig &config)
Read the operations defined within the given memory buffer, containing MLIR bytecode,...
LogicalResult verify(Operation *op, bool verifyRecursively=true)
Perform (potentially expensive) checks of invariants, used to detect compiler bugs,...
llvm::function_ref< Fn > function_ref
LogicalResult readResourceHandle(DialectBytecodeReader &reader, FailureOr< T > &value, Ts &&...params)
Helper for resource handle reading that returns LogicalResult.
SmallVector< Block *, 1 > successors
Successors of this operation and their respective operands.
SmallVector< Value, 4 > operands
SmallVector< std::unique_ptr< Region >, 1 > regions
Regions that the op will hold.
Attribute propertiesAttr
This Attribute is used to opaquely construct the properties of the operation.
SmallVector< Type, 4 > types
Types of the results of this operation.