Repository navigation
Expand file tree
/
Copy pathEmitPython.cpp
More file actions
4199 lines (4002 loc) · 167 KB
/
Copy pathEmitPython.cpp
File metadata and controls
4199 lines (4002 loc) · 167 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
// Emits Python source from an MLIR ModuleOp whose ops have already been
// lowered to a small, closed set: func / arith / scf / cf / llvm.call /
// llvm.alloca / llvm.load / llvm.store / llvm.mlir.global /
// llvm.mlir.addressof plus outlined llvm.func bodies (parfor / anonymous
// functions).
//
// Companion to EmitC.cpp: structure mirrors that emitter closely but
// targets Python (no types, native strings, `and`/`or`, ternary `a if c
// else b`). The emitted file imports `matlab_runtime` (NumPy-backed
// shim) and runs on CPython 3.10+.
#include "matlab/MLIR/Passes/Passes.h"
#include <cmath>
#include "matlab/Basic/SourceManager.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/Value.h"
#include "mlir/IR/Verifier.h"
#include "mlir/Support/LLVM.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include <cctype>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <sstream>
#include <string>
namespace matlab {
namespace mlirgen {
namespace {
/// One class method (constructor / regular / get-property / operator)
/// captured during the pre-pass. The same struct doubles as the value
/// type of the call-site lookup table that drives method-call rewrites.
struct ClassMethodInfo {
mlir::func::FuncOp Func;
std::string ClassName;
enum Kind { Ctor, Method, Get, Operator, Static } Kind = Method;
std::string EmitName; // Python `def` name (e.g. `__init__`, `deposit`,
// `Overdrawn`, `__eq__`).
std::string OpSpelling; // Operator spelling for `Operator` kind only —
// e.g. `==` so call sites can render `a == b`.
};
/// Metadata for one MATLAB classdef: its (optional) superclass and
/// every method in the order Sema emitted them (mirrors source order).
struct ClassDef {
std::string Super;
llvm::SmallVector<ClassMethodInfo, 8> Methods;
};
/// Metadata for an scf.while op that matched the canonical for-loop shape
/// (one f64 iter-arg, condition `iv <= end` or `iv >= end`, body ends with
/// `iv += step ; yield`). Mirrors the C emitter's ForLoopInfo so the same
/// loops collapse to a clean `for iv in range(...)` / `for iv in
/// rt.frange(...)` in Python.
struct ForLoopInfo {
mlir::Value Init;
mlir::Value End;
mlir::Value Step;
bool IsDecreasing = false;
// The arith.addf and scf.yield at the tail of the after-region; absorbed
// into the for-head and never emitted as their own statements.
mlir::Operation *AddOp = nullptr;
mlir::Operation *YieldOp = nullptr;
// The store-to-slot that copies the iter-arg into the user-visible
// induction variable, plus the slot's alloca. Both are skipped when the
// loop owns the slot exclusively (FuseSlot = true).
mlir::Operation *BindStore = nullptr;
mlir::Operation *SlotAlloca = nullptr;
bool FuseSlot = false;
// The Python identifier used for the induction variable in the emitted
// `for iv in ...:` head.
std::string IvName;
};
class Emitter {
public:
Emitter(std::ostream &OS, bool NoLine, const matlab::SourceManager *SM)
: OS(OS), NoLine(NoLine), SM(SM) {}
bool run(mlir::ModuleOp M);
private:
// --- Naming ------------------------------------------------------------
std::string name(mlir::Value V);
std::string freshName(const char *Prefix = "v");
std::string uniqueName(llvm::StringRef Hint);
std::string sanitizeIdent(llvm::StringRef In);
// --- Region / block printing ------------------------------------------
void emitRegion(mlir::Region &R, int Indent);
void emitBlock(mlir::Block &B, int Indent);
void emitOp(mlir::Operation &Op, int Indent);
// --- Top-level --------------------------------------------------------
void emitGlobal(mlir::LLVM::GlobalOp G);
void emitFuncFunc(mlir::func::FuncOp F);
void emitLLVMFunc(mlir::LLVM::LLVMFuncOp F);
void emitProlog();
void precomputeModuleProperties(mlir::ModuleOp M);
// --- Helpers ----------------------------------------------------------
void indent(int N) { for (int i = 0; i < N; ++i) OS << " "; }
std::string constStr(mlir::LLVM::GlobalOp G);
void fail(llvm::StringRef Msg) {
if (!Failed)
std::cerr << "error: emit-python: " << Msg.str() << "\n";
Failed = true;
}
// Advance the source-line tracker to match `L`, emitting any leading
// `%` comments / preserved blank lines from the MATLAB source.
void advanceTo(mlir::Location L, int Indent);
bool emitLeadingComments(llvm::StringRef FullPath, int AfterLine,
int Line, int Indent, bool FunctionHeader = false);
// --- Single-use inlining ----------------------------------------------
std::string exprFor(mlir::Value V);
std::string stmtExpr(mlir::Value V);
void computeInlines(mlir::Region &R);
bool canInline(mlir::Operation &Op);
bool buildInlineExpr(mlir::Operation &Op, std::string &Expr);
// --- Break/continue flag un-lowering ----------------------------------
// Walk a region and tag every break / continue flag slot, the false
// stores that initialise/reset them, and the scf.if ops that should
// collapse into native `break` / `continue` one-liners.
void scanBreakContinueFlags(mlir::Region &R);
bool isFlagInversion(mlir::Value V);
void gatherNonFlagConjuncts(mlir::Value V,
llvm::SmallVectorImpl<mlir::Value> &Out);
// --- For-loop pattern detection ---------------------------------------
// Match an scf.while produced by LowerSeqLoops::lowerForOp. Populates
// ForPatterns / SuppressedOps / FusedForSlots so the scf.while emitter
// can print `for iv in range(...):` (or `rt.frange(...)`) instead of the
// 4-line while-emulated shape.
bool matchForPattern(mlir::scf::WhileOp W, ForLoopInfo &Info);
void scanForLoopPatterns(mlir::Region &R);
// Try to evaluate V as a compile-time integer-valued literal (covers
// both arith.constant f64 / i64 and llvm.mlir.constant). Returns true
// and writes Out when the value is exactly an integer.
static bool tryEvalIntLiteral(mlir::Value V, long long &Out);
// Compile-time triple-check: are all of init/end/step integer literals?
static bool forBoundsAreIntLiterals(const ForLoopInfo &Info,
long long &Init, long long &End,
long long &Step);
// --- Callee remap: llvm.call @matlab_foo -> rt.foo --------------------
static std::string remapRuntimeCallee(llvm::StringRef Name);
// True when the runtime helper named (without `matlab_` prefix) takes a
// string-length operand we can drop in Python (where strings carry
// their own length).
static bool calleeHasDroppableLengthArg(llvm::StringRef Suffix,
unsigned &LengthArgIdx);
// True when V is a constant condition we can fold at emit time.
// Returns 1 for static-true, 0 for static-false, -1 for "not foldable".
static int evalConstCond(mlir::Value V);
// Try to rewrite a `matlab_<suffix>` call as an inline numpy / Python
// operator expression. Returns true on success and writes the
// replacement into Out (with parens around binary forms so the result
// composes cleanly inside other expressions).
bool tryRewriteAsNumpy(mlir::LLVM::CallOp C, std::string &Out);
// Try to rewrite obj_get_f64 / obj_set_f64 calls as Python attribute
// access. obj_get_f64 produces a value expression; obj_set_f64 only
// makes sense as a statement. The field-name operand must be a
// string-global addressof matching a valid Python identifier.
bool tryRewriteObjGet(mlir::LLVM::CallOp C, std::string &Out);
bool tryRewriteObjSet(mlir::LLVM::CallOp C, std::string &Out);
// Walk the module and group every classdef method by `matlab.class_name`
// into Classes; populate CalleeIndex so call-site rewrites can look
// up `BankAccount__deposit` and emit `acc.deposit(...)`. Expensive to
// do per-call, hence the one-shot pre-pass.
void collectClasses(mlir::ModuleOp M);
// Emit one classdef as a Python `class` block (with `(Super)` when set).
void emitClassBlock(llvm::StringRef ClassName, const ClassDef &CI);
// Emit a single method inside an open class block. `Indent` is the
// method-body indent (the `class` block uses Indent-1).
void emitClassMethod(const ClassMethodInfo &CMI, int Indent);
// Try to rewrite `<ClassName>__<method>(args...)` as one of:
// - constructor: `ClassName(args)`
// - regular call: `args[0].method(args[1:])`
// - operator: `args[0] OP args[1]`
// - get-property: `args[0].PropName`
// Returns true on success and writes the replacement into Out.
bool tryRewriteAsClassCall(llvm::StringRef Callee,
mlir::ValueRange Operands,
std::string &Out);
std::ostream &OS;
bool NoLine;
const matlab::SourceManager *SM;
bool Failed = false;
llvm::DenseMap<mlir::Value, std::string> Names;
llvm::DenseMap<mlir::Operation *, std::string> GlobalStrs;
llvm::StringSet<> UsedNames;
llvm::DenseMap<mlir::Value, std::string> InlineExprs;
llvm::DenseSet<mlir::Operation *> InlinedOps;
// Allocas whose entire use set is plain load/store. For these, the
// pointer indirection collapses to a plain Python variable. Maps
// alloca-op -> the Python identifier of the backing slot.
llvm::DenseMap<mlir::Operation *, std::string> DirectSlots;
// Per-function (persistent_name → wrap-spec) for scalar persistents.
// Populated by the early walk below; consumed at every
// matlab_global_set_f64 emit site so the wrap call uses a stable
// (WL, signed) regardless of whether the local store carries the
// fi attrs or even a typed operand.
struct WrapSpec { int WL = 0; bool Signed = false; };
llvm::StringMap<WrapSpec> PersistWrapSpec;
// Alloca ops that hold arrays (from matrix-literal materialization);
// they render as `name = [0.0] * N`, with stores/loads going via
// indexing.
llvm::DenseMap<mlir::Operation *, std::string> ArraySlots;
// Subset of ArraySlots whose backing buffer was already emitted as a
// collapsed Python list literal (`slot = [v0, v1, ...]`) — the
// GEP/store ops that filled it have been absorbed and must not emit
// their own statements. Keyed off SuppressedOps below.
// Ops whose emission has been folded into a different op (e.g. the
// GEP+store pairs that filled a matrix literal). Skip these in
// emitOp().
llvm::DenseSet<mlir::Operation *> SuppressedOps;
// Break / continue flag slot allocas (matlab.name = "__did_break" /
// "__did_continue"). The frontend lowers MATLAB `break`/`continue`
// through these flags; the emitter un-lowers them back to native
// Python keywords.
llvm::DenseSet<mlir::Operation *> BreakFlagSlots;
llvm::DenseSet<mlir::Operation *> ContinueFlagSlots;
// scf.if ops whose entire body is a single flag-store; re-emit as
// `if cond: break` (or continue). Value is the keyword to print.
llvm::DenseMap<mlir::Operation *, const char *> FlagIfKind;
// scf.if ops whose condition is purely a break/continue flag check
// (`!did_break [& !did_continue]`) guarding a real body; emit the
// then-region inline at the parent's indent.
llvm::DenseSet<mlir::Operation *> InlinedIfs;
// String globals (llvm.mlir.global with a StringAttr value), keyed off
// the global's symbol name. When the AddressOf op for one of these is
// inlined, return the Python literal directly so the emitted source
// reads `rt.disp_str("Hello")` instead of `rt.disp_str(__matlab_str0)`.
llvm::StringMap<std::string> StringGlobalLits;
// Globals (any kind) that have already been inlined at every use site;
// skip the top-of-file `name = "..."` declaration for them.
llvm::StringSet<> SuppressedGlobals;
// For-loop pattern matches (key: scf.while op).
llvm::DenseMap<mlir::Operation *, ForLoopInfo> ForPatterns;
// Slots whose alloca is owned by a for-loop's induction variable; the
// alloca itself is suppressed and the slot name is the loop's IV name.
llvm::DenseSet<mlir::Operation *> FusedForSlots;
llvm::DenseMap<mlir::Operation *, std::string> FusedForSlotName;
/* Per-function tracking for the persistent-snapshot prelude.
* When the body has one or more `if isempty(p) || reset` arms
* (shape 2 in the recognizer), the snap captures must run
* AFTER every reset arm has executed — otherwise on a reset
* cycle the snapshot would hold the pre-reset value while
* the persistent's actual storage holds the reset value.
* `ResetArmGuards` collects those scf.if ops; the scf.if emit
* path checks the set after emitting and, when the set drains,
* flushes `PendingSnapshotPrelude`. If no reset arm is present
* (shape 1, the canonical isempty-only init that gets fully
* suppressed), the prelude is emitted at function start
* immediately, since there's no arm to wait for. */
llvm::DenseSet<mlir::Operation *> ResetArmGuards;
std::string PendingSnapshotPrelude;
// Classdef registry. Classes maps the class name to its method list;
// CalleeIndex maps every class-method symbol (`BankAccount__deposit`)
// to its info so call-site rewriting can resolve it without scanning.
llvm::StringMap<ClassDef> Classes;
llvm::StringMap<ClassMethodInfo> CalleeIndex;
int NextId = 0;
// Most recent line emitted; used to suppress duplicate line markers
// and to drive leading-comment emission on forward jumps.
std::string LastLineFile;
int LastLineNum = -1;
bool AtBlockStart = true;
// When non-empty, advanceTo's first-call branch (which would scan
// back from the first op's line for leading comments) skips any
// line ≤ this value in the matching file. We set it after hoisting
// the script's top-of-file comment block to module-top so the same
// lines aren't re-emitted at @main's first op.
std::string PreEmittedCommentFile;
int PreEmittedCommentLine = 0;
// Top-level script body (the body of `@main`) is hoisted to module
// scope. While emitting that body this flag is true so we don't add
// a surrounding `def main()`.
bool InMainHoist = false;
};
// ---------------------------------------------------------------------------
// Naming
// ---------------------------------------------------------------------------
std::string Emitter::freshName(const char *Prefix) {
for (;;) {
std::string S = Prefix;
S += std::to_string(NextId++);
if (UsedNames.insert(S).second) return S;
}
}
std::string Emitter::sanitizeIdent(llvm::StringRef In) {
std::string Out;
Out.reserve(In.size() + 1);
for (char C : In) {
if ((C >= 'A' && C <= 'Z') || (C >= 'a' && C <= 'z') ||
(C >= '0' && C <= '9') || C == '_') {
Out += C;
} else {
Out += '_';
}
}
if (Out.empty()) Out = "v";
else if (Out[0] >= '0' && Out[0] <= '9') Out = "_" + Out;
return Out;
}
std::string Emitter::uniqueName(llvm::StringRef Hint) {
std::string Base = sanitizeIdent(Hint);
if (UsedNames.insert(Base).second) return Base;
for (int k = 2; ; ++k) {
std::string Cand = Base + "_" + std::to_string(k);
if (UsedNames.insert(Cand).second) return Cand;
}
}
std::string Emitter::name(mlir::Value V) {
auto It = Names.find(V);
if (It != Names.end()) return It->second;
// Prefer the user-source variable name carried through SlotPromotion +
// LowerTensorOps (and any other pass that sets `matlab.name` on a
// value's defining op). Falling back to a fresh `vN` only when no
// hint is available keeps generated source readable for matrix
// literals: `A = np.array(...)` instead of `v0 = np.array(...)`.
if (auto *D = V.getDefiningOp()) {
if (auto NA = D->getAttrOfType<mlir::StringAttr>("matlab.name")) {
std::string N = uniqueName(NA.getValue());
Names[V] = N;
return N;
}
}
std::string N = freshName();
Names[V] = N;
return N;
}
// ---------------------------------------------------------------------------
// Literal formatting
// ---------------------------------------------------------------------------
static std::string formatIntAttr(mlir::IntegerAttr IA, bool Unsigned = false) {
auto T = mlir::dyn_cast<mlir::IntegerType>(IA.getType());
if (T && T.getWidth() == 1) {
return (IA.getValue().getZExtValue() & 1u) ? "True" : "False";
}
char Buf[64];
if (Unsigned) {
snprintf(Buf, sizeof(Buf), "%llu",
(unsigned long long)IA.getValue().getZExtValue());
} else {
snprintf(Buf, sizeof(Buf), "%lld", (long long)IA.getInt());
}
return Buf;
}
static std::string formatFloatAttr(mlir::FloatAttr FA) {
// Pick the shortest precision (1..17) whose `%g` text round-trips
// exactly back to D — that's what Python's `repr(0.05)` does, and what
// a user reading the generated source expects (`0.05`, not
// `0.050000000000000003`). We also avoid scientific notation when a
// longer decimal form is available — `10.0` reads better than `1e+01`.
double D = FA.getValueAsDouble();
// NaN / Inf have no Python literal — `%g` would emit bare `nan`/`inf`
// (a NameError at runtime). Emit a valid float() constructor. (#197)
if (std::isnan(D)) return "float(\"nan\")";
if (std::isinf(D)) return D < 0 ? "float(\"-inf\")" : "float(\"inf\")";
char Buf[64];
// `%.17g` is the conservative reference: any value round-trips at 17.
snprintf(Buf, sizeof(Buf), "%.17g", D);
std::string Ref17 = Buf;
bool Ref17HasE = (Ref17.find('e') != std::string::npos ||
Ref17.find('E') != std::string::npos);
std::string S;
for (int P = 1; P <= 17; ++P) {
snprintf(Buf, sizeof(Buf), "%.*g", P, D);
if (strtod(Buf, nullptr) != D) continue;
bool ThisHasE = (strchr(Buf, 'e') || strchr(Buf, 'E'));
// Reject a shorter form that switches to scientific notation when
// the conservative reference renders cleanly in decimal.
if (!Ref17HasE && ThisHasE) continue;
S = Buf;
break;
}
if (S.empty()) S = Ref17;
bool HasDotOrExp = false;
for (char C : S) {
if (C == '.' || C == 'e' || C == 'E' || C == 'n') {
HasDotOrExp = true;
break;
}
}
if (!HasDotOrExp) S += ".0";
return S;
}
static std::string dropOuterParens(std::string E) {
if (E.size() < 2 || E.front() != '(' || E.back() != ')') return E;
int Depth = 0;
for (size_t i = 0; i < E.size(); ++i) {
if (E[i] == '(') ++Depth;
else if (E[i] == ')') {
--Depth;
if (Depth == 0 && i + 1 < E.size()) return E;
}
}
return E.substr(1, E.size() - 2);
}
// ---------------------------------------------------------------------------
// Runtime-symbol remap (`matlab_foo` -> `rt.foo`)
// ---------------------------------------------------------------------------
std::string Emitter::remapRuntimeCallee(llvm::StringRef Name) {
// Every matlab_* runtime entry maps to `rt.<suffix>`. Keep non-matlab_
// names verbatim so user-outlined helpers still resolve.
if (Name.starts_with("matlab_")) {
std::string Suf = Name.drop_front(strlen("matlab_")).str();
// Suffixes that collide with Python keywords need an underscore so
// `rt.assert(...)` parses. Kept in-sync with the runtime's
// keyword-adjacent helpers.
if (Suf == "assert" || Suf == "is" || Suf == "in" || Suf == "del" ||
Suf == "if" || Suf == "else" || Suf == "elif" || Suf == "not" ||
Suf == "and" || Suf == "or" || Suf == "lambda" || Suf == "pass" ||
Suf == "class" || Suf == "def" || Suf == "return" ||
Suf == "from" || Suf == "import" || Suf == "try" || Suf == "except"||
Suf == "finally" || Suf == "raise" || Suf == "with" ||
Suf == "while" || Suf == "for" || Suf == "yield" ||
Suf == "global" || Suf == "nonlocal" ||
Suf == "None" || Suf == "True" || Suf == "False")
Suf += "_";
return "rt." + Suf;
}
return Name.str();
}
// ---------------------------------------------------------------------------
// Single-use inlining
// ---------------------------------------------------------------------------
std::string Emitter::exprFor(mlir::Value V) {
auto NI = Names.find(V);
if (NI != Names.end()) return NI->second;
auto II = InlineExprs.find(V);
if (II != InlineExprs.end()) return II->second;
if (mlir::Operation *Def = V.getDefiningOp()) {
if (InlinedOps.count(Def)) {
std::string Expr;
if (buildInlineExpr(*Def, Expr)) {
InlineExprs[V] = Expr;
return Expr;
}
}
}
return name(V);
}
std::string Emitter::stmtExpr(mlir::Value V) {
return dropOuterParens(exprFor(V));
}
bool Emitter::canInline(mlir::Operation &Op) {
using namespace mlir;
if (Op.getNumResults() != 1) return false;
Value V = Op.getResult(0);
// Always-inline: constants / zero / addressof.
if (isa<LLVM::ConstantOp, arith::ConstantOp, LLVM::ZeroOp,
LLVM::AddressOfOp>(Op))
return true;
if (!V.hasOneUse()) return false;
Operation *User = V.getUses().begin()->getOwner();
if (User->getBlock() != Op.getBlock()) return false;
if (isa<arith::AddFOp, arith::SubFOp, arith::MulFOp, arith::DivFOp,
arith::AddIOp, arith::SubIOp, arith::MulIOp,
arith::AndIOp, arith::OrIOp, arith::XOrIOp,
arith::CmpFOp, arith::CmpIOp, arith::SelectOp,
arith::SIToFPOp, arith::UIToFPOp,
arith::FPToSIOp, arith::FPToUIOp,
arith::ExtSIOp, arith::ExtUIOp, arith::TruncIOp,
arith::TruncFOp, arith::ExtFOp,
LLVM::GEPOp>(Op))
return true;
// Unregistered matlab.* binops on scalar primitives — same
// shape and constraints as the registered arith.* ops above.
{
StringRef MN = Op.getName().getStringRef();
if (Op.getNumOperands() == 2 && Op.getNumResults() == 1 &&
(MN == "matlab.add" || MN == "matlab.sub" ||
MN == "matlab.emul" || MN == "matlab.matmul" ||
MN == "matlab.ediv" || MN == "matlab.matdiv" ||
MN == "matlab.eq" || MN == "matlab.ne" ||
MN == "matlab.lt" || MN == "matlab.le" ||
MN == "matlab.gt" || MN == "matlab.ge" ||
MN == "matlab.short_or" || MN == "matlab.short_and"))
return true;
// Unary `matlab.not` — bool NOT, common in HDL code (`~data_in`,
// `if ~rst`, etc.) and emitted by the frontend with i1 result.
if (MN == "matlab.not" && Op.getNumOperands() == 1 &&
Op.getNumResults() == 1)
return true;
// matlab.load — slot triplet for HDL-targeted code that didn't
// promote to llvm.alloca. Resolves through DirectSlots in
// tryInlineExpr.
if (MN == "matlab.load" && Op.getNumOperands() == 1 &&
Op.getNumResults() == 1)
return true;
}
// Is this LLVM call to a runtime helper that's known to be a pure
// read with no side effects? Such calls don't block inlining of an
// earlier value across them.
auto isPureReadCall = [](Operation &Op2) -> bool {
auto C = dyn_cast<LLVM::CallOp>(Op2);
if (!C || !C.getCallee()) return false;
StringRef N = *C.getCallee();
if (!N.starts_with("matlab_")) return false;
StringRef S = N.drop_front(strlen("matlab_"));
// Conservative allowlist of known-pure runtime accessors. Adding
// the wrong helper here would visibly reorder side effects in the
// generated source, so we keep this list small and explicit.
return S == "obj_get_f64" || S == "size" || S == "size_dim" ||
S == "numel" || S == "numel3" || S == "length" ||
S == "ndims" || S == "isempty" || S == "isnumeric" ||
S == "isscalar" || S == "ismatrix" || S == "isvector" ||
S == "isstruct" || S == "isfield" || S == "iscell" ||
S == "isstring" || S == "string_len";
};
if (auto L = dyn_cast<LLVM::LoadOp>(Op)) {
Value AddrV = L.getAddr();
Block *BB = Op.getBlock();
for (auto It = ++Block::iterator(&Op);
It != BB->end() && &*It != User; ++It) {
if (auto S = dyn_cast<LLVM::StoreOp>(&*It))
if (S.getAddr() == AddrV) return false;
if (isa<func::CallOp>(&*It)) return false;
if (isa<LLVM::CallOp>(&*It)) {
if (!isPureReadCall(*It)) return false;
}
}
return true;
}
if (auto C = dyn_cast<func::CallOp>(Op)) {
Block *BB = Op.getBlock();
for (auto It = ++Block::iterator(&Op);
It != BB->end() && &*It != User; ++It) {
if (isa<LLVM::StoreOp>(*It)) return false;
if (isa<func::CallOp>(*It)) return false;
if (isa<LLVM::CallOp>(*It)) {
if (!isPureReadCall(*It)) return false;
}
}
(void)C;
return true;
}
if (auto C = dyn_cast<LLVM::CallOp>(Op)) {
if (!C.getCallee()) return false;
Block *BB = Op.getBlock();
for (auto It = ++Block::iterator(&Op);
It != BB->end() && &*It != User; ++It) {
if (isa<LLVM::StoreOp>(*It)) return false;
if (isa<func::CallOp>(*It)) return false;
if (isa<LLVM::CallOp>(*It)) {
if (!isPureReadCall(*It)) return false;
}
}
return true;
}
return false;
}
// Is the value's type `i1` (as opposed to a wider integer)?
static bool isI1(mlir::Type T) {
auto IT = mlir::dyn_cast<mlir::IntegerType>(T);
return IT && IT.getWidth() == 1;
}
bool Emitter::buildInlineExpr(mlir::Operation &Op, std::string &Expr) {
using namespace mlir;
if (auto C = dyn_cast<LLVM::ConstantOp>(Op)) {
auto A = C.getValue();
bool Unsigned = (bool)Op.getAttr("matlab.unsigned");
if (auto IA = dyn_cast<IntegerAttr>(A)) {
Expr = formatIntAttr(IA, Unsigned); return true;
}
if (auto FA = dyn_cast<FloatAttr>(A)) {
Expr = formatFloatAttr(FA); return true;
}
return false;
}
if (auto C = dyn_cast<arith::ConstantOp>(Op)) {
auto A = C.getValue();
bool Unsigned = (bool)Op.getAttr("matlab.unsigned");
if (auto FA = dyn_cast<FloatAttr>(A)) {
Expr = formatFloatAttr(FA); return true;
}
if (auto IA = dyn_cast<IntegerAttr>(A)) {
Expr = formatIntAttr(IA, Unsigned); return true;
}
return false;
}
if (isa<LLVM::ZeroOp>(Op)) { Expr = "0"; return true; }
if (auto A = dyn_cast<LLVM::AddressOfOp>(Op)) {
// String globals fold to a Python literal at the use site so the
// emitted source reads `rt.disp_str("Hello")` instead of
// `rt.disp_str(__matlab_str0)`. Function-symbol addressofs (function
// handles) keep the bare name so they decay to the Python callable.
auto It = StringGlobalLits.find(A.getGlobalName());
if (It != StringGlobalLits.end()) {
Expr = It->second;
SuppressedGlobals.insert(A.getGlobalName());
return true;
}
Expr = A.getGlobalName().str();
return true;
}
auto bin = [&](const char *cc) {
Expr = "(" + exprFor(Op.getOperand(0)) + " " + cc + " "
+ exprFor(Op.getOperand(1)) + ")";
return true;
};
// Per-op wrap for integer overflow. Python's int has unbounded
// precision, so chained arith on iN values diverges from the SV
// DUT's mid-computation truncation: `(a + b) * c` in i16 wraps
// twice in SV (after `+`, after `*`), but Python keeps the
// intermediate at full precision and only the final wrap fires.
// Wrap each addi / subi / muli / shli result here so the Python
// ref matches SV's two's-complement semantics on every overflow-
// capable op. Bitwise ops (and / or / xor) and right shifts
// can't overflow and skip the wrap. i1 booleans skip too.
auto wrapForResult = [&](std::string E) -> std::string {
// For matlab.* unregistered binops the result type is often
// `none`; fall back to the operand type so the wrap width
// still matches the underlying datapath. Both arith.* and
// matlab.* shapes go through this same path.
mlir::IntegerType IT;
if (auto T = mlir::dyn_cast<mlir::IntegerType>(
Op.getResult(0).getType()))
IT = T;
else if (Op.getNumOperands() >= 1) {
if (auto T = mlir::dyn_cast<mlir::IntegerType>(
Op.getOperand(0).getType()))
IT = T;
else if (Op.getNumOperands() >= 2)
if (auto T = mlir::dyn_cast<mlir::IntegerType>(
Op.getOperand(1).getType()))
IT = T;
}
if (!IT || IT.getWidth() < 2 || IT.getWidth() > 64) return E;
// Signedness inference for the wrap helper. Walk one operand
// back through transparent ops looking for a matlab.unsigned
// marker — same heuristic as the func-return wrap. Default
// signed (the SV emitter's default for multi-bit values).
auto unsignedRoot = [&](mlir::Value V) -> bool {
mlir::Value Cur = V;
for (int Hops = 0; Hops < 4; ++Hops) {
auto *Def = Cur.getDefiningOp();
if (!Def) return false;
if (Def->getAttr("matlab.unsigned")) return true;
if (mlir::isa<mlir::arith::ExtUIOp, mlir::arith::ShRUIOp,
mlir::arith::AndIOp>(Def))
return true;
if (mlir::isa<mlir::arith::ExtSIOp, mlir::arith::ShRSIOp>(Def))
return false;
if (Def->getNumOperands() == 0) return false;
Cur = Def->getOperand(0);
}
return false;
};
bool Sgn = !(unsignedRoot(Op.getOperand(0)) ||
unsignedRoot(Op.getOperand(1)));
return std::string(Sgn ? "rt.fi_wrap_s(" : "rt.fi_wrap_u(") +
dropOuterParens(std::move(E)) + ", " +
std::to_string(IT.getWidth()) + ")";
};
auto binWrap = [&](const char *cc) {
bin(cc);
Expr = wrapForResult(std::move(Expr));
return true;
};
if (isa<arith::AddFOp>(Op)) return bin("+");
if (isa<arith::SubFOp>(Op)) return bin("-");
if (isa<arith::MulFOp>(Op)) return bin("*");
if (isa<arith::DivFOp>(Op)) return bin("/");
if (isa<arith::AddIOp>(Op)) return binWrap("+");
if (isa<arith::SubIOp>(Op)) return binWrap("-");
if (isa<arith::MulIOp>(Op)) return binWrap("*");
// arith.shli / shrsi / shrui from LowerFixedPoint. Python `>>` on int
// is arithmetic (sign-preserving) and floors toward -inf — exactly what
// matlab_fi_round_floor_s does on the C side. Left shift can lose
// bits at the top; wrap the result to the declared width. Right
// shifts can't overflow and skip the wrap.
if (isa<arith::ShLIOp>(Op)) return binWrap("<<");
if (isa<arith::ShRSIOp>(Op)) return bin(">>");
// Logical right shift — Python's `>>` is arithmetic (sign-
// preserving) but SV's `>>` is logical (zero-fill). Mask the
// operand to its unsigned bit pattern first so the shifted
// bits come back as zero rather than the sign extension.
if (isa<arith::ShRUIOp>(Op)) {
auto IT = mlir::dyn_cast<mlir::IntegerType>(
Op.getOperand(0).getType());
if (IT && IT.getWidth() >= 1 && IT.getWidth() <= 64) {
uint64_t Mask = (IT.getWidth() == 64) ? ~uint64_t(0)
: (uint64_t(1) << IT.getWidth()) - 1;
Expr = "((" + exprFor(Op.getOperand(0)) + " & " +
std::to_string(Mask) + ") >> " +
exprFor(Op.getOperand(1)) + ")";
return true;
}
return bin(">>");
}
// Bitwise vs logical split on i1. `and`/`or` on bools is shorter;
// `^` doesn't have a short logical form, so emit `!=` (works because
// `True != False`).
if (auto A = dyn_cast<arith::AndIOp>(Op)) {
if (isI1(A.getType())) return bin("and");
return bin("&");
}
if (auto O = dyn_cast<arith::OrIOp>(Op)) {
if (isI1(O.getType())) return bin("or");
return bin("|");
}
if (auto X = dyn_cast<arith::XOrIOp>(Op)) {
if (isI1(X.getType())) return bin("!=");
return bin("^");
}
if (auto C = dyn_cast<arith::CmpFOp>(Op)) {
const char *cc = "==";
switch (C.getPredicate()) {
case arith::CmpFPredicate::OEQ:
case arith::CmpFPredicate::UEQ: cc = "=="; break;
case arith::CmpFPredicate::ONE:
case arith::CmpFPredicate::UNE: cc = "!="; break;
case arith::CmpFPredicate::OLT:
case arith::CmpFPredicate::ULT: cc = "<"; break;
case arith::CmpFPredicate::OLE:
case arith::CmpFPredicate::ULE: cc = "<="; break;
case arith::CmpFPredicate::OGT:
case arith::CmpFPredicate::UGT: cc = ">"; break;
case arith::CmpFPredicate::OGE:
case arith::CmpFPredicate::UGE: cc = ">="; break;
default: return false;
}
Expr = "(" + exprFor(C.getLhs()) + " " + cc + " " + exprFor(C.getRhs()) + ")";
return true;
}
if (auto C = dyn_cast<arith::CmpIOp>(Op)) {
const char *cc = "==";
switch (C.getPredicate()) {
case arith::CmpIPredicate::eq: cc = "=="; break;
case arith::CmpIPredicate::ne: cc = "!="; break;
case arith::CmpIPredicate::slt:
case arith::CmpIPredicate::ult: cc = "<"; break;
case arith::CmpIPredicate::sle:
case arith::CmpIPredicate::ule: cc = "<="; break;
case arith::CmpIPredicate::sgt:
case arith::CmpIPredicate::ugt: cc = ">"; break;
case arith::CmpIPredicate::sge:
case arith::CmpIPredicate::uge: cc = ">="; break;
}
Expr = "(" + exprFor(C.getLhs()) + " " + cc + " " + exprFor(C.getRhs()) + ")";
return true;
}
// Unregistered matlab.* binops on scalar primitives — same set
// and shape as the registered arith.* ops above. Renders as
// single-expression so chains collapse to one Python line.
{
StringRef MN = Op.getName().getStringRef();
if (Op.getNumOperands() == 2 && Op.getNumResults() == 1) {
const char *cc = nullptr;
bool Overflow = false;
if (MN == "matlab.add") { cc = "+"; Overflow = true; }
else if (MN == "matlab.sub") { cc = "-"; Overflow = true; }
else if (MN == "matlab.emul" || MN == "matlab.matmul") {
cc = "*"; Overflow = true;
}
else if (MN == "matlab.ediv" || MN == "matlab.matdiv") cc = "/";
else if (MN == "matlab.eq") cc = "==";
else if (MN == "matlab.ne") cc = "!=";
else if (MN == "matlab.lt") cc = "<";
else if (MN == "matlab.le") cc = "<=";
else if (MN == "matlab.gt") cc = ">";
else if (MN == "matlab.ge") cc = ">=";
else if (MN == "matlab.short_or") cc = "or";
else if (MN == "matlab.short_and") cc = "and";
if (cc) {
if (Overflow) return binWrap(cc);
return bin(cc);
}
}
// `matlab.not` — bool NOT. The op's i1 result coerces from any
// integer / float operand the same way `if` would in MATLAB
// (non-zero → true, zero → false). Render as `(not <operand>)`
// so the Python operand precedence is unambiguous.
if (MN == "matlab.not" && Op.getNumOperands() == 1 &&
Op.getNumResults() == 1) {
Expr = "(not " + dropOuterParens(exprFor(Op.getOperand(0))) + ")";
return true;
}
}
if (auto S = dyn_cast<arith::SelectOp>(Op)) {
// Common shape from MATLAB's logical-to-double coercion: select(c,
// 1.0, 0.0). Fold to `float(c)` instead of the ternary so the
// emitted source reads like the MATLAB expression that produced it.
auto isLit = [](Value V, double Want) -> bool {
if (auto *D = V.getDefiningOp()) {
FloatAttr FA;
if (auto C = dyn_cast<arith::ConstantOp>(D))
FA = dyn_cast<FloatAttr>(C.getValue());
else if (auto C = dyn_cast<LLVM::ConstantOp>(D))
FA = dyn_cast<FloatAttr>(C.getValue());
return FA && FA.getValueAsDouble() == Want;
}
return false;
};
if (isLit(S.getTrueValue(), 1.0) && isLit(S.getFalseValue(), 0.0)) {
Expr = "float(" + dropOuterParens(exprFor(S.getCondition())) + ")";
return true;
}
// Python ternary: `a if c else b`.
Expr = "(" + exprFor(S.getTrueValue()) + " if "
+ dropOuterParens(exprFor(S.getCondition())) + " else "
+ exprFor(S.getFalseValue()) + ")";
return true;
}
if (isa<arith::SIToFPOp, arith::UIToFPOp>(Op)) {
Expr = "float(" + dropOuterParens(exprFor(Op.getOperand(0))) + ")";
return true;
}
if (isa<arith::FPToSIOp, arith::FPToUIOp>(Op)) {
Expr = "int(" + dropOuterParens(exprFor(Op.getOperand(0))) + ")";
return true;
}
// extsi/extui/trunci/extf/truncf are no-ops in Python.
if (isa<arith::ExtSIOp, arith::ExtUIOp, arith::TruncIOp,
arith::TruncFOp, arith::ExtFOp>(Op)) {
Expr = exprFor(Op.getOperand(0));
return true;
}
if (auto L = dyn_cast<LLVM::LoadOp>(Op)) {
if (auto *D = L.getAddr().getDefiningOp()) {
auto It = DirectSlots.find(D);
if (It != DirectSlots.end()) { Expr = It->second; return true; }
}
// Non-direct slot: the address itself IS the value (typically a
// GEP expression we materialised as an index). For GEPs, the load
// resolves to `base[idx]` syntax; the GEP's inline expression
// already carries that form.
Expr = exprFor(L.getAddr());
return true;
}
// matlab.load — symmetric with LLVM::LoadOp for slot triplets that
// survived as unregistered ops (matlab.alloc → matlab.store /
// matlab.load, all `none`-typed) on HDL-targeted code.
if (Op.getName().getStringRef() == "matlab.load" &&
Op.getNumOperands() == 1 && Op.getNumResults() == 1) {
if (auto *D = Op.getOperand(0).getDefiningOp()) {
auto It = DirectSlots.find(D);
if (It != DirectSlots.end()) { Expr = It->second; return true; }
}
Expr = exprFor(Op.getOperand(0));
return true;
}
if (auto G = dyn_cast<LLVM::GEPOp>(Op)) {
// GEP into an array slot: produce `base[idx]` for a single-index
// GEP. Multi-index GEPs are uncommon in our snapshot (only
// matrix-literal buffers). Fall back to the first index, summed.
std::string Base;
if (auto *D = G.getBase().getDefiningOp()) {
auto It = ArraySlots.find(D);
if (It != ArraySlots.end()) Base = It->second;
}
if (Base.empty()) Base = exprFor(G.getBase());
std::string Idx;
bool First = true;
for (auto I : G.getIndices()) {
std::string Term;
if (auto Vv = llvm::dyn_cast<mlir::Value>(I))
Term = dropOuterParens(exprFor(Vv));
else if (auto IA = llvm::dyn_cast<mlir::IntegerAttr>(I))
Term = std::to_string(IA.getInt());
else continue;
if (First) { Idx = Term; First = false; }
else { Idx = "(" + Idx + " + " + Term + ")"; }
}
if (Idx.empty()) Idx = "0";
Expr = Base + "[" + Idx + "]";
return true;
}
if (auto C = dyn_cast<func::CallOp>(Op)) {
// Class-method call: rewrite to `obj.method(args)` / `Class(args)` /
// operator form when the callee resolves to a class method.
if (tryRewriteAsClassCall(C.getCallee(), C.getOperands(), Expr))
return true;
std::string E = C.getCallee().str() + "(";
for (unsigned i = 0; i < C.getNumOperands(); ++i) {
if (i) E += ", ";
E += dropOuterParens(exprFor(C.getOperand(i)));
}
E += ")";
Expr = E;
return true;
}
if (auto C = dyn_cast<LLVM::CallOp>(Op)) {
if (!C.getCallee()) return false;
// Class-field read: obj_get_f64(obj, "X") → obj.X.
if (tryRewriteObjGet(C, Expr)) return true;
// Class-method call: prefer `obj.method(...)` / `Class(...)` /
// operator form when the callee is one of our classdef methods.
if (tryRewriteAsClassCall(*C.getCallee(), C.getOperands(), Expr))
return true;
// Prefer the numpy / Python-operator rewrite for matrix builtins —
// it reads as the natural translation instead of a runtime trampoline.
if (tryRewriteAsNumpy(C, Expr)) return true;
std::string Callee = remapRuntimeCallee(*C.getCallee());
unsigned LengthIdx = ~0u;
bool DropLen = false;
if (C.getCallee()->starts_with("matlab_")) {
unsigned Idx;
if (calleeHasDroppableLengthArg(
C.getCallee()->drop_front(strlen("matlab_")), Idx)) {
LengthIdx = Idx;
DropLen = true;
}
}
std::string E = Callee + "(";
bool First = true;
for (unsigned i = 0; i < C.getNumOperands(); ++i) {
if (DropLen && i == LengthIdx) continue;
if (!First) E += ", ";
First = false;
E += dropOuterParens(exprFor(C.getOperand(i)));
}
E += ")";
Expr = E;
return true;
}
return false;
}
// Is V a constant integer with the given value?
static bool isConstInt(mlir::Value V, uint64_t Want) {
auto *D = V.getDefiningOp();
if (!D) return false;
if (auto C = mlir::dyn_cast<mlir::arith::ConstantOp>(D))
if (auto IA = mlir::dyn_cast<mlir::IntegerAttr>(C.getValue()))
return IA.getValue().getZExtValue() == Want;
if (auto C = mlir::dyn_cast<mlir::LLVM::ConstantOp>(D))
if (auto IA = mlir::dyn_cast<mlir::IntegerAttr>(C.getValue()))
return IA.getValue().getZExtValue() == Want;
return false;
}
bool Emitter::isFlagInversion(mlir::Value V) {
// True if V reduces to a static `True` once break/continue flags are
// un-lowered: a constant true, the xor(load flag, true) idiom, or the
// xor(const-false, const-true) Mem2RegLite leaves when a flag has no
// store-of-true.
if (!V.getType().isInteger(1)) return false;
if (isConstInt(V, 1)) return true;
auto Xor = V.getDefiningOp<mlir::arith::XOrIOp>();
if (!Xor) return false;
if (!Xor.getResult().getType().isInteger(1)) return false;