-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathFlatteningPass.cpp
More file actions
1926 lines (1715 loc) · 79.2 KB
/
FlatteningPass.cpp
File metadata and controls
1926 lines (1715 loc) · 79.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- LLZKFlatteningPass.cpp - Implements -llzk-flatten pass --*- C++ -*-===//
//
// Part of the LLZK Project, under the Apache License v2.0.
// See LICENSE.txt for license information.
// Copyright 2025 Veridise Inc.
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements the `-llzk-flatten` pass.
///
//===----------------------------------------------------------------------===//
#include "llzk/Analysis/SymbolDefTree.h"
#include "llzk/Analysis/SymbolUseGraph.h"
#include "llzk/Dialect/Array/IR/Ops.h"
#include "llzk/Dialect/Cast/IR/Dialect.h"
#include "llzk/Dialect/Constrain/IR/Ops.h"
#include "llzk/Dialect/Felt/IR/Ops.h"
#include "llzk/Dialect/Function/IR/Ops.h"
#include "llzk/Dialect/LLZK/IR/AttributeHelper.h"
#include "llzk/Dialect/LLZK/IR/Attrs.h"
#include "llzk/Dialect/Polymorphic/IR/Ops.h"
#include "llzk/Dialect/Polymorphic/Transforms/TransformationPasses.h"
#include "llzk/Dialect/String/IR/Dialect.h"
#include "llzk/Dialect/Struct/IR/Ops.h"
#include "llzk/Util/Concepts.h"
#include "llzk/Util/Debug.h"
#include "llzk/Util/SymbolHelper.h"
#include "llzk/Util/SymbolLookup.h"
#include "llzk/Util/SymbolTableLLZK.h"
#include "llzk/Util/TypeHelper.h"
#include <mlir/Dialect/Affine/IR/AffineOps.h>
#include <mlir/Dialect/Affine/LoopUtils.h>
#include <mlir/Dialect/Arith/IR/Arith.h>
#include <mlir/Dialect/SCF/IR/SCF.h>
#include <mlir/Dialect/SCF/Utils/Utils.h>
#include <mlir/Dialect/Utils/StaticValueUtils.h>
#include <mlir/IR/Attributes.h>
#include <mlir/IR/BuiltinAttributes.h>
#include <mlir/IR/BuiltinOps.h>
#include <mlir/IR/BuiltinTypes.h>
#include <mlir/Interfaces/InferTypeOpInterface.h>
#include <mlir/Pass/PassManager.h>
#include <mlir/Support/LLVM.h>
#include <mlir/Support/LogicalResult.h>
#include <mlir/Transforms/DialectConversion.h>
#include <mlir/Transforms/GreedyPatternRewriteDriver.h>
#include <llvm/ADT/APInt.h>
#include <llvm/ADT/DenseMap.h>
#include <llvm/ADT/DepthFirstIterator.h>
#include <llvm/ADT/STLExtras.h>
#include <llvm/ADT/SmallVector.h>
#include <llvm/ADT/TypeSwitch.h>
#include <llvm/Support/Debug.h>
// Include the generated base pass class definitions.
namespace llzk::polymorphic {
#define GEN_PASS_DECL_FLATTENINGPASS
#define GEN_PASS_DEF_FLATTENINGPASS
#include "llzk/Dialect/Polymorphic/Transforms/TransformationPasses.h.inc"
} // namespace llzk::polymorphic
#include "SharedImpl.h"
#define DEBUG_TYPE "llzk-flatten"
using namespace mlir;
using namespace llzk;
using namespace llzk::array;
using namespace llzk::component;
using namespace llzk::constrain;
using namespace llzk::felt;
using namespace llzk::function;
using namespace llzk::polymorphic;
using namespace llzk::polymorphic::detail;
namespace {
class ConversionTracker {
/// Tracks if some step performed a modification of the code such that another pass should be run.
bool modified;
/// Maps original remote (i.e., use site) type to new remote type.
/// Note: The keys are always parameterized StructType and the values are no-parameter StructType.
DenseMap<StructType, StructType> structInstantiations;
/// Contains the reverse of mappings in `structInstantiations` for use in legal conversion check.
DenseMap<StructType, StructType> reverseInstantiations;
/// Maps new remote type (i.e., the values in 'structInstantiations') to a list of Diagnostic
/// to report at the location(s) of the compute() that causes the instantiation to the StructType.
DenseMap<StructType, SmallVector<Diagnostic>> delayedDiagnostics;
public:
bool isModified() const { return modified; }
void resetModifiedFlag() { modified = false; }
void updateModifiedFlag(bool currStepModified) { modified |= currStepModified; }
void recordInstantiation(StructType oldType, StructType newType) {
assert(!isNullOrEmpty(oldType.getParams()) && "cannot instantiate with no params");
auto forwardResult = structInstantiations.try_emplace(oldType, newType);
if (forwardResult.second) {
// Insertion was successful
// ASSERT: The reverse map does not contain this mapping either
assert(!reverseInstantiations.contains(newType));
reverseInstantiations[newType] = oldType;
// Set the modified flag
modified = true;
} else {
// ASSERT: If a mapping already existed for `oldType` it must be `newType`
assert(forwardResult.first->getSecond() == newType);
// ASSERT: The reverse mapping is already present as well
assert(reverseInstantiations.lookup(newType) == oldType);
}
assert(structInstantiations.size() == reverseInstantiations.size());
}
/// Return the instantiated type of the given StructType, if any.
std::optional<StructType> getInstantiation(StructType oldType) const {
auto cachedResult = structInstantiations.find(oldType);
if (cachedResult != structInstantiations.end()) {
return cachedResult->second;
}
return std::nullopt;
}
/// Collect the fully-qualified names of all structs that were instantiated.
DenseSet<SymbolRefAttr> getInstantiatedStructNames() const {
DenseSet<SymbolRefAttr> instantiatedNames;
for (const auto &[origRemoteTy, _] : structInstantiations) {
instantiatedNames.insert(origRemoteTy.getNameRef());
}
return instantiatedNames;
}
void reportDelayedDiagnostics(StructType newType, CallOp caller) {
auto res = delayedDiagnostics.find(newType);
if (res == delayedDiagnostics.end()) {
return;
}
DiagnosticEngine &engine = caller.getContext()->getDiagEngine();
for (Diagnostic &diag : res->second) {
// Update any notes referencing an UnknownLoc to use the CallOp location.
for (Diagnostic ¬e : diag.getNotes()) {
assert(note.getNotes().empty() && "notes cannot have notes attached");
if (llvm::isa<UnknownLoc>(note.getLocation())) {
note = std::move(Diagnostic(caller.getLoc(), note.getSeverity()).append(note.str()));
}
}
// Report. Based on InFlightDiagnostic::report().
engine.emit(std::move(diag));
}
// Emitting a Diagnostic consumes it (per DiagnosticEngine::emit) so remove them from the map.
// Unfortunately, this means if the key StructType is the result of instantiation at multiple
// `compute()` calls it will only be reported at one of those locations, not all.
delayedDiagnostics.erase(newType);
}
SmallVector<Diagnostic> &delayedDiagnosticSet(StructType newType) {
return delayedDiagnostics[newType];
}
/// Check if the type conversion is legal, i.e., the new type unifies with and is more concrete
/// than the old type with additional allowance for the results of struct flattening conversions.
bool isLegalConversion(Type oldType, Type newType, const char *patName) const {
std::function<bool(Type, Type)> checkInstantiations = [&](Type oTy, Type nTy) {
// Check if `oTy` is a struct with a known instantiation to `nTy`
if (StructType oldStructType = llvm::dyn_cast<StructType>(oTy)) {
// Note: The values in `structInstantiations` must be no-parameter struct types
// so there is no need for recursive check, simple equality is sufficient.
if (this->structInstantiations.lookup(oldStructType) == nTy) {
return true;
}
}
// Check if `nTy` is the result of a struct instantiation and if the pre-image of
// that instantiation (i.e., the parameterized version of the instantiated struct)
// is a more concrete unification of `oTy`.
if (StructType newStructType = llvm::dyn_cast<StructType>(nTy)) {
if (auto preImage = this->reverseInstantiations.lookup(newStructType)) {
if (isMoreConcreteUnification(oTy, preImage, checkInstantiations)) {
return true;
}
}
}
return false;
};
if (isMoreConcreteUnification(oldType, newType, checkInstantiations)) {
return true;
}
LLVM_DEBUG(
llvm::dbgs() << "[" << patName << "] Cannot replace old type " << oldType
<< " with new type " << newType
<< " because it does not define a compatible and more concrete type.\n";
);
return false;
}
template <typename T, typename U>
inline bool areLegalConversions(T oldTypes, U newTypes, const char *patName) const {
return llvm::all_of(
llvm::zip_equal(oldTypes, newTypes), [this, &patName](std::tuple<Type, Type> oldThenNew) {
return this->isLegalConversion(std::get<0>(oldThenNew), std::get<1>(oldThenNew), patName);
}
);
}
};
/// Patterns can use this listener and call notifyMatchFailure(..) for failures where the entire
/// pass must fail, i.e., where instantiation would introduce an illegal type conversion.
struct MatchFailureListener : public RewriterBase::Listener {
bool hadFailure = false;
~MatchFailureListener() override {}
void notifyMatchFailure(Location loc, function_ref<void(Diagnostic &)> reasonCallback) override {
hadFailure = true;
InFlightDiagnostic diag = emitError(loc);
reasonCallback(*diag.getUnderlyingDiagnostic());
diag.report();
}
};
static LogicalResult
applyAndFoldGreedily(ModuleOp modOp, ConversionTracker &tracker, RewritePatternSet &&patterns) {
bool currStepModified = false;
MatchFailureListener failureListener;
LogicalResult result = applyPatternsGreedily(
modOp->getRegion(0), std::move(patterns),
GreedyRewriteConfig {.maxIterations = 20, .listener = &failureListener, .fold = true},
&currStepModified
);
tracker.updateModifiedFlag(currStepModified);
return failure(result.failed() || failureListener.hadFailure);
}
template <bool AllowStructParams = true> bool isConcreteAttr(Attribute a) {
if (TypeAttr tyAttr = dyn_cast<TypeAttr>(a)) {
return isConcreteType(tyAttr.getValue(), AllowStructParams);
}
if (IntegerAttr intAttr = dyn_cast<IntegerAttr>(a)) {
return !isDynamic(intAttr);
}
return false;
}
namespace Step1_InstantiateStructs {
static inline bool tableOffsetIsntSymbol(FieldReadOp op) {
return !llvm::isa_and_present<SymbolRefAttr>(op.getTableOffset().value_or(nullptr));
}
/// Implements cloning a `StructDefOp` for a specific instantiation site, using the concrete
/// parameters from the instantiation to replace parameters from the original `StructDefOp`.
class StructCloner {
ConversionTracker &tracker_;
ModuleOp rootMod;
SymbolTableCollection symTables;
class MappedTypeConverter : public TypeConverter {
StructType origTy;
StructType newTy;
const DenseMap<Attribute, Attribute> ¶mNameToValue;
inline Attribute convertIfPossible(Attribute a) const {
auto res = this->paramNameToValue.find(a);
return (res != this->paramNameToValue.end()) ? res->second : a;
}
public:
MappedTypeConverter(
StructType originalType, StructType newType,
/// Instantiated values for the parameter names in `originalType`
const DenseMap<Attribute, Attribute> ¶mNameToInstantiatedValue
)
: TypeConverter(), origTy(originalType), newTy(newType),
paramNameToValue(paramNameToInstantiatedValue) {
addConversion([](Type inputTy) { return inputTy; });
addConversion([this](StructType inputTy) {
LLVM_DEBUG(llvm::dbgs() << "[MappedTypeConverter] convert " << inputTy << '\n');
// Check for replacement of the full type
if (inputTy == this->origTy) {
return this->newTy;
}
// Check for replacement of parameter symbol names with concrete values
if (ArrayAttr inputTyParams = inputTy.getParams()) {
SmallVector<Attribute> updated;
for (Attribute a : inputTyParams) {
if (TypeAttr ta = dyn_cast<TypeAttr>(a)) {
updated.push_back(TypeAttr::get(this->convertType(ta.getValue())));
} else {
updated.push_back(convertIfPossible(a));
}
}
return StructType::get(
inputTy.getNameRef(), ArrayAttr::get(inputTy.getContext(), updated)
);
}
// Otherwise, return the type unchanged
return inputTy;
});
addConversion([this](ArrayType inputTy) {
// Check for replacement of parameter symbol names with concrete values
ArrayRef<Attribute> dimSizes = inputTy.getDimensionSizes();
if (!dimSizes.empty()) {
SmallVector<Attribute> updated;
for (Attribute a : dimSizes) {
updated.push_back(convertIfPossible(a));
}
return ArrayType::get(this->convertType(inputTy.getElementType()), updated);
}
// Otherwise, return the type unchanged
return inputTy;
});
addConversion([this](TypeVarType inputTy) -> Type {
// Check for replacement of parameter symbol name with a concrete type
if (TypeAttr tyAttr = llvm::dyn_cast<TypeAttr>(convertIfPossible(inputTy.getNameRef()))) {
Type convertedType = tyAttr.getValue();
// Use the new type unless it contains a TypeVarType because a TypeVarType from a
// different struct references a parameter name from that other struct, not from the
// current struct so the reference would be invalid.
if (isConcreteType(convertedType)) {
return convertedType;
}
}
return inputTy;
});
}
};
template <typename Impl, typename Op, typename... HandledAttrs>
class SymbolUserHelper : public OpConversionPattern<Op> {
private:
const DenseMap<Attribute, Attribute> ¶mNameToValue;
SymbolUserHelper(
TypeConverter &converter, MLIRContext *ctx, unsigned Benefit,
const DenseMap<Attribute, Attribute> ¶mNameToInstantiatedValue
)
: OpConversionPattern<Op>(converter, ctx, Benefit),
paramNameToValue(paramNameToInstantiatedValue) {}
public:
using OpAdaptor = typename mlir::OpConversionPattern<Op>::OpAdaptor;
virtual Attribute getNameAttr(Op) const = 0;
virtual LogicalResult handleDefaultRewrite(
Attribute, Op op, OpAdaptor, ConversionPatternRewriter &, Attribute a
) const {
return op->emitOpError().append("expected value with type ", op.getType(), " but found ", a);
}
LogicalResult
matchAndRewrite(Op op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override {
auto res = this->paramNameToValue.find(getNameAttr(op));
if (res == this->paramNameToValue.end()) {
LLVM_DEBUG(llvm::dbgs() << "[StructCloner] no instantiation for " << op << '\n');
return failure();
}
llvm::TypeSwitch<Attribute, LogicalResult> TS(res->second);
llvm::TypeSwitch<Attribute, LogicalResult> *ptr = &TS;
((ptr = &(ptr->template Case<HandledAttrs>([&](HandledAttrs a) {
return static_cast<const Impl *>(this)->handleRewrite(res->first, op, adaptor, rewriter, a);
}))),
...);
return TS.Default([&](Attribute a) {
return handleDefaultRewrite(res->first, op, adaptor, rewriter, a);
});
}
friend Impl;
};
class ClonedStructConstReadOpPattern
: public SymbolUserHelper<
ClonedStructConstReadOpPattern, ConstReadOp, IntegerAttr, FeltConstAttr> {
SmallVector<Diagnostic> &diagnostics;
using super =
SymbolUserHelper<ClonedStructConstReadOpPattern, ConstReadOp, IntegerAttr, FeltConstAttr>;
public:
ClonedStructConstReadOpPattern(
TypeConverter &converter, MLIRContext *ctx,
const DenseMap<Attribute, Attribute> ¶mNameToInstantiatedValue,
SmallVector<Diagnostic> &instantiationDiagnostics
)
// Must use higher benefit than GeneralTypeReplacePattern so this pattern will be applied
// instead of the GeneralTypeReplacePattern<ConstReadOp> from newGeneralRewritePatternSet().
: super(converter, ctx, /*benefit=*/2, paramNameToInstantiatedValue),
diagnostics(instantiationDiagnostics) {}
Attribute getNameAttr(ConstReadOp op) const override { return op.getConstNameAttr(); }
LogicalResult handleRewrite(
Attribute sym, ConstReadOp op, OpAdaptor, ConversionPatternRewriter &rewriter, IntegerAttr a
) const {
APInt attrValue = a.getValue();
Type origResTy = op.getType();
if (llvm::isa<FeltType>(origResTy)) {
replaceOpWithNewOp<FeltConstantOp>(
rewriter, op, FeltConstAttr::get(getContext(), attrValue)
);
return success();
}
if (llvm::isa<IndexType>(origResTy)) {
replaceOpWithNewOp<arith::ConstantIndexOp>(rewriter, op, fromAPInt(attrValue));
return success();
}
if (origResTy.isSignlessInteger(1)) {
// Treat 0 as false and any other value as true (but give a warning if it's not 1)
if (attrValue.isZero()) {
replaceOpWithNewOp<arith::ConstantIntOp>(rewriter, op, false, origResTy);
return success();
}
if (!attrValue.isOne()) {
Location opLoc = op.getLoc();
Diagnostic diag(opLoc, DiagnosticSeverity::Warning);
diag << "Interpreting non-zero value " << stringWithoutType(a) << " as true";
if (getContext()->shouldPrintOpOnDiagnostic()) {
diag.attachNote(opLoc) << "see current operation: " << *op;
}
diag.attachNote(UnknownLoc::get(getContext()))
<< "when instantiating '" << StructDefOp::getOperationName() << "' parameter \""
<< sym << "\" for this call";
diagnostics.push_back(std::move(diag));
}
replaceOpWithNewOp<arith::ConstantIntOp>(rewriter, op, true, origResTy);
return success();
}
return op->emitOpError().append("unexpected result type ", origResTy);
}
LogicalResult handleRewrite(
Attribute, ConstReadOp op, OpAdaptor, ConversionPatternRewriter &rewriter, FeltConstAttr a
) const {
replaceOpWithNewOp<FeltConstantOp>(rewriter, op, a);
return success();
}
};
class ClonedStructFieldReadOpPattern
: public SymbolUserHelper<
ClonedStructFieldReadOpPattern, FieldReadOp, IntegerAttr, FeltConstAttr> {
using super =
SymbolUserHelper<ClonedStructFieldReadOpPattern, FieldReadOp, IntegerAttr, FeltConstAttr>;
public:
ClonedStructFieldReadOpPattern(
TypeConverter &converter, MLIRContext *ctx,
const DenseMap<Attribute, Attribute> ¶mNameToInstantiatedValue
)
// Must use higher benefit than GeneralTypeReplacePattern so this pattern will be applied
// instead of the GeneralTypeReplacePattern<FieldReadOp> from newGeneralRewritePatternSet().
: super(converter, ctx, /*benefit=*/2, paramNameToInstantiatedValue) {}
Attribute getNameAttr(FieldReadOp op) const override {
return op.getTableOffset().value_or(nullptr);
}
template <typename Attr>
LogicalResult handleRewrite(
Attribute, FieldReadOp op, OpAdaptor, ConversionPatternRewriter &rewriter, Attr a
) const {
rewriter.modifyOpInPlace(op, [&]() {
op.setTableOffsetAttr(rewriter.getIndexAttr(fromAPInt(a.getValue())));
});
return success();
}
LogicalResult matchAndRewrite(
FieldReadOp op, OpAdaptor adaptor, ConversionPatternRewriter &rewriter
) const override {
if (tableOffsetIsntSymbol(op)) {
return failure();
}
return super::matchAndRewrite(op, adaptor, rewriter);
}
};
FailureOr<StructType> genClone(StructType typeAtCaller, ArrayRef<Attribute> typeAtCallerParams) {
// Find the StructDefOp for the original StructType
FailureOr<SymbolLookupResult<StructDefOp>> r = typeAtCaller.getDefinition(symTables, rootMod);
if (failed(r)) {
LLVM_DEBUG(llvm::dbgs() << "[StructCloner] skip: cannot find StructDefOp \n");
return failure(); // getDefinition() already emits a sufficient error message
}
StructDefOp origStruct = r->get();
StructType typeAtDef = origStruct.getType();
MLIRContext *ctx = origStruct.getContext();
// Map of StructDefOp parameter name to concrete Attribute at the current instantiation site.
DenseMap<Attribute, Attribute> paramNameToConcrete;
// List of concrete Attributes from the struct instantiation with `nullptr` at any positions
// where the original attribute from the current instantiation site was not concrete. This is
// used for generating the new struct name. See `BuildShortTypeString::from()`.
SmallVector<Attribute> attrsForInstantiatedNameSuffix;
// Parameter list for the new StructDefOp containing the names that must be preserved because
// they were not assigned concrete values at the current instantiation site.
ArrayAttr reducedParamNameList = nullptr;
// Reduced from `typeAtCallerParams` to contain only the non-concrete Attributes.
ArrayAttr reducedCallerParams = nullptr;
{
ArrayAttr paramNames = typeAtDef.getParams();
// pre-conditions
assert(!isNullOrEmpty(paramNames));
assert(paramNames.size() == typeAtCallerParams.size());
SmallVector<Attribute> remainingNames;
SmallVector<Attribute> nonConcreteParams;
for (size_t i = 0, e = paramNames.size(); i < e; ++i) {
Attribute next = typeAtCallerParams[i];
if (isConcreteAttr<false>(next)) {
paramNameToConcrete[paramNames[i]] = next;
attrsForInstantiatedNameSuffix.push_back(next);
} else {
remainingNames.push_back(paramNames[i]);
nonConcreteParams.push_back(next);
attrsForInstantiatedNameSuffix.push_back(nullptr);
}
}
// post-conditions
assert(remainingNames.size() == nonConcreteParams.size());
assert(attrsForInstantiatedNameSuffix.size() == paramNames.size());
assert(remainingNames.size() + paramNameToConcrete.size() == paramNames.size());
if (paramNameToConcrete.empty()) {
LLVM_DEBUG(llvm::dbgs() << "[StructCloner] skip: no concrete params \n");
return failure();
}
if (!remainingNames.empty()) {
reducedParamNameList = ArrayAttr::get(ctx, remainingNames);
reducedCallerParams = ArrayAttr::get(ctx, nonConcreteParams);
}
}
// Clone the original struct, apply the new name, and set the parameter list of the new struct
// to contain only those that did not have concrete instantiated values.
StructDefOp newStruct = origStruct.clone();
newStruct.setConstParamsAttr(reducedParamNameList);
newStruct.setSymName(
BuildShortTypeString::from(
typeAtCaller.getNameRef().getLeafReference().str(), attrsForInstantiatedNameSuffix
)
);
// Insert 'newStruct' into the parent ModuleOp of the original StructDefOp. Use the
// `SymbolTable::insert()` function directly so that the name will be made unique.
ModuleOp parentModule = origStruct.getParentOp<ModuleOp>(); // parent is ModuleOp per ODS
symTables.getSymbolTable(parentModule).insert(newStruct, Block::iterator(origStruct));
// Retrieve the new type AFTER inserting since the name may be appended to make it unique and
// use the remaining non-concrete parameters from the original type.
StructType newRemoteType = newStruct.getType(reducedCallerParams);
LLVM_DEBUG({
llvm::dbgs() << "[StructCloner] original def type: " << typeAtDef << '\n';
llvm::dbgs() << "[StructCloner] cloned def type: " << newStruct.getType() << '\n';
llvm::dbgs() << "[StructCloner] original remote type: " << typeAtCaller << '\n';
llvm::dbgs() << "[StructCloner] cloned remote type: " << newRemoteType << '\n';
});
// Within the new struct, replace all references to the original StructType (i.e., the
// locally-parameterized version) with the new locally-parameterized StructType,
// and replace all uses of the removed struct parameters with the concrete values.
MappedTypeConverter tyConv(typeAtDef, newStruct.getType(), paramNameToConcrete);
ConversionTarget target =
newConverterDefinedTarget<EmitEqualityOp>(tyConv, ctx, tableOffsetIsntSymbol);
target.addDynamicallyLegalOp<ConstReadOp>([¶mNameToConcrete](ConstReadOp op) {
// Legal if it's not in the map of concrete attribute instantiations
return paramNameToConcrete.find(op.getConstNameAttr()) == paramNameToConcrete.end();
});
RewritePatternSet patterns = newGeneralRewritePatternSet<EmitEqualityOp>(tyConv, ctx, target);
patterns.add<ClonedStructConstReadOpPattern>(
tyConv, ctx, paramNameToConcrete, tracker_.delayedDiagnosticSet(newRemoteType)
);
patterns.add<ClonedStructFieldReadOpPattern>(tyConv, ctx, paramNameToConcrete);
if (failed(applyFullConversion(newStruct, target, std::move(patterns)))) {
LLVM_DEBUG(llvm::dbgs() << "[StructCloner] instantiating body of struct failed \n");
return failure();
}
return newRemoteType;
}
public:
StructCloner(ConversionTracker &tracker, ModuleOp root)
: tracker_(tracker), rootMod(root), symTables() {}
FailureOr<StructType> createInstantiatedClone(StructType orig) {
LLVM_DEBUG(llvm::dbgs() << "[StructCloner] orig: " << orig << '\n');
if (ArrayAttr params = orig.getParams()) {
return genClone(orig, params.getValue());
}
LLVM_DEBUG(llvm::dbgs() << "[StructCloner] skip: nullptr for params \n");
return failure();
}
};
class ParameterizedStructUseTypeConverter : public TypeConverter {
ConversionTracker &tracker_;
StructCloner cloner;
public:
ParameterizedStructUseTypeConverter(ConversionTracker &tracker, ModuleOp root)
: TypeConverter(), tracker_(tracker), cloner(tracker, root) {
addConversion([](Type inputTy) { return inputTy; });
addConversion([this](StructType inputTy) -> StructType {
// First check for a cached entry
if (auto opt = tracker_.getInstantiation(inputTy)) {
return opt.value();
}
// Otherwise, try to create a clone of the struct with instantiated params. If that can't be
// done, return the original type to indicate that it's still legal (for this step at least).
FailureOr<StructType> cloneRes = cloner.createInstantiatedClone(inputTy);
if (failed(cloneRes)) {
return inputTy;
}
StructType newTy = cloneRes.value();
LLVM_DEBUG(
llvm::dbgs() << "[ParameterizedStructUseTypeConverter] instantiating " << inputTy
<< " as " << newTy << '\n'
);
tracker_.recordInstantiation(inputTy, newTy);
return newTy;
});
addConversion([this](ArrayType inputTy) {
return inputTy.cloneWith(convertType(inputTy.getElementType()));
});
}
};
class CallStructFuncPattern : public OpConversionPattern<CallOp> {
ConversionTracker &tracker_;
public:
CallStructFuncPattern(TypeConverter &converter, MLIRContext *ctx, ConversionTracker &tracker)
// Must use higher benefit than CallOpClassReplacePattern so this pattern will be applied
// instead of the CallOpClassReplacePattern from newGeneralRewritePatternSet().
: OpConversionPattern<CallOp>(converter, ctx, /*benefit=*/2), tracker_(tracker) {}
LogicalResult matchAndRewrite(
CallOp op, OpAdaptor adapter, ConversionPatternRewriter &rewriter
) const override {
LLVM_DEBUG(llvm::dbgs() << "[CallStructFuncPattern] CallOp: " << op << '\n');
// Convert the result types of the CallOp
SmallVector<Type> newResultTypes;
if (failed(getTypeConverter()->convertTypes(op.getResultTypes(), newResultTypes))) {
return op->emitError("Could not convert Op result types.");
}
LLVM_DEBUG({
llvm::dbgs() << "[CallStructFuncPattern] newResultTypes: "
<< debug::toStringList(newResultTypes) << '\n';
});
// Update the callee to reflect the new struct target if necessary. These checks are based on
// `CallOp::calleeIsStructC*()` but the types must not come from the CallOp in this case.
// Instead they must come from the converted versions.
SymbolRefAttr calleeAttr = op.getCalleeAttr();
if (op.calleeIsStructCompute()) {
if (StructType newStTy = getIfSingleton<StructType>(newResultTypes)) {
LLVM_DEBUG(llvm::dbgs() << "[CallStructFuncPattern] newStTy: " << newStTy << '\n');
calleeAttr = appendLeaf(newStTy.getNameRef(), calleeAttr.getLeafReference());
tracker_.reportDelayedDiagnostics(newStTy, op);
}
} else if (op.calleeIsStructConstrain()) {
if (StructType newStTy = getAtIndex<StructType>(adapter.getArgOperands().getTypes(), 0)) {
LLVM_DEBUG(llvm::dbgs() << "[CallStructFuncPattern] newStTy: " << newStTy << '\n');
calleeAttr = appendLeaf(newStTy.getNameRef(), calleeAttr.getLeafReference());
}
}
LLVM_DEBUG(llvm::dbgs() << "[CallStructFuncPattern] replaced " << op);
CallOp newOp = replaceOpWithNewOp<CallOp>(
rewriter, op, newResultTypes, calleeAttr, adapter.getMapOperands(),
op.getNumDimsPerMapAttr(), adapter.getArgOperands()
);
(void)newOp; // tell compiler it's intentionally unused in release builds
LLVM_DEBUG(llvm::dbgs() << " with " << newOp << '\n');
return success();
}
};
// This one ensures FieldDefOp types are converted even if there are no reads/writes to them.
class FieldDefOpPattern : public OpConversionPattern<FieldDefOp> {
public:
FieldDefOpPattern(TypeConverter &converter, MLIRContext *ctx, ConversionTracker &)
// Must use higher benefit than GeneralTypeReplacePattern so this pattern will be applied
// instead of the GeneralTypeReplacePattern<FieldDefOp> from newGeneralRewritePatternSet().
: OpConversionPattern<FieldDefOp>(converter, ctx, /*benefit=*/2) {}
LogicalResult matchAndRewrite(
FieldDefOp op, OpAdaptor adapter, ConversionPatternRewriter &rewriter
) const override {
LLVM_DEBUG(llvm::dbgs() << "[FieldDefOpPattern] FieldDefOp: " << op << '\n');
Type oldFieldType = op.getType();
Type newFieldType = getTypeConverter()->convertType(oldFieldType);
if (oldFieldType == newFieldType) {
// nothing changed
return failure();
}
rewriter.modifyOpInPlace(op, [&op, &newFieldType]() { op.setType(newFieldType); });
return success();
}
};
LogicalResult run(ModuleOp modOp, ConversionTracker &tracker) {
MLIRContext *ctx = modOp.getContext();
ParameterizedStructUseTypeConverter tyConv(tracker, modOp);
ConversionTarget target = newConverterDefinedTarget<>(tyConv, ctx);
RewritePatternSet patterns = newGeneralRewritePatternSet(tyConv, ctx, target);
patterns.add<CallStructFuncPattern, FieldDefOpPattern>(tyConv, ctx, tracker);
return applyPartialConversion(modOp, target, std::move(patterns));
}
} // namespace Step1_InstantiateStructs
namespace Step2_Unroll {
// TODO: not guaranteed to work with WhileOp, can try with our custom attributes though.
template <HasInterface<LoopLikeOpInterface> OpClass>
class LoopUnrollPattern : public OpRewritePattern<OpClass> {
public:
using OpRewritePattern<OpClass>::OpRewritePattern;
LogicalResult matchAndRewrite(OpClass loopOp, PatternRewriter &rewriter) const override {
if (auto maybeConstant = getConstantTripCount(loopOp)) {
uint64_t tripCount = *maybeConstant;
if (tripCount == 0) {
rewriter.eraseOp(loopOp);
return success();
} else if (tripCount == 1) {
return loopOp.promoteIfSingleIteration(rewriter);
}
return loopUnrollByFactor(loopOp, tripCount);
}
return failure();
}
private:
/// Returns the trip count of the loop-like op if its low bound, high bound and step are
/// constants, `nullopt` otherwise. Trip count is computed as ceilDiv(highBound - lowBound, step).
static std::optional<int64_t> getConstantTripCount(LoopLikeOpInterface loopOp) {
std::optional<OpFoldResult> lbVal = loopOp.getSingleLowerBound();
std::optional<OpFoldResult> ubVal = loopOp.getSingleUpperBound();
std::optional<OpFoldResult> stepVal = loopOp.getSingleStep();
if (!lbVal.has_value() || !ubVal.has_value() || !stepVal.has_value()) {
return std::nullopt;
}
return constantTripCount(lbVal.value(), ubVal.value(), stepVal.value());
}
};
LogicalResult run(ModuleOp modOp, ConversionTracker &tracker) {
MLIRContext *ctx = modOp.getContext();
RewritePatternSet patterns(ctx);
patterns.add<LoopUnrollPattern<scf::ForOp>>(ctx);
patterns.add<LoopUnrollPattern<affine::AffineForOp>>(ctx);
return applyAndFoldGreedily(modOp, tracker, std::move(patterns));
}
} // namespace Step2_Unroll
namespace Step3_InstantiateAffineMaps {
// Adapted from `mlir::getConstantIntValues()` but that one failed in CI for an unknown reason. This
// version uses a basic loop instead of llvm::map_to_vector().
std::optional<SmallVector<int64_t>> getConstantIntValues(ArrayRef<OpFoldResult> ofrs) {
SmallVector<int64_t> res;
for (OpFoldResult ofr : ofrs) {
std::optional<int64_t> cv = getConstantIntValue(ofr);
if (!cv.has_value()) {
return std::nullopt;
}
res.push_back(cv.value());
}
return res;
}
struct AffineMapFolder {
struct Input {
OperandRangeRange mapOpGroups;
DenseI32ArrayAttr dimsPerGroup;
ArrayRef<Attribute> paramsOfStructTy;
};
struct Output {
SmallVector<SmallVector<Value>> mapOpGroups;
SmallVector<int32_t> dimsPerGroup;
SmallVector<Attribute> paramsOfStructTy;
};
static inline SmallVector<ValueRange> getConvertedMapOpGroups(Output out) {
return llvm::map_to_vector(out.mapOpGroups, [](const SmallVector<Value> &grp) {
return ValueRange(grp);
});
}
static LogicalResult
fold(PatternRewriter &rewriter, const Input &in, Output &out, Operation *op, const char *aspect) {
if (in.mapOpGroups.empty()) {
// No affine map operands so nothing to do
return failure();
}
assert(in.mapOpGroups.size() <= in.paramsOfStructTy.size());
assert(std::cmp_equal(in.mapOpGroups.size(), in.dimsPerGroup.size()));
size_t idx = 0; // index in `mapOpGroups`, i.e., the number of AffineMapAttr encountered
for (Attribute sizeAttr : in.paramsOfStructTy) {
if (AffineMapAttr m = dyn_cast<AffineMapAttr>(sizeAttr)) {
ValueRange currMapOps = in.mapOpGroups[idx++];
LLVM_DEBUG(
llvm::dbgs() << "[AffineMapFolder] currMapOps: " << debug::toStringList(currMapOps)
<< '\n'
);
SmallVector<OpFoldResult> currMapOpsCast = getAsOpFoldResult(currMapOps);
LLVM_DEBUG(
llvm::dbgs() << "[AffineMapFolder] currMapOps as fold results: "
<< debug::toStringList(currMapOpsCast) << '\n'
);
if (auto constOps = Step3_InstantiateAffineMaps::getConstantIntValues(currMapOpsCast)) {
SmallVector<Attribute> result;
bool hasPoison = false; // indicates divide by 0 or mod by <1
auto constAttrs = llvm::map_to_vector(*constOps, [&rewriter](int64_t v) -> Attribute {
return rewriter.getIndexAttr(v);
});
LogicalResult foldResult = m.getAffineMap().constantFold(constAttrs, result, &hasPoison);
if (hasPoison) {
// Diagnostic remark: could be removed for release builds if too noisy
op->emitRemark()
.append(
"Cannot fold affine_map for ", aspect, " ", out.paramsOfStructTy.size(),
" due to divide by 0 or modulus with negative divisor"
)
.report();
return failure();
}
if (failed(foldResult)) {
// Diagnostic remark: could be removed for release builds if too noisy
op->emitRemark()
.append(
"Folding affine_map for ", aspect, " ", out.paramsOfStructTy.size(), " failed"
)
.report();
return failure();
}
if (result.size() != 1) {
// Diagnostic remark: could be removed for release builds if too noisy
op->emitRemark()
.append(
"Folding affine_map for ", aspect, " ", out.paramsOfStructTy.size(),
" produced ", result.size(), " results but expected 1"
)
.report();
return failure();
}
assert(!llvm::isa<AffineMapAttr>(result[0]) && "not converted");
out.paramsOfStructTy.push_back(result[0]);
continue;
}
// If affine but not foldable, preserve the map ops
out.mapOpGroups.emplace_back(currMapOps);
out.dimsPerGroup.push_back(in.dimsPerGroup[idx - 1]); // idx was already incremented
}
// If not affine and foldable, preserve the original
out.paramsOfStructTy.push_back(sizeAttr);
}
assert(idx == in.mapOpGroups.size() && "all affine_map not processed");
assert(
in.paramsOfStructTy.size() == out.paramsOfStructTy.size() &&
"produced wrong number of dimensions"
);
return success();
}
};
/// At CreateArrayOp, instantiate ArrayType parameterized with affine_map dimension size(s)
class InstantiateAtCreateArrayOp final : public OpRewritePattern<CreateArrayOp> {
[[maybe_unused]]
ConversionTracker &tracker_;
public:
InstantiateAtCreateArrayOp(MLIRContext *ctx, ConversionTracker &tracker)
: OpRewritePattern(ctx), tracker_(tracker) {}
LogicalResult matchAndRewrite(CreateArrayOp op, PatternRewriter &rewriter) const override {
ArrayType oldResultType = op.getType();
AffineMapFolder::Output out;
AffineMapFolder::Input in = {
op.getMapOperands(),
op.getNumDimsPerMapAttr(),
oldResultType.getDimensionSizes(),
};
if (failed(AffineMapFolder::fold(rewriter, in, out, op, "array dimension"))) {
return failure();
}
ArrayType newResultType = ArrayType::get(oldResultType.getElementType(), out.paramsOfStructTy);
if (newResultType == oldResultType) {
// nothing changed
return failure();
}
// ASSERT: folding only preserves the original Attribute or converts affine to integer
assert(tracker_.isLegalConversion(oldResultType, newResultType, "InstantiateAtCreateArrayOp"));
LLVM_DEBUG(
llvm::dbgs() << "[InstantiateAtCreateArrayOp] instantiating " << oldResultType << " as "
<< newResultType << " in \"" << op << "\"\n"
);
replaceOpWithNewOp<CreateArrayOp>(
rewriter, op, newResultType, AffineMapFolder::getConvertedMapOpGroups(out), out.dimsPerGroup
);
return success();
}
};
/// Instantiate parameterized StructType resulting from CallOp targeting "compute()" functions.
class InstantiateAtCallOpCompute final : public OpRewritePattern<CallOp> {
ConversionTracker &tracker_;
public:
InstantiateAtCallOpCompute(MLIRContext *ctx, ConversionTracker &tracker)
: OpRewritePattern(ctx), tracker_(tracker) {}
LogicalResult matchAndRewrite(CallOp op, PatternRewriter &rewriter) const override {
if (!op.calleeIsStructCompute()) {
// this pattern only applies when the callee is "compute()" within a struct
return failure();
}
LLVM_DEBUG(llvm::dbgs() << "[InstantiateAtCallOpCompute] target: " << op.getCallee() << '\n');
StructType oldRetTy = op.getSingleResultTypeOfCompute();
LLVM_DEBUG(llvm::dbgs() << "[InstantiateAtCallOpCompute] oldRetTy: " << oldRetTy << '\n');
ArrayAttr params = oldRetTy.getParams();
if (isNullOrEmpty(params)) {
// nothing to do if the StructType is not parameterized
return failure();
}
AffineMapFolder::Output out;
AffineMapFolder::Input in = {
op.getMapOperands(),
op.getNumDimsPerMapAttr(),
params.getValue(),
};
if (!in.mapOpGroups.empty()) {
// If there are affine map operands, attempt to fold them to a constant.
if (failed(AffineMapFolder::fold(rewriter, in, out, op, "struct parameter"))) {
return failure();
}
LLVM_DEBUG({
llvm::dbgs() << "[InstantiateAtCallOpCompute] folded affine_map in result type params\n";
});
} else {
// If there are no affine map operands, attempt to refine the result type of the CallOp using
// the function argument types and the type of the target function.
auto callArgTypes = op.getArgOperands().getTypes();
if (callArgTypes.empty()) {
// no refinement possible if no function arguments
return failure();
}
SymbolTableCollection tables;
auto lookupRes = lookupTopLevelSymbol<FuncDefOp>(tables, op.getCalleeAttr(), op);
if (failed(lookupRes)) {
return failure();
}
if (failed(instantiateViaTargetType(in, out, callArgTypes, lookupRes->get()))) {
return failure();
}
LLVM_DEBUG({
llvm::dbgs() << "[InstantiateAtCallOpCompute] propagated instantiations via symrefs in "
"result type params: "
<< debug::toStringList(out.paramsOfStructTy) << '\n';
});
}
StructType newRetTy = StructType::get(oldRetTy.getNameRef(), out.paramsOfStructTy);
LLVM_DEBUG(llvm::dbgs() << "[InstantiateAtCallOpCompute] newRetTy: " << newRetTy << '\n');