CIRCT 24.0.0git
Loading...
Searching...
No Matches
ElaborationPass.cpp
Go to the documentation of this file.
1//===- ElaborationPass.cpp - RTG ElaborationPass implementation -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass elaborates the random parts of the RTG dialect.
10// It performs randomization top-down, i.e., random constructs in a sequence
11// that is invoked multiple times can yield different randomization results
12// for each invokation.
13//
14//===----------------------------------------------------------------------===//
15
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"
32#include <memory>
33#include <random>
34#include <type_traits>
35
36namespace circt {
37namespace rtg {
38#define GEN_PASS_DEF_ELABORATIONPASS
39#include "circt/Dialect/RTG/Transforms/RTGPasses.h.inc"
40} // namespace rtg
41} // namespace circt
42
43using namespace mlir;
44using namespace circt;
45using namespace circt::rtg;
46
47#define DEBUG_TYPE "rtg-elaboration"
48
49namespace {
50/// Helper class to generate random numbers supporting scopes of randomization.
51struct RngScope {
52 RngScope() = delete;
53 RngScope(const RngScope &) = default;
54 RngScope &operator=(const RngScope &) = default;
55
56 RngScope(RngScope &&) = default;
57 RngScope &operator=(RngScope &&) = default;
58
59 explicit RngScope(uint32_t seed) : rng(seed) {}
60
61 //===--------------------------------------------------------------------===//
62 // Uniform Distribution Helper
63 //
64 // Simplified version of
65 // https://github.com/llvm/llvm-project/blob/main/libcxx/include/__random/uniform_int_distribution.h
66 // We use our custom version here to get the same results when compiled with
67 // different compiler versions and standard libraries.
68 //===--------------------------------------------------------------------===//
69
70 /// Get a number uniformly at random in the in specified range.
71 uint32_t getUniformlyInRange(uint32_t a, uint32_t b) {
72 const uint32_t diff = b - a + 1;
73 if (diff == 1)
74 return a;
75
76 if (diff == 0)
77 return rng();
78
79 uint32_t mask =
80 std::numeric_limits<uint32_t>::max() >> (32 - llvm::Log2_32_Ceil(diff));
81 uint32_t u;
82 do {
83 u = rng() & mask;
84 } while (u >= diff);
85
86 return u + a;
87 }
88
89 RngScope getNested() { return RngScope(rng()); }
90
91private:
92 std::mt19937 rng;
93};
94} // namespace
95
96//===----------------------------------------------------------------------===//
97// Elaborator Value
98//===----------------------------------------------------------------------===//
99
100namespace {
101struct ArrayStorage;
102struct BagStorage;
103struct SequenceStorage;
104struct RandomizedSequenceStorage;
105struct InterleavedSequenceStorage;
106struct SetStorage;
107struct VirtualRegisterStorage;
108struct UniqueLabelStorage;
109struct TupleStorage;
110struct StructStorage;
111struct VariantStorage;
112struct MemoryStorage;
113struct MemoryBlockStorage;
114struct SymbolicComputationWithIdentityStorage;
115struct SymbolicComputationWithIdentityValue;
116struct SymbolicComputationStorage;
117struct OpaqueExternalStorage;
118struct MutStorage;
119struct ContinuationStorage;
120
121/// The abstract base class for elaborated values.
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>;
131
132// NOLINTNEXTLINE(readability-identifier-naming)
133llvm::hash_code hash_value(const ElaboratorValue &val) {
134 return std::visit(
135 [&val](const auto &alternative) {
136 // Include index in hash to make sure same value as different
137 // alternatives don't collide.
138 return llvm::hash_combine(val.index(), alternative);
139 },
140 val);
141}
142
143} // namespace
144
145namespace llvm {
146
147template <>
148struct DenseMapInfo<bool> {
149 static unsigned getHashValue(const bool &val) { return val * 37U; }
150
151 static bool isEqual(const bool &lhs, const bool &rhs) { return lhs == rhs; }
152};
153
154} // namespace llvm
155
156//===----------------------------------------------------------------------===//
157// Elaborator Value Storages and Internalization
158//===----------------------------------------------------------------------===//
159
160namespace {
161
162/// Lightweight object to be used as the key for internalization sets. It caches
163/// the hashcode of the internalized object and a pointer to it. This allows a
164/// delayed allocation and construction of the actual object and thus only has
165/// to happen if the object is not already in the set.
166template <typename StorageTy>
167struct HashedStorage {
168 HashedStorage(unsigned hashcode = 0, StorageTy *storage = nullptr)
169 : hashcode(hashcode), storage(storage) {}
170
171 unsigned hashcode;
172 StorageTy *storage;
173};
174
175/// A DenseMapInfo implementation to support 'insert_as' for the internalization
176/// sets. When comparing two 'HashedStorage's we can just compare the already
177/// internalized storage pointers, otherwise we have to call the costly
178/// 'isEqual' method.
179template <typename StorageTy>
180struct StorageKeyInfo {
181 static inline unsigned getHashValue(const HashedStorage<StorageTy> &key) {
182 return key.hashcode;
183 }
184 static inline unsigned getHashValue(const StorageTy &key) {
185 return key.hashcode;
186 }
187
188 static inline bool isEqual(const HashedStorage<StorageTy> &lhs,
189 const HashedStorage<StorageTy> &rhs) {
190 return lhs.storage == rhs.storage;
191 }
192 static inline bool isEqual(const StorageTy &lhs,
193 const HashedStorage<StorageTy> &rhs) {
194 if (!rhs.storage)
195 return false;
196
197 return lhs.isEqual(rhs.storage);
198 }
199};
200
201// Values with structural equivalence intended to be internalized.
202//===----------------------------------------------------------------------===//
203
204/// Base class for all storage objects that can be materialized as attributes.
205/// This provides a cache for the attribute that was materialized from this
206/// storage.
207struct CachableStorage {
208 TypedAttr attrCache;
209};
210
211/// Storage object for an '!rtg.set<T>'.
212struct SetStorage : CachableStorage {
213 static unsigned computeHash(const SetVector<ElaboratorValue> &set,
214 Type type) {
215 llvm::hash_code setHash = 0;
216 for (auto el : set) {
217 // Just XOR all hashes because it's a commutative operation and
218 // `llvm::hash_combine_range` is not commutative.
219 // We don't want the order in which elements were added to influence the
220 // hash and thus the equivalence of sets.
221 setHash = setHash ^ llvm::hash_combine(el);
222 }
223 return llvm::hash_combine(type, setHash);
224 }
225
226 SetStorage(SetVector<ElaboratorValue> &&set, Type type)
227 : hashcode(computeHash(set, type)), set(std::move(set)), type(type) {}
228
229 bool isEqual(const SetStorage *other) const {
230 // Note: we are not using the `==` operator of `SetVector` because it
231 // takes the order in which elements were added into account (since it's a
232 // vector after all). We just use it as a convenient way to keep track of a
233 // deterministic order for re-materialization.
234 bool allContained = true;
235 for (auto el : set)
236 allContained &= other->set.contains(el);
237
238 return hashcode == other->hashcode && set.size() == other->set.size() &&
239 allContained && type == other->type;
240 }
241
242 // The cached hashcode to avoid repeated computations.
243 const unsigned hashcode;
244
245 // Stores the elaborated values contained in the set.
246 const SetVector<ElaboratorValue> set;
247
248 // Store the set type such that we can materialize this evaluated value
249 // also in the case where the set is empty.
250 const Type type;
251};
252
253/// Storage object for an '!rtg.bag<T>'.
254struct BagStorage {
255 BagStorage(MapVector<ElaboratorValue, uint64_t> &&bag, Type type)
256 : hashcode(llvm::hash_combine(
257 type, llvm::hash_combine_range(bag.begin(), bag.end()))),
258 bag(std::move(bag)), type(type) {}
259
260 bool isEqual(const BagStorage *other) const {
261 return hashcode == other->hashcode && llvm::equal(bag, other->bag) &&
262 type == other->type;
263 }
264
265 // The cached hashcode to avoid repeated computations.
266 const unsigned hashcode;
267
268 // Stores the elaborated values contained in the bag with their number of
269 // occurences.
270 const MapVector<ElaboratorValue, uint64_t> bag;
271
272 // Store the bag type such that we can materialize this evaluated value
273 // also in the case where the bag is empty.
274 const Type type;
275};
276
277/// Storage object for an '!rtg.sequence'.
278struct SequenceStorage {
279 SequenceStorage(StringAttr familyName, SmallVector<ElaboratorValue> &&args)
280 : hashcode(llvm::hash_combine(
281 familyName, llvm::hash_combine_range(args.begin(), args.end()))),
282 familyName(familyName), args(std::move(args)) {}
283
284 bool isEqual(const SequenceStorage *other) const {
285 return hashcode == other->hashcode && familyName == other->familyName &&
286 args == other->args;
287 }
288
289 // The cached hashcode to avoid repeated computations.
290 const unsigned hashcode;
291
292 // The name of the sequence family this sequence is derived from.
293 const StringAttr familyName;
294
295 // The elaborator values used during substitution of the sequence family.
296 const SmallVector<ElaboratorValue> args;
297};
298
299/// Storage object for interleaved '!rtg.randomized_sequence'es.
300struct InterleavedSequenceStorage {
301 InterleavedSequenceStorage(SmallVector<ElaboratorValue> &&sequences,
302 uint32_t batchSize)
303 : sequences(std::move(sequences)), batchSize(batchSize),
304 hashcode(llvm::hash_combine(
305 llvm::hash_combine_range(sequences.begin(), sequences.end()),
306 batchSize)) {}
307
308 explicit InterleavedSequenceStorage(RandomizedSequenceStorage *sequence)
309 : sequences(SmallVector<ElaboratorValue>(1, sequence)), batchSize(1),
310 hashcode(llvm::hash_combine(
311 llvm::hash_combine_range(sequences.begin(), sequences.end()),
312 batchSize)) {}
313
314 bool isEqual(const InterleavedSequenceStorage *other) const {
315 return hashcode == other->hashcode && sequences == other->sequences &&
316 batchSize == other->batchSize;
317 }
318
319 const SmallVector<ElaboratorValue> sequences;
320
321 const uint32_t batchSize;
322
323 // The cached hashcode to avoid repeated computations.
324 const unsigned hashcode;
325};
326
327/// Storage object for '!rtg.array`-typed values.
328struct ArrayStorage {
329 ArrayStorage(Type type, SmallVector<ElaboratorValue> &&array)
330 : hashcode(llvm::hash_combine(
331 type, llvm::hash_combine_range(array.begin(), array.end()))),
332 type(type), array(array) {}
333
334 bool isEqual(const ArrayStorage *other) const {
335 return hashcode == other->hashcode && type == other->type &&
336 array == other->array;
337 }
338
339 // The cached hashcode to avoid repeated computations.
340 const unsigned hashcode;
341
342 /// The type of the array. This is necessary because an array of size 0
343 /// cannot be reconstructed without knowing the original element type.
344 const Type type;
345
346 /// The label name. For unique labels, this is just the prefix.
347 const SmallVector<ElaboratorValue> array;
348};
349
350/// Storage object for 'tuple`-typed values.
351struct TupleStorage : CachableStorage {
352 TupleStorage(SmallVector<ElaboratorValue> &&values)
353 : hashcode(llvm::hash_combine_range(values.begin(), values.end())),
354 values(std::move(values)) {}
355
356 bool isEqual(const TupleStorage *other) const {
357 return hashcode == other->hashcode && values == other->values;
358 }
359
360 // The cached hashcode to avoid repeated computations.
361 const unsigned hashcode;
362
363 const SmallVector<ElaboratorValue> values;
364};
365
366/// Storage object for nominal struct values. The type is part of the identity
367/// because two struct families with equal fields are not interchangeable.
368struct StructStorage : CachableStorage {
369 StructStorage(StructType type, SmallVector<ElaboratorValue> &&fields)
370 : hashcode(llvm::hash_combine(
371 type, llvm::hash_combine_range(fields.begin(), fields.end()))),
372 type(type), fields(std::move(fields)) {}
373
374 bool isEqual(const StructStorage *other) const {
375 return hashcode == other->hashcode && type == other->type &&
376 fields == other->fields;
377 }
378
379 const unsigned hashcode;
380 const StructType type;
381 const SmallVector<ElaboratorValue> fields;
382};
383
384/// Storage object for nominal variant values. The constructor label and payload
385/// define runtime identity within the nominal type.
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) {}
391
392 bool isEqual(const VariantStorage *other) const {
393 return hashcode == other->hashcode && type == other->type &&
394 constructor == other->constructor && payload == other->payload;
395 }
396
397 const unsigned hashcode;
398 const VariantType type;
399 const StringAttr constructor;
400 const ElaboratorValue payload;
401};
402
403struct SymbolicComputationStorage {
404 SymbolicComputationStorage(const DenseMap<Value, ElaboratorValue> &state,
405 Operation *op)
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())) {}
414
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;
419 }
420
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;
427};
428
429// Values with identity not intended to be internalized.
430//===----------------------------------------------------------------------===//
431
432/// Base class for storages that represent values with identity, i.e., two
433/// values are not considered equivalent if they are structurally the same, but
434/// each definition of such a value is unique. E.g., unique labels or virtual
435/// registers. These cannot be materialized anew in each nested sequence, but
436/// must be passed as arguments.
437struct IdentityValue {
438
439 IdentityValue(Type type, Location loc) : type(type), loc(loc) {}
440
441#ifndef NDEBUG
442
443 /// In debug mode, track whether this value was already materialized to
444 /// assert if it's illegally materialized multiple times.
445 ///
446 /// Instead of deleting operations defining these values and materializing
447 /// them again, we could retain the operations. However, we still need
448 /// specific storages to represent these values in some cases, e.g., to get
449 /// the size of a memory allocation. Also, elaboration of nested control-flow
450 /// regions (e.g. `scf.for`) relies on materialization of such values lazily
451 /// instead of cloning the operations eagerly.
452 bool alreadyMaterialized = false;
453
454#endif
455
456 const Type type;
457 const Location loc;
458};
459
460/// Represents a unique virtual register.
461struct VirtualRegisterStorage : IdentityValue {
462 VirtualRegisterStorage(VirtualRegisterConfigAttr allowedRegs, Type type,
463 Location loc)
464 : IdentityValue(type, loc), allowedRegs(allowedRegs) {}
465
466 // NOTE: we don't need an 'isEqual' function and 'hashcode' here because
467 // VirtualRegisters are never internalized.
468
469 // The list of fixed registers allowed to be selected for this virtual
470 // register.
471 const VirtualRegisterConfigAttr allowedRegs;
472};
473
474struct UniqueLabelStorage : IdentityValue {
475 UniqueLabelStorage(const ElaboratorValue &name, Location loc)
476 : IdentityValue(LabelType::get(loc->getContext()), loc), name(name) {}
477
478 // NOTE: we don't need an 'isEqual' function and 'hashcode' here because
479 // VirtualRegisters are never internalized.
480
481 /// The label name. For unique labels, this is just the prefix.
482 const ElaboratorValue name;
483};
484
485/// Storage object for '!rtg.isa.memoryblock`-typed values.
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) {}
491
492 // The base address of the memory. The width of the APInt also represents the
493 // address width of the memory. This is an APInt to support memories of
494 // >64-bit machines.
495 const APInt baseAddress;
496
497 // The last address of the memory.
498 const APInt endAddress;
499};
500
501/// Storage object for '!rtg.isa.memory`-typed values.
502struct MemoryStorage : IdentityValue {
503 MemoryStorage(MemoryBlockStorage *memoryBlock, size_t size, size_t alignment,
504 Location loc)
505 : IdentityValue(MemoryType::get(memoryBlock->type.getContext(),
506 memoryBlock->baseAddress.getBitWidth()),
507 loc),
508 memoryBlock(memoryBlock), size(size), alignment(alignment) {}
509
510 MemoryBlockStorage *memoryBlock;
511 const size_t size;
512 const size_t alignment;
513};
514
515/// Storage object for an '!rtg.randomized_sequence'.
516struct RandomizedSequenceStorage : IdentityValue {
517 RandomizedSequenceStorage(ContextResourceAttrInterface context,
518 SequenceStorage *sequence, Location loc)
519 : IdentityValue(
520 RandomizedSequenceType::get(sequence->familyName.getContext()),
521 loc),
522 context(context), sequence(sequence) {}
523
524 // The context under which this sequence is placed.
525 const ContextResourceAttrInterface context;
526
527 const SequenceStorage *sequence;
528};
529
530/// Operation must have at least 1 result.
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()) {}
540
541 const OperationName name;
542 const SmallVector<Type> resultTypes;
543 const SmallVector<ElaboratorValue> operands;
544 const DictionaryAttr attributes;
545 const Attribute properties;
546};
547
548struct SymbolicComputationWithIdentityValue : IdentityValue {
549 SymbolicComputationWithIdentityValue(
550 Type type, const SymbolicComputationWithIdentityStorage *storage,
551 unsigned idx)
552 : IdentityValue(type, storage->loc), storage(storage), idx(idx) {
553 assert(
554 idx != 0 &&
555 "Use SymbolicComputationWithIdentityStorage for result with index 0.");
556 }
557
558 const SymbolicComputationWithIdentityStorage *storage;
559 const unsigned idx;
560};
561
562/// Storage for SSA values produced by external ops with regions — block
563/// arguments and results. Carries identity only; the corresponding new-IR
564/// `Value` is registered via `Materializer::map()` immediately upon creation so
565/// `Materializer::materialize()` always hits its cache and never dispatches
566// through `visit()`.
567struct OpaqueExternalStorage : IdentityValue {
568 OpaqueExternalStorage(Type type, Location loc) : IdentityValue(type, loc) {}
569};
570
571struct ContinuationBoundary {
572 uint64_t sequence = 0;
573 SmallVector<uint64_t> externalRegions;
574 uint64_t elaborator = 0;
575};
576
577/// Storage object for '!rtg.mut<T>' — a mutable elaboration-time cell.
578/// Each rtg.mut_create produces a unique cell (identity value).
579struct MutStorage : IdentityValue {
580 MutStorage(Type type, Location loc, ContinuationBoundary boundary)
581 : IdentityValue(type, loc), boundary(std::move(boundary)) {}
582
583 /// Boundaries whose lifetime contains this cell.
584 ContinuationBoundary boundary;
585};
586
587/// Maps effect names to their handler regions within a single rtg.handle op.
588struct HandlerFrame {
589 uint64_t promptToken = 0;
590 DenseMap<StringAttr, Region *> handlers;
591};
592
593/// A block invocation owns its lexical bindings and instruction cursor.
594struct BlockFrame {
595 Block *block = nullptr;
596 Operation *nextOp = nullptr;
597 bool keepTerminator = false;
598 bool eraseTerminator = true;
599 bool replay = false;
600 LexicalEnvironment environment;
601};
602
603/// Completion frames make nested-region control flow explicit and replayable.
604class Elaborator;
605
606struct ScfIfFrame {
607 scf::IfOp op;
608 bool replay = false;
609
610 LogicalResult step(Elaborator &elaborator,
611 ArrayRef<ElaboratorValue> yieldedValues);
612};
613
614struct VariantMatchFrame {
615 VariantMatchOp op;
616};
617
618struct ScfForFrame {
619 scf::ForOp op;
620 size_t nextIteration = 0;
621 size_t upperBound = 0;
622 size_t loopStep = 1;
623 bool replay = false;
624 bool completed = false;
625 LexicalEnvironment loopEnvironment;
626
627 LogicalResult step(Elaborator &elaborator,
628 ArrayRef<ElaboratorValue> yieldedValues);
629};
630
631struct RandomScopeFrame {
632 RandomScopeOp op;
633 RngScope outerRng;
634 bool replay = false;
635
636 RandomScopeFrame(RandomScopeOp op, RngScope outerRng, bool replay)
637 : op(op), outerRng(std::move(outerRng)), replay(replay) {}
638};
639
640struct WithHandlersFrame {
641 WithHandlersOp op;
642 uint64_t promptId = 0;
643 bool replay = false;
644};
645
646struct HandlerClauseFrame {};
647
648struct FunctionCallFrame {
649 func::CallOp call;
650};
651
652/// The materialized shell owns an external region while its block is visited.
653struct ExternalOpFrame {
654 Operation *originalOp = nullptr;
655 Operation *materializedOp = nullptr;
656 size_t nextRegion = 0;
657 uint64_t activeBoundary = 0;
658 bool replay = false;
659 LexicalEnvironment parentEnvironment;
660 OpBuilder::InsertPoint parentInsertionPoint;
661};
662
663/// Saves the handler and RNG context around one replay shot.
664struct ResumeFrame {
665 SmallVector<HandlerFrame> handlerStack;
666 RngScope rng;
667
668 ResumeFrame(SmallVector<HandlerFrame> handlerStack, RngScope rng)
669 : handlerStack(std::move(handlerStack)), rng(std::move(rng)) {}
670};
671
672using EvalFramePayload =
673 std::variant<BlockFrame, ScfIfFrame, VariantMatchFrame, ScfForFrame,
674 RandomScopeFrame, WithHandlersFrame, HandlerClauseFrame,
675 FunctionCallFrame, ExternalOpFrame, ResumeFrame>;
676
677struct EvalFrame {
678 EvalFramePayload payload;
679
680 template <typename FrameTy>
681 explicit EvalFrame(FrameTy &&frame) : payload(std::forward<FrameTy>(frame)) {}
682
683 EvalFrame(const EvalFrame &) = default;
684
685 std::unique_ptr<EvalFrame> clone() const {
686 return std::make_unique<EvalFrame>(*this);
687 }
688
689 template <typename FrameTy>
690 FrameTy *getIf() {
691 return std::get_if<FrameTy>(&payload);
692 }
693
694 template <typename FrameTy>
695 const FrameTy *getIf() const {
696 return std::get_if<FrameTy>(&payload);
697 }
698
699 template <typename FrameTy>
700 FrameTy &get() {
701 return std::get<FrameTy>(payload);
702 }
703
704 template <typename FrameTy>
705 bool holds() const {
706 return std::holds_alternative<FrameTy>(payload);
707 }
708};
709
710using EvalFrameStack = SmallVector<std::unique_ptr<EvalFrame>, 0>;
711
712/// Storage object for '!rtg.continuation<T>' — a captured elaboration frame.
713/// Holds a replayable lexical environment and evaluator frames to resume.
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,
720 Location loc)
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)) {}
727
728 /// Suspended evaluator frames from the perform site up to the handler prompt.
729 EvalFrameStack capturedFrames;
730 /// The SSA result of the rtg.perform op (null for unit-result effects).
731 Value performResult;
732 /// Handler-stack snapshot at the point the perform was triggered.
733 SmallVector<HandlerFrame> capturedHandlerStack;
734 /// SSA bindings at the perform site. Identity-bearing cells remain shared.
735 LexicalEnvironment capturedEnvironment;
736 /// RNG state at the perform site, restored independently for each shot.
737 RngScope capturedRng;
738 /// Dynamic handler installation that delimits this continuation.
739 uint64_t promptToken;
740 /// Dynamic boundaries that the captured ops must not outlive.
741 ContinuationBoundary boundary;
742};
743
744/// An 'Internalizer' object internalizes storages and takes ownership of them.
745/// When the initializer object is destroyed, all owned storages are also
746/// deallocated and thus must not be accessed anymore.
747class Internalizer {
748public:
749 ~Internalizer() {
750 for (auto it = destructors.rbegin(); it != destructors.rend(); ++it)
751 it->second(it->first);
752 }
753
754 /// Internalize a storage of type `StorageTy` constructed with arguments
755 /// `args`. The pointers returned by this method can be used to compare
756 /// objects when, e.g., computing set differences, uniquing the elements in a
757 /// set, etc. Otherwise, we'd need to do a deep value comparison in those
758 /// situations.
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");
763
764 StorageTy storage(std::forward<Args>(args)...);
765
766 auto existing = getInternSet<StorageTy>().insert_as(
767 HashedStorage<StorageTy>(storage.hashcode), storage);
768 StorageTy *&storagePtr = existing.first->storage;
769 if (existing.second) {
770 storagePtr =
771 new (allocator.Allocate<StorageTy>()) StorageTy(std::move(storage));
772 registerDestructor(storagePtr);
773 }
774
775 return storagePtr;
776 }
777
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");
782
783 StorageTy *storage = new (allocator.Allocate<StorageTy>())
784 StorageTy(std::forward<Args>(args)...);
785 registerDestructor(storage);
786 return storage;
787 }
788
789private:
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();
795 });
796 }
797
798 template <typename StorageTy>
799 DenseSet<HashedStorage<StorageTy>, StorageKeyInfo<StorageTy>> &
800 getInternSet() {
801 if constexpr (std::is_same_v<StorageTy, ArrayStorage>)
802 return internedArrays;
803 else if constexpr (std::is_same_v<StorageTy, SetStorage>)
804 return internedSets;
805 else if constexpr (std::is_same_v<StorageTy, BagStorage>)
806 return internedBags;
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;
821 else
822 static_assert(!sizeof(StorageTy),
823 "no intern set available for this storage type.");
824 }
825
826 // This allocator allocates raw storage on the heap and releases it when
827 // destroyed. The registered destructors above handle object lifetimes.
828 llvm::BumpPtrAllocator allocator;
829
830 /// BumpPtrAllocator releases raw storage but does not destroy objects placed
831 /// in it. Track non-trivial objects so their owned heap allocations are
832 /// freed.
833 SmallVector<std::pair<void *, void (*)(void *)>> destructors;
834
835 // The sets holding the internalized objects. We use one set per storage type
836 // such that we can have a simpler equality checking function (no need to
837 // compare some sort of TypeIDs).
838 DenseSet<HashedStorage<ArrayStorage>, StorageKeyInfo<ArrayStorage>>
839 internedArrays;
840 DenseSet<HashedStorage<SetStorage>, StorageKeyInfo<SetStorage>> internedSets;
841 DenseSet<HashedStorage<BagStorage>, StorageKeyInfo<BagStorage>> internedBags;
842 DenseSet<HashedStorage<SequenceStorage>, StorageKeyInfo<SequenceStorage>>
843 internedSequences;
844 DenseSet<HashedStorage<RandomizedSequenceStorage>,
845 StorageKeyInfo<RandomizedSequenceStorage>>
846 internedRandomizedSequences;
847 DenseSet<HashedStorage<InterleavedSequenceStorage>,
848 StorageKeyInfo<InterleavedSequenceStorage>>
849 internedInterleavedSequences;
850 DenseSet<HashedStorage<TupleStorage>, StorageKeyInfo<TupleStorage>>
851 internedTuples;
852 DenseSet<HashedStorage<StructStorage>, StorageKeyInfo<StructStorage>>
853 internedStructs;
854 DenseSet<HashedStorage<VariantStorage>, StorageKeyInfo<VariantStorage>>
855 internedVariants;
856 DenseSet<HashedStorage<SymbolicComputationStorage>,
857 StorageKeyInfo<SymbolicComputationStorage>>
858 internedSymbolicComputationWithIdentityValues;
859};
860
861} // namespace
862
863#ifndef NDEBUG
864
865static llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
866 const ElaboratorValue &value);
867
868static void print(TypedAttr val, llvm::raw_ostream &os) {
869 os << "<attr " << val << ">";
870}
871
872static void print(BagStorage *val, llvm::raw_ostream &os) {
873 os << "<bag {";
874 llvm::interleaveComma(val->bag, os,
875 [&](const std::pair<ElaboratorValue, uint64_t> &el) {
876 os << el.first << " -> " << el.second;
877 });
878 os << "} at " << val << ">";
879}
880
881static void print(bool val, llvm::raw_ostream &os) {
882 os << "<bool " << (val ? "true" : "false") << ">";
883}
884
885static void print(size_t val, llvm::raw_ostream &os) {
886 os << "<index " << val << ">";
887}
888
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 << ">";
894}
895
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 << ">";
903}
904
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 << ">";
910}
911
912static void print(ArrayStorage *val, llvm::raw_ostream &os) {
913 os << "<array [";
914 llvm::interleaveComma(val->array, os,
915 [&](const ElaboratorValue &val) { os << val; });
916 os << "] at " << val << ">";
917}
918
919static void print(SetStorage *val, llvm::raw_ostream &os) {
920 os << "<set {";
921 llvm::interleaveComma(val->set, os,
922 [&](const ElaboratorValue &val) { os << val; });
923 os << "} at " << val << ">";
924}
925
926static void print(const VirtualRegisterStorage *val, llvm::raw_ostream &os) {
927 os << "<virtual-register " << val << " " << val->allowedRegs << ">";
928}
929
930static void print(const UniqueLabelStorage *val, llvm::raw_ostream &os) {
931 os << "<unique-label " << val << " " << val->name << ">";
932}
933
934static void print(const TupleStorage *val, llvm::raw_ostream &os) {
935 os << "<tuple (";
936 llvm::interleaveComma(val->values, os,
937 [&](const ElaboratorValue &val) { os << val; });
938 os << ")>";
939}
940
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; });
945 os << "]>";
946}
947
948static void print(const VariantStorage *val, llvm::raw_ostream &os) {
949 os << "<variant " << val->type << " " << val->constructor << " "
950 << val->payload << ">";
951}
952
953static void print(const MemoryStorage *val, llvm::raw_ostream &os) {
954 os << "<memory {" << ElaboratorValue(val->memoryBlock)
955 << ", size=" << val->size << ", alignment=" << val->alignment << "}>";
956}
957
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 << "}>";
963}
964
965static void print(const SymbolicComputationWithIdentityValue *val,
966 llvm::raw_ostream &os) {
967 os << "<symbolic-computation-with-identity-value (" << val->storage << ") at "
968 << val->idx << ">";
969}
970
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;
978 os << ">";
979}
980
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;
988 os << ">";
989}
990
991static void print(const OpaqueExternalStorage *val, llvm::raw_ostream &os) {
992 os << "<opaque-external " << val->type << ">";
993}
994
995static void print(const MutStorage *val, llvm::raw_ostream &os) {
996 os << "<mut at " << val << ">";
997}
998
999static void print(const ContinuationStorage *val, llvm::raw_ostream &os) {
1000 os << "<continuation with " << val->capturedFrames.size() << " frames at "
1001 << val << ">";
1002}
1003
1004static llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
1005 const ElaboratorValue &value) {
1006 std::visit([&](auto val) { print(val, os); }, value);
1007
1008 return os;
1009}
1010
1011#endif
1012
1013//===----------------------------------------------------------------------===//
1014// Attribute <-> ElaboratorValue Converters
1015//===----------------------------------------------------------------------===//
1016
1017namespace {
1018
1019/// Convert an attribute to an ElaboratorValue. This handles nested attributes
1020/// like SetAttr and TupleAttr recursively.
1021class AttributeToElaboratorValueConverter {
1022public:
1023 AttributeToElaboratorValueConverter(Internalizer &internalizer)
1024 : internalizer(internalizer) {}
1025
1026 /// Convert an attribute to an ElaboratorValue.
1027 // NOLINTBEGIN(misc-no-recursion): Nested attributes are converted
1028 // recursively.
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);
1035 })
1036 .Default(
1037 [&](Attribute) -> FailureOr<ElaboratorValue> { return failure(); });
1038 }
1039
1040private:
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);
1047 }
1048
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))
1054 return failure();
1055 set.insert(*converted);
1056 }
1057 auto *storage =
1058 internalizer.internalize<SetStorage>(std::move(set), setAttr.getType());
1059 // Cache the original attribute for efficient materialization
1060 storage->attrCache = setAttr;
1061 return ElaboratorValue(storage);
1062 }
1063
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))
1069 return failure();
1070 values.push_back(*converted);
1071 }
1072 auto *storage = internalizer.internalize<TupleStorage>(std::move(values));
1073 // Cache the original attribute for efficient materialization
1074 storage->attrCache = tupleAttr;
1075 return ElaboratorValue(storage);
1076 }
1077
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))
1083 return failure();
1084 fields.push_back(*converted);
1085 }
1086 auto *storage = internalizer.internalize<StructStorage>(
1087 structAttr.getType(), std::move(fields));
1088 storage->attrCache = structAttr;
1089 return ElaboratorValue(storage);
1090 }
1091
1092 FailureOr<ElaboratorValue> convert(VariantAttr variantAttr) {
1093 auto payload = convert(variantAttr.getPayload());
1094 if (failed(payload))
1095 return failure();
1096 auto *storage = internalizer.internalize<VariantStorage>(
1097 variantAttr.getType(), variantAttr.getConstructor(), *payload);
1098 storage->attrCache = variantAttr;
1099 return ElaboratorValue(storage);
1100 }
1101 // NOLINTEND(misc-no-recursion)
1102
1103 Internalizer &internalizer;
1104};
1105
1106/// Convert an ElaboratorValue to an attribute when possible. Not all
1107/// ElaboratorValues can be converted to attributes (e.g., values with
1108/// identity).
1109class ElaboratorValueToAttributeConverter {
1110public:
1111 ElaboratorValueToAttributeConverter(MLIRContext *context)
1112 : context(context) {}
1113
1114 /// Convert an ElaboratorValue to an attribute. Returns a null attribute if
1115 /// the conversion is not possible.
1116 TypedAttr convert(const ElaboratorValue &value) {
1117 return std::visit(
1118 [&](auto val) -> TypedAttr {
1119 if constexpr (std::is_base_of_v<CachableStorage,
1120 std::remove_pointer_t<
1121 std::decay_t<decltype(value)>>>) {
1122 if (val->attrCache)
1123 return val->attrCache;
1124 }
1125 return visit(val);
1126 },
1127 value);
1128 }
1129
1130private:
1131 TypedAttr visit(TypedAttr val) { return val; }
1132
1133 TypedAttr visit(bool val) {
1134 return IntegerAttr::get(IntegerType::get(context, 1), val);
1135 }
1136
1137 TypedAttr visit(size_t val) {
1138 return IntegerAttr::get(IndexType::get(context), val);
1139 }
1140
1141 TypedAttr visit(SetStorage *val) {
1142 DenseSet<TypedAttr> elements;
1143 for (auto element : val->set) {
1144 auto converted = convert(element);
1145 if (!converted)
1146 return {};
1147 auto typedAttr = dyn_cast<TypedAttr>(converted);
1148 if (!typedAttr)
1149 return {};
1150 elements.insert(typedAttr);
1151 }
1152 return SetAttr::get(cast<SetType>(val->type), &elements);
1153 }
1154
1155 TypedAttr visit(TupleStorage *val) {
1156 SmallVector<TypedAttr> elements;
1157 for (auto element : val->values) {
1158 auto converted = convert(element);
1159 if (!converted)
1160 return {};
1161 auto typedAttr = dyn_cast<TypedAttr>(converted);
1162 if (!typedAttr)
1163 return {};
1164 elements.push_back(typedAttr);
1165 }
1166 return TupleAttr::get(context, elements);
1167 }
1168
1169 TypedAttr visit(StructStorage *val) {
1170 SmallVector<TypedAttr> fields;
1171 for (auto field : val->fields) {
1172 auto converted = convert(field);
1173 if (!converted)
1174 return {};
1175 fields.push_back(converted);
1176 }
1177 return StructAttr::get(context, val->type, fields);
1178 }
1179
1180 TypedAttr visit(VariantStorage *val) {
1181 TypedAttr payload = convert(val->payload);
1182 if (!payload)
1183 return {};
1184 return VariantAttr::get(context, val->type, val->constructor, payload);
1185 }
1186
1187 // Default implementation for storage types that cannot be converted to
1188 // attributes. Using a macro to avoid repetition. std::visit does not support
1189 // any kind of "default" clauses, unfortunately.
1190#define VISIT_UNSUPPORTED(STORAGETYPE) \
1191 /* NOLINTNEXTLINE(bugprone-macro-parentheses)*/ \
1192 TypedAttr visit(STORAGETYPE *val) { return {}; }
1193
1194 VISIT_UNSUPPORTED(ArrayStorage)
1195 VISIT_UNSUPPORTED(BagStorage)
1196 VISIT_UNSUPPORTED(SequenceStorage)
1197 VISIT_UNSUPPORTED(RandomizedSequenceStorage)
1198 VISIT_UNSUPPORTED(InterleavedSequenceStorage)
1199 VISIT_UNSUPPORTED(VirtualRegisterStorage)
1200 VISIT_UNSUPPORTED(UniqueLabelStorage)
1201 VISIT_UNSUPPORTED(MemoryStorage)
1202 VISIT_UNSUPPORTED(MemoryBlockStorage)
1203 VISIT_UNSUPPORTED(SymbolicComputationWithIdentityStorage)
1204 VISIT_UNSUPPORTED(SymbolicComputationWithIdentityValue)
1205 VISIT_UNSUPPORTED(SymbolicComputationStorage)
1206 VISIT_UNSUPPORTED(OpaqueExternalStorage)
1207 VISIT_UNSUPPORTED(MutStorage)
1208 VISIT_UNSUPPORTED(ContinuationStorage)
1209
1210#undef VISIT_UNSUPPORTED
1211
1212 MLIRContext *context;
1213};
1214
1215} // namespace
1216
1217//===----------------------------------------------------------------------===//
1218// Elaborator Value Materialization
1219//===----------------------------------------------------------------------===//
1220
1221namespace {
1222
1223/// State that should be shared by all elaborator and materializer instances.
1224struct SharedState {
1225 SharedState(MLIRContext *ctxt, SymbolTable &table)
1226 : ctxt(ctxt), table(table) {}
1227
1228 uint64_t createBoundaryToken() { return nextBoundaryToken++; }
1229
1230 MLIRContext *ctxt;
1231 SymbolTable &table;
1232 Namespace names;
1233 Internalizer internalizer;
1234 DenseMap<MutStorage *, ElaboratorValue> mutableStore;
1235
1236private:
1237 uint64_t nextBoundaryToken = 1;
1238};
1239
1240/// A collection of state per RTG test.
1241struct TestState {
1242 explicit TestState(unsigned seed) : rng(RngScope(seed)) {}
1243
1244 /// The name of the test.
1245 StringAttr name;
1246
1247 /// The context switches registered for this test.
1248 MapVector<
1249 std::pair<ContextResourceAttrInterface, ContextResourceAttrInterface>,
1250 SequenceStorage *>
1251 contextSwitches;
1252
1253 /// The root RNG scope for this test.
1254 RngScope rng;
1255};
1256
1257/// Construct an SSA value from a given elaborated value.
1258class Materializer {
1259public:
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()) {}
1266
1267 /// Materialize IR representing the provided `ElaboratorValue` and return the
1268 /// `Value` or a null value on failure.
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;
1274
1275 LLVM_DEBUG(llvm::dbgs() << "Materializing " << val);
1276
1277 if (auto res = tryMaterializeAsConstant(val, loc))
1278 return res;
1279
1280 // In debug mode, track whether values with identity were already
1281 // materialized before and assert in such a situation.
1282 Value res = std::visit(
1283 [&](auto value) {
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)) {
1288#ifndef NDEBUG
1289 bool &materialized =
1290 static_cast<IdentityValue *>(value)->alreadyMaterialized;
1291 assert(!materialized && "must not already be materialized");
1292 materialized = true;
1293#endif
1294
1295 return visit(value, loc, emitError);
1296 }
1297
1298 Value arg = builder.getBlock()->addArgument(value->type, loc);
1299 blockArgs.push_back(val);
1300 blockArgTypes.push_back(arg.getType());
1301 materializedValues[val] = arg;
1302 return arg;
1303 }
1304
1305 return visit(value, loc, emitError);
1306 },
1307 val);
1308
1309 LLVM_DEBUG(llvm::dbgs() << " to\n" << res << "\n\n");
1310
1311 return res;
1312 }
1313
1314 bool isInPlace(Operation *op) const {
1315 return builder.getBlock()->getParent() == op->getParentRegion();
1316 }
1317
1318 /// If `op` is not in the same region as the materializer insertion point, a
1319 /// clone is created at the materializer's insertion point by also
1320 /// materializing the `ElaboratorValue`s for each operand just before it.
1321 /// Otherwise, all operations after the materializer's insertion point are
1322 /// deleted until `op` is reached. An error is returned if the operation is
1323 /// before the insertion point.
1324 LogicalResult materialize(Operation *op,
1325 DenseMap<Value, ElaboratorValue> &state,
1326 bool forceClone = false) {
1327 // Region-bearing ops must be elaborated away before reaching here (either
1328 // by a dedicated visitor, or by visitExternalOp which performs its own
1329 // structural rewrite). Routing them through this generic operand-only
1330 // materialize path would silently keep un-elaborated regions in the
1331 // output.
1332 if (op->getNumRegions() > 0)
1333 return op->emitOpError("ops with nested regions must be elaborated away");
1334
1335 // A retained operation's used results need an elaborated representation so
1336 // later operations can rematerialize them at the rewritten call site.
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");
1341
1342 Operation *sourceOp = op;
1343 if (isInPlace(op) && !forceClone) {
1344 // We are doing in-place materialization, so mark all ops deleted until we
1345 // reach the one to be materialized and modify it in-place.
1346 deleteOpsUntil([&](auto iter) { return &*iter == op; });
1347
1348 if (builder.getInsertionPoint() == builder.getBlock()->end())
1349 return op->emitError("operation did not occur after the current "
1350 "materializer insertion point");
1351
1352 LLVM_DEBUG(llvm::dbgs() << "Modifying in-place: " << *op << "\n\n");
1353 } else {
1354 LLVM_DEBUG(llvm::dbgs() << "Materializing a clone of " << *op << "\n\n");
1355 op = builder.clone(*op);
1356 builder.setInsertionPoint(op);
1357 }
1358
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();
1365 return diag;
1366 };
1367
1368 auto elabVal = state.at(operand.get());
1369 Value val = materialize(elabVal, op->getLoc(), emitError);
1370 if (!val)
1371 return failure();
1372
1373 state[val] = elabVal;
1374 operand.set(val);
1375 }
1376
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;
1381
1382 builder.setInsertionPointAfter(op);
1383 return success();
1384 }
1385
1386 /// Should be called once the `Region` is successfully materialized. No calls
1387 /// to `materialize` should happen after this anymore.
1388 void finalize() {
1389 deleteOpsUntil([](auto iter) { return false; });
1390
1391 for (auto *op : llvm::reverse(toDelete))
1392 op->erase();
1393 }
1394
1395 /// Tell this materializer that it is responsible for materializing the given
1396 /// identity value at the earliest position it is needed, and should't
1397 /// request the value via block argument.
1398 void registerIdentityValue(IdentityValue *val) {
1399 identityValueRoot.insert(val);
1400 }
1401
1402 ArrayRef<Type> getBlockArgTypes() const { return blockArgTypes; }
1403
1404 void map(ElaboratorValue eval, Value val) { materializedValues[eval] = val; }
1405
1406 OpBuilder &getBuilder() { return builder; }
1407
1408 template <typename OpTy, typename... Args>
1409 OpTy create(Location location, Args &&...args) {
1410 return OpTy::create(builder, location, std::forward<Args>(args)...);
1411 }
1412
1413private:
1414 Value tryMaterializeAsConstant(ElaboratorValue val, Location loc) {
1415 if (auto attr = attrConverter.convert(val)) {
1416 // Hoist constants to the materializer's root block when the builder's
1417 // current insertion point is in a nested region. This ensures the
1418 // constant's defining region dominates every potential use, including
1419 // sibling regions that share this materializer's value cache.
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;
1425 return res;
1426 }
1427
1428 return Value();
1429 }
1430
1431 SequenceOp elaborateSequence(const RandomizedSequenceStorage *seq,
1432 SmallVector<ElaboratorValue> &elabArgs);
1433
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);
1439
1440 builder.setInsertionPointAfter(&*ip);
1441 ip = builder.getInsertionPoint();
1442 }
1443 }
1444
1445 Value visit(TypedAttr val, Location loc,
1446 function_ref<InFlightDiagnostic()> emitError) {
1447 return {};
1448 }
1449
1450 Value visit(size_t val, Location loc,
1451 function_ref<InFlightDiagnostic()> emitError) {
1452 return {};
1453 }
1454
1455 Value visit(bool val, Location loc,
1456 function_ref<InFlightDiagnostic()> emitError) {
1457 return {};
1458 }
1459
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);
1466 if (!materialized)
1467 return Value();
1468
1469 elements.push_back(materialized);
1470 }
1471
1472 Value res = ArrayCreateOp::create(builder, loc, val->type, elements);
1473 materializedValues[val] = res;
1474 return res;
1475 }
1476
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);
1483 if (!materialized)
1484 return Value();
1485
1486 elements.push_back(materialized);
1487 }
1488
1489 auto res = SetCreateOp::create(builder, loc, val->type, elements);
1490 materializedValues[val] = res;
1491 return res;
1492 }
1493
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)
1503 return Value();
1504
1505 values.push_back(materializedVal);
1506 weights.push_back(materializedWeight);
1507 }
1508
1509 auto res = BagCreateOp::create(builder, loc, val->type, values, weights);
1510 materializedValues[val] = res;
1511 return res;
1512 }
1513
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;
1522 return res;
1523 }
1524
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))
1531 return {};
1532
1533 Value res =
1534 MemoryAllocOp::create(builder, val->loc, memBlock, memSize, memAlign);
1535 materializedValues[val] = res;
1536 return res;
1537 }
1538
1539 Value visit(SequenceStorage *val, Location loc,
1540 function_ref<InFlightDiagnostic()> emitError) {
1541 emitError() << "materializing a non-randomized sequence not supported yet";
1542 return Value();
1543 }
1544
1545 Value visit(RandomizedSequenceStorage *val, Location loc,
1546 function_ref<InFlightDiagnostic()> emitError) {
1547 // To know which values we have to pass by argument (and not just pass all
1548 // that migth be used eagerly), we have to elaborate the sequence family if
1549 // not already done so.
1550 // We need to get back the sequence to reference, and the list of elaborated
1551 // values to pass as arguments.
1552 SmallVector<ElaboratorValue> elabArgs;
1553 // NOTE: we wouldn't need to elaborate the sequence if it doesn't contain
1554 // randomness to be elaborated.
1555 SequenceOp seqOp = elaborateSequence(val, elabArgs);
1556 if (!seqOp)
1557 return {};
1558
1559 // Materialize all the values we need to pass as arguments and collect their
1560 // types.
1561 SmallVector<Value> args;
1562 SmallVector<Type> argTypes;
1563 for (auto arg : elabArgs) {
1564 Value materialized = materialize(arg, val->loc, emitError);
1565 if (!materialized)
1566 return {};
1567
1568 args.push_back(materialized);
1569 argTypes.push_back(materialized.getType());
1570 }
1571
1572 Value res = GetSequenceOp::create(
1573 builder, val->loc, SequenceType::get(builder.getContext(), argTypes),
1574 seqOp.getSymName());
1575
1576 // Only materialize a substitute_sequence op when we have arguments to
1577 // substitute since this op does not support 0 arguments.
1578 if (!args.empty())
1579 res = SubstituteSequenceOp::create(builder, val->loc, res, args);
1580
1581 res = RandomizeSequenceOp::create(builder, val->loc, res);
1582
1583 materializedValues[val] = res;
1584 return res;
1585 }
1586
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);
1592 if (!materialized)
1593 return {};
1594
1595 sequences.push_back(materialized);
1596 }
1597
1598 if (sequences.size() == 1)
1599 return sequences[0];
1600
1601 Value res =
1602 InterleaveSequencesOp::create(builder, loc, sequences, val->batchSize);
1603 materializedValues[val] = res;
1604 return res;
1605 }
1606
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;
1611 return res;
1612 }
1613
1614 Value visit(UniqueLabelStorage *val, Location loc,
1615 function_ref<InFlightDiagnostic()> emitError) {
1616 auto materialized = materialize(val->name, val->loc, emitError);
1617 if (!materialized)
1618 return {};
1619 Value res = LabelUniqueDeclOp::create(builder, val->loc, materialized);
1620 materializedValues[val] = res;
1621 return res;
1622 }
1623
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);
1630 if (!value)
1631 return {};
1632 materialized.push_back(value);
1633 }
1634 Value res = TupleCreateOp::create(builder, loc, materialized);
1635 materializedValues[val] = res;
1636 return res;
1637 }
1638
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);
1645 if (!value)
1646 return {};
1647 fields.push_back(value);
1648 }
1649 Value res = StructCreateOp::create(builder, loc, val->type, fields);
1650 materializedValues[val] = res;
1651 return res;
1652 }
1653
1654 Value visit(VariantStorage *val, Location loc,
1655 function_ref<InFlightDiagnostic()> emitError) {
1656 Value payload = materialize(val->payload, loc, emitError);
1657 if (!payload)
1658 return {};
1659 Value result =
1660 VariantCreateOp::create(builder, loc, val->type, ValueRange{payload},
1661 val->constructor.getValue());
1662 materializedValues[val] = result;
1663 return result;
1664 }
1665
1666 Value visit(MutStorage *val, Location loc,
1667 function_ref<InFlightDiagnostic()> emitError) {
1668 emitError() << "mutable cell cannot escape into materialized IR";
1669 return {};
1670 }
1671
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";
1676 return {};
1677 }
1678
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);
1684 if (!res0)
1685 return {};
1686
1687 auto *op = res0.getDefiningOp();
1688 auto res = op->getResults()[val->idx];
1689 materializedValues[val] = res;
1690 return res;
1691 }
1692
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);
1698 if (!materialized)
1699 return {};
1700
1701 operands.push_back(materialized);
1702 }
1703
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);
1710
1711 materializedValues[val] = op->getResult(0);
1712 return op->getResult(0);
1713 }
1714
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);
1720 if (!materialized)
1721 return {};
1722
1723 operands.push_back(materialized);
1724 }
1725
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);
1732
1733 for (auto res : op->getResults())
1734 materializedValues[val] = res;
1735
1736 return op->getResult(0);
1737 }
1738
1739 Value visit(OpaqueExternalStorage *val, Location loc,
1740 function_ref<InFlightDiagnostic()> emitError) {
1741 // Opaque external values (block arguments and results of external
1742 // region-bearing ops) are always pre-mapped to a concrete SSA value by
1743 // visitExternalOp, so materialize() short-circuits via the cache before
1744 // reaching here.
1745 emitError() << "cannot materialize opaque external value";
1746 return {};
1747 }
1748
1749private:
1750 /// Cache values we have already materialized to reuse them later. We start
1751 /// with an insertion point at the start of the block and cache the (updated)
1752 /// insertion point such that future materializations can also reuse previous
1753 /// materializations without running into dominance issues (or requiring
1754 /// additional checks to avoid them).
1755 DenseMap<ElaboratorValue, Value> materializedValues;
1756
1757 /// Cache the builder to continue insertions at their current insertion point
1758 /// for the reason stated above.
1759 OpBuilder builder;
1760
1761 /// The block this materializer was constructed at. Used as the hoist target
1762 /// for constants that would otherwise be sunk into nested sibling regions.
1763 Block *rootBlock;
1764
1765 SmallVector<Operation *> toDelete;
1766
1767 TestState &testState;
1768 SharedState &sharedState;
1769
1770 /// Keep track of the block arguments we had to add to this materializer's
1771 /// block for identity values and also remember which elaborator values are
1772 /// expected to be passed as arguments from outside.
1773 SmallVector<ElaboratorValue> &blockArgs;
1774 SmallVector<Type> blockArgTypes;
1775
1776 /// Identity values in this set are materialized by this materializer,
1777 /// otherwise they are added as block arguments and the block that wants to
1778 /// embed this sequence is expected to provide a value for it.
1779 DenseSet<IdentityValue *> identityValueRoot;
1780
1781 /// Helper to convert ElaboratorValues to attributes.
1782 ElaboratorValueToAttributeConverter attrConverter;
1783};
1784
1785//===----------------------------------------------------------------------===//
1786// Elaboration Visitor
1787//===----------------------------------------------------------------------===//
1788
1789/// Used to signal to the elaboration driver whether the operation should be
1790/// removed.
1791enum class DeletionKind { Keep, Delete };
1792
1793/// A perform yields control to the trampoline instead of recursively invoking
1794/// its handler. The prompt identifies the matching dynamic handler frame.
1795struct ControlTransfer {
1796 uint64_t promptId;
1797 PerformOp perform;
1798};
1799
1800/// Interprets the IR to perform and lower the represented randomizations.
1801class Elaborator : public RTGOpVisitor<Elaborator, FailureOr<DeletionKind>> {
1802public:
1803 using RTGBase = RTGOpVisitor<Elaborator, FailureOr<DeletionKind>>;
1804 using RTGBase::visitOp;
1805
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) {}
1816
1817 template <typename ValueTy>
1818 inline ValueTy get(Value val) const {
1819 return std::get<ValueTy>(state.at(val));
1820 }
1821
1822 /// Print a nice error message for operations we don't support yet.
1823 FailureOr<DeletionKind> visitUnhandledOp(Operation *op) {
1824 return visitOpGeneric(op);
1825 }
1826
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");
1832 }
1833
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;
1840 }
1841
1842 FailureOr<DeletionKind> visitOp(SubstituteSequenceOp op) {
1843 if (isSymbolic(state.at(op.getSequence())))
1844 return visitOpGeneric(op);
1845
1846 auto *seq = get<SequenceStorage *>(op.getSequence());
1847
1848 SmallVector<ElaboratorValue> replacements(seq->args);
1849 for (auto replacement : op.getReplacements())
1850 replacements.push_back(state.at(replacement));
1851
1852 state[op.getResult()] =
1853 sharedState.internalizer.internalize<SequenceStorage>(
1854 seq->familyName, std::move(replacements));
1855
1856 return DeletionKind::Delete;
1857 }
1858
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>(
1867 randomizedSeq);
1868 return DeletionKind::Delete;
1869 }
1870
1871 FailureOr<DeletionKind> visitOp(InterleaveSequencesOp op) {
1872 SmallVector<ElaboratorValue> sequences;
1873 for (auto seq : op.getSequences())
1874 sequences.push_back(state.at(seq));
1875
1876 state[op.getResult()] =
1877 sharedState.internalizer.internalize<InterleavedSequenceStorage>(
1878 std::move(sequences), op.getBatchSize());
1879 return DeletionKind::Delete;
1880 }
1881
1882 // NOLINTNEXTLINE(misc-no-recursion)
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 "
1889 << currentContext
1890 << ", but it was previously randomized for context ";
1891 if (seq->context)
1892 err << seq->context;
1893 else
1894 err << "'default'";
1895 return err;
1896 }
1897 return success();
1898 }
1899
1900 auto *interVal = std::get<InterleavedSequenceStorage *>(value);
1901 for (auto val : interVal->sequences)
1902 if (failed(isValidContext(val, op)))
1903 return failure();
1904 return success();
1905 }
1906
1907 FailureOr<DeletionKind> visitOp(EmbedSequenceOp op) {
1908 auto *seqVal = get<InterleavedSequenceStorage *>(op.getSequence());
1909 if (failed(isValidContext(seqVal, op)))
1910 return failure();
1911
1912 return DeletionKind::Keep;
1913 }
1914
1915 FailureOr<DeletionKind> visitOp(SetCreateOp op) {
1916 SetVector<ElaboratorValue> set;
1917 for (auto val : op.getElements())
1918 set.insert(state.at(val));
1919
1920 state[op.getSet()] = sharedState.internalizer.internalize<SetStorage>(
1921 std::move(set), op.getSet().getType());
1922 return DeletionKind::Delete;
1923 }
1924
1925 FailureOr<DeletionKind> visitOp(SetSelectRandomOp op) {
1926 auto set = get<SetStorage *>(op.getSet())->set;
1927
1928 if (set.empty())
1929 return op->emitError("cannot select from an empty set");
1930
1931 size_t selected = testState.rng.getUniformlyInRange(0, set.size() - 1);
1932 state[op.getResult()] = set[selected];
1933 return DeletionKind::Delete;
1934 }
1935
1936 FailureOr<DeletionKind> visitOp(SetDifferenceOp op) {
1937 auto original = get<SetStorage *>(op.getOriginal())->set;
1938 auto diff = get<SetStorage *>(op.getDiff())->set;
1939
1940 SetVector<ElaboratorValue> result(original);
1941 result.set_subtract(diff);
1942
1943 state[op.getResult()] = sharedState.internalizer.internalize<SetStorage>(
1944 std::move(result), op.getResult().getType());
1945 return DeletionKind::Delete;
1946 }
1947
1948 FailureOr<DeletionKind> visitOp(SetUnionOp op) {
1949 SetVector<ElaboratorValue> result;
1950 for (auto set : op.getSets())
1951 result.set_union(get<SetStorage *>(set)->set);
1952
1953 state[op.getResult()] = sharedState.internalizer.internalize<SetStorage>(
1954 std::move(result), op.getType());
1955 return DeletionKind::Delete;
1956 }
1957
1958 FailureOr<DeletionKind> visitOp(SetSizeOp op) {
1959 auto size = get<SetStorage *>(op.getSet())->set.size();
1960 state[op.getResult()] = size;
1961 return DeletionKind::Delete;
1962 }
1963
1964 // {a0,a1} x {b0,b1} x {c0,c1} -> {(a0), (a1)} -> {(a0,b0), (a0,b1), (a1,b0),
1965 // (a1,b1)} -> {(a0,b0,c0), (a0,b0,c1), (a0,b1,c0), (a0,b1,c1), (a1,b0,c0),
1966 // (a1,b0,c1), (a1,b1,c0), (a1,b1,c1)}
1967 FailureOr<DeletionKind> visitOp(SetCartesianProductOp op) {
1968 SetVector<ElaboratorValue> result;
1969 SmallVector<SmallVector<ElaboratorValue>> tuples;
1970 tuples.push_back({});
1971
1972 for (auto input : op.getInputs()) {
1973 auto &set = get<SetStorage *>(input)->set;
1974 if (set.empty()) {
1975 SetVector<ElaboratorValue> empty;
1976 state[op.getResult()] =
1977 sharedState.internalizer.internalize<SetStorage>(std::move(empty),
1978 op.getType());
1979 return DeletionKind::Delete;
1980 }
1981
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);
1986 }
1987 tuples[i].push_back(set.back());
1988 }
1989 }
1990
1991 for (auto &tup : tuples)
1992 result.insert(
1993 sharedState.internalizer.internalize<TupleStorage>(std::move(tup)));
1994
1995 state[op.getResult()] = sharedState.internalizer.internalize<SetStorage>(
1996 std::move(result), op.getType());
1997 return DeletionKind::Delete;
1998 }
1999
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;
2008 }
2009
2010 FailureOr<DeletionKind> visitOp(BagCreateOp op) {
2011 MapVector<ElaboratorValue, uint64_t> bag;
2012 for (auto [val, multiple] :
2013 llvm::zip(op.getElements(), op.getMultiples())) {
2014 // If the multiple is not stored as an AttributeValue, the elaboration
2015 // must have already failed earlier (since we don't have
2016 // unevaluated/opaque values).
2017 bag[state.at(val)] += get<size_t>(multiple);
2018 }
2019
2020 state[op.getBag()] = sharedState.internalizer.internalize<BagStorage>(
2021 std::move(bag), op.getType());
2022 return DeletionKind::Delete;
2023 }
2024
2025 FailureOr<DeletionKind> visitOp(BagSelectRandomOp op) {
2026 auto bag = get<BagStorage *>(op.getBag())->bag;
2027
2028 if (bag.empty())
2029 return op->emitError("cannot select from an empty bag");
2030
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});
2037 }
2038
2039 auto idx = testState.rng.getUniformlyInRange(0, accumulator - 1);
2040 auto *iter = llvm::upper_bound(
2041 prefixSum, idx,
2042 [](uint32_t a, const std::pair<ElaboratorValue, uint32_t> &b) {
2043 return a < b.second;
2044 });
2045
2046 state[op.getResult()] = iter->first;
2047 return DeletionKind::Delete;
2048 }
2049
2050 FailureOr<DeletionKind> visitOp(BagDifferenceOp op) {
2051 auto original = get<BagStorage *>(op.getOriginal())->bag;
2052 auto diff = get<BagStorage *>(op.getDiff())->bag;
2053
2054 MapVector<ElaboratorValue, uint64_t> result;
2055 for (const auto &el : original) {
2056 if (!diff.contains(el.first)) {
2057 result.insert(el);
2058 continue;
2059 }
2060
2061 if (op.getInf())
2062 continue;
2063
2064 auto toDiff = diff.lookup(el.first);
2065 if (el.second <= toDiff)
2066 continue;
2067
2068 result.insert({el.first, el.second - toDiff});
2069 }
2070
2071 state[op.getResult()] = sharedState.internalizer.internalize<BagStorage>(
2072 std::move(result), op.getType());
2073 return DeletionKind::Delete;
2074 }
2075
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;
2082 }
2083
2084 state[op.getResult()] = sharedState.internalizer.internalize<BagStorage>(
2085 std::move(result), op.getType());
2086 return DeletionKind::Delete;
2087 }
2088
2089 FailureOr<DeletionKind> visitOp(BagUniqueSizeOp op) {
2090 auto size = get<BagStorage *>(op.getBag())->bag.size();
2091 state[op.getResult()] = size;
2092 return DeletionKind::Delete;
2093 }
2094
2095 FailureOr<DeletionKind> visitOp(BagConvertToSetOp op) {
2096 auto bag = get<BagStorage *>(op.getInput())->bag;
2097 SetVector<ElaboratorValue> set;
2098 for (auto [k, v] : bag)
2099 set.insert(k);
2100 state[op.getResult()] = sharedState.internalizer.internalize<SetStorage>(
2101 std::move(set), op.getType());
2102 return DeletionKind::Delete;
2103 }
2104
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;
2111 }
2112
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));
2118
2119 state[op.getResult()] = sharedState.internalizer.internalize<ArrayStorage>(
2120 op.getResult().getType(), std::move(array));
2121 return DeletionKind::Delete;
2122 }
2123
2124 FailureOr<DeletionKind> visitOp(StringToASCIIArrayOp op) {
2125 auto opaque = state.at(op.getString());
2126 if (isSymbolic(opaque))
2127 return visitOpGeneric(op);
2128
2129 auto strAttr = dyn_cast<StringAttr>(std::get<TypedAttr>(opaque));
2130 if (!strAttr)
2131 return op->emitError("expected a string attribute");
2132
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)));
2138
2139 state[op.getResult()] = sharedState.internalizer.internalize<ArrayStorage>(
2140 op.getResult().getType(), std::move(array));
2141 return DeletionKind::Delete;
2142 }
2143
2144 FailureOr<DeletionKind> visitOp(ArrayExtractOp op) {
2145 auto array = get<ArrayStorage *>(op.getArray())->array;
2146 size_t idx = get<size_t>(op.getIndex());
2147
2148 if (array.size() <= idx)
2149 return op->emitError("invalid to access index ")
2150 << idx << " of an array with " << array.size() << " elements";
2151
2152 state[op.getResult()] = array[idx];
2153 return DeletionKind::Delete;
2154 }
2155
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);
2161
2162 auto array = std::get<ArrayStorage *>(arrayOpaque)->array;
2163 size_t idx = std::get<size_t>(idxOpaque);
2164
2165 if (array.size() <= idx)
2166 return op->emitError("invalid to access index ")
2167 << idx << " of an array with " << array.size() << " elements";
2168
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;
2173 }
2174
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;
2181 }
2182
2183 FailureOr<DeletionKind> visitOp(ArraySizeOp op) {
2184 auto array = get<ArrayStorage *>(op.getArray())->array;
2185 state[op.getResult()] = array.size();
2186 return DeletionKind::Delete;
2187 }
2188
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;
2195 }
2196
2197 FailureOr<DeletionKind> visitOp(RandomScopeOp op) {
2198 return op->emitOpError("random_scope must be scheduled by the evaluator");
2199 }
2200
2201 FailureOr<DeletionKind> visitOp(RandomNumberInRangeOp op) {
2202 size_t lower = get<size_t>(op.getLowerBound());
2203 size_t upper = get<size_t>(op.getUpperBound());
2204 if (lower > upper)
2205 return op->emitError("cannot select a number from an empty range");
2206
2207 state[op.getResult()] =
2208 size_t(testState.rng.getUniformlyInRange(lower, upper));
2209 return DeletionKind::Delete;
2210 }
2211
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
2218 << " bits";
2219
2220 state[op.getResult()] =
2221 IntegerAttr::get(IntegerType::get(op.getContext(), width), input);
2222 return DeletionKind::Delete;
2223 }
2224
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());
2231
2232 auto emitError = [&]() {
2233 auto diag = op.emitError();
2234 diag.attachNote(op.getLoc())
2235 << "while materializing value for context switching for " << op;
2236 return diag;
2237 };
2238
2239 if (from == to) {
2240 Value seqVal = materializer.materialize(
2241 get<SequenceStorage *>(op.getSequence()), op.getLoc(), emitError);
2242 if (!seqVal)
2243 return failure();
2244
2245 Value randSeqVal =
2246 materializer.create<RandomizeSequenceOp>(op.getLoc(), seqVal);
2247 materializer.create<EmbedSequenceOp>(op.getLoc(), randSeqVal);
2248 return DeletionKind::Delete;
2249 }
2250
2251 // Switch to the desired context.
2252 // First, check if a context switch is registered that has the concrete
2253 // context as source and target.
2254 auto *iter = testState.contextSwitches.find({from, to});
2255
2256 // Try with 'any' context as target and the concrete context as source.
2257 if (iter == testState.contextSwitches.end())
2258 iter = testState.contextSwitches.find(
2259 {from, AnyContextAttr::get(op->getContext(), to.getType())});
2260
2261 // Try with 'any' context as source and the concrete context as target.
2262 if (iter == testState.contextSwitches.end())
2263 iter = testState.contextSwitches.find(
2264 {AnyContextAttr::get(op->getContext(), from.getType()), to});
2265
2266 // Try with 'any' context for both the source and the target.
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())});
2271
2272 // Otherwise, fail with an error because we couldn't find a user
2273 // specification on how to switch between the requested contexts.
2274 // NOTE: we could think about supporting context switching via intermediate
2275 // context, i.e., treat it as a transitive relation.
2276 if (iter == testState.contextSwitches.end())
2277 return op->emitError("no context transition registered to switch from ")
2278 << from << " to " << to;
2279
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);
2289 if (!seqVal)
2290 return failure();
2291
2292 materializer.create<EmbedSequenceOp>(op.getLoc(), seqVal);
2293 return DeletionKind::Delete;
2294 }
2295
2296 FailureOr<DeletionKind> visitOp(ContextSwitchOp op) {
2297 testState.contextSwitches[{op.getFromAttr(), op.getToAttr()}] =
2298 get<SequenceStorage *>(op.getSequence());
2299 return DeletionKind::Delete;
2300 }
2301
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;
2308 }
2309
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;
2319 }
2320
2321 FailureOr<DeletionKind> visitOp(MemorySizeOp op) {
2322 auto *memory = get<MemoryStorage *>(op.getMemory());
2323 state[op.getResult()] = memory->size;
2324 return DeletionKind::Delete;
2325 }
2326
2327 // Mutable cell ops
2328 //===--------------------------------------------------------------------===//
2329
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;
2339 }
2340
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");
2345
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");
2349
2350 return *mut;
2351 }
2352
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);
2358 return;
2359 }
2360
2361 if (auto *mut = std::get_if<MutStorage *>(&value)) {
2362 if (!visited.insert(*mut).second)
2363 return;
2364 auto it = sharedState.mutableStore.find(*mut);
2365 if (it != sharedState.mutableStore.end())
2366 collectContinuations(it->second, result, visited);
2367 return;
2368 }
2369
2370 auto collectRange = [&](auto &&range) {
2371 for (auto nested : range)
2372 collectContinuations(nested, result, visited);
2373 };
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 *>(
2399 &value)) {
2400 if (visited.insert(*symbolic).second)
2401 collectRange((*symbolic)->operands);
2402 } else if (auto *symbolic =
2403 std::get_if<SymbolicComputationWithIdentityValue *>(
2404 &value)) {
2405 if (visited.insert(*symbolic).second)
2406 collectRange((*symbolic)->storage->operands);
2407 }
2408 }
2409
2410 FailureOr<DeletionKind> visitOp(MutReadOp op) {
2411 auto mut = getMutableCell(op.getRef(), op);
2412 if (failed(mut))
2413 return failure();
2414 state[op.getValue()] = sharedState.mutableStore.at(*mut);
2415 return DeletionKind::Delete;
2416 }
2417
2418 FailureOr<DeletionKind> visitOp(MutWriteOp op) {
2419 auto mut = getMutableCell(op.getRef(), op);
2420 if (failed(mut))
2421 return failure();
2422
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 "
2433 "mutable storage");
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");
2438 }
2439
2440 sharedState.mutableStore[*mut] = state.at(op.getNewValue());
2441 return DeletionKind::Delete;
2442 }
2443
2444 // Effect handler ops
2445 //===--------------------------------------------------------------------===//
2446
2447 FailureOr<DeletionKind> visitOp(EffectOp op) { return DeletionKind::Keep; }
2448
2449 FailureOr<DeletionKind> visitOp(WithHandlersOp op) {
2450 return op->emitOpError("with_handlers must be scheduled by the evaluator");
2451 }
2452
2453 FailureOr<DeletionKind> visitOp(PerformOp op) {
2454 return op->emitOpError("perform must return a control transfer");
2455 }
2456
2457 FailureOr<DeletionKind> visitOp(ResumeOp op) {
2458 return op->emitOpError("resume must be scheduled by the evaluator");
2459 }
2460
2461 //===--------------------------------------------------------------------===//
2462
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));
2468
2469 state[op.getResult()] =
2470 sharedState.internalizer.internalize<TupleStorage>(std::move(values));
2471 return DeletionKind::Delete;
2472 }
2473
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;
2478 }
2479
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;
2488 }
2489
2490 FailureOr<DeletionKind> visitOp(StructExtractOp op) {
2491 auto *structure = get<StructStorage *>(op.getValue());
2492 auto declaration = SymbolTable::lookupNearestSymbolFrom<StructDeclOp>(
2493 op, structure->type.getDeclaration());
2494 if (!declaration)
2495 return op.emitOpError("references an unknown struct declaration");
2496 auto index = declaration.getFieldIndex(op.getFieldNameAttr().getValue());
2497 if (!index)
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;
2502 }
2503
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>{});
2510 else
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;
2516 }
2517
2518 FailureOr<DeletionKind> visitOp(scf::IfOp op) {
2519 return op->emitOpError("scf.if must be scheduled by the evaluator");
2520 }
2521
2522 FailureOr<DeletionKind> visitOp(scf::ForOp op) {
2523 return op->emitOpError("scf.for must be scheduled by the evaluator");
2524 }
2525
2526 FailureOr<DeletionKind> visitOp(arith::AddIOp op) {
2527 if (!isa<IndexType>(op.getType()))
2528 return visitOpGeneric(op);
2529
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;
2534 }
2535
2536 FailureOr<DeletionKind> visitOp(arith::AndIOp op) {
2537 if (!op.getType().isSignlessInteger(1))
2538 return visitOpGeneric(op);
2539
2540 bool lhs = get<bool>(op.getLhs());
2541 bool rhs = get<bool>(op.getRhs());
2542 state[op.getResult()] = lhs && rhs;
2543 return DeletionKind::Delete;
2544 }
2545
2546 FailureOr<DeletionKind> visitOp(arith::XOrIOp op) {
2547 if (!op.getType().isSignlessInteger(1))
2548 return visitOpGeneric(op);
2549
2550 bool lhs = get<bool>(op.getLhs());
2551 bool rhs = get<bool>(op.getRhs());
2552 state[op.getResult()] = lhs != rhs;
2553 return DeletionKind::Delete;
2554 }
2555
2556 FailureOr<DeletionKind> visitOp(arith::OrIOp op) {
2557 if (!op.getType().isSignlessInteger(1))
2558 return visitOpGeneric(op);
2559
2560 bool lhs = get<bool>(op.getLhs());
2561 bool rhs = get<bool>(op.getRhs());
2562 state[op.getResult()] = lhs || rhs;
2563 return DeletionKind::Delete;
2564 }
2565
2566 FailureOr<DeletionKind> visitOp(arith::SelectOp op) {
2567 auto condOpaque = state.at(op.getCondition());
2568 if (isSymbolic(condOpaque))
2569 return visitOpGeneric(op);
2570
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;
2576 }
2577
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;
2583 }
2584
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;
2590 }
2591
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;
2597 }
2598
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());
2602
2603 if (rhs == 0)
2604 return op->emitOpError("attempted division by zero");
2605
2606 state[op.getResult()] = lhs / rhs;
2607 return DeletionKind::Delete;
2608 }
2609
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());
2613
2614 if (rhs == 0)
2615 return op->emitOpError("attempted division by zero");
2616
2617 if (lhs == 0)
2618 state[op.getResult()] = (lhs + rhs - 1) / rhs;
2619 else
2620 state[op.getResult()] = 1 + ((lhs - 1) / rhs);
2621
2622 return DeletionKind::Delete;
2623 }
2624
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());
2628
2629 if (rhs == 0)
2630 return op->emitOpError("attempted division by zero");
2631
2632 state[op.getResult()] = lhs % rhs;
2633 return DeletionKind::Delete;
2634 }
2635
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;
2641 }
2642
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;
2648 }
2649
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;
2655 }
2656
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;
2662 }
2663
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;
2669 }
2670
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;
2676 }
2677
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;
2683 }
2684
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());
2688 bool result;
2689 switch (op.getPred()) {
2690 case index::IndexCmpPredicate::EQ:
2691 result = lhs == rhs;
2692 break;
2693 case index::IndexCmpPredicate::NE:
2694 result = lhs != rhs;
2695 break;
2696 case index::IndexCmpPredicate::ULT:
2697 result = lhs < rhs;
2698 break;
2699 case index::IndexCmpPredicate::ULE:
2700 result = lhs <= rhs;
2701 break;
2702 case index::IndexCmpPredicate::UGT:
2703 result = lhs > rhs;
2704 break;
2705 case index::IndexCmpPredicate::UGE:
2706 result = lhs >= rhs;
2707 break;
2708 default:
2709 return op->emitOpError("elaboration not supported");
2710 }
2711 state[op.getResult()] = result;
2712 return DeletionKind::Delete;
2713 }
2714
2715 bool isSymbolic(ElaboratorValue val) {
2716 return std::holds_alternative<SymbolicComputationWithIdentityValue *>(
2717 val) ||
2718 std::holds_alternative<SymbolicComputationWithIdentityStorage *>(
2719 val) ||
2720 std::holds_alternative<SymbolicComputationStorage *>(val) ||
2721 std::holds_alternative<OpaqueExternalStorage *>(val);
2722 }
2723
2724 bool isSymbolic(Operation *op) {
2725 return llvm::any_of(op->getOperands(), [&](auto operand) {
2726 auto val = state.at(operand);
2727 return isSymbolic(val);
2728 });
2729 }
2730
2731 /// If all operands are constants, try to fold the operation and register its
2732 /// result values with the folded results in the elaborator state.
2733 /// Returns 'false' if operation has to be handled symbolically.
2734 bool attemptConcreteCase(Operation *op) {
2735 if (op->getNumResults() == 0)
2736 return false;
2737
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);
2743 }
2744
2745 SmallVector<OpFoldResult> results;
2746 if (failed(op->fold(operands, results)))
2747 return false;
2748
2749 if (results.size() != op->getNumResults())
2750 return false;
2751
2752 for (auto [res, val] : llvm::zip(results, op->getResults())) {
2753 auto attr = llvm::dyn_cast_or_null<TypedAttr>(res.dyn_cast<Attribute>());
2754 if (!attr)
2755 return false;
2756
2757 if (attr.getType() != val.getType())
2758 return false;
2759
2760 // Try to convert the attribute to an ElaboratorValue
2761 auto converted = attrConverter.convert(attr);
2762 if (succeeded(converted)) {
2763 state[val] = *converted;
2764 continue;
2765 }
2766 return false;
2767 }
2768
2769 return true;
2770 }
2771
2772 FailureOr<DeletionKind> visitOpGeneric(Operation *op) {
2773 if (op->getNumResults() == 0)
2774 return DeletionKind::Keep;
2775
2776 if (attemptConcreteCase(op))
2777 return DeletionKind::Delete;
2778
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");
2784
2785 state[op->getResult(0)] =
2786 sharedState.internalizer.internalize<SymbolicComputationStorage>(
2787 state, op);
2788 return DeletionKind::Delete;
2789 }
2790
2791 // We assume that reordering operations with only allocate effects is
2792 // allowed.
2793 // FIXME: this is not how the MLIR MemoryEffects interface intends it.
2794 // We should create our own interface/trait for that use-case.
2795 // Or modify the elaboration pass to keep track of the ordering of such
2796 // instructions and materialize all operations that are not already
2797 // materialized but have to happen before the current alloc operation to be
2798 // materialized.
2799 bool onlyAlloc = mlir::hasSingleEffect<mlir::MemoryEffects::Allocate>(op);
2800 onlyAlloc |= isa<ValidateOp>(op);
2801
2802 auto *validationVal =
2803 sharedState.internalizer.create<SymbolicComputationWithIdentityStorage>(
2804 state, op);
2805 materializer.registerIdentityValue(validationVal);
2806 state[op->getResult(0)] = validationVal;
2807
2808 for (auto [i, res] : llvm::enumerate(op->getResults())) {
2809 if (i == 0)
2810 continue;
2811 auto *val =
2812 sharedState.internalizer.create<SymbolicComputationWithIdentityValue>(
2813 res.getType(), validationVal, i);
2814 state[res] = val;
2815 materializer.registerIdentityValue(val);
2816 }
2817 return onlyAlloc ? DeletionKind::Delete : DeletionKind::Keep;
2818 }
2819
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);
2825 }
2826
2827 FailureOr<DeletionKind> dispatchOpVisitor(Operation *op) {
2828 if (isSymbolic(op) && !supportsSymbolicValuesNonGenerically(op))
2829 return visitOpGeneric(op);
2830
2831 return TypeSwitch<Operation *, FailureOr<DeletionKind>>(op)
2832 .Case<
2833 // Arith ops
2834 arith::AddIOp, arith::XOrIOp, arith::AndIOp, arith::OrIOp,
2835 arith::SelectOp,
2836 // Index ops
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); })
2841 .Default([&](Operation *op) { return RTGBase::dispatchOpVisitor(op); });
2842 }
2843
2844 LogicalResult pushRegionFrame(Region &region,
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");
2852
2853 Block &block = region.front();
2854 for (auto [arg, value] : llvm::zip(block.getArguments(), regionArguments))
2855 environment[arg] = value;
2856
2857 BlockFrame frame;
2858 frame.block = &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)));
2865 return success();
2866 }
2867
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};
2874 }
2875
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";
2880 return diag;
2881 }
2882
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;
2892 break;
2893 }
2894 }
2895 if (!handlerRegion || handlerIndex == handlerStack.size())
2896 return transfer.perform->emitOpError(
2897 "control transfer no longer has a matching handler");
2898
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) {
2903 promptIndex = i;
2904 break;
2905 }
2906 if (promptIndex == workStack.size())
2907 return transfer.perform->emitOpError(
2908 "active handler prompt has no evaluator frame");
2909
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");
2915
2916 auto *activeBlock = workStack.back()->getIf<BlockFrame>();
2917 if (!activeBlock)
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;
2926
2927 Value performResult = transfer.perform.getNumResults()
2928 ? Value(transfer.perform.getResult())
2929 : Value();
2930 Type resumeType = performResult
2931 ? performResult.getType()
2932 : NoneType::get(transfer.perform.getContext());
2933
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;
2947 }
2948 workStack.pop_back();
2949 }
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);
2957
2958 SmallVector<ElaboratorValue> handlerArguments;
2959 for (Value operand : transfer.perform.getOperands())
2960 handlerArguments.push_back(performEnvironment.at(operand));
2961 handlerArguments.push_back(continuation);
2962
2963 handlerStack.resize(handlerIndex);
2964 state = performEnvironment;
2965 workStack.emplace_back(std::make_unique<EvalFrame>(HandlerClauseFrame{}));
2966 return pushRegionFrame(*handlerRegion, handlerArguments,
2967 /*keepTerminator=*/false, /*replay=*/false,
2968 std::move(performEnvironment));
2969 }
2970
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");
2979
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");
2989
2990 std::optional<ElaboratorValue> resumeValue;
2991 if (cont->performResult && op.getValue())
2992 resumeValue = state.at(op.getValue());
2993
2994 auto *block = workStack.back()->getIf<BlockFrame>();
2995 if (!block)
2996 return op->emitOpError("resume is not executing in a block frame");
2997 block->environment = state;
2998
2999 workStack.emplace_back(
3000 std::make_unique<EvalFrame>(ResumeFrame(handlerStack, testState.rng)));
3001 handlerStack = cont->capturedHandlerStack;
3002 testState.rng = cont->capturedRng;
3003
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;
3021 }
3022 if (resumeValue) {
3023 auto *performBlock = replayFrames.back()->getIf<BlockFrame>();
3024 if (!performBlock)
3025 return op->emitOpError(
3026 "captured continuation does not end in a block frame");
3027 performBlock->environment[cont->performResult] = *resumeValue;
3028 }
3029 for (auto &frame : replayFrames)
3030 workStack.push_back(std::move(frame));
3031 return success();
3032 }
3033
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())
3041 continue;
3042 if (oldRegion.getBlocks().size() != 1)
3043 return frame.originalOp->emitOpError(
3044 "regions with anything other than one block are not supported");
3045
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);
3056 }
3057
3058 uint64_t boundary = sharedState.createBoundaryToken();
3059 frame.activeBoundary = boundary;
3060 externalRegionStack.push_back(boundary);
3061 materializer.getBuilder().setInsertionPoint(&newBlock, newBlock.begin());
3062 started = true;
3063 return pushRegionFrame(oldRegion, {}, /*keepTerminator=*/true,
3064 frame.replay, std::move(environment));
3065 }
3066 started = false;
3067 return success();
3068 }
3069
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";
3081 return diag;
3082 };
3083 Value value = materializer.materialize(state.at(operand.get()),
3084 newOp->getLoc(), emitError);
3085 if (!value)
3086 return failure();
3087 operand.set(value);
3088 }
3089 builder.setInsertionPointAfter(newOp);
3090
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)))
3100 return failure();
3101 if (!started)
3102 return finishExternalOp(workStack.size() - 1);
3103 return success();
3104 }
3105
3106 LogicalResult finishExternalOp(size_t frameIndex) {
3107 auto &frame = workStack[frameIndex]->get<ExternalOpFrame>();
3108 auto *parent = workStack[frameIndex - 1]->getIf<BlockFrame>();
3109 if (!parent)
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);
3119 }
3120 workStack.pop_back();
3121 return success();
3122 }
3123
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>();
3128 if (!parent)
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;
3134 return success();
3135 }
3136
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 /*keepTerminator=*/false, frame.replay,
3143 std::move(environment));
3144 }
3145
3146 LogicalResult completeFrame(SmallVector<ElaboratorValue> yieldedValues) {
3147 if (workStack.empty() || workStack.back()->holds<BlockFrame>())
3148 return success();
3149
3150 if (auto *frame = workStack.back()->getIf<ScfIfFrame>()) {
3151 if (failed(frame->step(*this, yieldedValues)))
3152 return failure();
3153 workStack.pop_back();
3154 return success();
3155 }
3156
3157 if (auto *frame = workStack.back()->getIf<VariantMatchFrame>()) {
3158 auto *parent = workStack[workStack.size() - 2]->getIf<BlockFrame>();
3159 if (!parent)
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();
3165 return success();
3166 }
3167
3168 if (auto *frame = workStack.back()->getIf<ScfForFrame>()) {
3169 if (failed(frame->step(*this, yieldedValues)))
3170 return failure();
3171 if (frame->completed)
3172 workStack.pop_back();
3173 return success();
3174 }
3175
3176 if (auto *frame = workStack.back()->getIf<RandomScopeFrame>()) {
3177 auto *parent = workStack[workStack.size() - 2]->getIf<BlockFrame>();
3178 if (!parent)
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();
3186 return success();
3187 }
3188
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();
3196 return success();
3197 }
3198
3199 if (workStack.back()->holds<HandlerClauseFrame>()) {
3200 workStack.pop_back();
3201 return success();
3202 }
3203
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>();
3211 if (!parent)
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();
3218 return success();
3219 }
3220
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;
3227 }
3228 materializer.getBuilder().restoreInsertionPoint(
3229 frame->parentInsertionPoint);
3230 bool started = false;
3231 if (failed(startExternalRegion(workStack.size() - 1, started)))
3232 return failure();
3233 if (started)
3234 return success();
3235
3236 return finishExternalOp(workStack.size() - 1);
3237 }
3238
3239 if (auto *frame = workStack.back()->getIf<ResumeFrame>()) {
3240 handlerStack = std::move(frame->handlerStack);
3241 testState.rng = frame->rng;
3242 workStack.pop_back();
3243 return success();
3244 }
3245 llvm_unreachable("unknown evaluator frame");
3246 }
3247
3248 LogicalResult runTrampoline(SmallVector<ElaboratorValue> &rootValues) {
3249 while (!workStack.empty()) {
3250 auto *frame = workStack.back()->getIf<BlockFrame>();
3251 if (!frame) {
3252 if (failed(completeFrame({})))
3253 return failure();
3254 continue;
3255 }
3256
3257 Operation *op = frame->nextOp;
3258 if (!op ||
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()) {
3271 // The builder stores its insertion point as a block iterator.
3272 // Move it to the stable end iterator before erasing that node.
3273 builder.setInsertionPointToEnd(terminator->getBlock());
3274 }
3275 terminator->erase();
3276 }
3277 }
3278 workStack.pop_back();
3279 if (workStack.empty()) {
3280 rootValues = std::move(yieldedValues);
3281 break;
3282 }
3283 if (failed(completeFrame(std::move(yieldedValues))))
3284 return failure();
3285 continue;
3286 }
3287
3288 Operation *nextOp = op->getNextNode();
3289 bool replay = frame->replay;
3290 frame->nextOp = nextOp;
3291 state = frame->environment;
3292
3293 if (isSymbolic(op) && !supportsSymbolicValuesNonGenerically(op)) {
3294 auto result = visitOpGeneric(op);
3295 if (failed(result))
3296 return failure();
3297 if (*result == DeletionKind::Keep &&
3298 failed(materializer.materialize(op, state, replay)))
3299 return failure();
3300 workStack.back()->get<BlockFrame>().environment = state;
3301 continue;
3302 }
3303
3304 if (auto perform = dyn_cast<PerformOp>(op)) {
3305 auto transfer = visitPerformTransfer(perform);
3306 if (failed(transfer))
3307 return failure();
3308 workStack.back()->get<BlockFrame>().environment = state;
3309 if (failed(handleControlTransfer(*transfer)))
3310 return failure();
3311 continue;
3312 }
3313
3314 if (auto resume = dyn_cast<ResumeOp>(op)) {
3315 if (failed(scheduleResume(resume)))
3316 return failure();
3317 continue;
3318 }
3319
3320 if (isa<func::CallIndirectOp>(op))
3321 return op->emitOpError("cannot elaborate indirect function call");
3322
3323 if (auto call = dyn_cast<func::CallOp>(op)) {
3324 auto callee = sharedState.table.lookup<func::FuncOp>(call.getCallee());
3325 if (!callee)
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");
3332
3333 SmallVector<ElaboratorValue> arguments;
3334 arguments.reserve(call.getNumOperands());
3335 for (Value operand : call.getOperands())
3336 arguments.push_back(state.at(operand));
3337
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,
3342 /*keepTerminator=*/false, replay,
3343 /*environment=*/{},
3344 /*eraseTerminator=*/false)))
3345 return failure();
3346 continue;
3347 }
3348
3349 if (auto ifOp = dyn_cast<scf::IfOp>(op)) {
3350 bool condition = get<bool>(ifOp.getCondition());
3351 Region &region =
3352 condition ? ifOp.getThenRegion() : ifOp.getElseRegion();
3353 workStack.back()->get<BlockFrame>().environment = state;
3354 if (region.empty())
3355 continue;
3356 workStack.emplace_back(
3357 std::make_unique<EvalFrame>(ScfIfFrame{ifOp, replay}));
3358 if (failed(pushRegionFrame(region, {}, /*keepTerminator=*/false, replay,
3359 state)))
3360 return failure();
3361 continue;
3362 }
3363
3364 if (auto matchOp = dyn_cast<VariantMatchOp>(op)) {
3365 auto selectorValue = state.at(matchOp.getValue());
3366 auto *variant = std::get_if<VariantStorage *>(&selectorValue);
3367 if (!variant)
3368 return matchOp.emitOpError(
3369 "cannot evaluate match with a non-concrete variant selector");
3370
3371 auto caseIndex =
3372 matchOp.getCaseIndex((*variant)->constructor.getValue());
3373 Region &region = matchOp.getCaseRegions()[*caseIndex];
3374 SmallVector<ElaboratorValue> regionArguments{(*variant)->payload};
3375
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 /*keepTerminator=*/false, replay, state)))
3381 return failure();
3382 continue;
3383 }
3384
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());
3393 if (!step)
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);
3405 continue;
3406 }
3407 workStack.emplace_back(std::make_unique<EvalFrame>(
3408 ScfForFrame{forOp, lower, upper, step, replay, /*completed=*/false,
3409 std::move(loopEnvironment)}));
3410 if (failed(startForIteration(workStack.size() - 1)))
3411 return failure();
3412 continue;
3413 }
3414
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 /*keepTerminator=*/false, replay, state)))
3425 return failure();
3426 continue;
3427 }
3428
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()] =
3435 &region;
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 /*keepTerminator=*/false, replay, state)))
3443 return failure();
3444 continue;
3445 }
3446
3447 if (op->getNumRegions() != 0) {
3448 workStack.back()->get<BlockFrame>().environment = state;
3449 if (failed(startExternalOp(op, replay)))
3450 return failure();
3451 continue;
3452 }
3453
3454 auto result = dispatchOpVisitor(op);
3455 if (failed(result))
3456 return failure();
3457 if (*result == DeletionKind::Keep &&
3458 failed(materializer.materialize(op, state, replay)))
3459 return failure();
3460 workStack.back()->get<BlockFrame>().environment = state;
3461
3462 LLVM_DEBUG({
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);
3467 else
3468 llvm::dbgs() << "unknown";
3469 });
3470 llvm::dbgs() << "]\n\n";
3471 });
3472 }
3473 return success();
3474 }
3475
3476 LogicalResult elaborate(Region &region,
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 /*replay=*/false, std::move(environment)))) {
3487 state = std::move(savedState);
3488 return failure();
3489 }
3490 bool failedEvaluation = failed(runTrampoline(terminatorOperands));
3491 state = std::move(savedState);
3492 return failedEvaluation ? failure() : success();
3493 }
3494
3495private:
3496 // State to be shared between all elaborator instances.
3497 SharedState &sharedState;
3498
3499 // State to a specific RTG test and the sequences placed within it.
3500 TestState &testState;
3501
3502 // Allows us to materialize ElaboratorValues to the IR operations necessary to
3503 // obtain an SSA value representing that elaborated value.
3504 Materializer &materializer;
3505
3506 // A map from SSA values to a pointer of an interned elaborator value.
3507 LexicalEnvironment state;
3508
3509 // The current context we are elaborating under.
3510 ContextResourceAttrInterface currentContext;
3511
3512 /// Dynamic sequence invocation enclosing this elaborator, or zero at module
3513 /// scope.
3514 uint64_t sequenceBoundaryToken;
3515
3516 /// Lifetime of this evaluator and the copyable frame executors it owns.
3517 uint64_t elaboratorBoundaryToken;
3518
3519 /// Opaque external regions currently being interpreted.
3520 SmallVector<uint64_t> externalRegionStack;
3521
3522 // Allows us to convert attributes to ElaboratorValues.
3523 AttributeToElaboratorValueConverter attrConverter;
3524
3525 // Allows us to convert ElaboratorValues to attributes.
3526 ElaboratorValueToAttributeConverter elabValConverter;
3527
3528 // Stack of handler frames for rtg.handle scopes, innermost last.
3529 SmallVector<HandlerFrame> handlerStack;
3530
3531 /// Cloneable evaluator state from the outermost block to the current step.
3532 EvalFrameStack workStack;
3533
3534 friend struct ScfIfFrame;
3535 friend struct VariantMatchFrame;
3536 friend struct ScfForFrame;
3537};
3538
3539LogicalResult ScfIfFrame::step(Elaborator &elaborator,
3540 ArrayRef<ElaboratorValue> yieldedValues) {
3541 auto *parent = elaborator.workStack[elaborator.workStack.size() - 2]
3542 ->getIf<BlockFrame>();
3543 if (!parent)
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;
3547 return success();
3548}
3549
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);
3555}
3556} // namespace
3557
3558SequenceOp
3559Materializer::elaborateSequence(const RandomizedSequenceStorage *seq,
3560 SmallVector<ElaboratorValue> &elabArgs) {
3561 auto familyOp =
3562 sharedState.table.lookup<SequenceOp>(seq->sequence->familyName);
3563 // TODO: don't clone if this is the only remaining reference to this
3564 // sequence
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");
3572
3573 LLVM_DEBUG(llvm::dbgs() << "\n=== Elaborating sequence family @"
3574 << familyOp.getSymName() << " into @"
3575 << seqOp.getSymName() << " under context "
3576 << seq->context << "\n\n");
3577
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 /*keepTerminator=*/false, yieldedVals)))
3585 return {};
3586
3587 seqOp.setSequenceType(
3588 SequenceType::get(builder.getContext(), materializer.getBlockArgTypes()));
3589 materializer.finalize();
3590
3591 return seqOp;
3592}
3593
3594//===----------------------------------------------------------------------===//
3595// Elaborator Pass
3596//===----------------------------------------------------------------------===//
3597
3598namespace {
3599struct ElaborationPass
3600 : public rtg::impl::ElaborationPassBase<ElaborationPass> {
3601 using Base::Base;
3602
3603 void runOnOperation() override;
3604 void matchTestsAgainstTargets(SymbolTable &table);
3605 LogicalResult elaborateModule(ModuleOp moduleOp, SymbolTable &table);
3606};
3607} // namespace
3608
3609void ElaborationPass::runOnOperation() {
3610 auto moduleOp = getOperation();
3611 SymbolTable table(moduleOp);
3612
3613 matchTestsAgainstTargets(table);
3614
3615 if (failed(elaborateModule(moduleOp, table)))
3616 return signalPassFailure();
3617}
3618
3619void ElaborationPass::matchTestsAgainstTargets(SymbolTable &table) {
3620 auto moduleOp = getOperation();
3621
3622 for (auto test : llvm::make_early_inc_range(moduleOp.getOps<TestOp>())) {
3623 if (test.getTargetAttr())
3624 continue;
3625
3626 bool matched = false;
3627
3628 for (auto target : moduleOp.getOps<TargetOp>()) {
3629 // Check if the target type is a subtype of the test's target type
3630 // This means that for each entry in the test's target type, there must be
3631 // a corresponding entry with the same name and type in the target's type
3632 bool isSubtype = true;
3633 auto testEntries = test.getTargetType().getEntries();
3634 auto targetEntries = target.getTarget().getEntries();
3635
3636 // Check if target is a subtype of test requirements
3637 // Since entries are sorted by name, we can do this in a single pass
3638 size_t targetIdx = 0;
3639 for (auto testEntry : testEntries) {
3640 // Find the matching entry in target entries.
3641 while (targetIdx < targetEntries.size() &&
3642 targetEntries[targetIdx].name.getValue() <
3643 testEntry.name.getValue())
3644 targetIdx++;
3645
3646 // Check if we found a matching entry with the same name and type
3647 if (targetIdx >= targetEntries.size() ||
3648 targetEntries[targetIdx].name != testEntry.name ||
3649 targetEntries[targetIdx].type != testEntry.type) {
3650 isSubtype = false;
3651 break;
3652 }
3653 }
3654
3655 if (!isSubtype)
3656 continue;
3657
3658 IRRewriter rewriter(test);
3659 // Create a new test for the matched target
3660 auto newTest = cast<TestOp>(test->clone());
3661 newTest.setSymName(test.getSymName().str() + "_" +
3662 target.getSymName().str());
3663
3664 // Set the target symbol specifying that this test is only suitable for
3665 // that target.
3666 newTest.setTargetAttr(target.getSymNameAttr());
3667
3668 table.insert(newTest, rewriter.getInsertionPoint());
3669 matched = true;
3670 }
3671
3672 if (matched || deleteUnmatchedTests)
3673 test->erase();
3674 }
3675}
3676
3677static bool onlyLegalToMaterializeInTarget(Type type) {
3678 return isa<MemoryBlockType, ContextResourceTypeInterface>(type);
3679}
3680
3681LogicalResult ElaborationPass::elaborateModule(ModuleOp moduleOp,
3682 SymbolTable &table) {
3683 SharedState state(moduleOp.getContext(), table);
3684
3685 // Update the name cache
3686 state.names.add(moduleOp);
3687
3688 struct TargetElabResult {
3689 TargetElabResult(DictType targetType, uint32_t seed)
3690 : targetType(targetType), testState(seed) {}
3691
3692 DictType targetType;
3693 SmallVector<ElaboratorValue> yields;
3694 TestState testState;
3695 };
3696
3697 // Map to store elaborated targets
3698 DenseMap<StringAttr, TargetElabResult> targetMap;
3699 for (auto targetOp : moduleOp.getOps<TargetOp>()) {
3700 LLVM_DEBUG(llvm::dbgs() << "=== Elaborating target @"
3701 << targetOp.getSymName() << "\n\n");
3702
3703 auto [it, inserted] = targetMap.try_emplace(targetOp.getSymNameAttr(),
3704 targetOp.getTarget(), seed);
3705 auto &result = it->second;
3706
3707 SmallVector<ElaboratorValue> blockArgs;
3708 Materializer targetMaterializer(OpBuilder::atBlockBegin(targetOp.getBody()),
3709 result.testState, state, blockArgs);
3710 Elaborator targetElaborator(state, result.testState, targetMaterializer);
3711
3712 // Elaborate the target
3713 if (failed(targetElaborator.elaborate(targetOp.getBodyRegion(), {},
3714 /*keepTerminator=*/true,
3715 result.yields)))
3716 return failure();
3717
3718 targetMaterializer.finalize();
3719 }
3720
3721 // Initialize the worklist with the test ops since they cannot be placed by
3722 // other ops.
3723 for (auto testOp : moduleOp.getOps<TestOp>()) {
3724 // Skip tests without a target attribute - these couldn't be matched
3725 // against any target but can be useful to keep around for reporting
3726 // purposes.
3727 if (!testOp.getTargetAttr())
3728 continue;
3729
3730 LLVM_DEBUG(llvm::dbgs()
3731 << "\n=== Elaborating test @" << testOp.getTemplateName()
3732 << " for target @" << *testOp.getTarget() << "\n\n");
3733
3734 // Get the target for this test
3735 auto &targetResult = targetMap.at(testOp.getTargetAttr());
3736 TestState testState(seed);
3737 testState.contextSwitches = targetResult.testState.contextSwitches;
3738 testState.name = testOp.getSymNameAttr();
3739
3740 SmallVector<ElaboratorValue> filteredYields;
3741 unsigned i = 0;
3742 for (auto [entry, yield] :
3743 llvm::zip(targetResult.targetType.getEntries(), targetResult.yields)) {
3744 if (i >= testOp.getTargetType().getEntries().size())
3745 break;
3746
3747 if (entry.name == testOp.getTargetType().getEntries()[i].name) {
3748 filteredYields.push_back(yield);
3749 ++i;
3750 }
3751 }
3752
3753 // Now elaborate the test with the same state, passing the target yield
3754 // values as arguments
3755 SmallVector<ElaboratorValue> blockArgs;
3756 Materializer materializer(OpBuilder::atBlockBegin(testOp.getBody()),
3757 testState, state, blockArgs);
3758
3759 for (auto [arg, val] :
3760 llvm::zip(testOp.getBody()->getArguments(), filteredYields))
3761 if (onlyLegalToMaterializeInTarget(arg.getType()))
3762 materializer.map(val, arg);
3763
3764 Elaborator elaborator(state, testState, materializer);
3765 SmallVector<ElaboratorValue> ignore;
3766 if (failed(elaborator.elaborate(testOp.getBodyRegion(), filteredYields,
3767 /*keepTerminator=*/false, ignore)))
3768 return failure();
3769
3770 materializer.finalize();
3771 }
3772
3773 return success();
3774}
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)
Definition Mem2Reg.cpp:193
false return failure()
Parse an optional keyword or string and set instance into 'result'.
if(parseOptionalKeywordOrOptionalString(parser, result.rawName, found)) return failure()
return success()
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.
Definition Namespace.h:86
This helps visit TypeOp nodes.
Definition RTGVisitors.h:25
FailureOr< DeletionKind > dispatchOpVisitor(Operation *op, ExtraArgs... args)
Definition RTGVisitors.h:27
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
Definition CalyxOps.cpp:56
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)
Definition HWTypes.h:67
int64_t getBitWidth(mlir::Type type)
Return the hardware bit width of a type.
Definition HWTypes.cpp:122
@ Delete
Erase the matched ops.
Definition SVPasses.h:25
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.
Definition Utils.h:36
static bool isEqual(const bool &lhs, const bool &rhs)
static unsigned getHashValue(const bool &val)