21#include "mlir/Dialect/Arith/IR/Arith.h"
22#include "mlir/Dialect/Func/IR/FuncOps.h"
23#include "mlir/Dialect/Index/IR/IndexDialect.h"
24#include "mlir/Dialect/Index/IR/IndexOps.h"
25#include "mlir/Dialect/SCF/IR/SCF.h"
26#include "mlir/IR/IRMapping.h"
27#include "mlir/IR/PatternMatch.h"
28#include "llvm/ADT/DenseMapInfoVariant.h"
29#include "llvm/ADT/ScopeExit.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/Support/Debug.h"
38#define GEN_PASS_DEF_ELABORATIONPASS
39#include "circt/Dialect/RTG/Transforms/RTGPasses.h.inc"
47#define DEBUG_TYPE "rtg-elaboration"
53 RngScope(
const RngScope &) =
default;
54 RngScope &operator=(
const RngScope &) =
default;
56 RngScope(RngScope &&) =
default;
57 RngScope &operator=(RngScope &&) =
default;
59 explicit RngScope(uint32_t seed) : rng(seed) {}
71 uint32_t getUniformlyInRange(uint32_t a, uint32_t b) {
72 const uint32_t diff = b - a + 1;
80 std::numeric_limits<uint32_t>::max() >> (32 - llvm::Log2_32_Ceil(diff));
89 RngScope getNested() {
return RngScope(rng()); }
103struct SequenceStorage;
104struct RandomizedSequenceStorage;
105struct InterleavedSequenceStorage;
107struct VirtualRegisterStorage;
108struct UniqueLabelStorage;
111struct VariantStorage;
113struct MemoryBlockStorage;
114struct SymbolicComputationWithIdentityStorage;
115struct SymbolicComputationWithIdentityValue;
116struct SymbolicComputationStorage;
117struct OpaqueExternalStorage;
119struct ContinuationStorage;
122using ElaboratorValue = std::variant<
123 TypedAttr, BagStorage *, bool, size_t, SequenceStorage *,
124 RandomizedSequenceStorage *, InterleavedSequenceStorage *, SetStorage *,
125 VirtualRegisterStorage *, UniqueLabelStorage *, ArrayStorage *,
126 TupleStorage *, StructStorage *, VariantStorage *, MemoryStorage *,
127 MemoryBlockStorage *, SymbolicComputationWithIdentityStorage *,
128 SymbolicComputationWithIdentityValue *, SymbolicComputationStorage *,
129 OpaqueExternalStorage *, MutStorage *, ContinuationStorage *>;
130using LexicalEnvironment = DenseMap<Value, ElaboratorValue>;
133llvm::hash_code
hash_value(
const ElaboratorValue &val) {
135 [&val](
const auto &alternative) {
138 return llvm::hash_combine(val.index(), alternative);
151 static bool isEqual(
const bool &lhs,
const bool &rhs) {
return lhs == rhs; }
166template <
typename StorageTy>
167struct HashedStorage {
168 HashedStorage(
unsigned hashcode = 0, StorageTy *storage =
nullptr)
169 : hashcode(hashcode), storage(storage) {}
179template <
typename StorageTy>
180struct StorageKeyInfo {
181 static inline unsigned getHashValue(
const HashedStorage<StorageTy> &key) {
184 static inline unsigned getHashValue(
const StorageTy &key) {
188 static inline bool isEqual(
const HashedStorage<StorageTy> &lhs,
189 const HashedStorage<StorageTy> &rhs) {
190 return lhs.storage == rhs.storage;
192 static inline bool isEqual(
const StorageTy &lhs,
193 const HashedStorage<StorageTy> &rhs) {
197 return lhs.isEqual(rhs.storage);
207struct CachableStorage {
212struct SetStorage : CachableStorage {
213 static unsigned computeHash(
const SetVector<ElaboratorValue> &set,
215 llvm::hash_code setHash = 0;
216 for (
auto el : set) {
221 setHash = setHash ^ llvm::hash_combine(el);
223 return llvm::hash_combine(type, setHash);
226 SetStorage(SetVector<ElaboratorValue> &&set, Type type)
227 : hashcode(computeHash(set, type)), set(std::move(set)), type(type) {}
229 bool isEqual(
const SetStorage *other)
const {
234 bool allContained =
true;
236 allContained &= other->set.contains(el);
238 return hashcode == other->hashcode && set.size() == other->set.size() &&
239 allContained && type == other->type;
243 const unsigned hashcode;
246 const SetVector<ElaboratorValue> set;
255 BagStorage(MapVector<ElaboratorValue, uint64_t> &&bag, Type type)
257 type, llvm::hash_combine_range(bag.begin(), bag.
end()))),
258 bag(std::move(bag)), type(type) {}
260 bool isEqual(
const BagStorage *other)
const {
261 return hashcode == other->hashcode && llvm::equal(bag, other->bag) &&
266 const unsigned hashcode;
270 const MapVector<ElaboratorValue, uint64_t> bag;
278struct SequenceStorage {
279 SequenceStorage(StringAttr familyName, SmallVector<ElaboratorValue> &&args)
281 familyName, llvm::hash_combine_range(args.begin(), args.
end()))),
282 familyName(familyName), args(std::move(args)) {}
284 bool isEqual(
const SequenceStorage *other)
const {
285 return hashcode == other->hashcode && familyName == other->familyName &&
290 const unsigned hashcode;
293 const StringAttr familyName;
296 const SmallVector<ElaboratorValue> args;
300struct InterleavedSequenceStorage {
301 InterleavedSequenceStorage(SmallVector<ElaboratorValue> &&sequences,
303 : sequences(std::move(sequences)), batchSize(batchSize),
305 llvm::hash_combine_range(sequences.begin(), sequences.
end()),
308 explicit InterleavedSequenceStorage(RandomizedSequenceStorage *sequence)
309 : sequences(SmallVector<ElaboratorValue>(1, sequence)), batchSize(1),
311 llvm::hash_combine_range(sequences.begin(), sequences.
end()),
314 bool isEqual(
const InterleavedSequenceStorage *other)
const {
315 return hashcode == other->hashcode && sequences == other->sequences &&
316 batchSize == other->batchSize;
319 const SmallVector<ElaboratorValue> sequences;
321 const uint32_t batchSize;
324 const unsigned hashcode;
329 ArrayStorage(Type type, SmallVector<ElaboratorValue> &&array)
331 type, llvm::hash_combine_range(array.begin(), array.
end()))),
332 type(type), array(array) {}
334 bool isEqual(
const ArrayStorage *other)
const {
335 return hashcode == other->hashcode && type == other->type &&
336 array == other->array;
340 const unsigned hashcode;
347 const SmallVector<ElaboratorValue> array;
351struct TupleStorage : CachableStorage {
352 TupleStorage(SmallVector<ElaboratorValue> &&values)
353 : hashcode(llvm::hash_combine_range(values.begin(), values.
end())),
354 values(std::move(values)) {}
356 bool isEqual(
const TupleStorage *other)
const {
357 return hashcode == other->hashcode && values == other->values;
361 const unsigned hashcode;
363 const SmallVector<ElaboratorValue> values;
368struct StructStorage : CachableStorage {
369 StructStorage(StructType type, SmallVector<ElaboratorValue> &&fields)
371 type, llvm::hash_combine_range(fields.begin(), fields.
end()))),
372 type(type), fields(std::move(fields)) {}
374 bool isEqual(
const StructStorage *other)
const {
375 return hashcode == other->hashcode && type == other->type &&
376 fields == other->fields;
379 const unsigned hashcode;
380 const StructType type;
381 const SmallVector<ElaboratorValue> fields;
386struct VariantStorage : CachableStorage {
387 VariantStorage(VariantType type, StringAttr constructor,
388 ElaboratorValue payload)
389 : hashcode(llvm::
hash_combine(type, constructor, payload)), type(type),
390 constructor(constructor), payload(payload) {}
392 bool isEqual(
const VariantStorage *other)
const {
393 return hashcode == other->hashcode && type == other->type &&
394 constructor == other->constructor && payload == other->payload;
397 const unsigned hashcode;
398 const VariantType type;
399 const StringAttr constructor;
400 const ElaboratorValue payload;
403struct SymbolicComputationStorage {
404 SymbolicComputationStorage(
const DenseMap<Value, ElaboratorValue> &state,
406 : name(op->
getName()), resultTypes(op->getResultTypes()),
407 operands(llvm::map_range(op->getOperands(),
408 [&](Value v) {
return state.lookup(v); })),
409 attributes(op->getAttrDictionary()),
410 properties(op->getPropertiesAsAttribute()),
411 hashcode(llvm::hash_combine(name, llvm::hash_combine_range(resultTypes),
412 llvm::hash_combine_range(operands),
413 attributes, op->hashProperties())) {}
415 bool isEqual(
const SymbolicComputationStorage *other)
const {
416 return hashcode == other->hashcode && name == other->name &&
417 resultTypes == other->resultTypes && operands == other->operands &&
418 attributes == other->attributes && properties == other->properties;
421 const OperationName name;
422 const SmallVector<Type> resultTypes;
423 const SmallVector<ElaboratorValue> operands;
424 const DictionaryAttr attributes;
425 const Attribute properties;
426 const unsigned hashcode;
437struct IdentityValue {
439 IdentityValue(Type type, Location loc) : type(type), loc(loc) {}
452 bool alreadyMaterialized =
false;
461struct VirtualRegisterStorage : IdentityValue {
462 VirtualRegisterStorage(VirtualRegisterConfigAttr allowedRegs, Type type,
464 : IdentityValue(type, loc), allowedRegs(allowedRegs) {}
471 const VirtualRegisterConfigAttr allowedRegs;
474struct UniqueLabelStorage : IdentityValue {
475 UniqueLabelStorage(
const ElaboratorValue &name, Location loc)
476 : IdentityValue(LabelType::
get(loc->getContext()), loc), name(name) {}
482 const ElaboratorValue name;
486struct MemoryBlockStorage : IdentityValue {
487 MemoryBlockStorage(
const APInt &baseAddress,
const APInt &endAddress,
488 Type type, Location loc)
489 : IdentityValue(type, loc), baseAddress(baseAddress),
490 endAddress(endAddress) {}
495 const APInt baseAddress;
498 const APInt endAddress;
502struct MemoryStorage : IdentityValue {
503 MemoryStorage(MemoryBlockStorage *memoryBlock,
size_t size,
size_t alignment,
505 : IdentityValue(MemoryType::
get(memoryBlock->type.getContext(),
508 memoryBlock(memoryBlock), size(size), alignment(alignment) {}
510 MemoryBlockStorage *memoryBlock;
512 const size_t alignment;
516struct RandomizedSequenceStorage : IdentityValue {
517 RandomizedSequenceStorage(ContextResourceAttrInterface context,
518 SequenceStorage *sequence, Location loc)
520 RandomizedSequenceType::
get(sequence->familyName.getContext()),
522 context(context), sequence(sequence) {}
525 const ContextResourceAttrInterface context;
527 const SequenceStorage *sequence;
531struct SymbolicComputationWithIdentityStorage : IdentityValue {
532 SymbolicComputationWithIdentityStorage(
533 const DenseMap<Value, ElaboratorValue> &state, Operation *op)
534 : IdentityValue(op->getResult(0).getType(), op->
getLoc()),
535 name(op->
getName()), resultTypes(op->getResultTypes()),
536 operands(llvm::map_range(op->getOperands(),
537 [&](Value v) {
return state.lookup(v); })),
538 attributes(op->getAttrDictionary()),
539 properties(op->getPropertiesAsAttribute()) {}
541 const OperationName name;
542 const SmallVector<Type> resultTypes;
543 const SmallVector<ElaboratorValue> operands;
544 const DictionaryAttr attributes;
545 const Attribute properties;
548struct SymbolicComputationWithIdentityValue : IdentityValue {
549 SymbolicComputationWithIdentityValue(
550 Type type,
const SymbolicComputationWithIdentityStorage *storage,
552 : IdentityValue(type, storage->loc), storage(storage), idx(idx) {
555 "Use SymbolicComputationWithIdentityStorage for result with index 0.");
558 const SymbolicComputationWithIdentityStorage *storage;
567struct OpaqueExternalStorage : IdentityValue {
568 OpaqueExternalStorage(Type type, Location loc) : IdentityValue(type, loc) {}
571struct ContinuationBoundary {
572 uint64_t sequence = 0;
573 SmallVector<uint64_t> externalRegions;
574 uint64_t elaborator = 0;
579struct MutStorage : IdentityValue {
580 MutStorage(Type type, Location loc, ContinuationBoundary boundary)
581 : IdentityValue(type, loc), boundary(std::move(boundary)) {}
584 ContinuationBoundary boundary;
589 uint64_t promptToken = 0;
590 DenseMap<StringAttr, Region *> handlers;
595 Block *block =
nullptr;
596 Operation *nextOp =
nullptr;
597 bool keepTerminator =
false;
598 bool eraseTerminator =
true;
600 LexicalEnvironment environment;
610 LogicalResult step(Elaborator &elaborator,
611 ArrayRef<ElaboratorValue> yieldedValues);
614struct VariantMatchFrame {
620 size_t nextIteration = 0;
621 size_t upperBound = 0;
624 bool completed =
false;
625 LexicalEnvironment loopEnvironment;
627 LogicalResult step(Elaborator &elaborator,
628 ArrayRef<ElaboratorValue> yieldedValues);
631struct RandomScopeFrame {
636 RandomScopeFrame(RandomScopeOp op, RngScope outerRng,
bool replay)
637 : op(op), outerRng(std::move(outerRng)), replay(replay) {}
640struct WithHandlersFrame {
642 uint64_t promptId = 0;
646struct HandlerClauseFrame {};
648struct FunctionCallFrame {
653struct ExternalOpFrame {
654 Operation *originalOp =
nullptr;
655 Operation *materializedOp =
nullptr;
656 size_t nextRegion = 0;
657 uint64_t activeBoundary = 0;
659 LexicalEnvironment parentEnvironment;
660 OpBuilder::InsertPoint parentInsertionPoint;
665 SmallVector<HandlerFrame> handlerStack;
668 ResumeFrame(SmallVector<HandlerFrame> handlerStack, RngScope rng)
669 : handlerStack(std::move(handlerStack)), rng(std::move(rng)) {}
672using EvalFramePayload =
673 std::variant<BlockFrame, ScfIfFrame, VariantMatchFrame, ScfForFrame,
674 RandomScopeFrame, WithHandlersFrame, HandlerClauseFrame,
675 FunctionCallFrame, ExternalOpFrame, ResumeFrame>;
678 EvalFramePayload payload;
680 template <
typename FrameTy>
681 explicit EvalFrame(FrameTy &&frame) : payload(std::forward<FrameTy>(frame)) {}
683 EvalFrame(
const EvalFrame &) =
default;
685 std::unique_ptr<EvalFrame> clone()
const {
686 return std::make_unique<EvalFrame>(*
this);
689 template <
typename FrameTy>
691 return std::get_if<FrameTy>(&payload);
694 template <
typename FrameTy>
695 const FrameTy *getIf()
const {
696 return std::get_if<FrameTy>(&payload);
699 template <
typename FrameTy>
701 return std::get<FrameTy>(payload);
704 template <
typename FrameTy>
706 return std::holds_alternative<FrameTy>(payload);
710using EvalFrameStack = SmallVector<std::unique_ptr<EvalFrame>, 0>;
714struct ContinuationStorage : IdentityValue {
715 ContinuationStorage(EvalFrameStack capturedFrames, Value performResult,
716 SmallVector<HandlerFrame> capturedHandlerStack,
717 const LexicalEnvironment &capturedEnvironment,
718 RngScope capturedRng, uint64_t promptToken,
719 ContinuationBoundary boundary, Type resumeType,
721 : IdentityValue(ContinuationType::
get(loc.getContext(), resumeType), loc),
722 capturedFrames(std::move(capturedFrames)), performResult(performResult),
723 capturedHandlerStack(std::move(capturedHandlerStack)),
724 capturedEnvironment(capturedEnvironment),
725 capturedRng(std::move(capturedRng)), promptToken(promptToken),
726 boundary(std::move(boundary)) {}
729 EvalFrameStack capturedFrames;
733 SmallVector<HandlerFrame> capturedHandlerStack;
735 LexicalEnvironment capturedEnvironment;
737 RngScope capturedRng;
739 uint64_t promptToken;
741 ContinuationBoundary boundary;
750 for (
auto it = destructors.rbegin(); it != destructors.rend(); ++it)
751 it->second(it->first);
759 template <
typename StorageTy,
typename... Args>
760 StorageTy *internalize(Args &&...args) {
761 static_assert(!std::is_base_of_v<IdentityValue, StorageTy> &&
762 "values with identity must not be internalized");
764 StorageTy storage(std::forward<Args>(args)...);
766 auto existing = getInternSet<StorageTy>().insert_as(
767 HashedStorage<StorageTy>(storage.hashcode), storage);
768 StorageTy *&storagePtr = existing.first->storage;
769 if (existing.second) {
771 new (allocator.Allocate<StorageTy>()) StorageTy(std::move(storage));
772 registerDestructor(storagePtr);
778 template <
typename StorageTy,
typename... Args>
779 StorageTy *create(Args &&...args) {
780 static_assert(std::is_base_of_v<IdentityValue, StorageTy> &&
781 "values with structural equivalence must be internalized");
783 StorageTy *storage =
new (allocator.Allocate<StorageTy>())
784 StorageTy(std::forward<Args>(args)...);
785 registerDestructor(storage);
790 template <
typename StorageTy>
791 void registerDestructor(StorageTy *storage) {
792 if constexpr (!std::is_trivially_destructible_v<StorageTy>)
793 destructors.emplace_back(storage, [](
void *ptr) {
794 static_cast<StorageTy *>(ptr)->~StorageTy();
798 template <
typename StorageTy>
799 DenseSet<HashedStorage<StorageTy>, StorageKeyInfo<StorageTy>> &
801 if constexpr (std::is_same_v<StorageTy, ArrayStorage>)
802 return internedArrays;
803 else if constexpr (std::is_same_v<StorageTy, SetStorage>)
805 else if constexpr (std::is_same_v<StorageTy, BagStorage>)
807 else if constexpr (std::is_same_v<StorageTy, SequenceStorage>)
808 return internedSequences;
809 else if constexpr (std::is_same_v<StorageTy, RandomizedSequenceStorage>)
810 return internedRandomizedSequences;
811 else if constexpr (std::is_same_v<StorageTy, InterleavedSequenceStorage>)
812 return internedInterleavedSequences;
813 else if constexpr (std::is_same_v<StorageTy, TupleStorage>)
814 return internedTuples;
815 else if constexpr (std::is_same_v<StorageTy, StructStorage>)
816 return internedStructs;
817 else if constexpr (std::is_same_v<StorageTy, VariantStorage>)
818 return internedVariants;
819 else if constexpr (std::is_same_v<StorageTy, SymbolicComputationStorage>)
820 return internedSymbolicComputationWithIdentityValues;
822 static_assert(!
sizeof(StorageTy),
823 "no intern set available for this storage type.");
828 llvm::BumpPtrAllocator allocator;
833 SmallVector<std::pair<
void *, void (*)(
void *)>> destructors;
838 DenseSet<HashedStorage<ArrayStorage>, StorageKeyInfo<ArrayStorage>>
840 DenseSet<HashedStorage<SetStorage>, StorageKeyInfo<SetStorage>> internedSets;
841 DenseSet<HashedStorage<BagStorage>, StorageKeyInfo<BagStorage>> internedBags;
842 DenseSet<HashedStorage<SequenceStorage>, StorageKeyInfo<SequenceStorage>>
844 DenseSet<HashedStorage<RandomizedSequenceStorage>,
845 StorageKeyInfo<RandomizedSequenceStorage>>
846 internedRandomizedSequences;
847 DenseSet<HashedStorage<InterleavedSequenceStorage>,
848 StorageKeyInfo<InterleavedSequenceStorage>>
849 internedInterleavedSequences;
850 DenseSet<HashedStorage<TupleStorage>, StorageKeyInfo<TupleStorage>>
852 DenseSet<HashedStorage<StructStorage>, StorageKeyInfo<StructStorage>>
854 DenseSet<HashedStorage<VariantStorage>, StorageKeyInfo<VariantStorage>>
856 DenseSet<HashedStorage<SymbolicComputationStorage>,
857 StorageKeyInfo<SymbolicComputationStorage>>
858 internedSymbolicComputationWithIdentityValues;
865static llvm::raw_ostream &
operator<<(llvm::raw_ostream &os,
866 const ElaboratorValue &value);
868static void print(TypedAttr val, llvm::raw_ostream &os) {
869 os <<
"<attr " << val <<
">";
872static void print(BagStorage *val, llvm::raw_ostream &os) {
874 llvm::interleaveComma(val->bag, os,
875 [&](
const std::pair<ElaboratorValue, uint64_t> &el) {
876 os << el.first <<
" -> " << el.second;
878 os <<
"} at " << val <<
">";
881static void print(
bool val, llvm::raw_ostream &os) {
882 os <<
"<bool " << (val ?
"true" :
"false") <<
">";
885static void print(
size_t val, llvm::raw_ostream &os) {
886 os <<
"<index " << val <<
">";
889static void print(SequenceStorage *val, llvm::raw_ostream &os) {
890 os <<
"<sequence @" << val->familyName.getValue() <<
"(";
891 llvm::interleaveComma(val->args, os,
892 [&](
const ElaboratorValue &val) { os << val; });
893 os <<
") at " << val <<
">";
896static void print(RandomizedSequenceStorage *val, llvm::raw_ostream &os) {
897 os <<
"<randomized-sequence derived from @"
898 << val->sequence->familyName.getValue() <<
" under context "
899 << val->context <<
"(";
900 llvm::interleaveComma(val->sequence->args, os,
901 [&](
const ElaboratorValue &val) { os << val; });
902 os <<
") at " << val <<
">";
905static void print(InterleavedSequenceStorage *val, llvm::raw_ostream &os) {
906 os <<
"<interleaved-sequence [";
907 llvm::interleaveComma(val->sequences, os,
908 [&](
const ElaboratorValue &val) { os << val; });
909 os <<
"] batch-size " << val->batchSize <<
" at " << val <<
">";
912static void print(ArrayStorage *val, llvm::raw_ostream &os) {
914 llvm::interleaveComma(val->array, os,
915 [&](
const ElaboratorValue &val) { os << val; });
916 os <<
"] at " << val <<
">";
919static void print(SetStorage *val, llvm::raw_ostream &os) {
921 llvm::interleaveComma(val->set, os,
922 [&](
const ElaboratorValue &val) { os << val; });
923 os <<
"} at " << val <<
">";
926static void print(
const VirtualRegisterStorage *val, llvm::raw_ostream &os) {
927 os <<
"<virtual-register " << val <<
" " << val->allowedRegs <<
">";
930static void print(
const UniqueLabelStorage *val, llvm::raw_ostream &os) {
931 os <<
"<unique-label " << val <<
" " << val->name <<
">";
934static void print(
const TupleStorage *val, llvm::raw_ostream &os) {
936 llvm::interleaveComma(val->values, os,
937 [&](
const ElaboratorValue &val) { os << val; });
941static void print(
const StructStorage *val, llvm::raw_ostream &os) {
942 os <<
"<struct " << val->type <<
" [";
943 llvm::interleaveComma(val->fields, os,
944 [&](
const ElaboratorValue &field) { os << field; });
948static void print(
const VariantStorage *val, llvm::raw_ostream &os) {
949 os <<
"<variant " << val->type <<
" " << val->constructor <<
" "
950 << val->payload <<
">";
953static void print(
const MemoryStorage *val, llvm::raw_ostream &os) {
954 os <<
"<memory {" << ElaboratorValue(val->memoryBlock)
955 <<
", size=" << val->size <<
", alignment=" << val->alignment <<
"}>";
958static void print(
const MemoryBlockStorage *val, llvm::raw_ostream &os) {
959 os <<
"<memory-block {"
960 <<
", address-width=" << val->baseAddress.getBitWidth()
961 <<
", base-address=" << val->baseAddress
962 <<
", end-address=" << val->endAddress <<
"}>";
965static void print(
const SymbolicComputationWithIdentityValue *val,
966 llvm::raw_ostream &os) {
967 os <<
"<symbolic-computation-with-identity-value (" << val->storage <<
") at "
971static void print(
const SymbolicComputationWithIdentityStorage *val,
972 llvm::raw_ostream &os) {
973 os <<
"<symbolic-computation-with-identity " << val->name <<
"(";
974 llvm::interleaveComma(val->operands, os,
975 [&](
const ElaboratorValue &val) { os << val; });
976 os <<
") -> " << val->resultTypes <<
" with attributes " << val->attributes
977 <<
" and properties " << val->properties;
981static void print(
const SymbolicComputationStorage *val,
982 llvm::raw_ostream &os) {
983 os <<
"<symbolic-computation " << val->name <<
"(";
984 llvm::interleaveComma(val->operands, os,
985 [&](
const ElaboratorValue &val) { os << val; });
986 os <<
") -> " << val->resultTypes <<
" with attributes " << val->attributes
987 <<
" and properties " << val->properties;
991static void print(
const OpaqueExternalStorage *val, llvm::raw_ostream &os) {
992 os <<
"<opaque-external " << val->type <<
">";
995static void print(
const MutStorage *val, llvm::raw_ostream &os) {
996 os <<
"<mut at " << val <<
">";
999static void print(
const ContinuationStorage *val, llvm::raw_ostream &os) {
1000 os <<
"<continuation with " << val->capturedFrames.size() <<
" frames at "
1005 const ElaboratorValue &value) {
1006 std::visit([&](
auto val) {
print(val, os); }, value);
1021class AttributeToElaboratorValueConverter {
1023 AttributeToElaboratorValueConverter(Internalizer &internalizer)
1024 : internalizer(internalizer) {}
1029 FailureOr<ElaboratorValue>
convert(Attribute attr) {
1030 return llvm::TypeSwitch<Attribute, FailureOr<ElaboratorValue>>(attr)
1031 .Case<IntegerAttr, SetAttr, TupleAttr, StructAttr, VariantAttr>(
1032 [&](
auto attr) {
return convert(attr); })
1033 .Case<TypedAttr>([&](
auto typedAttr) -> FailureOr<ElaboratorValue> {
1034 return ElaboratorValue(typedAttr);
1037 [&](Attribute) -> FailureOr<ElaboratorValue> {
return failure(); });
1041 FailureOr<ElaboratorValue>
convert(IntegerAttr attr) {
1042 if (attr.getType().isSignlessInteger(1))
1043 return ElaboratorValue(
bool(attr.getInt()));
1044 if (isa<IndexType>(attr.getType()))
1045 return ElaboratorValue(
size_t(attr.getInt()));
1046 return ElaboratorValue(attr);
1049 FailureOr<ElaboratorValue>
convert(SetAttr setAttr) {
1050 SetVector<ElaboratorValue> set;
1051 for (
auto element : *setAttr.getElements()) {
1052 auto converted =
convert(element);
1053 if (failed(converted))
1055 set.insert(*converted);
1058 internalizer.internalize<SetStorage>(std::move(set), setAttr.getType());
1060 storage->attrCache = setAttr;
1061 return ElaboratorValue(storage);
1064 FailureOr<ElaboratorValue>
convert(TupleAttr tupleAttr) {
1065 SmallVector<ElaboratorValue> values;
1066 for (
auto element : tupleAttr.getElements()) {
1067 auto converted =
convert(element);
1068 if (failed(converted))
1070 values.push_back(*converted);
1072 auto *storage = internalizer.internalize<TupleStorage>(std::move(values));
1074 storage->attrCache = tupleAttr;
1075 return ElaboratorValue(storage);
1078 FailureOr<ElaboratorValue>
convert(StructAttr structAttr) {
1079 SmallVector<ElaboratorValue> fields;
1080 for (
auto field : structAttr.getFields()) {
1081 auto converted =
convert(field);
1082 if (failed(converted))
1084 fields.push_back(*converted);
1086 auto *storage = internalizer.internalize<StructStorage>(
1087 structAttr.getType(), std::move(fields));
1088 storage->attrCache = structAttr;
1089 return ElaboratorValue(storage);
1092 FailureOr<ElaboratorValue>
convert(VariantAttr variantAttr) {
1093 auto payload =
convert(variantAttr.getPayload());
1094 if (failed(payload))
1096 auto *storage = internalizer.internalize<VariantStorage>(
1097 variantAttr.getType(), variantAttr.getConstructor(), *payload);
1098 storage->attrCache = variantAttr;
1099 return ElaboratorValue(storage);
1103 Internalizer &internalizer;
1109class ElaboratorValueToAttributeConverter {
1111 ElaboratorValueToAttributeConverter(MLIRContext *context)
1112 : context(context) {}
1116 TypedAttr
convert(
const ElaboratorValue &value) {
1118 [&](
auto val) -> TypedAttr {
1119 if constexpr (std::is_base_of_v<CachableStorage,
1120 std::remove_pointer_t<
1121 std::decay_t<
decltype(value)>>>) {
1123 return val->attrCache;
1131 TypedAttr visit(TypedAttr val) {
return val; }
1133 TypedAttr visit(
bool val) {
1134 return IntegerAttr::get(IntegerType::get(context, 1), val);
1137 TypedAttr visit(
size_t val) {
1138 return IntegerAttr::get(IndexType::get(context), val);
1141 TypedAttr visit(SetStorage *val) {
1142 DenseSet<TypedAttr> elements;
1143 for (
auto element : val->set) {
1144 auto converted =
convert(element);
1147 auto typedAttr = dyn_cast<TypedAttr>(converted);
1150 elements.insert(typedAttr);
1152 return SetAttr::get(cast<SetType>(val->type), &elements);
1155 TypedAttr visit(TupleStorage *val) {
1156 SmallVector<TypedAttr> elements;
1157 for (
auto element : val->values) {
1158 auto converted =
convert(element);
1161 auto typedAttr = dyn_cast<TypedAttr>(converted);
1164 elements.push_back(typedAttr);
1166 return TupleAttr::get(context, elements);
1169 TypedAttr visit(StructStorage *val) {
1170 SmallVector<TypedAttr> fields;
1171 for (
auto field : val->fields) {
1172 auto converted =
convert(field);
1175 fields.push_back(converted);
1177 return StructAttr::get(context, val->type, fields);
1180 TypedAttr visit(VariantStorage *val) {
1181 TypedAttr payload =
convert(val->payload);
1184 return VariantAttr::get(context, val->type, val->constructor, payload);
1190#define VISIT_UNSUPPORTED(STORAGETYPE) \
1192 TypedAttr visit(STORAGETYPE *val) { return {}; }
1210#undef VISIT_UNSUPPORTED
1225 SharedState(MLIRContext *ctxt, SymbolTable &table)
1226 : ctxt(ctxt), table(table) {}
1228 uint64_t createBoundaryToken() {
return nextBoundaryToken++; }
1233 Internalizer internalizer;
1234 DenseMap<MutStorage *, ElaboratorValue> mutableStore;
1237 uint64_t nextBoundaryToken = 1;
1242 explicit TestState(
unsigned seed) : rng(RngScope(seed)) {}
1249 std::pair<ContextResourceAttrInterface, ContextResourceAttrInterface>,
1260 Materializer(OpBuilder builder, TestState &testState,
1261 SharedState &sharedState,
1262 SmallVector<ElaboratorValue> &blockArgs)
1263 : builder(builder), rootBlock(builder.getBlock()), testState(testState),
1264 sharedState(sharedState), blockArgs(blockArgs),
1265 attrConverter(builder.getContext()) {}
1269 Value materialize(ElaboratorValue val, Location loc,
1270 function_ref<InFlightDiagnostic()> emitError) {
1271 auto iter = materializedValues.find(val);
1272 if (iter != materializedValues.end())
1273 return iter->second;
1275 LLVM_DEBUG(llvm::dbgs() <<
"Materializing " << val);
1277 if (
auto res = tryMaterializeAsConstant(val, loc))
1282 Value res = std::visit(
1284 if constexpr (std::is_base_of_v<IdentityValue,
1285 std::remove_pointer_t<
1286 std::decay_t<
decltype(value)>>>) {
1287 if (identityValueRoot.contains(value)) {
1289 bool &materialized =
1290 static_cast<IdentityValue *
>(value)->alreadyMaterialized;
1291 assert(!materialized &&
"must not already be materialized");
1292 materialized =
true;
1295 return visit(value, loc, emitError);
1298 Value arg = builder.getBlock()->addArgument(value->type, loc);
1299 blockArgs.push_back(val);
1300 blockArgTypes.push_back(arg.getType());
1301 materializedValues[val] = arg;
1305 return visit(value, loc, emitError);
1309 LLVM_DEBUG(llvm::dbgs() <<
" to\n" << res <<
"\n\n");
1314 bool isInPlace(Operation *op)
const {
1315 return builder.getBlock()->getParent() == op->getParentRegion();
1324 LogicalResult materialize(Operation *op,
1325 DenseMap<Value, ElaboratorValue> &state,
1326 bool forceClone =
false) {
1332 if (op->getNumRegions() > 0)
1333 return op->emitOpError(
"ops with nested regions must be elaborated away");
1337 for (
auto res : op->getResults())
1338 if (!res.use_empty() && !state.contains(res))
1339 return op->emitOpError(
1340 "ops with results that have uses are not supported");
1342 Operation *sourceOp = op;
1343 if (isInPlace(op) && !forceClone) {
1346 deleteOpsUntil([&](
auto iter) {
return &*iter == op; });
1348 if (builder.getInsertionPoint() == builder.getBlock()->end())
1349 return op->emitError(
"operation did not occur after the current "
1350 "materializer insertion point");
1352 LLVM_DEBUG(llvm::dbgs() <<
"Modifying in-place: " << *op <<
"\n\n");
1354 LLVM_DEBUG(llvm::dbgs() <<
"Materializing a clone of " << *op <<
"\n\n");
1355 op = builder.clone(*op);
1356 builder.setInsertionPoint(op);
1359 for (
auto &operand : op->getOpOperands()) {
1360 auto emitError = [&]() {
1361 auto diag = op->emitError();
1362 diag.attachNote(op->getLoc())
1363 <<
"while materializing value for operand#"
1364 << operand.getOperandNumber();
1368 auto elabVal = state.at(operand.get());
1369 Value val = materialize(elabVal, op->getLoc(), emitError);
1373 state[val] = elabVal;
1377 for (
auto [sourceResult, result] :
1378 llvm::zip_equal(sourceOp->getResults(), op->getResults()))
1379 if (
auto it = state.find(sourceResult); it != state.end())
1380 materializedValues[it->second] = result;
1382 builder.setInsertionPointAfter(op);
1389 deleteOpsUntil([](
auto iter) {
return false; });
1391 for (
auto *op : llvm::reverse(toDelete))
1398 void registerIdentityValue(IdentityValue *val) {
1399 identityValueRoot.insert(val);
1402 ArrayRef<Type> getBlockArgTypes()
const {
return blockArgTypes; }
1404 void map(ElaboratorValue eval, Value val) { materializedValues[eval] = val; }
1406 OpBuilder &getBuilder() {
return builder; }
1408 template <
typename OpTy,
typename... Args>
1409 OpTy create(Location location, Args &&...args) {
1410 return OpTy::create(builder, location, std::forward<Args>(args)...);
1414 Value tryMaterializeAsConstant(ElaboratorValue val, Location loc) {
1415 if (
auto attr = attrConverter.convert(val)) {
1420 OpBuilder::InsertionGuard guard(builder);
1421 if (builder.getBlock() != rootBlock)
1422 builder.setInsertionPointToStart(rootBlock);
1423 Value res = ConstantOp::create(builder, loc, attr);
1424 materializedValues[val] = res;
1431 SequenceOp elaborateSequence(
const RandomizedSequenceStorage *seq,
1432 SmallVector<ElaboratorValue> &elabArgs);
1434 void deleteOpsUntil(function_ref<
bool(Block::iterator)> stop) {
1435 auto ip = builder.getInsertionPoint();
1436 while (ip != builder.getBlock()->end() && !stop(ip)) {
1437 LLVM_DEBUG(llvm::dbgs() <<
"Marking to be deleted: " << *ip <<
"\n\n");
1438 toDelete.push_back(&*ip);
1440 builder.setInsertionPointAfter(&*ip);
1441 ip = builder.getInsertionPoint();
1445 Value visit(TypedAttr val, Location loc,
1446 function_ref<InFlightDiagnostic()> emitError) {
1450 Value visit(
size_t val, Location loc,
1451 function_ref<InFlightDiagnostic()> emitError) {
1455 Value visit(
bool val, Location loc,
1456 function_ref<InFlightDiagnostic()> emitError) {
1460 Value visit(ArrayStorage *val, Location loc,
1461 function_ref<InFlightDiagnostic()> emitError) {
1462 SmallVector<Value> elements;
1463 elements.reserve(val->array.size());
1464 for (
auto el : val->array) {
1465 auto materialized = materialize(el, loc, emitError);
1469 elements.push_back(materialized);
1472 Value res = ArrayCreateOp::create(builder, loc, val->type, elements);
1473 materializedValues[val] = res;
1477 Value visit(SetStorage *val, Location loc,
1478 function_ref<InFlightDiagnostic()> emitError) {
1479 SmallVector<Value> elements;
1480 elements.reserve(val->set.size());
1481 for (
auto el : val->set) {
1482 auto materialized = materialize(el, loc, emitError);
1486 elements.push_back(materialized);
1489 auto res = SetCreateOp::create(builder, loc, val->type, elements);
1490 materializedValues[val] = res;
1494 Value visit(BagStorage *val, Location loc,
1495 function_ref<InFlightDiagnostic()> emitError) {
1496 SmallVector<Value> values, weights;
1497 values.reserve(val->bag.size());
1498 weights.reserve(val->bag.size());
1499 for (
auto [val, weight] : val->bag) {
1500 auto materializedVal = materialize(val, loc, emitError);
1501 auto materializedWeight = materialize(weight, loc, emitError);
1502 if (!materializedVal || !materializedWeight)
1505 values.push_back(materializedVal);
1506 weights.push_back(materializedWeight);
1509 auto res = BagCreateOp::create(builder, loc, val->type, values, weights);
1510 materializedValues[val] = res;
1514 Value visit(MemoryBlockStorage *val, Location loc,
1515 function_ref<InFlightDiagnostic()> emitError) {
1516 auto intType = builder.getIntegerType(val->baseAddress.getBitWidth());
1517 Value res = MemoryBlockDeclareOp::create(
1518 builder, val->loc, val->type,
1519 IntegerAttr::get(intType, val->baseAddress),
1520 IntegerAttr::get(intType, val->endAddress));
1521 materializedValues[val] = res;
1525 Value visit(MemoryStorage *val, Location loc,
1526 function_ref<InFlightDiagnostic()> emitError) {
1527 auto memBlock = materialize(val->memoryBlock, val->loc, emitError);
1528 auto memSize = materialize(val->size, val->loc, emitError);
1529 auto memAlign = materialize(val->alignment, val->loc, emitError);
1530 if (!(memBlock && memSize && memAlign))
1534 MemoryAllocOp::create(builder, val->loc, memBlock, memSize, memAlign);
1535 materializedValues[val] = res;
1539 Value visit(SequenceStorage *val, Location loc,
1540 function_ref<InFlightDiagnostic()> emitError) {
1541 emitError() <<
"materializing a non-randomized sequence not supported yet";
1545 Value visit(RandomizedSequenceStorage *val, Location loc,
1546 function_ref<InFlightDiagnostic()> emitError) {
1552 SmallVector<ElaboratorValue> elabArgs;
1555 SequenceOp seqOp = elaborateSequence(val, elabArgs);
1561 SmallVector<Value> args;
1562 SmallVector<Type> argTypes;
1563 for (
auto arg : elabArgs) {
1564 Value materialized = materialize(arg, val->loc, emitError);
1568 args.push_back(materialized);
1569 argTypes.push_back(materialized.getType());
1572 Value res = GetSequenceOp::create(
1573 builder, val->loc, SequenceType::get(builder.getContext(), argTypes),
1574 seqOp.getSymName());
1579 res = SubstituteSequenceOp::create(builder, val->loc, res, args);
1581 res = RandomizeSequenceOp::create(builder, val->loc, res);
1583 materializedValues[val] = res;
1587 Value visit(InterleavedSequenceStorage *val, Location loc,
1588 function_ref<InFlightDiagnostic()> emitError) {
1589 SmallVector<Value> sequences;
1590 for (
auto seqVal : val->sequences) {
1591 Value materialized = materialize(seqVal, loc, emitError);
1595 sequences.push_back(materialized);
1598 if (sequences.size() == 1)
1599 return sequences[0];
1602 InterleaveSequencesOp::create(builder, loc, sequences, val->batchSize);
1603 materializedValues[val] = res;
1607 Value visit(VirtualRegisterStorage *val, Location loc,
1608 function_ref<InFlightDiagnostic()> emitError) {
1609 Value res = VirtualRegisterOp::create(builder, val->loc, val->allowedRegs);
1610 materializedValues[val] = res;
1614 Value visit(UniqueLabelStorage *val, Location loc,
1615 function_ref<InFlightDiagnostic()> emitError) {
1616 auto materialized = materialize(val->name, val->loc, emitError);
1619 Value res = LabelUniqueDeclOp::create(builder, val->loc, materialized);
1620 materializedValues[val] = res;
1624 Value visit(TupleStorage *val, Location loc,
1625 function_ref<InFlightDiagnostic()> emitError) {
1626 SmallVector<Value> materialized;
1627 materialized.reserve(val->values.size());
1628 for (
auto v : val->values) {
1629 Value value = materialize(v, loc, emitError);
1632 materialized.push_back(value);
1634 Value res = TupleCreateOp::create(builder, loc, materialized);
1635 materializedValues[val] = res;
1639 Value visit(StructStorage *val, Location loc,
1640 function_ref<InFlightDiagnostic()> emitError) {
1641 SmallVector<Value> fields;
1642 fields.reserve(val->fields.size());
1643 for (
auto field : val->fields) {
1644 Value value = materialize(field, loc, emitError);
1647 fields.push_back(value);
1649 Value res = StructCreateOp::create(builder, loc, val->type, fields);
1650 materializedValues[val] = res;
1654 Value visit(VariantStorage *val, Location loc,
1655 function_ref<InFlightDiagnostic()> emitError) {
1656 Value payload = materialize(val->payload, loc, emitError);
1660 VariantCreateOp::create(builder, loc, val->type, ValueRange{payload},
1661 val->constructor.getValue());
1662 materializedValues[val] = result;
1666 Value visit(MutStorage *val, Location loc,
1667 function_ref<InFlightDiagnostic()> emitError) {
1668 emitError() <<
"mutable cell cannot escape into materialized IR";
1672 Value visit(ContinuationStorage *val, Location loc,
1673 function_ref<InFlightDiagnostic()> emitError) {
1674 emitError() <<
"continuation cannot escape through materialized IR, "
1675 "a sequence, or an opaque external-region shell";
1679 Value visit(SymbolicComputationWithIdentityValue *val, Location loc,
1680 function_ref<InFlightDiagnostic()> emitError) {
1681 auto *noConstStorage =
1682 const_cast<SymbolicComputationWithIdentityStorage *
>(val->storage);
1683 auto res0 = materialize(noConstStorage, loc, emitError);
1687 auto *op = res0.getDefiningOp();
1688 auto res = op->getResults()[val->idx];
1689 materializedValues[val] = res;
1693 Value visit(SymbolicComputationWithIdentityStorage *val, Location loc,
1694 function_ref<InFlightDiagnostic()> emitError) {
1695 SmallVector<Value> operands;
1696 for (
auto operand : val->operands) {
1697 auto materialized = materialize(operand, val->loc, emitError);
1701 operands.push_back(materialized);
1704 OperationState state(val->loc, val->name);
1705 state.addTypes(val->resultTypes);
1706 state.attributes = val->attributes;
1707 state.propertiesAttr = val->properties;
1708 state.addOperands(operands);
1709 auto *op = builder.create(state);
1711 materializedValues[val] = op->getResult(0);
1712 return op->getResult(0);
1715 Value visit(SymbolicComputationStorage *val, Location loc,
1716 function_ref<InFlightDiagnostic()> emitError) {
1717 SmallVector<Value> operands;
1718 for (
auto operand : val->operands) {
1719 auto materialized = materialize(operand, loc, emitError);
1723 operands.push_back(materialized);
1726 OperationState state(loc, val->name);
1727 state.addTypes(val->resultTypes);
1728 state.attributes = val->attributes;
1729 state.propertiesAttr = val->properties;
1730 state.addOperands(operands);
1731 auto *op = builder.create(state);
1733 for (
auto res : op->getResults())
1734 materializedValues[val] = res;
1736 return op->getResult(0);
1739 Value visit(OpaqueExternalStorage *val, Location loc,
1740 function_ref<InFlightDiagnostic()> emitError) {
1745 emitError() <<
"cannot materialize opaque external value";
1755 DenseMap<ElaboratorValue, Value> materializedValues;
1765 SmallVector<Operation *> toDelete;
1767 TestState &testState;
1768 SharedState &sharedState;
1773 SmallVector<ElaboratorValue> &blockArgs;
1774 SmallVector<Type> blockArgTypes;
1779 DenseSet<IdentityValue *> identityValueRoot;
1782 ElaboratorValueToAttributeConverter attrConverter;
1791enum class DeletionKind { Keep,
Delete };
1795struct ControlTransfer {
1801class Elaborator :
public RTGOpVisitor<Elaborator, FailureOr<DeletionKind>> {
1803 using RTGBase = RTGOpVisitor<Elaborator, FailureOr<DeletionKind>>;
1804 using RTGBase::visitOp;
1806 Elaborator(SharedState &sharedState, TestState &testState,
1807 Materializer &materializer,
1808 ContextResourceAttrInterface currentContext = {},
1809 uint64_t sequenceBoundaryToken = 0)
1810 : sharedState(sharedState), testState(testState),
1811 materializer(materializer), currentContext(currentContext),
1812 sequenceBoundaryToken(sequenceBoundaryToken),
1813 elaboratorBoundaryToken(sharedState.createBoundaryToken()),
1814 attrConverter(sharedState.internalizer),
1815 elabValConverter(sharedState.ctxt) {}
1817 template <
typename ValueTy>
1818 inline ValueTy
get(Value val)
const {
1819 return std::get<ValueTy>(state.at(val));
1823 FailureOr<DeletionKind> visitUnhandledOp(Operation *op) {
1824 return visitOpGeneric(op);
1827 FailureOr<DeletionKind> visitExternalOp(Operation *op) {
1828 if (op->getNumRegions() == 0)
1829 return visitOpGeneric(op);
1830 return op->emitOpError(
1831 "region-bearing operations must be scheduled by the evaluator");
1834 FailureOr<DeletionKind> visitOp(GetSequenceOp op) {
1835 SmallVector<ElaboratorValue> replacements;
1836 state[op.getResult()] =
1837 sharedState.internalizer.internalize<SequenceStorage>(
1838 op.getSequenceAttr().getAttr(), std::move(replacements));
1839 return DeletionKind::Delete;
1842 FailureOr<DeletionKind> visitOp(SubstituteSequenceOp op) {
1843 if (isSymbolic(state.at(op.getSequence())))
1844 return visitOpGeneric(op);
1846 auto *seq = get<SequenceStorage *>(op.getSequence());
1848 SmallVector<ElaboratorValue> replacements(seq->args);
1849 for (
auto replacement : op.getReplacements())
1850 replacements.push_back(state.at(replacement));
1852 state[op.getResult()] =
1853 sharedState.internalizer.internalize<SequenceStorage>(
1854 seq->familyName, std::move(replacements));
1856 return DeletionKind::Delete;
1859 FailureOr<DeletionKind> visitOp(RandomizeSequenceOp op) {
1860 auto *seq = get<SequenceStorage *>(op.getSequence());
1861 auto *randomizedSeq =
1862 sharedState.internalizer.create<RandomizedSequenceStorage>(
1863 currentContext, seq, op.getLoc());
1864 materializer.registerIdentityValue(randomizedSeq);
1865 state[op.getResult()] =
1866 sharedState.internalizer.internalize<InterleavedSequenceStorage>(
1868 return DeletionKind::Delete;
1871 FailureOr<DeletionKind> visitOp(InterleaveSequencesOp op) {
1872 SmallVector<ElaboratorValue> sequences;
1873 for (
auto seq : op.getSequences())
1874 sequences.push_back(state.at(seq));
1876 state[op.getResult()] =
1877 sharedState.internalizer.internalize<InterleavedSequenceStorage>(
1878 std::move(sequences), op.getBatchSize());
1879 return DeletionKind::Delete;
1883 LogicalResult isValidContext(ElaboratorValue value, Operation *op)
const {
1884 if (std::holds_alternative<RandomizedSequenceStorage *>(value)) {
1885 auto *seq = std::get<RandomizedSequenceStorage *>(value);
1886 if (seq->context != currentContext) {
1887 auto err = op->emitError(
"attempting to place sequence derived from ")
1888 << seq->sequence->familyName.getValue() <<
" under context "
1890 <<
", but it was previously randomized for context ";
1892 err << seq->context;
1900 auto *interVal = std::get<InterleavedSequenceStorage *>(value);
1901 for (
auto val : interVal->sequences)
1902 if (failed(isValidContext(val, op)))
1907 FailureOr<DeletionKind> visitOp(EmbedSequenceOp op) {
1908 auto *seqVal = get<InterleavedSequenceStorage *>(op.getSequence());
1909 if (failed(isValidContext(seqVal, op)))
1912 return DeletionKind::Keep;
1915 FailureOr<DeletionKind> visitOp(SetCreateOp op) {
1916 SetVector<ElaboratorValue> set;
1917 for (
auto val : op.getElements())
1918 set.insert(state.at(val));
1920 state[op.getSet()] = sharedState.internalizer.internalize<SetStorage>(
1921 std::move(set), op.getSet().getType());
1922 return DeletionKind::Delete;
1925 FailureOr<DeletionKind> visitOp(SetSelectRandomOp op) {
1926 auto set = get<SetStorage *>(op.getSet())->set;
1929 return op->emitError(
"cannot select from an empty set");
1931 size_t selected = testState.rng.getUniformlyInRange(0, set.size() - 1);
1932 state[op.getResult()] = set[selected];
1933 return DeletionKind::Delete;
1936 FailureOr<DeletionKind> visitOp(SetDifferenceOp op) {
1937 auto original = get<SetStorage *>(op.getOriginal())->set;
1938 auto diff = get<SetStorage *>(op.getDiff())->set;
1940 SetVector<ElaboratorValue> result(original);
1941 result.set_subtract(diff);
1943 state[op.getResult()] = sharedState.internalizer.internalize<SetStorage>(
1944 std::move(result), op.getResult().getType());
1945 return DeletionKind::Delete;
1948 FailureOr<DeletionKind> visitOp(SetUnionOp op) {
1949 SetVector<ElaboratorValue> result;
1950 for (
auto set : op.getSets())
1951 result.set_union(get<SetStorage *>(set)->set);
1953 state[op.getResult()] = sharedState.internalizer.internalize<SetStorage>(
1954 std::move(result), op.getType());
1955 return DeletionKind::Delete;
1958 FailureOr<DeletionKind> visitOp(SetSizeOp op) {
1959 auto size = get<SetStorage *>(op.getSet())->set.size();
1960 state[op.getResult()] = size;
1961 return DeletionKind::Delete;
1967 FailureOr<DeletionKind> visitOp(SetCartesianProductOp op) {
1968 SetVector<ElaboratorValue> result;
1969 SmallVector<SmallVector<ElaboratorValue>> tuples;
1970 tuples.push_back({});
1972 for (
auto input : op.getInputs()) {
1973 auto &set = get<SetStorage *>(input)->set;
1975 SetVector<ElaboratorValue>
empty;
1976 state[op.getResult()] =
1977 sharedState.internalizer.internalize<SetStorage>(std::move(
empty),
1979 return DeletionKind::Delete;
1982 for (
unsigned i = 0, e = tuples.size(); i < e; ++i) {
1983 for (
auto setEl : set.getArrayRef().drop_back()) {
1984 tuples.push_back(tuples[i]);
1985 tuples.back().push_back(setEl);
1987 tuples[i].push_back(set.back());
1991 for (
auto &tup : tuples)
1993 sharedState.internalizer.internalize<TupleStorage>(std::move(tup)));
1995 state[op.getResult()] = sharedState.internalizer.internalize<SetStorage>(
1996 std::move(result), op.getType());
1997 return DeletionKind::Delete;
2000 FailureOr<DeletionKind> visitOp(SetConvertToBagOp op) {
2001 auto set = get<SetStorage *>(op.getInput())->set;
2002 MapVector<ElaboratorValue, uint64_t> bag;
2003 for (
auto val : set)
2004 bag.insert({val, 1});
2005 state[op.getResult()] = sharedState.internalizer.internalize<BagStorage>(
2006 std::move(bag), op.getType());
2007 return DeletionKind::Delete;
2010 FailureOr<DeletionKind> visitOp(BagCreateOp op) {
2011 MapVector<ElaboratorValue, uint64_t> bag;
2012 for (
auto [val, multiple] :
2013 llvm::zip(op.getElements(), op.getMultiples())) {
2017 bag[state.at(val)] += get<size_t>(multiple);
2020 state[op.getBag()] = sharedState.internalizer.internalize<BagStorage>(
2021 std::move(bag), op.getType());
2022 return DeletionKind::Delete;
2025 FailureOr<DeletionKind> visitOp(BagSelectRandomOp op) {
2026 auto bag = get<BagStorage *>(op.getBag())->bag;
2029 return op->emitError(
"cannot select from an empty bag");
2031 SmallVector<std::pair<ElaboratorValue, uint32_t>> prefixSum;
2032 prefixSum.reserve(bag.size());
2033 uint32_t accumulator = 0;
2034 for (
auto [val, weight] : bag) {
2035 accumulator += weight;
2036 prefixSum.push_back({val, accumulator});
2039 auto idx = testState.rng.getUniformlyInRange(0, accumulator - 1);
2040 auto *iter = llvm::upper_bound(
2042 [](uint32_t a,
const std::pair<ElaboratorValue, uint32_t> &b) {
2043 return a < b.second;
2046 state[op.getResult()] = iter->first;
2047 return DeletionKind::Delete;
2050 FailureOr<DeletionKind> visitOp(BagDifferenceOp op) {
2051 auto original = get<BagStorage *>(op.getOriginal())->bag;
2052 auto diff = get<BagStorage *>(op.getDiff())->bag;
2054 MapVector<ElaboratorValue, uint64_t> result;
2055 for (
const auto &el : original) {
2056 if (!diff.contains(el.first)) {
2064 auto toDiff = diff.lookup(el.first);
2065 if (el.second <= toDiff)
2068 result.insert({el.first, el.second - toDiff});
2071 state[op.getResult()] = sharedState.internalizer.internalize<BagStorage>(
2072 std::move(result), op.getType());
2073 return DeletionKind::Delete;
2076 FailureOr<DeletionKind> visitOp(BagUnionOp op) {
2077 MapVector<ElaboratorValue, uint64_t> result;
2078 for (
auto bag : op.getBags()) {
2079 auto val = get<BagStorage *>(bag)->bag;
2080 for (
auto [el, multiple] : val)
2081 result[el] += multiple;
2084 state[op.getResult()] = sharedState.internalizer.internalize<BagStorage>(
2085 std::move(result), op.getType());
2086 return DeletionKind::Delete;
2089 FailureOr<DeletionKind> visitOp(BagUniqueSizeOp op) {
2090 auto size = get<BagStorage *>(op.getBag())->bag.size();
2091 state[op.getResult()] = size;
2092 return DeletionKind::Delete;
2095 FailureOr<DeletionKind> visitOp(BagConvertToSetOp op) {
2096 auto bag = get<BagStorage *>(op.getInput())->bag;
2097 SetVector<ElaboratorValue> set;
2098 for (
auto [k, v] : bag)
2100 state[op.getResult()] = sharedState.internalizer.internalize<SetStorage>(
2101 std::move(set), op.getType());
2102 return DeletionKind::Delete;
2105 FailureOr<DeletionKind> visitOp(VirtualRegisterOp op) {
2106 auto *val = sharedState.internalizer.create<VirtualRegisterStorage>(
2107 op.getAllowedRegsAttr(), op.getType(), op.getLoc());
2108 state[op.getResult()] = val;
2109 materializer.registerIdentityValue(val);
2110 return DeletionKind::Delete;
2113 FailureOr<DeletionKind> visitOp(ArrayCreateOp op) {
2114 SmallVector<ElaboratorValue> array;
2115 array.reserve(op.getElements().size());
2116 for (
auto val : op.getElements())
2117 array.emplace_back(state.at(val));
2119 state[op.getResult()] = sharedState.internalizer.internalize<ArrayStorage>(
2120 op.getResult().getType(), std::move(array));
2121 return DeletionKind::Delete;
2124 FailureOr<DeletionKind> visitOp(StringToASCIIArrayOp op) {
2125 auto opaque = state.at(op.getString());
2126 if (isSymbolic(opaque))
2127 return visitOpGeneric(op);
2129 auto strAttr = dyn_cast<StringAttr>(std::get<TypedAttr>(opaque));
2131 return op->emitError(
"expected a string attribute");
2133 auto i8Ty = IntegerType::get(op.getContext(), 8);
2134 SmallVector<ElaboratorValue> array;
2135 array.reserve(strAttr.getValue().size());
2136 for (
unsigned char c : strAttr.getValue())
2137 array.push_back(ElaboratorValue(IntegerAttr::get(i8Ty, c)));
2139 state[op.getResult()] = sharedState.internalizer.internalize<ArrayStorage>(
2140 op.getResult().getType(), std::move(array));
2141 return DeletionKind::Delete;
2144 FailureOr<DeletionKind> visitOp(ArrayExtractOp op) {
2145 auto array = get<ArrayStorage *>(op.getArray())->array;
2146 size_t idx = get<size_t>(op.getIndex());
2148 if (array.size() <= idx)
2149 return op->emitError(
"invalid to access index ")
2150 << idx <<
" of an array with " << array.size() <<
" elements";
2152 state[op.getResult()] = array[idx];
2153 return DeletionKind::Delete;
2156 FailureOr<DeletionKind> visitOp(ArrayInjectOp op) {
2157 auto arrayOpaque = state.at(op.getArray());
2158 auto idxOpaque = state.at(op.getIndex());
2159 if (isSymbolic(arrayOpaque) || isSymbolic(idxOpaque))
2160 return visitOpGeneric(op);
2162 auto array = std::get<ArrayStorage *>(arrayOpaque)->array;
2163 size_t idx = std::get<size_t>(idxOpaque);
2165 if (array.size() <= idx)
2166 return op->emitError(
"invalid to access index ")
2167 << idx <<
" of an array with " << array.size() <<
" elements";
2169 array[idx] = state.at(op.getValue());
2170 state[op.getResult()] = sharedState.internalizer.internalize<ArrayStorage>(
2171 op.getResult().getType(), std::move(array));
2172 return DeletionKind::Delete;
2175 FailureOr<DeletionKind> visitOp(ArrayAppendOp op) {
2176 auto array = std::get<ArrayStorage *>(state.at(op.getArray()))->array;
2177 array.push_back(state.at(op.getElement()));
2178 state[op.getResult()] = sharedState.internalizer.internalize<ArrayStorage>(
2179 op.getResult().getType(), std::move(array));
2180 return DeletionKind::Delete;
2183 FailureOr<DeletionKind> visitOp(ArraySizeOp op) {
2184 auto array = get<ArrayStorage *>(op.getArray())->array;
2185 state[op.getResult()] = array.size();
2186 return DeletionKind::Delete;
2189 FailureOr<DeletionKind> visitOp(LabelUniqueDeclOp op) {
2190 auto *val = sharedState.internalizer.create<UniqueLabelStorage>(
2191 state.at(op.getNamePrefix()), op.getLoc());
2192 state[op.getLabel()] = val;
2193 materializer.registerIdentityValue(val);
2194 return DeletionKind::Delete;
2197 FailureOr<DeletionKind> visitOp(RandomScopeOp op) {
2198 return op->emitOpError(
"random_scope must be scheduled by the evaluator");
2201 FailureOr<DeletionKind> visitOp(RandomNumberInRangeOp op) {
2202 size_t lower = get<size_t>(op.getLowerBound());
2203 size_t upper = get<size_t>(op.getUpperBound());
2205 return op->emitError(
"cannot select a number from an empty range");
2207 state[op.getResult()] =
2208 size_t(testState.rng.getUniformlyInRange(lower, upper));
2209 return DeletionKind::Delete;
2212 FailureOr<DeletionKind> visitOp(IntToImmediateOp op) {
2213 size_t input = get<size_t>(op.getInput());
2214 auto width = op.getType().getWidth();
2215 auto emitError = [&]() {
return op->emitError(); };
2216 if (input > APInt::getAllOnes(width).getZExtValue())
2217 return emitError() <<
"cannot represent " << input <<
" with " << width
2220 state[op.getResult()] =
2221 IntegerAttr::get(IntegerType::get(op.getContext(), width), input);
2222 return DeletionKind::Delete;
2225 FailureOr<DeletionKind> visitOp(OnContextOp op) {
2226 ContextResourceAttrInterface from = currentContext,
2227 to = cast<ContextResourceAttrInterface>(
2228 get<TypedAttr>(op.getContext()));
2229 if (!currentContext)
2230 from = DefaultContextAttr::get(op->getContext(), to.getType());
2232 auto emitError = [&]() {
2233 auto diag = op.emitError();
2234 diag.attachNote(op.getLoc())
2235 <<
"while materializing value for context switching for " << op;
2240 Value seqVal = materializer.materialize(
2241 get<SequenceStorage *>(op.getSequence()), op.getLoc(), emitError);
2246 materializer.create<RandomizeSequenceOp>(op.getLoc(), seqVal);
2247 materializer.create<EmbedSequenceOp>(op.getLoc(), randSeqVal);
2248 return DeletionKind::Delete;
2254 auto *iter = testState.contextSwitches.find({from, to});
2257 if (iter == testState.contextSwitches.end())
2258 iter = testState.contextSwitches.find(
2259 {from, AnyContextAttr::get(op->getContext(), to.getType())});
2262 if (iter == testState.contextSwitches.end())
2263 iter = testState.contextSwitches.find(
2264 {AnyContextAttr::get(op->getContext(), from.getType()), to});
2267 if (iter == testState.contextSwitches.end())
2268 iter = testState.contextSwitches.find(
2269 {AnyContextAttr::get(op->getContext(), from.getType()),
2270 AnyContextAttr::get(op->getContext(), to.getType())});
2276 if (iter == testState.contextSwitches.end())
2277 return op->emitError(
"no context transition registered to switch from ")
2278 << from <<
" to " << to;
2280 auto familyName = iter->second->familyName;
2281 SmallVector<ElaboratorValue> args{from, to,
2282 get<SequenceStorage *>(op.getSequence())};
2283 auto *seq = sharedState.internalizer.internalize<SequenceStorage>(
2284 familyName, std::move(args));
2285 auto *randSeq = sharedState.internalizer.create<RandomizedSequenceStorage>(
2286 to, seq, op.getLoc());
2287 materializer.registerIdentityValue(randSeq);
2288 Value seqVal = materializer.materialize(randSeq, op.getLoc(), emitError);
2292 materializer.create<EmbedSequenceOp>(op.getLoc(), seqVal);
2293 return DeletionKind::Delete;
2296 FailureOr<DeletionKind> visitOp(ContextSwitchOp op) {
2297 testState.contextSwitches[{op.getFromAttr(), op.getToAttr()}] =
2298 get<SequenceStorage *>(op.getSequence());
2299 return DeletionKind::Delete;
2302 FailureOr<DeletionKind> visitOp(MemoryBlockDeclareOp op) {
2303 auto *val = sharedState.internalizer.create<MemoryBlockStorage>(
2304 op.getBaseAddress(), op.getEndAddress(), op.getType(), op.getLoc());
2305 state[op.getResult()] = val;
2306 materializer.registerIdentityValue(val);
2307 return DeletionKind::Delete;
2310 FailureOr<DeletionKind> visitOp(MemoryAllocOp op) {
2311 size_t size = get<size_t>(op.getSize());
2312 size_t alignment = get<size_t>(op.getAlignment());
2313 auto *memBlock = get<MemoryBlockStorage *>(op.getMemoryBlock());
2314 auto *val = sharedState.internalizer.create<MemoryStorage>(
2315 memBlock, size, alignment, op.getLoc());
2316 state[op.getResult()] = val;
2317 materializer.registerIdentityValue(val);
2318 return DeletionKind::Delete;
2321 FailureOr<DeletionKind> visitOp(MemorySizeOp op) {
2322 auto *memory = get<MemoryStorage *>(op.getMemory());
2323 state[op.getResult()] = memory->size;
2324 return DeletionKind::Delete;
2330 FailureOr<DeletionKind> visitOp(MutCreateOp op) {
2331 auto *mut = sharedState.internalizer.create<MutStorage>(
2332 op.getRef().getType(), op.getLoc(),
2333 ContinuationBoundary{sequenceBoundaryToken, externalRegionStack,
2334 elaboratorBoundaryToken});
2335 sharedState.mutableStore[mut] = state.at(op.getInitialValue());
2336 state[op.getRef()] = mut;
2337 materializer.registerIdentityValue(mut);
2338 return DeletionKind::Delete;
2341 FailureOr<MutStorage *> getMutableCell(Value ref, Operation *op) {
2342 auto it = state.find(ref);
2343 if (it == state.end())
2344 return op->emitOpError(
"mutable reference has no elaborated value");
2346 auto *mut = std::get_if<MutStorage *>(&it->second);
2347 if (!mut || !*mut || !sharedState.mutableStore.contains(*mut))
2348 return op->emitOpError(
"invalid mutable cell reference");
2353 void collectContinuations(ElaboratorValue value,
2354 SmallVectorImpl<ContinuationStorage *> &result,
2355 SmallPtrSetImpl<const void *> &visited)
const {
2356 if (
auto *continuation = std::get_if<ContinuationStorage *>(&value)) {
2357 result.push_back(*continuation);
2361 if (
auto *mut = std::get_if<MutStorage *>(&value)) {
2362 if (!visited.insert(*mut).second)
2364 auto it = sharedState.mutableStore.find(*mut);
2365 if (it != sharedState.mutableStore.end())
2366 collectContinuations(it->second, result, visited);
2370 auto collectRange = [&](
auto &&range) {
2371 for (
auto nested : range)
2372 collectContinuations(nested, result, visited);
2374 if (
auto *set = std::get_if<SetStorage *>(&value)) {
2375 if (visited.insert(*set).second)
2376 collectRange((*set)->set);
2377 }
else if (
auto *bag = std::get_if<BagStorage *>(&value)) {
2378 if (visited.insert(*bag).second)
2379 for (
const auto &entry : (*bag)->bag)
2380 collectContinuations(entry.first, result, visited);
2381 }
else if (
auto *array = std::get_if<ArrayStorage *>(&value)) {
2382 if (visited.insert(*array).second)
2383 collectRange((*array)->array);
2384 }
else if (
auto *tuple = std::get_if<TupleStorage *>(&value)) {
2385 if (visited.insert(*tuple).second)
2386 collectRange((*tuple)->values);
2387 }
else if (
auto *structure = std::get_if<StructStorage *>(&value)) {
2388 if (visited.insert(*structure).second)
2389 collectRange((*structure)->fields);
2390 }
else if (
auto *variant = std::get_if<VariantStorage *>(&value)) {
2391 if (visited.insert(*variant).second)
2392 collectContinuations((*variant)->payload, result, visited);
2393 }
else if (
auto *symbolic =
2394 std::get_if<SymbolicComputationStorage *>(&value)) {
2395 if (visited.insert(*symbolic).second)
2396 collectRange((*symbolic)->operands);
2397 }
else if (
auto *symbolic =
2398 std::get_if<SymbolicComputationWithIdentityStorage *>(
2400 if (visited.insert(*symbolic).second)
2401 collectRange((*symbolic)->operands);
2402 }
else if (
auto *symbolic =
2403 std::get_if<SymbolicComputationWithIdentityValue *>(
2405 if (visited.insert(*symbolic).second)
2406 collectRange((*symbolic)->storage->operands);
2410 FailureOr<DeletionKind> visitOp(MutReadOp op) {
2411 auto mut = getMutableCell(op.getRef(), op);
2414 state[op.getValue()] = sharedState.mutableStore.at(*mut);
2415 return DeletionKind::Delete;
2418 FailureOr<DeletionKind> visitOp(MutWriteOp op) {
2419 auto mut = getMutableCell(op.getRef(), op);
2423 SmallVector<ContinuationStorage *> continuations;
2424 SmallPtrSet<const void *, 16> visited;
2425 collectContinuations(state.at(op.getNewValue()), continuations, visited);
2426 for (
auto *continuation : continuations) {
2427 if (continuation->boundary.sequence != (*mut)->boundary.sequence)
2428 return op->emitOpError(
"continuation cannot escape a sequence boundary "
2429 "through mutable storage");
2430 if (continuation->boundary.elaborator != (*mut)->boundary.elaborator)
2431 return op->emitOpError(
2432 "continuation cannot escape its elaborator invocation through "
2434 if (!llvm::equal(continuation->boundary.externalRegions,
2435 (*mut)->boundary.externalRegions))
2436 return op->emitOpError(
"continuation cannot escape an opaque "
2437 "external-region shell through mutable storage");
2440 sharedState.mutableStore[*mut] = state.at(op.getNewValue());
2441 return DeletionKind::Delete;
2447 FailureOr<DeletionKind> visitOp(EffectOp op) {
return DeletionKind::Keep; }
2449 FailureOr<DeletionKind> visitOp(WithHandlersOp op) {
2450 return op->emitOpError(
"with_handlers must be scheduled by the evaluator");
2453 FailureOr<DeletionKind> visitOp(PerformOp op) {
2454 return op->emitOpError(
"perform must return a control transfer");
2457 FailureOr<DeletionKind> visitOp(ResumeOp op) {
2458 return op->emitOpError(
"resume must be scheduled by the evaluator");
2463 FailureOr<DeletionKind> visitOp(TupleCreateOp op) {
2464 SmallVector<ElaboratorValue> values;
2465 values.reserve(op.getElements().size());
2466 for (
auto el : op.getElements())
2467 values.push_back(state.at(el));
2469 state[op.getResult()] =
2470 sharedState.internalizer.internalize<TupleStorage>(std::move(values));
2471 return DeletionKind::Delete;
2474 FailureOr<DeletionKind> visitOp(TupleExtractOp op) {
2475 auto *tuple = get<TupleStorage *>(op.getTuple());
2476 state[op.getResult()] = tuple->values[op.getIndex().getZExtValue()];
2477 return DeletionKind::Delete;
2480 FailureOr<DeletionKind> visitOp(StructCreateOp op) {
2481 SmallVector<ElaboratorValue> fields;
2482 fields.reserve(op.getFields().size());
2483 for (Value field : op.getFields())
2484 fields.push_back(state.at(field));
2485 state[op.getResult()] = sharedState.internalizer.internalize<StructStorage>(
2486 op.getResult().getType(), std::move(fields));
2487 return DeletionKind::Delete;
2490 FailureOr<DeletionKind> visitOp(StructExtractOp op) {
2491 auto *structure = get<StructStorage *>(op.getValue());
2492 auto declaration = SymbolTable::lookupNearestSymbolFrom<StructDeclOp>(
2493 op, structure->type.getDeclaration());
2495 return op.emitOpError(
"references an unknown struct declaration");
2496 auto index = declaration.getFieldIndex(op.getFieldNameAttr().getValue());
2498 return op.emitOpError() <<
"field '" << op.getFieldNameAttr().getValue()
2499 <<
"' is not declared by " << structure->type;
2500 state[op.getResult()] = structure->fields[*index];
2501 return DeletionKind::Delete;
2504 FailureOr<DeletionKind> visitOp(VariantCreateOp op) {
2505 auto type = op.getResult().getType();
2506 ElaboratorValue payload;
2507 if (op.getPayload().empty())
2508 payload = sharedState.internalizer.internalize<TupleStorage>(
2509 SmallVector<ElaboratorValue>{});
2511 payload = state.at(op.getPayload().front());
2512 state[op.getResult()] =
2513 sharedState.internalizer.internalize<VariantStorage>(
2514 type, op.getConstructorAttr(), payload);
2515 return DeletionKind::Delete;
2518 FailureOr<DeletionKind> visitOp(scf::IfOp op) {
2519 return op->emitOpError(
"scf.if must be scheduled by the evaluator");
2522 FailureOr<DeletionKind> visitOp(scf::ForOp op) {
2523 return op->emitOpError(
"scf.for must be scheduled by the evaluator");
2526 FailureOr<DeletionKind> visitOp(arith::AddIOp op) {
2527 if (!isa<IndexType>(op.getType()))
2528 return visitOpGeneric(op);
2530 size_t lhs = get<size_t>(op.getLhs());
2531 size_t rhs = get<size_t>(op.getRhs());
2532 state[op.getResult()] = lhs + rhs;
2533 return DeletionKind::Delete;
2536 FailureOr<DeletionKind> visitOp(arith::AndIOp op) {
2537 if (!op.getType().isSignlessInteger(1))
2538 return visitOpGeneric(op);
2540 bool lhs = get<bool>(op.getLhs());
2541 bool rhs = get<bool>(op.getRhs());
2542 state[op.getResult()] = lhs && rhs;
2543 return DeletionKind::Delete;
2546 FailureOr<DeletionKind> visitOp(arith::XOrIOp op) {
2547 if (!op.getType().isSignlessInteger(1))
2548 return visitOpGeneric(op);
2550 bool lhs = get<bool>(op.getLhs());
2551 bool rhs = get<bool>(op.getRhs());
2552 state[op.getResult()] = lhs != rhs;
2553 return DeletionKind::Delete;
2556 FailureOr<DeletionKind> visitOp(arith::OrIOp op) {
2557 if (!op.getType().isSignlessInteger(1))
2558 return visitOpGeneric(op);
2560 bool lhs = get<bool>(op.getLhs());
2561 bool rhs = get<bool>(op.getRhs());
2562 state[op.getResult()] = lhs || rhs;
2563 return DeletionKind::Delete;
2566 FailureOr<DeletionKind> visitOp(arith::SelectOp op) {
2567 auto condOpaque = state.at(op.getCondition());
2568 if (isSymbolic(condOpaque))
2569 return visitOpGeneric(op);
2571 bool cond = std::get<bool>(condOpaque);
2572 auto trueVal = state.at(op.getTrueValue());
2573 auto falseVal = state.at(op.getFalseValue());
2574 state[op.getResult()] = cond ? trueVal : falseVal;
2575 return DeletionKind::Delete;
2578 FailureOr<DeletionKind> visitOp(index::AddOp op) {
2579 size_t lhs = get<size_t>(op.getLhs());
2580 size_t rhs = get<size_t>(op.getRhs());
2581 state[op.getResult()] = lhs + rhs;
2582 return DeletionKind::Delete;
2585 FailureOr<DeletionKind> visitOp(index::SubOp op) {
2586 size_t lhs = get<size_t>(op.getLhs());
2587 size_t rhs = get<size_t>(op.getRhs());
2588 state[op.getResult()] = lhs - rhs;
2589 return DeletionKind::Delete;
2592 FailureOr<DeletionKind> visitOp(index::MulOp op) {
2593 size_t lhs = get<size_t>(op.getLhs());
2594 size_t rhs = get<size_t>(op.getRhs());
2595 state[op.getResult()] = lhs * rhs;
2596 return DeletionKind::Delete;
2599 FailureOr<DeletionKind> visitOp(index::DivUOp op) {
2600 size_t lhs = get<size_t>(op.getLhs());
2601 size_t rhs = get<size_t>(op.getRhs());
2604 return op->emitOpError(
"attempted division by zero");
2606 state[op.getResult()] = lhs / rhs;
2607 return DeletionKind::Delete;
2610 FailureOr<DeletionKind> visitOp(index::CeilDivUOp op) {
2611 size_t lhs = get<size_t>(op.getLhs());
2612 size_t rhs = get<size_t>(op.getRhs());
2615 return op->emitOpError(
"attempted division by zero");
2618 state[op.getResult()] = (lhs + rhs - 1) / rhs;
2620 state[op.getResult()] = 1 + ((lhs - 1) / rhs);
2622 return DeletionKind::Delete;
2625 FailureOr<DeletionKind> visitOp(index::RemUOp op) {
2626 size_t lhs = get<size_t>(op.getLhs());
2627 size_t rhs = get<size_t>(op.getRhs());
2630 return op->emitOpError(
"attempted division by zero");
2632 state[op.getResult()] = lhs % rhs;
2633 return DeletionKind::Delete;
2636 FailureOr<DeletionKind> visitOp(index::AndOp op) {
2637 size_t lhs = get<size_t>(op.getLhs());
2638 size_t rhs = get<size_t>(op.getRhs());
2639 state[op.getResult()] = lhs & rhs;
2640 return DeletionKind::Delete;
2643 FailureOr<DeletionKind> visitOp(index::OrOp op) {
2644 size_t lhs = get<size_t>(op.getLhs());
2645 size_t rhs = get<size_t>(op.getRhs());
2646 state[op.getResult()] = lhs | rhs;
2647 return DeletionKind::Delete;
2650 FailureOr<DeletionKind> visitOp(index::XOrOp op) {
2651 size_t lhs = get<size_t>(op.getLhs());
2652 size_t rhs = get<size_t>(op.getRhs());
2653 state[op.getResult()] = lhs ^ rhs;
2654 return DeletionKind::Delete;
2657 FailureOr<DeletionKind> visitOp(index::ShlOp op) {
2658 size_t lhs = get<size_t>(op.getLhs());
2659 size_t rhs = get<size_t>(op.getRhs());
2660 state[op.getResult()] = lhs << rhs;
2661 return DeletionKind::Delete;
2664 FailureOr<DeletionKind> visitOp(index::ShrUOp op) {
2665 size_t lhs = get<size_t>(op.getLhs());
2666 size_t rhs = get<size_t>(op.getRhs());
2667 state[op.getResult()] = lhs >> rhs;
2668 return DeletionKind::Delete;
2671 FailureOr<DeletionKind> visitOp(index::MaxUOp op) {
2672 size_t lhs = get<size_t>(op.getLhs());
2673 size_t rhs = get<size_t>(op.getRhs());
2674 state[op.getResult()] = std::max(lhs, rhs);
2675 return DeletionKind::Delete;
2678 FailureOr<DeletionKind> visitOp(index::MinUOp op) {
2679 size_t lhs = get<size_t>(op.getLhs());
2680 size_t rhs = get<size_t>(op.getRhs());
2681 state[op.getResult()] = std::min(lhs, rhs);
2682 return DeletionKind::Delete;
2685 FailureOr<DeletionKind> visitOp(index::CmpOp op) {
2686 size_t lhs = get<size_t>(op.getLhs());
2687 size_t rhs = get<size_t>(op.getRhs());
2689 switch (op.getPred()) {
2690 case index::IndexCmpPredicate::EQ:
2691 result = lhs == rhs;
2693 case index::IndexCmpPredicate::NE:
2694 result = lhs != rhs;
2696 case index::IndexCmpPredicate::ULT:
2699 case index::IndexCmpPredicate::ULE:
2700 result = lhs <= rhs;
2702 case index::IndexCmpPredicate::UGT:
2705 case index::IndexCmpPredicate::UGE:
2706 result = lhs >= rhs;
2709 return op->emitOpError(
"elaboration not supported");
2711 state[op.getResult()] = result;
2712 return DeletionKind::Delete;
2715 bool isSymbolic(ElaboratorValue val) {
2716 return std::holds_alternative<SymbolicComputationWithIdentityValue *>(
2718 std::holds_alternative<SymbolicComputationWithIdentityStorage *>(
2720 std::holds_alternative<SymbolicComputationStorage *>(val) ||
2721 std::holds_alternative<OpaqueExternalStorage *>(val);
2724 bool isSymbolic(Operation *op) {
2725 return llvm::any_of(op->getOperands(), [&](
auto operand) {
2726 auto val = state.at(operand);
2727 return isSymbolic(val);
2734 bool attemptConcreteCase(Operation *op) {
2735 if (op->getNumResults() == 0)
2738 SmallVector<Attribute> operands;
2739 for (
auto operand : op->getOperands()) {
2740 auto evalValue = state[operand];
2741 auto attr = elabValConverter.convert(evalValue);
2742 operands.push_back(attr);
2745 SmallVector<OpFoldResult> results;
2746 if (failed(op->fold(operands, results)))
2749 if (results.size() != op->getNumResults())
2752 for (
auto [res, val] : llvm::zip(results, op->getResults())) {
2753 auto attr = llvm::dyn_cast_or_null<TypedAttr>(res.dyn_cast<Attribute>());
2757 if (attr.getType() != val.getType())
2761 auto converted = attrConverter.convert(attr);
2762 if (succeeded(converted)) {
2763 state[val] = *converted;
2772 FailureOr<DeletionKind> visitOpGeneric(Operation *op) {
2773 if (op->getNumResults() == 0)
2774 return DeletionKind::Keep;
2776 if (attemptConcreteCase(op))
2777 return DeletionKind::Delete;
2779 if (mlir::isMemoryEffectFree(op)) {
2780 if (op->getNumResults() != 1)
2781 return op->emitOpError(
2782 "symbolic elaboration of memory-effect-free operations with "
2783 "multiple results not supported");
2785 state[op->getResult(0)] =
2786 sharedState.internalizer.internalize<SymbolicComputationStorage>(
2788 return DeletionKind::Delete;
2799 bool onlyAlloc = mlir::hasSingleEffect<mlir::MemoryEffects::Allocate>(op);
2800 onlyAlloc |= isa<ValidateOp>(op);
2802 auto *validationVal =
2803 sharedState.internalizer.create<SymbolicComputationWithIdentityStorage>(
2805 materializer.registerIdentityValue(validationVal);
2806 state[op->getResult(0)] = validationVal;
2808 for (
auto [i, res] : llvm::enumerate(op->getResults())) {
2812 sharedState.internalizer.create<SymbolicComputationWithIdentityValue>(
2813 res.getType(), validationVal, i);
2815 materializer.registerIdentityValue(val);
2817 return onlyAlloc ? DeletionKind::Delete : DeletionKind::Keep;
2820 bool supportsSymbolicValuesNonGenerically(Operation *op) {
2821 return isa<SubstituteSequenceOp, ArrayCreateOp, ArrayInjectOp,
2822 TupleCreateOp, StructCreateOp, VariantCreateOp, VariantMatchOp,
2823 MutCreateOp, MutReadOp, MutWriteOp, arith::SelectOp,
2824 func::CallOp, func::CallIndirectOp>(op);
2827 FailureOr<DeletionKind> dispatchOpVisitor(Operation *op) {
2828 if (isSymbolic(op) && !supportsSymbolicValuesNonGenerically(op))
2829 return visitOpGeneric(op);
2831 return TypeSwitch<Operation *, FailureOr<DeletionKind>>(op)
2834 arith::AddIOp, arith::XOrIOp, arith::AndIOp, arith::OrIOp,
2837 index::AddOp, index::SubOp, index::MulOp, index::DivUOp,
2838 index::CeilDivUOp, index::RemUOp, index::AndOp, index::OrOp,
2839 index::XOrOp, index::ShlOp, index::ShrUOp, index::MaxUOp,
2840 index::MinUOp, index::CmpOp>([&](
auto op) {
return visitOp(op); })
2844 LogicalResult pushRegionFrame(Region ®ion,
2845 ArrayRef<ElaboratorValue> regionArguments,
2846 bool keepTerminator,
bool replay,
2847 LexicalEnvironment environment,
2848 bool eraseTerminator =
true) {
2849 if (region.getBlocks().size() != 1)
2850 return region.getParentOp()->emitOpError(
2851 "regions with anything other than one block are not supported");
2853 Block &block = region.front();
2854 for (
auto [arg, value] : llvm::zip(block.getArguments(), regionArguments))
2855 environment[arg] = value;
2858 frame.block = █
2859 frame.nextOp = block.empty() ? nullptr : &block.front();
2860 frame.keepTerminator = keepTerminator;
2861 frame.eraseTerminator = eraseTerminator;
2862 frame.replay = replay;
2863 frame.environment = std::move(environment);
2864 workStack.emplace_back(std::make_unique<EvalFrame>(std::move(frame)));
2868 FailureOr<ControlTransfer> visitPerformTransfer(PerformOp op) {
2869 StringAttr effectName = op.getEffectAttr().getAttr();
2870 for (
size_t i = handlerStack.size(); i > 0; --i) {
2871 const HandlerFrame &frame = handlerStack[i - 1];
2872 if (frame.handlers.contains(effectName))
2873 return ControlTransfer{frame.promptToken, op};
2876 auto diag = op->emitError(
"no handler for effect @")
2877 << effectName.getValue();
2878 if (sequenceBoundaryToken)
2879 diag <<
"; effects cannot be handled across a sequence boundary";
2883 LogicalResult handleControlTransfer(ControlTransfer transfer) {
2884 size_t handlerIndex = handlerStack.size();
2885 Region *handlerRegion =
nullptr;
2886 StringAttr effectName = transfer.perform.getEffectAttr().getAttr();
2887 for (
size_t i = handlerStack.size(); i > 0; --i) {
2888 auto it = handlerStack[i - 1].handlers.find(effectName);
2889 if (it != handlerStack[i - 1].handlers.end()) {
2890 handlerIndex = i - 1;
2891 handlerRegion = it->second;
2895 if (!handlerRegion || handlerIndex == handlerStack.size())
2896 return transfer.perform->emitOpError(
2897 "control transfer no longer has a matching handler");
2899 size_t promptIndex = workStack.size();
2900 for (
size_t i = 0; i < workStack.size(); ++i)
2901 if (
auto *frame = workStack[i]->getIf<WithHandlersFrame>();
2902 frame && frame->promptId == transfer.promptId) {
2906 if (promptIndex == workStack.size())
2907 return transfer.perform->emitOpError(
2908 "active handler prompt has no evaluator frame");
2910 for (
size_t i = promptIndex + 1; i < workStack.size(); ++i)
2911 if (workStack[i]->holds<ExternalOpFrame>())
2912 return transfer.perform->emitError(
2913 "effect handler cannot capture control across an opaque "
2914 "external-region shell");
2916 auto *activeBlock = workStack.back()->getIf<BlockFrame>();
2918 return transfer.perform->emitOpError(
2919 "perform is not executing in a block frame");
2920 LexicalEnvironment performEnvironment = activeBlock->environment;
2921 SmallVector<HandlerFrame> capturedHandlerStack(handlerStack);
2922 RngScope capturedRng = testState.rng;
2923 ContinuationBoundary capturedBoundary{
2924 sequenceBoundaryToken, externalRegionStack, elaboratorBoundaryToken};
2925 EvalFrameStack capturedFrames;
2927 Value performResult = transfer.perform.getNumResults()
2928 ? Value(transfer.perform.getResult())
2930 Type resumeType = performResult
2931 ? performResult.getType()
2932 : NoneType::get(transfer.perform.getContext());
2934 while (workStack.size() > promptIndex) {
2935 EvalFrame &frame = *workStack.back();
2936 capturedFrames.push_back(frame.clone());
2937 if (auto *randomScope = frame.getIf<RandomScopeFrame>()) {
2938 testState.rng = randomScope->outerRng;
2939 }
else if (
auto *external = frame.getIf<ExternalOpFrame>()) {
2940 if (external->activeBoundary && !externalRegionStack.empty())
2941 externalRegionStack.pop_back();
2942 materializer.getBuilder().restoreInsertionPoint(
2943 external->parentInsertionPoint);
2944 }
else if (
auto *resume = frame.getIf<ResumeFrame>()) {
2945 handlerStack = resume->handlerStack;
2946 testState.rng = resume->rng;
2948 workStack.pop_back();
2950 std::reverse(capturedFrames.begin(), capturedFrames.end());
2951 auto *continuation = sharedState.internalizer.create<ContinuationStorage>(
2952 std::move(capturedFrames), performResult,
2953 std::move(capturedHandlerStack), performEnvironment,
2954 std::move(capturedRng), transfer.promptId, std::move(capturedBoundary),
2955 resumeType, transfer.perform.getLoc());
2956 materializer.registerIdentityValue(continuation);
2958 SmallVector<ElaboratorValue> handlerArguments;
2959 for (Value operand : transfer.perform.getOperands())
2960 handlerArguments.push_back(performEnvironment.at(operand));
2961 handlerArguments.push_back(continuation);
2963 handlerStack.resize(handlerIndex);
2964 state = performEnvironment;
2965 workStack.emplace_back(std::make_unique<EvalFrame>(HandlerClauseFrame{}));
2966 return pushRegionFrame(*handlerRegion, handlerArguments,
2968 std::move(performEnvironment));
2971 LogicalResult scheduleResume(ResumeOp op) {
2972 auto stateIt = state.find(op.getContinuation());
2973 if (stateIt == state.end())
2974 return op->emitOpError(
"continuation has no elaborated value");
2975 auto *continuation = std::get_if<ContinuationStorage *>(&stateIt->second);
2976 if (!continuation || !*continuation)
2977 return op->emitOpError(
2978 "cannot resume a continuation that is not owned by the elaborator");
2980 ContinuationStorage *cont = *continuation;
2981 if (cont->boundary.sequence != sequenceBoundaryToken)
2982 return op->emitError(
"continuation cannot escape a sequence boundary");
2983 if (cont->boundary.elaborator != elaboratorBoundaryToken)
2984 return op->emitError(
2985 "continuation cannot escape its elaborator invocation");
2986 if (!llvm::equal(cont->boundary.externalRegions, externalRegionStack))
2987 return op->emitError(
2988 "continuation cannot escape an opaque external-region shell");
2990 std::optional<ElaboratorValue> resumeValue;
2991 if (cont->performResult && op.getValue())
2992 resumeValue = state.at(op.getValue());
2994 auto *block = workStack.back()->getIf<BlockFrame>();
2996 return op->emitOpError(
"resume is not executing in a block frame");
2997 block->environment = state;
2999 workStack.emplace_back(
3000 std::make_unique<EvalFrame>(ResumeFrame(handlerStack, testState.rng)));
3001 handlerStack = cont->capturedHandlerStack;
3002 testState.rng = cont->capturedRng;
3004 EvalFrameStack replayFrames;
3005 for (
const auto &prototype : cont->capturedFrames)
3006 replayFrames.push_back(prototype->clone());
3007 for (
auto &framePtr : replayFrames) {
3008 EvalFrame &frame = *framePtr;
3009 if (
auto *blockFrame = frame.getIf<BlockFrame>())
3010 blockFrame->replay =
true;
3011 else if (
auto *ifFrame = frame.getIf<ScfIfFrame>())
3012 ifFrame->replay =
true;
3013 else if (
auto *forFrame = frame.getIf<ScfForFrame>())
3014 forFrame->replay =
true;
3015 else if (
auto *scopeFrame = frame.getIf<RandomScopeFrame>())
3016 scopeFrame->replay =
true;
3017 else if (
auto *handlerFrame = frame.getIf<WithHandlersFrame>())
3018 handlerFrame->replay =
true;
3019 else if (
auto *externalFrame = frame.getIf<ExternalOpFrame>())
3020 externalFrame->replay =
true;
3023 auto *performBlock = replayFrames.back()->getIf<BlockFrame>();
3025 return op->emitOpError(
3026 "captured continuation does not end in a block frame");
3027 performBlock->environment[cont->performResult] = *resumeValue;
3029 for (
auto &frame : replayFrames)
3030 workStack.push_back(std::move(frame));
3034 LogicalResult startExternalRegion(
size_t frameIndex,
bool &started) {
3035 auto &frame = workStack[frameIndex]->get<ExternalOpFrame>();
3036 RegionRange oldRegions = frame.originalOp->getRegions();
3037 while (frame.nextRegion < oldRegions.size()) {
3038 size_t regionIndex = frame.nextRegion++;
3039 Region &oldRegion = *oldRegions[regionIndex];
3040 if (oldRegion.empty())
3042 if (oldRegion.getBlocks().size() != 1)
3043 return frame.originalOp->emitOpError(
3044 "regions with anything other than one block are not supported");
3046 Region &newRegion = frame.materializedOp->getRegion(regionIndex);
3047 Block &oldBlock = oldRegion.front();
3048 Block &newBlock = newRegion.emplaceBlock();
3049 LexicalEnvironment environment = frame.parentEnvironment;
3050 for (
auto oldArg : oldBlock.getArguments()) {
3051 Value newArg = newBlock.addArgument(oldArg.getType(), oldArg.getLoc());
3052 auto *storage = sharedState.internalizer.create<OpaqueExternalStorage>(
3053 oldArg.getType(), oldArg.getLoc());
3054 environment[oldArg] = storage;
3055 materializer.map(storage, newArg);
3058 uint64_t boundary = sharedState.createBoundaryToken();
3059 frame.activeBoundary = boundary;
3060 externalRegionStack.push_back(boundary);
3061 materializer.getBuilder().setInsertionPoint(&newBlock, newBlock.begin());
3063 return pushRegionFrame(oldRegion, {},
true,
3064 frame.replay, std::move(environment));
3070 LogicalResult startExternalOp(Operation *op,
bool replay) {
3071 auto &builder = materializer.getBuilder();
3072 Operation *newOp = op->cloneWithoutRegions();
3073 builder.insert(newOp);
3074 builder.setInsertionPoint(newOp);
3075 for (
auto &operand : newOp->getOpOperands()) {
3076 auto emitError = [&]() {
3077 auto diag = newOp->emitError();
3078 diag.attachNote(newOp->getLoc())
3079 <<
"while materializing operand#" << operand.getOperandNumber()
3080 <<
" of external region op";
3083 Value value = materializer.materialize(state.at(operand.get()),
3084 newOp->getLoc(), emitError);
3089 builder.setInsertionPointAfter(newOp);
3091 ExternalOpFrame frame;
3092 frame.originalOp = op;
3093 frame.materializedOp = newOp;
3094 frame.replay = replay;
3095 frame.parentEnvironment = state;
3096 frame.parentInsertionPoint = builder.saveInsertionPoint();
3097 workStack.emplace_back(std::make_unique<EvalFrame>(std::move(frame)));
3098 bool started =
false;
3099 if (failed(startExternalRegion(workStack.size() - 1, started)))
3102 return finishExternalOp(workStack.size() - 1);
3106 LogicalResult finishExternalOp(
size_t frameIndex) {
3107 auto &frame = workStack[frameIndex]->get<ExternalOpFrame>();
3108 auto *parent = workStack[frameIndex - 1]->getIf<BlockFrame>();
3110 return frame.originalOp->emitOpError(
3111 "external region op lost its parent block frame");
3112 for (
auto [oldResult, newResult] :
3113 llvm::zip(frame.originalOp->getResults(),
3114 frame.materializedOp->getResults())) {
3115 auto *storage = sharedState.internalizer.create<OpaqueExternalStorage>(
3116 oldResult.getType(), oldResult.getLoc());
3117 parent->environment[oldResult] = storage;
3118 materializer.map(storage, newResult);
3120 workStack.pop_back();
3124 LogicalResult startForIteration(
size_t frameIndex) {
3125 auto &frame = workStack[frameIndex]->get<ScfForFrame>();
3126 if (frame.nextIteration >= frame.upperBound) {
3127 auto *parent = workStack[frameIndex - 1]->getIf<BlockFrame>();
3129 return frame.op->emitOpError(
"scf.for lost its parent block frame");
3130 for (
auto [result, iterArg] :
3131 llvm::zip(frame.op->getResults(), frame.op.getRegionIterArgs()))
3132 parent->environment[result] = frame.loopEnvironment.at(iterArg);
3133 frame.completed =
true;
3137 size_t iteration = frame.nextIteration;
3138 frame.nextIteration += frame.loopStep;
3139 LexicalEnvironment environment = frame.loopEnvironment;
3140 environment[frame.op.getInductionVar()] = iteration;
3141 return pushRegionFrame(frame.op.getBodyRegion(), {},
3142 false, frame.replay,
3143 std::move(environment));
3146 LogicalResult completeFrame(SmallVector<ElaboratorValue> yieldedValues) {
3147 if (workStack.empty() || workStack.back()->holds<BlockFrame>())
3150 if (
auto *frame = workStack.back()->getIf<ScfIfFrame>()) {
3151 if (failed(frame->step(*
this, yieldedValues)))
3153 workStack.pop_back();
3157 if (
auto *frame = workStack.back()->getIf<VariantMatchFrame>()) {
3158 auto *parent = workStack[workStack.size() - 2]->getIf<BlockFrame>();
3160 return frame->op->emitOpError(
"rtg.match lost its parent block frame");
3161 for (
auto [result, value] :
3162 llvm::zip(frame->op.getResults(), yieldedValues))
3163 parent->environment[result] = value;
3164 workStack.pop_back();
3168 if (
auto *frame = workStack.back()->getIf<ScfForFrame>()) {
3169 if (failed(frame->step(*
this, yieldedValues)))
3171 if (frame->completed)
3172 workStack.pop_back();
3176 if (
auto *frame = workStack.back()->getIf<RandomScopeFrame>()) {
3177 auto *parent = workStack[workStack.size() - 2]->getIf<BlockFrame>();
3179 return frame->op->emitOpError(
3180 "random_scope lost its parent block frame");
3181 for (
auto [result, value] :
3182 llvm::zip(frame->op.getResults(), yieldedValues))
3183 parent->environment[result] = value;
3184 testState.rng = frame->outerRng;
3185 workStack.pop_back();
3189 if (
auto *frame = workStack.back()->getIf<WithHandlersFrame>()) {
3190 if (handlerStack.empty() ||
3191 handlerStack.back().promptToken != frame->promptId)
3192 return frame->op->emitOpError(
3193 "handler stack does not match completed scope");
3194 handlerStack.pop_back();
3195 workStack.pop_back();
3199 if (workStack.back()->holds<HandlerClauseFrame>()) {
3200 workStack.pop_back();
3204 if (
auto *frame = workStack.back()->getIf<FunctionCallFrame>()) {
3205 if (yieldedValues.size() != frame->call.getNumResults())
3206 return frame->call.emitOpError(
3207 "callee return values do not match call results");
3208 assert(workStack.size() >= 2 &&
3209 "function call frame must have a parent block frame");
3210 auto *parent = workStack[workStack.size() - 2]->getIf<BlockFrame>();
3212 return frame->call.emitOpError(
3213 "function call lost its parent block frame");
3214 for (
auto [result, value] :
3215 llvm::zip_equal(frame->call.getResults(), yieldedValues))
3216 parent->environment[result] = value;
3217 workStack.pop_back();
3221 if (
auto *frame = workStack.back()->getIf<ExternalOpFrame>()) {
3222 if (frame->activeBoundary) {
3223 assert(!externalRegionStack.empty() &&
3224 externalRegionStack.back() == frame->activeBoundary);
3225 externalRegionStack.pop_back();
3226 frame->activeBoundary = 0;
3228 materializer.getBuilder().restoreInsertionPoint(
3229 frame->parentInsertionPoint);
3230 bool started =
false;
3231 if (failed(startExternalRegion(workStack.size() - 1, started)))
3236 return finishExternalOp(workStack.size() - 1);
3239 if (
auto *frame = workStack.back()->getIf<ResumeFrame>()) {
3240 handlerStack = std::move(frame->handlerStack);
3241 testState.rng = frame->rng;
3242 workStack.pop_back();
3245 llvm_unreachable(
"unknown evaluator frame");
3248 LogicalResult runTrampoline(SmallVector<ElaboratorValue> &rootValues) {
3249 while (!workStack.empty()) {
3250 auto *frame = workStack.back()->getIf<BlockFrame>();
3252 if (failed(completeFrame({})))
3257 Operation *op = frame->nextOp;
3259 (!frame->keepTerminator && op->hasTrait<OpTrait::IsTerminator>())) {
3260 SmallVector<ElaboratorValue> yieldedValues;
3261 if (!frame->block->empty() &&
3262 frame->block->back().hasTrait<OpTrait::IsTerminator>()) {
3263 Operation *terminator = frame->block->getTerminator();
3264 for (Value operand : terminator->getOperands())
3265 yieldedValues.push_back(frame->environment.at(operand));
3266 if (!frame->keepTerminator && frame->eraseTerminator &&
3267 materializer.isInPlace(terminator)) {
3268 auto &builder = materializer.getBuilder();
3269 if (builder.getBlock() == terminator->getBlock() &&
3270 builder.getInsertionPoint() == terminator->getIterator()) {
3273 builder.setInsertionPointToEnd(terminator->getBlock());
3275 terminator->erase();
3278 workStack.pop_back();
3279 if (workStack.empty()) {
3280 rootValues = std::move(yieldedValues);
3283 if (failed(completeFrame(std::move(yieldedValues))))
3288 Operation *nextOp = op->getNextNode();
3289 bool replay = frame->replay;
3290 frame->nextOp = nextOp;
3291 state = frame->environment;
3293 if (isSymbolic(op) && !supportsSymbolicValuesNonGenerically(op)) {
3294 auto result = visitOpGeneric(op);
3297 if (*result == DeletionKind::Keep &&
3298 failed(materializer.materialize(op, state, replay)))
3300 workStack.back()->get<BlockFrame>().environment = state;
3304 if (
auto perform = dyn_cast<PerformOp>(op)) {
3305 auto transfer = visitPerformTransfer(perform);
3306 if (failed(transfer))
3308 workStack.back()->get<BlockFrame>().environment = state;
3309 if (failed(handleControlTransfer(*transfer)))
3314 if (
auto resume = dyn_cast<ResumeOp>(op)) {
3315 if (failed(scheduleResume(resume)))
3320 if (isa<func::CallIndirectOp>(op))
3321 return op->emitOpError(
"cannot elaborate indirect function call");
3323 if (
auto call = dyn_cast<func::CallOp>(op)) {
3324 auto callee = sharedState.table.lookup<func::FuncOp>(call.getCallee());
3326 return call.emitOpError(
"cannot elaborate unresolved function call");
3327 if (callee.isExternal())
3328 return call.emitOpError(
"cannot elaborate external function call");
3329 if (callee.getBody().getBlocks().size() != 1)
3330 return call.emitOpError(
3331 "RTG elaboration only supports single-block callees");
3333 SmallVector<ElaboratorValue> arguments;
3334 arguments.reserve(call.getNumOperands());
3335 for (Value operand : call.getOperands())
3336 arguments.push_back(state.at(operand));
3338 workStack.back()->get<BlockFrame>().environment = state;
3339 workStack.emplace_back(
3340 std::make_unique<EvalFrame>(FunctionCallFrame{call}));
3341 if (failed(pushRegionFrame(callee.getBody(), arguments,
3349 if (
auto ifOp = dyn_cast<scf::IfOp>(op)) {
3350 bool condition = get<bool>(ifOp.getCondition());
3352 condition ? ifOp.getThenRegion() : ifOp.getElseRegion();
3353 workStack.back()->get<BlockFrame>().environment = state;
3356 workStack.emplace_back(
3357 std::make_unique<EvalFrame>(ScfIfFrame{ifOp, replay}));
3358 if (failed(pushRegionFrame(region, {},
false, replay,
3364 if (
auto matchOp = dyn_cast<VariantMatchOp>(op)) {
3365 auto selectorValue = state.at(matchOp.getValue());
3366 auto *variant = std::get_if<VariantStorage *>(&selectorValue);
3368 return matchOp.emitOpError(
3369 "cannot evaluate match with a non-concrete variant selector");
3372 matchOp.getCaseIndex((*variant)->constructor.getValue());
3373 Region ®ion = matchOp.getCaseRegions()[*caseIndex];
3374 SmallVector<ElaboratorValue> regionArguments{(*variant)->payload};
3376 workStack.back()->get<BlockFrame>().environment = state;
3377 workStack.emplace_back(
3378 std::make_unique<EvalFrame>(VariantMatchFrame{matchOp}));
3379 if (failed(pushRegionFrame(region, regionArguments,
3380 false, replay, state)))
3385 if (
auto forOp = dyn_cast<scf::ForOp>(op)) {
3386 if (!(std::holds_alternative<size_t>(state.at(forOp.getLowerBound())) &&
3387 std::holds_alternative<size_t>(state.at(forOp.getStep())) &&
3388 std::holds_alternative<size_t>(state.at(forOp.getUpperBound()))))
3389 return forOp->emitOpError(
"can only elaborate index type iterator");
3390 size_t lower = get<size_t>(forOp.getLowerBound());
3391 size_t step = get<size_t>(forOp.getStep());
3392 size_t upper = get<size_t>(forOp.getUpperBound());
3394 return forOp->emitOpError(
"loop step must be greater than zero");
3395 LexicalEnvironment loopEnvironment = state;
3396 for (
auto [iterArg, initArg] :
3397 llvm::zip(forOp.getRegionIterArgs(), forOp.getInitArgs()))
3398 loopEnvironment[iterArg] = state.at(initArg);
3399 workStack.back()->get<BlockFrame>().environment = state;
3400 if (lower >= upper) {
3401 for (
auto [result, iterArg] :
3402 llvm::zip(forOp->getResults(), forOp.getRegionIterArgs()))
3403 workStack.back()->get<BlockFrame>().environment[result] =
3404 loopEnvironment.at(iterArg);
3407 workStack.emplace_back(std::make_unique<EvalFrame>(
3408 ScfForFrame{forOp, lower, upper, step, replay,
false,
3409 std::move(loopEnvironment)}));
3410 if (failed(startForIteration(workStack.size() - 1)))
3415 if (
auto randomScope = dyn_cast<RandomScopeOp>(op)) {
3416 RngScope outerRng = testState.rng;
3417 testState.rng = randomScope.getSeed()
3418 ? RngScope(randomScope.getSeed()->getZExtValue())
3419 : testState.rng.getNested();
3420 workStack.back()->get<BlockFrame>().environment = state;
3421 workStack.emplace_back(std::make_unique<EvalFrame>(
3422 RandomScopeFrame(randomScope, std::move(outerRng), replay)));
3423 if (failed(pushRegionFrame(randomScope.getBodyRegion(), {},
3424 false, replay, state)))
3429 if (
auto withHandlers = dyn_cast<WithHandlersOp>(op)) {
3430 HandlerFrame handlerFrame;
3431 handlerFrame.promptToken = sharedState.createBoundaryToken();
3432 for (
auto [effect, region] : llvm::zip(
3433 withHandlers.getEffects(), withHandlers.getHandlerRegions()))
3434 handlerFrame.handlers[cast<FlatSymbolRefAttr>(effect).getAttr()] =
3436 uint64_t promptId = handlerFrame.promptToken;
3437 handlerStack.push_back(std::move(handlerFrame));
3438 workStack.back()->get<BlockFrame>().environment = state;
3439 workStack.emplace_back(std::make_unique<EvalFrame>(
3440 WithHandlersFrame{withHandlers, promptId, replay}));
3441 if (failed(pushRegionFrame(withHandlers.getBody(), {},
3442 false, replay, state)))
3447 if (op->getNumRegions() != 0) {
3448 workStack.back()->get<BlockFrame>().environment = state;
3449 if (failed(startExternalOp(op, replay)))
3454 auto result = dispatchOpVisitor(op);
3457 if (*result == DeletionKind::Keep &&
3458 failed(materializer.materialize(op, state, replay)))
3460 workStack.back()->get<BlockFrame>().environment = state;
3463 llvm::dbgs() <<
"Elaborated " << *op <<
" to\n[";
3464 llvm::interleaveComma(op->getResults(), llvm::dbgs(), [&](
auto res) {
3465 if (state.contains(res))
3466 llvm::dbgs() << state.at(res);
3468 llvm::dbgs() <<
"unknown";
3470 llvm::dbgs() <<
"]\n\n";
3476 LogicalResult elaborate(Region ®ion,
3477 ArrayRef<ElaboratorValue> regionArguments,
3478 bool keepTerminator,
3479 SmallVector<ElaboratorValue> &terminatorOperands) {
3480 if (!workStack.empty())
3481 return region.getParentOp()->emitOpError(
3482 "top-level elaboration cannot start with active evaluator frames");
3483 LexicalEnvironment savedState = std::move(state);
3484 LexicalEnvironment environment = savedState;
3485 if (failed(pushRegionFrame(region, regionArguments, keepTerminator,
3486 false, std::move(environment)))) {
3487 state = std::move(savedState);
3490 bool failedEvaluation = failed(runTrampoline(terminatorOperands));
3491 state = std::move(savedState);
3497 SharedState &sharedState;
3500 TestState &testState;
3504 Materializer &materializer;
3507 LexicalEnvironment state;
3510 ContextResourceAttrInterface currentContext;
3514 uint64_t sequenceBoundaryToken;
3517 uint64_t elaboratorBoundaryToken;
3520 SmallVector<uint64_t> externalRegionStack;
3523 AttributeToElaboratorValueConverter attrConverter;
3526 ElaboratorValueToAttributeConverter elabValConverter;
3529 SmallVector<HandlerFrame> handlerStack;
3532 EvalFrameStack workStack;
3534 friend struct ScfIfFrame;
3535 friend struct VariantMatchFrame;
3536 friend struct ScfForFrame;
3539LogicalResult ScfIfFrame::step(Elaborator &elaborator,
3540 ArrayRef<ElaboratorValue> yieldedValues) {
3541 auto *parent = elaborator.workStack[elaborator.workStack.size() - 2]
3542 ->getIf<BlockFrame>();
3544 return op->emitOpError(
"scf.if lost its parent block frame");
3545 for (
auto [result, value] : llvm::zip(op.getResults(), yieldedValues))
3546 parent->environment[result] = value;
3550LogicalResult ScfForFrame::step(Elaborator &elaborator,
3551 ArrayRef<ElaboratorValue> yieldedValues) {
3552 for (
auto [iterArg, value] : llvm::zip(op.getRegionIterArgs(), yieldedValues))
3553 loopEnvironment[iterArg] = value;
3554 return elaborator.startForIteration(elaborator.workStack.size() - 1);
3559Materializer::elaborateSequence(
const RandomizedSequenceStorage *seq,
3560 SmallVector<ElaboratorValue> &elabArgs) {
3562 sharedState.table.lookup<SequenceOp>(seq->sequence->familyName);
3565 OpBuilder builder(familyOp);
3566 auto seqOp = builder.cloneWithoutRegions(familyOp);
3567 auto name = sharedState.names.
newName(seq->sequence->familyName.getValue());
3568 seqOp.setSymName(name);
3569 seqOp.getBodyRegion().emplaceBlock();
3570 sharedState.table.insert(seqOp);
3571 assert(seqOp.getSymName() == name &&
"should not have been renamed");
3573 LLVM_DEBUG(llvm::dbgs() <<
"\n=== Elaborating sequence family @"
3574 << familyOp.getSymName() <<
" into @"
3575 << seqOp.getSymName() <<
" under context "
3576 << seq->context <<
"\n\n");
3578 Materializer materializer(OpBuilder::atBlockBegin(seqOp.getBody()), testState,
3579 sharedState, elabArgs);
3580 Elaborator elaborator(sharedState, testState, materializer, seq->context,
3581 sharedState.createBoundaryToken());
3582 SmallVector<ElaboratorValue> yieldedVals;
3583 if (failed(elaborator.elaborate(familyOp.getBodyRegion(), seq->sequence->args,
3584 false, yieldedVals)))
3587 seqOp.setSequenceType(
3588 SequenceType::get(builder.getContext(), materializer.getBlockArgTypes()));
3589 materializer.finalize();
3599struct ElaborationPass
3600 :
public rtg::impl::ElaborationPassBase<ElaborationPass> {
3603 void runOnOperation()
override;
3604 void matchTestsAgainstTargets(SymbolTable &table);
3605 LogicalResult elaborateModule(ModuleOp moduleOp, SymbolTable &table);
3609void ElaborationPass::runOnOperation() {
3610 auto moduleOp = getOperation();
3611 SymbolTable table(moduleOp);
3613 matchTestsAgainstTargets(table);
3615 if (failed(elaborateModule(moduleOp, table)))
3616 return signalPassFailure();
3619void ElaborationPass::matchTestsAgainstTargets(SymbolTable &table) {
3620 auto moduleOp = getOperation();
3622 for (
auto test : llvm::make_early_inc_range(moduleOp.getOps<TestOp>())) {
3623 if (test.getTargetAttr())
3626 bool matched =
false;
3628 for (
auto target : moduleOp.getOps<TargetOp>()) {
3632 bool isSubtype =
true;
3633 auto testEntries = test.getTargetType().getEntries();
3634 auto targetEntries = target.getTarget().getEntries();
3638 size_t targetIdx = 0;
3639 for (
auto testEntry : testEntries) {
3641 while (targetIdx < targetEntries.size() &&
3642 targetEntries[targetIdx].name.getValue() <
3643 testEntry.name.getValue())
3647 if (targetIdx >= targetEntries.size() ||
3648 targetEntries[targetIdx].name != testEntry.name ||
3649 targetEntries[targetIdx].type != testEntry.type) {
3658 IRRewriter rewriter(test);
3660 auto newTest = cast<TestOp>(test->clone());
3661 newTest.setSymName(test.getSymName().str() +
"_" +
3662 target.getSymName().str());
3666 newTest.setTargetAttr(target.getSymNameAttr());
3668 table.insert(newTest, rewriter.getInsertionPoint());
3672 if (matched || deleteUnmatchedTests)
3678 return isa<MemoryBlockType, ContextResourceTypeInterface>(type);
3681LogicalResult ElaborationPass::elaborateModule(ModuleOp moduleOp,
3682 SymbolTable &table) {
3683 SharedState state(moduleOp.getContext(), table);
3686 state.names.add(moduleOp);
3688 struct TargetElabResult {
3689 TargetElabResult(DictType targetType, uint32_t seed)
3690 : targetType(targetType), testState(seed) {}
3692 DictType targetType;
3693 SmallVector<ElaboratorValue> yields;
3694 TestState testState;
3698 DenseMap<StringAttr, TargetElabResult> targetMap;
3699 for (
auto targetOp : moduleOp.getOps<TargetOp>()) {
3700 LLVM_DEBUG(llvm::dbgs() <<
"=== Elaborating target @"
3701 << targetOp.getSymName() <<
"\n\n");
3703 auto [it, inserted] = targetMap.try_emplace(targetOp.getSymNameAttr(),
3704 targetOp.getTarget(), seed);
3705 auto &result = it->second;
3707 SmallVector<ElaboratorValue> blockArgs;
3708 Materializer targetMaterializer(OpBuilder::atBlockBegin(targetOp.getBody()),
3709 result.testState, state, blockArgs);
3710 Elaborator targetElaborator(state, result.testState, targetMaterializer);
3713 if (failed(targetElaborator.elaborate(targetOp.getBodyRegion(), {},
3718 targetMaterializer.finalize();
3723 for (
auto testOp : moduleOp.getOps<TestOp>()) {
3727 if (!testOp.getTargetAttr())
3730 LLVM_DEBUG(llvm::dbgs()
3731 <<
"\n=== Elaborating test @" << testOp.getTemplateName()
3732 <<
" for target @" << *testOp.getTarget() <<
"\n\n");
3735 auto &targetResult = targetMap.at(testOp.getTargetAttr());
3736 TestState testState(seed);
3737 testState.contextSwitches = targetResult.testState.contextSwitches;
3738 testState.name = testOp.getSymNameAttr();
3740 SmallVector<ElaboratorValue> filteredYields;
3742 for (
auto [entry, yield] :
3743 llvm::zip(targetResult.targetType.getEntries(), targetResult.yields)) {
3744 if (i >= testOp.getTargetType().getEntries().size())
3747 if (entry.name == testOp.getTargetType().getEntries()[i].name) {
3748 filteredYields.push_back(yield);
3755 SmallVector<ElaboratorValue> blockArgs;
3756 Materializer materializer(OpBuilder::atBlockBegin(testOp.getBody()),
3757 testState, state, blockArgs);
3759 for (
auto [arg, val] :
3760 llvm::zip(testOp.getBody()->getArguments(), filteredYields))
3762 materializer.map(val, arg);
3764 Elaborator elaborator(state, testState, materializer);
3765 SmallVector<ElaboratorValue> ignore;
3766 if (failed(elaborator.elaborate(testOp.getBodyRegion(), filteredYields,
3770 materializer.finalize();
assert(baseType &&"element must be base type")
static std::unique_ptr< Context > context
static bool onlyLegalToMaterializeInTarget(Type type)
#define VISIT_UNSUPPORTED(STORAGETYPE)
static void print(TypedAttr val, llvm::raw_ostream &os)
static LogicalResult convert(arc::ExecuteOp op, arc::ExecuteOp::Adaptor adaptor, ConversionPatternRewriter &rewriter, const TypeConverter &converter)
static Location getLoc(DefSlot slot)
false return failure()
Parse an optional keyword or string and set instance into 'result'.
if(parseOptionalKeywordOrOptionalString(parser, result.rawName, found)) return failure()
static InstancePath empty
StringRef newName(const Twine &name)
Return a unique name, derived from the input name, and add the new name to the internal namespace.
This helps visit TypeOp nodes.
FailureOr< DeletionKind > dispatchOpVisitor(Operation *op, ExtraArgs... args)
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
StringAttr getName(ArrayAttr names, size_t idx)
Return the name at the specified index of the ArrayAttr or null if it cannot be determined.
OS & operator<<(OS &os, const InnerSymTarget &target)
Printing InnerSymTarget's.
static llvm::hash_code hash_value(const ModulePort &port)
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
@ Delete
Erase the matched ops.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
size_t hash_combine(size_t h1, size_t h2)
C++'s stdlib doesn't have a hash_combine function. This is a simple one.
static bool isEqual(const bool &lhs, const bool &rhs)
static unsigned getHashValue(const bool &val)