Repository navigation
Expand file tree
/
Copy pathLowerToLLVM.cpp
More file actions
8239 lines (6638 loc) · 360 KB
/
Copy pathLowerToLLVM.cpp
File metadata and controls
8239 lines (6638 loc) · 360 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
#include "TypeScript/Config.h"
#include "TypeScript/DataStructs.h"
#include "TypeScript/Defines.h"
#include "TypeScript/Passes.h"
#include "TypeScript/TypeScriptDialect.h"
#include "TypeScript/TypeScriptOps.h"
#include "mlir/Analysis/DataLayoutAnalysis.h"
#include "mlir/Conversion/AffineToStandard/AffineToStandard.h"
#include "mlir/Conversion/LLVMCommon/ConversionTarget.h"
#include "mlir/Conversion/LLVMCommon/TypeConverter.h"
#include "mlir/Conversion/LLVMCommon/Pattern.h"
#include "mlir/Conversion/ArithToLLVM/ArithToLLVM.h"
#include "mlir/Conversion/IndexToLLVM/IndexToLLVM.h"
#include "mlir/Conversion/ControlFlowToLLVM/ControlFlowToLLVM.h"
#include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h"
#include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVMPass.h"
#include "mlir/Conversion/MathToLLVM/MathToLLVM.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/Math/IR/Math.h"
#include "mlir/Dialect/Index/IR/IndexDialect.h"
#include "mlir/Dialect/Index/IR/IndexOps.h"
#ifdef ENABLE_ASYNC
#include "mlir/Conversion/AsyncToLLVM/AsyncToLLVM.h"
#endif
#include "mlir/Pass/Pass.h"
#include "mlir/Target/LLVMIR/ModuleTranslation.h"
#include "mlir/Transforms/DialectConversion.h"
#include "llvm/ADT/ScopedHashTable.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/Debug.h"
#include "llvm/IR/DIBuilder.h"
#include "TypeScript/TypeScriptPassContext.h"
#include "TypeScript/LowerToLLVMLogic.h"
#include "TypeScript/LowerToLLVM/LLVMDebugInfo.h"
#include "TypeScript/LowerToLLVM/LLVMDebugInfoFixer.h"
#include "scanner_enums.h"
#define DISABLE_SWITCH_STATE_PASS 1
#define ENABLE_MLIR_INIT
#define DEBUG_TYPE "llvm"
using namespace mlir;
using namespace ::typescript;
namespace mlir_ts = mlir::typescript;
//===----------------------------------------------------------------------===//
// TypeScriptToLLVM RewritePatterns
//===----------------------------------------------------------------------===//
namespace
{
struct TsLlvmContext
{
TsLlvmContext(CompileOptions& compileOptions) : compileOptions(compileOptions) {};
CompileOptions& compileOptions;
// the priority of the next global's own constructor, above every one MLIRGen made: LLVM leaves
// the order of equal priorities undefined, and a global may read one made before it (#446)
int64_t nextGlobalConstructorPriority = LAST_GLOBAL_CONSTRUCTOR_PRIORITY;
// the calls put into __mlir_gctors so far, with their priorities, to keep them in that order
std::vector<std::pair<int64_t, mlir::Operation *>> globalConstructorCalls;
};
template <typename OpTy> class TsLlvmPattern : public OpConversionPattern<OpTy>
{
public:
using Adaptor = typename OpTy::Adaptor;
TsLlvmPattern<OpTy>(mlir::LLVMTypeConverter &llvmTypeConverter, MLIRContext *context, TsLlvmContext *tsLlvmContext,
PatternBenefit benefit = 1)
: OpConversionPattern<OpTy>::OpConversionPattern(llvmTypeConverter, context, benefit),
tsLlvmContext(tsLlvmContext)
{
}
protected:
TsLlvmContext *tsLlvmContext;
};
class ConvertFOpLowering : public TsLlvmPattern<mlir_ts::ConvertFOp>
{
public:
using TsLlvmPattern<mlir_ts::ConvertFOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::ConvertFOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
TypeHelper th(rewriter);
LLVMCodeHelper ch(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
TypeConverterHelper tch(getTypeConverter());
auto loc = op->getLoc();
auto i8PtrTy = th.getPtrType();
auto llvmI32Type = tch.convertType(th.getI32Type());
auto llvmIndexType = tch.convertType(rewriter.getIndexType());
#ifdef WIN32
auto sprintfFuncOp = ch.getOrInsertFunction(
"sprintf_s", th.getFunctionType(rewriter.getI32Type(), {th.getPtrType(), llvmIndexType, th.getPtrType()}, true));
#else
auto sprintfFuncOp = ch.getOrInsertFunction(
"snprintf", th.getFunctionType(rewriter.getI32Type(), {th.getPtrType(), llvmIndexType, th.getPtrType()}, true));
#endif
auto bufferSizeValue = transformed.getBufferSize();
auto newStringValue = ch.MemoryAlloc(bufferSizeValue, MemoryAllocSet::Atomic);
auto formatSpecifierValue = transformed.getFormat();
SmallVector<mlir::Value> values;
values.push_back(newStringValue);
values.push_back(bufferSizeValue);
values.push_back(formatSpecifierValue);
for (auto inputVal : transformed.getInputs()) values.push_back(inputVal);
rewriter.create<LLVM::CallOp>(loc, sprintfFuncOp, values);
// Notify the rewriter that this operation has been removed.
rewriter.replaceOp(op, newStringValue);
return success();
}
};
class AssertOpLowering : public TsLlvmPattern<mlir_ts::AssertOp>
{
public:
using TsLlvmPattern<mlir_ts::AssertOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::AssertOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
TypeConverterHelper tch(getTypeConverter());
AssertLogic al(op, rewriter, tch, op->getLoc(), tsLlvmContext->compileOptions);
return al.logic(transformed.getArg(), op.getMsg().str(), transformed.getMessage());
}
};
// A string that is null reads as "null" where its text is used, as it prints and concatenates in
// JS; handed to puts/strlen as it is, it was a crash. The conversion to string keeps it null, so
// `let s: string = maybeNull` is still null afterwards.
static mlir::Value nullStringAsText(mlir::Location loc, mlir::Value text, ConversionPatternRewriter &rewriter,
TypeConverterHelper &tch)
{
auto ptrType = text.getType();
auto strType = mlir_ts::StringType::get(rewriter.getContext());
mlir::Value nullText = rewriter.create<mlir_ts::DialectCastOp>(
loc, tch.convertType(strType), rewriter.create<mlir_ts::ConstantOp>(loc, strType, rewriter.getStringAttr(NULL_NAME)));
auto nullPtr = rewriter.create<LLVM::ZeroOp>(loc, ptrType);
auto isNull = rewriter.create<LLVM::ICmpOp>(loc, LLVM::ICmpPredicate::eq, text, nullPtr);
return rewriter.create<LLVM::SelectOp>(loc, isNull, nullText, text);
}
class PrintOpLowering : public TsLlvmPattern<mlir_ts::PrintOp>
{
public:
using TsLlvmPattern<mlir_ts::PrintOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::PrintOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
TypeHelper th(rewriter);
LLVMCodeHelper ch(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
TypeConverterHelper tch(getTypeConverter());
CastLogicHelper castLogic(op, rewriter, tch, tsLlvmContext->compileOptions);
auto loc = op->getLoc();
auto i8PtrType = th.getPtrType();
auto ptrType = th.getPtrType();
// Get a symbol reference to the puts function, inserting it if necessary.
// Note: declared as returning void (not the libc i32) to match the signature MLIR's
// cf.assert-to-LLVM lowering expects when it reserves/looks up "puts" for its own use.
auto putsFuncOp = ch.getOrInsertFunction("puts", th.getFunctionType(th.getVoidType(), ptrType, false));
auto strType = mlir_ts::StringType::get(rewriter.getContext());
SmallVector<mlir::Value> values;
mlir::Value spaceString;
for (auto item : transformed.getInputs())
{
assert(item.getType() == i8PtrType);
if (values.size() > 0)
{
if (!spaceString)
{
spaceString = rewriter.create<mlir_ts::ConstantOp>(loc, strType, rewriter.getStringAttr(" "));
}
values.push_back(spaceString);
}
values.push_back(item);
}
auto size = values.size();
if (size > 1)
{
// TODO: review, why we need stack recovery here
auto stack = rewriter.create<LLVM::StackSaveOp>(loc, i8PtrType);
mlir::Value result =
rewriter.create<mlir_ts::StringConcatOp>(loc, strType, values, rewriter.getBoolAttr(true));
mlir::Value valueAsLLVMType = rewriter.create<mlir_ts::DialectCastOp>(loc, tch.convertType(strType), result);
mlir::Value valueAsPtr = rewriter.create<LLVM::BitcastOp>(loc, ptrType, valueAsLLVMType);
rewriter.create<LLVM::CallOp>(loc, putsFuncOp, valueAsPtr);
rewriter.create<LLVM::StackRestoreOp>(loc, stack);
}
else if (size == 0)
{
mlir::Value valueAsPtr = rewriter.create<mlir_ts::ConstantOp>(loc, strType, rewriter.getStringAttr(""));
mlir::Value valueAsLLVMType = rewriter.create<mlir_ts::DialectCastOp>(loc, tch.convertType(strType), valueAsPtr);
rewriter.create<LLVM::CallOp>(loc, putsFuncOp, valueAsLLVMType);
}
else
{
mlir::Value valueAsPtr = rewriter.create<LLVM::BitcastOp>(loc, ptrType, values.front());
rewriter.create<LLVM::CallOp>(loc, putsFuncOp, nullStringAsText(loc, valueAsPtr, rewriter, tch));
}
// Notify the rewriter that this operation has been removed.
rewriter.eraseOp(op);
return success();
}
};
class ParseIntOpLowering : public TsLlvmPattern<mlir_ts::ParseIntOp>
{
public:
using TsLlvmPattern<mlir_ts::ParseIntOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::ParseIntOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
TypeHelper th(rewriter);
LLVMCodeHelper ch(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
// A result wider than 32 bits (a bigint is an i64) needs the `long long` functions: `atoi`
// returns an int, and `strtol` a `long`, which is also 32 bits on Windows.
auto resultType = getTypeConverter()->convertType(op.getType());
auto wide = resultType.isIntOrFloat() && resultType.getIntOrFloatBitWidth() > 32;
auto parsedType = wide ? rewriter.getI64Type() : rewriter.getI32Type();
// Insert the `atoi` declaration if necessary.
auto i8PtrTy = th.getPtrType();
LLVM::LLVMFuncOp parseIntFuncOp;
if (transformed.getBase())
{
parseIntFuncOp = ch.getOrInsertFunction(
wide ? "strtoll" : "strtol",
th.getFunctionType(parsedType, {i8PtrTy, th.getPtrType(), rewriter.getI32Type()}));
auto nullOp = rewriter.create<LLVM::ZeroOp>(op->getLoc(), th.getPtrType());
rewriter.replaceOpWithNewOp<LLVM::CallOp>(op, parseIntFuncOp,
ValueRange{transformed.getArg(), nullOp, transformed.getBase()});
}
else
{
parseIntFuncOp = ch.getOrInsertFunction(wide ? "atoll" : "atoi", th.getFunctionType(parsedType, {i8PtrTy}));
rewriter.replaceOpWithNewOp<LLVM::CallOp>(op, parseIntFuncOp, ValueRange{transformed.getArg()});
}
return success();
}
};
class ParseFloatOpLowering : public TsLlvmPattern<mlir_ts::ParseFloatOp>
{
public:
using TsLlvmPattern<mlir_ts::ParseFloatOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::ParseFloatOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
TypeHelper th(rewriter);
LLVMCodeHelper ch(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
auto loc = op->getLoc();
// Insert the `atof` declaration if necessary.
auto i8PtrTy = th.getPtrType();
auto parseFloatFuncOp = ch.getOrInsertFunction("atof", th.getFunctionType(rewriter.getF64Type(), {i8PtrTy}));
// atof gives a double whatever the result is: `<f32>"2.5"` wants a float
auto funcCall = rewriter.create<LLVM::CallOp>(loc, parseFloatFuncOp, ValueRange{transformed.getArg()});
auto resultType = getTypeConverter()->convertType(op.getType());
if (resultType == rewriter.getF64Type())
{
rewriter.replaceOp(op, funcCall.getResult());
}
else
{
rewriter.replaceOpWithNewOp<LLVM::FPTruncOp>(op, resultType, funcCall.getResult());
}
return success();
}
};
class LoadLibraryPermanentlyOpLowering : public TsLlvmPattern<mlir_ts::LoadLibraryPermanentlyOp>
{
public:
using TsLlvmPattern<mlir_ts::LoadLibraryPermanentlyOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::LoadLibraryPermanentlyOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
TypeHelper th(rewriter);
LLVMCodeHelper ch(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
auto i8PtrTy = th.getPtrType();
auto loadLibraryPermanentlyFuncOp = ch.getOrInsertFunction("tslang_load_library_permanently", th.getFunctionType(rewriter.getI32Type(), {i8PtrTy}));
rewriter.replaceOpWithNewOp<LLVM::CallOp>(op, loadLibraryPermanentlyFuncOp, ValueRange{transformed.getFilename()});
return success();
}
};
class SearchForAddressOfSymbolOpLowering : public TsLlvmPattern<mlir_ts::SearchForAddressOfSymbolOp>
{
public:
using TsLlvmPattern<mlir_ts::SearchForAddressOfSymbolOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::SearchForAddressOfSymbolOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
TypeHelper th(rewriter);
LLVMCodeHelper ch(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
auto i8PtrTy = th.getPtrType();
auto searchForAddressOfSymbolFuncOp = ch.getOrInsertFunction("tslang_search_for_address_of_symbol", th.getFunctionType(i8PtrTy, {i8PtrTy}));
rewriter.replaceOpWithNewOp<LLVM::CallOp>(op, searchForAddressOfSymbolFuncOp, ValueRange{transformed.getSymbolName()});
return success();
}
};
class IsNaNOpLowering : public TsLlvmPattern<mlir_ts::IsNaNOp>
{
public:
using TsLlvmPattern<mlir_ts::IsNaNOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::IsNaNOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
auto loc = op->getLoc();
TypeHelper th(rewriter.getContext());
// uno (unordered) self-compare is true iff the value is NaN; `one` here would
// be constant false (ordered && x != x can never hold for a self-compare).
auto cmpValue = rewriter.create<LLVM::FCmpOp>(loc, th.getLLVMBoolType(), LLVM::FCmpPredicate::uno,
transformed.getArg(), transformed.getArg());
rewriter.replaceOp(op, ValueRange{cmpValue});
return success();
}
};
class TypeDescriptorOpLowering : public TsLlvmPattern<mlir_ts::TypeDescriptorOp>
{
public:
using TsLlvmPattern<mlir_ts::TypeDescriptorOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::TypeDescriptorOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
LLVMCodeHelper ch(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
TypeOfOpHelper toh(rewriter);
auto descriptorType = op.getDescriptorType();
auto name = toh.typeOfAsString(descriptorType);
if (name.empty())
{
// TypeOfOpHelper::typeDescriptorValue only builds this op when the type has a
// name, so an empty one here means a type grew a descriptor without growing a
// typeOf name.
op.emitError("no 'typeof' name for type: ") << descriptorType;
return mlir::failure();
}
// generated first: the descriptor's initializer takes the routine's address, so the
// symbol has to exist before the global is built
OwnershipRoutineLogic orl(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
auto releaseRoutineName = orl.getOrCreateReleaseRoutine(descriptorType);
// Under own nothing retains: the descriptor's retain slot is read only from inside
// retain routines (retainViaDescriptor), none of which can run, and building one would
// bring `__tslang_inc_ref` into a model that promises it is never referenced. A Shared<T>
// handle is the exception: own counts it (spec 23.2), so its retain is kept.
auto retainRoutineName =
tsLlvmContext->compileOptions.memoryModel == MemoryModelOwn &&
!MLIRTypeHelper::isSharedHandleType(descriptorType)
? std::string()
: orl.getOrCreateRetainRoutine(descriptorType);
rewriter.replaceOp(op, ch.getOrCreateTypeDescriptorName(descriptorType, name,
TypeOfOpHelper::typeKindFromName(name),
releaseRoutineName, retainRoutineName));
return success();
}
};
// Retain and Release lower to nothing at all unless the memory model is reference
// counting. That is what lets MLIRGen state ownership unconditionally: the ops carry the
// intent, and the model decides whether it costs anything. It also means the collected
// builds cannot be broken by where the ops are placed, only the counted ones can.
class RetainOpLowering : public TsLlvmPattern<mlir_ts::RetainOp>
{
public:
using TsLlvmPattern<mlir_ts::RetainOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::RetainOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
// A handle is counted under own too, and inference leaves its retains (spec 23.2).
auto counted = MLIRTypeHelper::isSharedHandleType(op.getReference().getType());
// Under own, ownership inference erased every retain it could prove, and reported the
// rest; one that reaches here was neither, and erasing it would ship a double free.
if (tsLlvmContext->compileOptions.memoryModel == MemoryModelOwn && !counted)
{
return op.emitError("ownership inference left a retain behind");
}
if (tsLlvmContext->compileOptions.isRefCounted() || (tsLlvmContext->compileOptions.tracksOwnership() && counted))
{
OwnershipRoutineLogic orl(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
orl.emitRetainValue(op.getReference().getType(), transformed.getReference());
}
rewriter.eraseOp(op);
return mlir::success();
}
};
class ReleaseOpLowering : public TsLlvmPattern<mlir_ts::ReleaseOp>
{
public:
using TsLlvmPattern<mlir_ts::ReleaseOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::ReleaseOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
if (tsLlvmContext->compileOptions.tracksOwnership())
{
OwnershipRoutineLogic orl(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
orl.emitReleaseValue(op.getReference().getType(), transformed.getReference());
}
rewriter.eraseOp(op);
return mlir::success();
}
};
// The slot-addressed forms. Same erasure rule, and erasing one of these takes the whole
// access with it - there is no load to leave behind in a collected build.
class RetainSlotOpLowering : public TsLlvmPattern<mlir_ts::RetainSlotOp>
{
public:
using TsLlvmPattern<mlir_ts::RetainSlotOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::RetainSlotOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
// A slot holding a handle is counted under own too, and inference leaves its retains
// (spec 23.2).
auto counted =
MLIRTypeHelper::isSharedHandleType(cast<mlir_ts::RefType>(op.getSlot().getType()).getElementType());
// Under own, ownership inference erased every retain it could prove, and reported the
// rest; one that reaches here was neither, and erasing it would ship a double free.
if (tsLlvmContext->compileOptions.memoryModel == MemoryModelOwn && !counted)
{
return op.emitError("ownership inference left a retain behind");
}
if (tsLlvmContext->compileOptions.isRefCounted() || (tsLlvmContext->compileOptions.tracksOwnership() && counted))
{
OwnershipRoutineLogic orl(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
orl.emitRetainSlot(cast<mlir_ts::RefType>(op.getSlot().getType()).getElementType(), transformed.getSlot());
}
rewriter.eraseOp(op);
return mlir::success();
}
};
class ReleaseSlotOpLowering : public TsLlvmPattern<mlir_ts::ReleaseSlotOp>
{
public:
using TsLlvmPattern<mlir_ts::ReleaseSlotOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::ReleaseSlotOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
if (tsLlvmContext->compileOptions.tracksOwnership())
{
OwnershipRoutineLogic orl(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
orl.emitReleaseSlot(cast<mlir_ts::RefType>(op.getSlot().getType()).getElementType(), transformed.getSlot());
}
rewriter.eraseOp(op);
return mlir::success();
}
};
// The cell-addressed forms. The slot is itself a heap block - a captured variable's storage -
// so these count owners of that block, where the two above count owners of the value in it.
class RetainCellOpLowering : public TsLlvmPattern<mlir_ts::RetainCellOp>
{
public:
using TsLlvmPattern<mlir_ts::RetainCellOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::RetainCellOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
// Under own, ownership inference erased every retain it could prove, and reported the
// rest; one that reaches here was neither, and erasing it would ship a double free.
if (tsLlvmContext->compileOptions.memoryModel == MemoryModelOwn)
{
return op.emitError("ownership inference left a retain behind");
}
if (tsLlvmContext->compileOptions.isRefCounted())
{
OwnershipRoutineLogic orl(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
orl.emitRetainCell(transformed.getSlot());
}
rewriter.eraseOp(op);
return mlir::success();
}
};
class ReleaseCellOpLowering : public TsLlvmPattern<mlir_ts::ReleaseCellOp>
{
public:
using TsLlvmPattern<mlir_ts::ReleaseCellOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::ReleaseCellOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
if (tsLlvmContext->compileOptions.tracksOwnership())
{
OwnershipRoutineLogic orl(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
orl.emitReleaseCell(cast<mlir_ts::RefType>(op.getSlot().getType()).getElementType(),
transformed.getSlot(),
tsLlvmContext->compileOptions.memoryModel == MemoryModelOwn &&
op->hasAttr(OWN_CELL_BORROWS_ATTR_NAME));
}
rewriter.eraseOp(op);
return mlir::success();
}
};
class SizeOfOpLowering : public TsLlvmPattern<mlir_ts::SizeOfOp>
{
public:
using TsLlvmPattern<mlir_ts::SizeOfOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::SizeOfOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
TypeHelper th(rewriter);
TypeConverterHelper tch(getTypeConverter());
auto loc = op->getLoc();
auto storageType = op.getType();
// TODO: review usage SizeOf as for example when we allocate Array<Class1> we use size of element but element is Pointer
// if (auto classType = dyn_cast<mlir_ts::ClassType>(storageType))
// {
// storageType = classType.getStorageType();
// }
// else if (auto valueRefType = dyn_cast<mlir_ts::ValueRefType>(storageType))
// {
// storageType = valueRefType.getElementType();
// }
// else if (auto objectType = dyn_cast<mlir_ts::ObjectType>(storageType))
// {
// storageType = objectType.getStorageType();
// }
auto llvmStorageType = tch.convertType(storageType);
mlir::Type llvmStorageTypePtr = th.getPtrType();
auto llvmIndexType = tch.convertType(th.getIndexType());
auto nullPtrToTypeValue = rewriter.create<LLVM::ZeroOp>(loc, llvmStorageTypePtr);
LLVM_DEBUG(llvm::dbgs() << "\n!! size of - storage type: [" << storageType << "] llvm storage type: ["
<< llvmStorageType << "] llvm ptr: [" << llvmStorageTypePtr << "]\n";);
auto sizeOfSetAddr =
rewriter.create<LLVM::GEPOp>(loc, llvmStorageTypePtr, llvmStorageType, nullPtrToTypeValue, ArrayRef<LLVM::GEPArg>{1});
rewriter.replaceOpWithNewOp<LLVM::PtrToIntOp>(op, llvmIndexType, sizeOfSetAddr);
return success();
}
};
class LengthOfOpLowering : public TsLlvmPattern<mlir_ts::LengthOfOp>
{
public:
using TsLlvmPattern<mlir_ts::LengthOfOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::LengthOfOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
TypeHelper th(rewriter);
auto loc = op->getLoc();
rewriter.replaceOpWithNewOp<mlir::LLVM::ExtractValueOp>(op, typeConverter->convertType(th.getIndexType()), transformed.getOp(),
MLIRHelper::getStructIndex(rewriter, ARRAY_SIZE_INDEX));
return success();
}
};
class SetLengthOfOpLowering : public TsLlvmPattern<mlir_ts::SetLengthOfOp>
{
public:
using TsLlvmPattern<mlir_ts::SetLengthOfOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::SetLengthOfOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
LLVMCodeHelper ch(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
CodeLogicHelper clh(op, rewriter);
TypeConverterHelper tch(getTypeConverter());
TypeHelper th(rewriter);
auto loc = op.getLoc();
auto ptrType = th.getPtrType();
auto arrayType = cast<mlir_ts::ArrayType>(cast<mlir_ts::RefType>(op.getOp().getType()).getElementType());
auto elementType = arrayType.getElementType();
auto llvmArrayType = tch.convertType(arrayType);
auto llvmElementType = tch.convertType(elementType);
auto llvmIndexType = tch.convertType(th.getIndexType());
LLVM_DEBUG(llvm::dbgs() << "arrayType: elementType: " << elementType << "\n";);
LLVM_DEBUG(llvm::dbgs() << "arrayType: llvm: " << tch.convertType(arrayType) << "\n";);
auto currentPtrPtr = rewriter.create<LLVM::GEPOp>(loc, ptrType, llvmArrayType, transformed.getOp(),
ArrayRef<LLVM::GEPArg>{0, ARRAY_DATA_INDEX});
auto currentPtr = rewriter.create<LLVM::LoadOp>(loc, ptrType, currentPtrPtr);
auto countAsIndexTypePtr = rewriter.create<LLVM::GEPOp>(loc, ptrType, llvmArrayType, transformed.getOp(),
ArrayRef<LLVM::GEPArg>{0, ARRAY_SIZE_INDEX});
auto countAsIndexType = rewriter.create<LLVM::LoadOp>(loc, llvmIndexType, countAsIndexTypePtr);
auto newCountAsIndexType = op.getNewLength();
auto sizeOfTypeAsIndexType = rewriter.create<mlir_ts::SizeOfOp>(loc, th.getIndexType(), elementType);
auto multSizeOfTypeValue =
rewriter.create<mlir::index::MulOp>(loc, th.getIndexType(), ValueRange{sizeOfTypeAsIndexType, newCountAsIndexType});
auto allocated = ch.MemoryRealloc(currentPtr, multSizeOfTypeValue);
rewriter.create<LLVM::StoreOp>(loc, allocated, currentPtrPtr);
// `arr.length = n` on a grown array exposes slots the allocator has not written. They read
// as zero: the default library's Set and Map grow their `int[]` buckets this way and take
// an unwritten bucket for an empty one, and under rc and own a store into a slot gives up
// what the slot held first (`isOwnedElementSlot`), so the release would read whatever was
// last in that memory - `result.length = this.length` followed by `result[i] = ..` is the
// default library's `Array.map`, and `arrS.map(e => e + "_")` crashed about one run in
// three (§9.37).
//
// Every model but gc, whose collector hands back cleared memory - also when a block
// shrunk in place grows again, GC_realloc having cleared what the shrink gave up.
if (!tsLlvmContext->compileOptions.needsGCRuntime())
{
auto oldBytes = rewriter.create<mlir::index::MulOp>(loc, th.getIndexType(),
ValueRange{sizeOfTypeAsIndexType,
rewriter.create<mlir::index::CastUOp>(
loc, th.getIndexType(), countAsIndexType)});
auto grew = rewriter.create<mlir::index::CmpOp>(loc, mlir::index::IndexCmpPredicate::UGT,
multSizeOfTypeValue, oldBytes);
auto *currentBlock = rewriter.getInsertionBlock();
auto *continuationBlock = rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
auto *zeroBlock = rewriter.createBlock(continuationBlock);
rewriter.setInsertionPointToEnd(zeroBlock);
auto tailStart = rewriter.create<LLVM::GEPOp>(loc, ptrType, th.getI8Type(), allocated,
ValueRange{rewriter.create<mlir::index::CastUOp>(
loc, llvmIndexType, oldBytes)});
auto tailBytes = rewriter.create<mlir::index::SubOp>(loc, th.getIndexType(),
multSizeOfTypeValue, oldBytes);
rewriter.create<LLVM::MemsetOp>(
loc, tailStart,
rewriter.create<LLVM::ConstantOp>(loc, th.getI8Type(), rewriter.getI8IntegerAttr(0)),
rewriter.create<mlir::index::CastUOp>(loc, llvmIndexType, tailBytes), /*isVolatile=*/false);
rewriter.create<LLVM::BrOp>(loc, ValueRange{}, continuationBlock);
rewriter.setInsertionPointToEnd(currentBlock);
rewriter.create<LLVM::CondBrOp>(loc, grew, zeroBlock, continuationBlock);
rewriter.setInsertionPointToStart(continuationBlock);
}
auto newCountAsLLVMType = rewriter.create<mlir::index::CastUOp>(loc, llvmIndexType, newCountAsIndexType);
rewriter.create<LLVM::StoreOp>(loc, newCountAsLLVMType, countAsIndexTypePtr);
rewriter.eraseOp(op);
return success();
}
};
class StringLengthOpLowering : public TsLlvmPattern<mlir_ts::StringLengthOp>
{
public:
using TsLlvmPattern<mlir_ts::StringLengthOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::StringLengthOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
TypeHelper th(rewriter);
LLVMCodeHelper ch(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
TypeConverterHelper tch(getTypeConverter());
auto loc = op->getLoc();
auto i8PtrTy = th.getPtrType();
auto llvmIndexType = tch.convertType(th.getIndexType());
auto strlenFuncOp = ch.getOrInsertFunction("strlen", th.getFunctionType(llvmIndexType, {i8PtrTy}));
rewriter.replaceOpWithNewOp<LLVM::CallOp>(op, strlenFuncOp, transformed.getOp());
return success();
}
};
// A new block of `size` bytes with as much of the source as fits, its terminator included; the
// source is read and nothing else. A null source is copied as the empty string.
class StringResizeOpLowering : public TsLlvmPattern<mlir_ts::StringResizeOp>
{
public:
using TsLlvmPattern<mlir_ts::StringResizeOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::StringResizeOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
TypeHelper th(rewriter);
LLVMCodeHelper ch(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
TypeConverterHelper tch(getTypeConverter());
auto loc = op->getLoc();
auto i8PtrTy = th.getPtrType();
auto llvmIndexType = tch.convertType(th.getIndexType());
auto strType = mlir_ts::StringType::get(rewriter.getContext());
mlir::Value source = transformed.getOp();
mlir::Value emptyText = rewriter.create<mlir_ts::DialectCastOp>(
loc, tch.convertType(strType), rewriter.create<mlir_ts::ConstantOp>(loc, strType, rewriter.getStringAttr("")));
auto isNull = rewriter.create<LLVM::ICmpOp>(loc, LLVM::ICmpPredicate::eq, source,
rewriter.create<LLVM::ZeroOp>(loc, i8PtrTy));
source = rewriter.create<LLVM::SelectOp>(loc, isNull, emptyText, source);
mlir::Value size = transformed.getSize();
auto newStringValue = ch.MemoryAlloc(size);
auto strlenFuncOp = ch.getOrInsertFunction("strlen", th.getFunctionType(llvmIndexType, {i8PtrTy}));
mlir::Value sourceBytes = rewriter.create<LLVM::CallOp>(loc, strlenFuncOp, ValueRange{source}).getResult();
sourceBytes = rewriter.create<LLVM::AddOp>(
loc, llvmIndexType,
ValueRange{sourceBytes, rewriter.create<LLVM::ConstantOp>(loc, llvmIndexType, rewriter.getIntegerAttr(llvmIndexType, 1))});
auto fits = rewriter.create<LLVM::ICmpOp>(loc, LLVM::ICmpPredicate::ult, sourceBytes, size);
auto copyBytes = rewriter.create<LLVM::SelectOp>(loc, fits, sourceBytes, size);
rewriter.create<LLVM::MemcpyOp>(loc, newStringValue, source, copyBytes, /*isVolatile=*/false);
rewriter.replaceOp(op, ValueRange{newStringValue});
return success();
}
};
// LLVM's CoroSplit cannot spill variable-size allocas into the coroutine frame
// ("Coroutines cannot handle non static allocas yet"), so buffers inside a
// not-yet-split coroutine (async_execute_fn marked by the MLIR async lowering)
// must be heap-allocated instead.
static bool isInsidePresplitCoroutine(mlir::Operation *op)
{
for (auto *parent = op->getParentOp(); parent; parent = parent->getParentOp())
{
if (auto passthrough = parent->getAttrOfType<mlir::ArrayAttr>("passthrough"))
{
for (auto attr : passthrough)
{
if (auto strAttr = dyn_cast<mlir::StringAttr>(attr))
{
if (strAttr.getValue() == "presplitcoroutine")
{
return true;
}
}
}
}
}
return false;
}
class StringConcatOpLowering : public TsLlvmPattern<mlir_ts::StringConcatOp>
{
public:
using TsLlvmPattern<mlir_ts::StringConcatOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::StringConcatOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
TypeHelper th(rewriter);
CodeLogicHelper clh(op, rewriter);
LLVMCodeHelper ch(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
TypeConverterHelper tch(getTypeConverter());
auto loc = op->getLoc();
// TODO implement str concat
auto i8PtrTy = th.getPtrType();
auto i8PtrPtrTy = th.getPtrType();
auto llvmIndexType = tch.convertType(th.getIndexType());
auto strlenFuncOp = ch.getOrInsertFunction("strlen", th.getFunctionType(llvmIndexType, {i8PtrTy}));
auto strcpyFuncOp = ch.getOrInsertFunction("strcpy", th.getFunctionType(i8PtrTy, {i8PtrTy, i8PtrTy}));
auto strcatFuncOp = ch.getOrInsertFunction("strcat", th.getFunctionType(i8PtrTy, {i8PtrTy, i8PtrTy}));
SmallVector<mlir::Value> opers;
for (auto oper : transformed.getOps())
{
opers.push_back(nullStringAsText(loc, oper, rewriter, tch));
}
mlir::Value size = clh.createIndexConstantOf(llvmIndexType, 1);
// calc size
for (auto oper : opers)
{
auto size1 = rewriter.create<LLVM::CallOp>(loc, strlenFuncOp, oper);
size = rewriter.create<LLVM::AddOp>(loc, llvmIndexType, ValueRange{size, size1.getResult()});
}
auto allocInStack = op.getAllocInStack().has_value() && op.getAllocInStack().value()
&& !isInsidePresplitCoroutine(op);
mlir::Value newStringValue = allocInStack ? ch.Alloca(th.getI8Type(), size, true)
: ch.MemoryAlloc(size);
// copy
auto concat = false;
auto result = newStringValue;
for (auto oper : opers)
{
if (concat)
{
auto callResult = rewriter.create<LLVM::CallOp>(loc, strcatFuncOp, ValueRange{result, oper});
result = callResult.getResult();
}
else
{
auto callResult = rewriter.create<LLVM::CallOp>(loc, strcpyFuncOp, ValueRange{result, oper});
result = callResult.getResult();
}
concat = true;
}
rewriter.replaceOp(op, ValueRange{newStringValue});
return success();
}
};
// A copy of a string: `strlen + 1` bytes, from the allocator `ts.StringConcat` uses. A null string
// stays null and allocates nothing. An optional `{ptr, i1}` is copied only when it holds a value:
// a pointer whose flag says "none" may be anything.
class StringCopyOpLowering : public TsLlvmPattern<mlir_ts::StringCopyOp>
{
public:
using TsLlvmPattern<mlir_ts::StringCopyOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::StringCopyOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
TypeHelper th(rewriter);
LLVMCodeHelper ch(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
TypeConverterHelper tch(getTypeConverter());
CodeLogicHelper clh(op, rewriter);
auto loc = op->getLoc();
auto i8PtrTy = th.getPtrType();
auto llvmIndexType = tch.convertType(th.getIndexType());
auto llvmBoolType = th.getLLVMBoolType();
auto strlenFuncOp = ch.getOrInsertFunction("strlen", th.getFunctionType(llvmIndexType, {i8PtrTy}));
auto copyOf = [&](mlir::Value source, mlir::Value copyIt) {
return clh.conditionalExpressionLowering(
loc, i8PtrTy, copyIt,
[&](OpBuilder &, Location) -> mlir::Value {
mlir::Value bytes = rewriter.create<LLVM::CallOp>(loc, strlenFuncOp, ValueRange{source}).getResult();
bytes = rewriter.create<LLVM::AddOp>(
loc, llvmIndexType,
ValueRange{bytes, rewriter.create<LLVM::ConstantOp>(loc, llvmIndexType, rewriter.getIntegerAttr(llvmIndexType, 1))});
auto copy = ch.MemoryAlloc(bytes);
rewriter.create<LLVM::MemcpyOp>(loc, copy, source, bytes, /*isVolatile=*/false);
return copy;
},
[&](OpBuilder &, Location) -> mlir::Value { return source; });
};
mlir::Value in = transformed.getIn();
auto isSet = [&](mlir::Value pointer) -> mlir::Value {
return rewriter.create<LLVM::ICmpOp>(loc, LLVM::ICmpPredicate::ne, pointer, rewriter.create<LLVM::ZeroOp>(loc, i8PtrTy));
};
if (mlir::isa<LLVM::LLVMPointerType>(in.getType()))
{
rewriter.replaceOp(op, ValueRange{copyOf(in, isSet(in))});
return success();
}
// an optional: `{ptr, i1}`
auto optionalType = mlir::dyn_cast<LLVM::LLVMStructType>(in.getType());
if (!optionalType || optionalType.getBody().size() != 2 ||
!mlir::isa<LLVM::LLVMPointerType>(optionalType.getBody()[0]) || !optionalType.getBody()[1].isInteger(1))
{
return rewriter.notifyMatchFailure(op, "ts.StringCopy takes a pointer or a { ptr, i1 } optional");
}
auto pointer = rewriter.create<LLVM::ExtractValueOp>(loc, in, ArrayRef<int64_t>{0});
auto hasValue = rewriter.create<LLVM::ExtractValueOp>(loc, in, ArrayRef<int64_t>{1});
auto copyIt = rewriter.create<LLVM::AndOp>(loc, llvmBoolType, hasValue, isSet(pointer));
auto copied = copyOf(pointer, copyIt);
rewriter.replaceOp(op, ValueRange{rewriter.create<LLVM::InsertValueOp>(loc, in, copied, ArrayRef<int64_t>{0})});
return success();
}
};
// `new Shared(x)` (own spec 23): a heap block with the header every block has (a count under rc
// and own, born 0 like any block), whose payload is the value.
class SharedNewOpLowering : public TsLlvmPattern<mlir_ts::SharedNewOp>
{
public:
using TsLlvmPattern<mlir_ts::SharedNewOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::SharedNewOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
LLVMCodeHelper ch(op, rewriter, getTypeConverter(), tsLlvmContext->compileOptions);
auto elementType = mlir::cast<mlir_ts::SharedType>(op.getType()).getElementType();
auto handle = ch.MemoryAlloc(elementType, MemoryAllocSet::Zero);
rewriter.create<LLVM::StoreOp>(op->getLoc(), transformed.getValue(), handle);
rewriter.replaceOp(op, ValueRange{handle});
return success();
}
};
// `s.value`: the payload starts at the handle.
class SharedValueRefOpLowering : public TsLlvmPattern<mlir_ts::SharedValueRefOp>
{
public:
using TsLlvmPattern<mlir_ts::SharedValueRefOp>::TsLlvmPattern;
LogicalResult matchAndRewrite(mlir_ts::SharedValueRefOp op, Adaptor transformed,
ConversionPatternRewriter &rewriter) const final
{
rewriter.replaceOp(op, ValueRange{transformed.getShared()});
return success();
}