Repository navigation
Expand file tree
/
Copy pathMLIRGenExpressions.cpp
More file actions
1733 lines (1460 loc) · 71.7 KB
/
Copy pathMLIRGenExpressions.cpp
File metadata and controls
1733 lines (1460 loc) · 71.7 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
// Expression-level code generation methods of MLIRGenImpl (see MLIRGenImpl.h).
#include "MLIRGenImpl.h"
#include "mlir/Dialect/Async/IR/Async.h"
#undef DEBUG_TYPE
#define DEBUG_TYPE "mlir"
namespace typescript
{
namespace mlirgen
{
ValueOrLogicalResult MLIRGenImpl::mlirGen(Expression expressionAST, const GenContext &genContext)
{
auto kind = (SyntaxKind)expressionAST;
if (kind == SyntaxKind::Identifier)
{
return mlirGen(expressionAST.as<Identifier>(), genContext);
}
else if (kind == SyntaxKind::PropertyAccessExpression)
{
return mlirGen(expressionAST.as<PropertyAccessExpression>(), genContext);
}
else if (kind == SyntaxKind::CallExpression)
{
return mlirGen(expressionAST.as<CallExpression>(), genContext);
}
else if (kind == SyntaxKind::NumericLiteral)
{
return mlirGen(expressionAST.as<NumericLiteral>(), genContext);
}
else if (kind == SyntaxKind::StringLiteral)
{
return mlirGen(expressionAST.as<ts::StringLiteral>(), genContext);
}
else if (kind == SyntaxKind::NoSubstitutionTemplateLiteral)
{
return mlirGen(expressionAST.as<NoSubstitutionTemplateLiteral>(), genContext);
}
else if (kind == SyntaxKind::BigIntLiteral)
{
return mlirGen(expressionAST.as<BigIntLiteral>(), genContext);
}
else if (kind == SyntaxKind::RegularExpressionLiteral)
{
return mlirGen(expressionAST.as<RegularExpressionLiteral>(), genContext);
}
else if (kind == SyntaxKind::NullKeyword)
{
return mlirGen(expressionAST.as<NullLiteral>(), genContext);
}
else if (kind == SyntaxKind::TrueKeyword)
{
return mlirGen(expressionAST.as<TrueLiteral>(), genContext);
}
else if (kind == SyntaxKind::FalseKeyword)
{
return mlirGen(expressionAST.as<FalseLiteral>(), genContext);
}
else if (kind == SyntaxKind::ArrayLiteralExpression)
{
return mlirGen(expressionAST.as<ArrayLiteralExpression>(), genContext);
}
else if (kind == SyntaxKind::ObjectLiteralExpression)
{
return mlirGen(expressionAST.as<ObjectLiteralExpression>(), genContext);
}
else if (kind == SyntaxKind::SpreadElement)
{
return mlirGen(expressionAST.as<SpreadElement>(), genContext);
}
else if (kind == SyntaxKind::BinaryExpression)
{
return mlirGen(expressionAST.as<BinaryExpression>(), genContext);
}
else if (kind == SyntaxKind::PrefixUnaryExpression)
{
return mlirGen(expressionAST.as<PrefixUnaryExpression>(), genContext);
}
else if (kind == SyntaxKind::PostfixUnaryExpression)
{
return mlirGen(expressionAST.as<PostfixUnaryExpression>(), genContext);
}
else if (kind == SyntaxKind::ParenthesizedExpression)
{
return mlirGen(expressionAST.as<ParenthesizedExpression>(), genContext);
}
else if (kind == SyntaxKind::TypeOfExpression)
{
return mlirGen(expressionAST.as<TypeOfExpression>(), genContext);
}
else if (kind == SyntaxKind::ConditionalExpression)
{
return mlirGen(expressionAST.as<ConditionalExpression>(), genContext);
}
else if (kind == SyntaxKind::ElementAccessExpression)
{
return mlirGen(expressionAST.as<ElementAccessExpression>(), genContext);
}
else if (kind == SyntaxKind::FunctionExpression)
{
return mlirGen(expressionAST.as<FunctionExpression>(), genContext);
}
else if (kind == SyntaxKind::ArrowFunction)
{
return mlirGen(expressionAST.as<ArrowFunction>(), genContext);
}
else if (kind == SyntaxKind::TypeAssertionExpression)
{
return mlirGen(expressionAST.as<TypeAssertion>(), genContext);
}
else if (kind == SyntaxKind::AsExpression)
{
return mlirGen(expressionAST.as<AsExpression>(), genContext);
}
else if (kind == SyntaxKind::TemplateExpression)
{
return mlirGen(expressionAST.as<TemplateLiteralLikeNode>(), genContext);
}
else if (kind == SyntaxKind::TaggedTemplateExpression)
{
return mlirGen(expressionAST.as<TaggedTemplateExpression>(), genContext);
}
else if (kind == SyntaxKind::NewExpression)
{
return mlirGen(expressionAST.as<NewExpression>(), genContext);
}
else if (kind == SyntaxKind::DeleteExpression)
{
mlirGen(expressionAST.as<DeleteExpression>(), genContext);
return mlir::success();
}
else if (kind == SyntaxKind::ThisKeyword)
{
if ((expressionAST->internalFlags & InternalFlags::ThisArgAlias) == InternalFlags::ThisArgAlias)
{
return mlirGen(loc(expressionAST), THIS_ALIAS, genContext);
}
return mlirGen(loc(expressionAST), THIS_NAME, genContext);
}
else if (kind == SyntaxKind::SuperKeyword)
{
return mlirGen(loc(expressionAST), SUPER_NAME, genContext);
}
else if (kind == SyntaxKind::VoidExpression)
{
return mlirGen(expressionAST.as<VoidExpression>(), genContext);
}
else if (kind == SyntaxKind::YieldExpression)
{
return mlirGen(expressionAST.as<YieldExpression>(), genContext);
}
else if (kind == SyntaxKind::AwaitExpression)
{
return mlirGen(expressionAST.as<AwaitExpression>(), genContext);
}
else if (kind == SyntaxKind::NonNullExpression)
{
return mlirGen(expressionAST.as<NonNullExpression>(), genContext);
}
else if (kind == SyntaxKind::ClassExpression)
{
return mlirGen(expressionAST.as<ClassExpression>(), genContext);
}
else if (kind == SyntaxKind::OmittedExpression)
{
return mlirGen(expressionAST.as<OmittedExpression>(), genContext);
}
else if (kind == SyntaxKind::ExpressionWithTypeArguments)
{
return mlirGen(expressionAST.as<ExpressionWithTypeArguments>(), genContext);
}
else if (kind == SyntaxKind::Unknown /*TODO: temp solution to treat null expr as empty expr*/)
{
return mlir::success();
}
// e.g. a constructor parameter property combined with a destructuring pattern
// (`constructor(public {x, y}: T) {}`) - real TypeScript rejects that combination
// (TS2369, parameter properties can't use a binding pattern) but this compiler doesn't
// enforce that check, so the pattern's ObjectBindingPattern/ArrayBindingPattern name node
// (not an Expression kind at all) ends up passed to this dispatcher. Fail cleanly instead
// of crashing rather than trying to guess every non-Expression node kind that could land
// here.
emitError(loc(expressionAST)) << "unsupported expression";
return ValueOrLogicalResult(mlir::failure());
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(FunctionExpression functionExpressionAST, const GenContext &genContext)
{
auto location = loc(functionExpressionAST);
mlir_ts::FuncOp funcOp;
std::string funcName;
{
mlir::OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPointToStart(theModule.getBody());
// provide name for it
auto funcGenContext = GenContext(genContext);
funcGenContext.clearScopeVars();
funcGenContext.thisType = nullptr;
auto [result, funcOpRet, funcNameRet, isGenericRet] =
mlirGenFunctionLikeDeclaration(functionExpressionAST, funcGenContext);
if (mlir::failed(result))
{
return mlir::failure();
}
funcOp = funcOpRet;
funcName = funcNameRet;
}
// if funcOp is null, means lambda is generic]
if (!funcOp)
{
// return reference to generic method
if (getGenericFunctionMap().count(funcName))
{
auto genericFunctionInfo = getGenericFunctionMap().lookup(funcName);
// info: it will not take any capture now
return resolveFunctionWithCapture(location, genericFunctionInfo->name, genericFunctionInfo->funcType,
mlir::Value(), true, genContext);
}
else
{
emitError(location) << "can't find generic function: " << funcName;
return mlir::failure();
}
}
return resolveFunctionWithCapture(location, funcOp.getName(), funcOp.getFunctionType(), mlir::Value(), false, genContext);
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(ArrowFunction arrowFunctionAST, const GenContext &genContext)
{
auto location = loc(arrowFunctionAST);
mlir_ts::FuncOp funcOp;
std::string funcName;
bool isGeneric;
{
mlir::OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPointToStart(theModule.getBody());
// provide name for it
auto allowFuncGenContext = GenContext(genContext);
allowFuncGenContext.clearScopeVars();
// if we set it to value we will not capture 'this' references
allowFuncGenContext.thisType = nullptr;
auto [result, funcOpRet, funcNameRet, isGenericRet] =
mlirGenFunctionLikeDeclaration(arrowFunctionAST, allowFuncGenContext);
if (mlir::failed(result))
{
return mlir::failure();
}
funcOp = funcOpRet;
funcName = funcNameRet;
isGeneric = isGenericRet;
}
// if funcOp is null, means lambda is generic
if (!funcOp)
{
// return reference to generic method
if (getGenericFunctionMap().count(funcName))
{
auto genericFunctionInfo = getGenericFunctionMap().lookup(funcName);
auto funcType = genericFunctionInfo->funcType ? genericFunctionInfo->funcType : getFunctionType({}, {}, false);
// info: it will not take any capture now
return resolveFunctionWithCapture(location, genericFunctionInfo->name, funcType,
mlir::Value(), true, genContext);
}
else
{
emitError(location) << "can't find generic function: " << funcName;
return mlir::failure();
}
}
assert(funcOp);
return resolveFunctionWithCapture(location, funcOp.getName(), funcOp.getFunctionType(), mlir::Value(), isGeneric, genContext);
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(TypeAssertion typeAssertionAST, const GenContext &genContext)
{
auto location = loc(typeAssertionAST);
auto typeInfo = getType(typeAssertionAST->type, genContext);
if (!typeInfo)
{
return mlir::failure();
}
GenContext noReceiverGenContext(genContext);
noReceiverGenContext.clearReceiverTypes();
noReceiverGenContext.receiverType = typeInfo;
auto result = mlirGen(typeAssertionAST->expression, noReceiverGenContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
auto exprValue = V(result);
CAST_A(castedValue, location, typeInfo, exprValue, genContext);
return castedValue;
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(AsExpression asExpressionAST, const GenContext &genContext)
{
auto location = loc(asExpressionAST);
auto typeInfo = getType(asExpressionAST->type, genContext);
if (!typeInfo)
{
return mlir::failure();
}
GenContext noReceiverGenContext(genContext);
noReceiverGenContext.clearReceiverTypes();
noReceiverGenContext.receiverType = typeInfo;
auto result = mlirGen(asExpressionAST->expression, noReceiverGenContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
auto exprValue = V(result);
CAST_A(castedValue, location, typeInfo, exprValue, genContext);
return castedValue;
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(ComputedPropertyName computedPropertyNameAST, const GenContext &genContext)
{
auto result = mlirGen(computedPropertyNameAST->expression, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
auto exprValue = V(result);
return exprValue;
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(YieldExpression yieldExpressionAST, const GenContext &genContext)
{
if (yieldExpressionAST->asteriskToken)
{
return mlirGenYieldStar(yieldExpressionAST, genContext);
}
auto location = loc(yieldExpressionAST);
if (genContext.passResult)
{
genContext.passResult->functionReturnTypeShouldBeProvided = true;
}
// get state
auto state = 0;
if (genContext.state)
{
state = (*genContext.state)++;
}
else
{
assert(false);
}
// set restore point (return point)
stringstream num;
num << state;
NodeFactory nf(NodeFactoryFlags::None);
if (evaluateProperty(nf.createToken(SyntaxKind::ThisKeyword), GENERATOR_STEP, genContext))
{
// save return point - state -> this.step = xxx
auto setStateExpr = nf.createBinaryExpression(
nf.createPropertyAccessExpression(nf.createToken(SyntaxKind::ThisKeyword), nf.createIdentifier(S(GENERATOR_STEP))),
nf.createToken(SyntaxKind::EqualsToken), nf.createNumericLiteral(num.str(), TokenFlags::None));
mlirGen(setStateExpr, genContext);
}
else
{
// save return point - state -> step = xxx
auto setStateExpr = nf.createBinaryExpression(
nf.createIdentifier(S(GENERATOR_STEP)),
nf.createToken(SyntaxKind::EqualsToken), nf.createNumericLiteral(num.str(), TokenFlags::None));
mlirGen(setStateExpr, genContext);
}
// return value
auto yieldRetValue = getYieldReturnObject(nf, location, yieldExpressionAST->expression, false);
auto result = mlirGen(yieldRetValue, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
auto yieldValue = V(result);
mlirGenReturnValue(location, yieldValue, true, genContext);
std::stringstream label;
label << GENERATOR_STATELABELPREFIX << state;
builder.create<mlir_ts::StateLabelOp>(location, label.str());
// TODO: yield value to continue, should be loaded from "next(value)" parameter
// return yieldValue;
return mlir::success();
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(AwaitExpression awaitExpressionAST, const GenContext &genContext)
{
#ifdef ENABLE_ASYNC
// TODO: due to cloning code into next function, it is not fixing scope properly
auto location = stripMetadata(loc(awaitExpressionAST));
auto resultType = evaluate(awaitExpressionAST->expression, genContext);
if (resultType && isa<mlir_ts::VoidType>(resultType))
{
resultType = mlir::Type();
}
// The result travels through a slot in the awaiting function rather than through
// `!async.value<T>`. MLIR's async-to-LLVM conversion runs before the TypeScript types are
// lowered (see transform.cpp - createConvertAsyncToLLVMPass, then createLowerToLLVMPass),
// and it converts an async value's payload with its own LLVMTypeConverter, which knows
// nothing about this dialect. So a payload of any TypeScript type - `number`, `string`,
// `boolean`, a class, an array - failed with "failed to legalize operation
// 'async.runtime.load'", and only awaits whose payload happened to be a builtin type
// (`i32`, `i64`, `f32`) ever compiled. Section 9.56.
//
// A token carries no payload, so nothing has to convert. The awaited body writes into the
// slot, `async.await` on the token is what orders that write before the read, and the
// outlining pass passes the slot in as an argument like any other value the region uses
// from above.
mlir::Value resultSlot;
if (resultType)
{
resultSlot = builder.create<mlir_ts::VariableOp>(location, mlir_ts::RefType::get(resultType),
mlir::Value(), builder.getBoolAttr(false),
builder.getIndexAttr(0));
}
ValueOrLogicalResult result(mlir::failure());
auto slotOwnsResult = false;
auto asyncExecOp = builder.create<mlir::async::ExecuteOp>(
location, mlir::TypeRange(), mlir::ValueRange{},
mlir::ValueRange{}, [&](mlir::OpBuilder &builder, mlir::Location location, mlir::ValueRange values) {
DITableScopeT debugAsyncCodeScope(debugScope);
MLIRDebugInfoHelper mdi(builder, debugScope);
// TODO: temp hack to break wrong chain on scopes because 'await' create extra function wrap
mdi.clearDebugScope();
mdi.setLexicalBlock(location);
result = mlirGen(awaitExpressionAST->expression, genContext);
if (result)
{
auto value = V(result);
// No cast: `resultType` is what `evaluate` said this same expression produces,
// and the yield that used to carry it had to match the execute's result type
// for the op to verify at all.
if (value && resultSlot)
{
// Under reference counting the slot is what keeps the result alive across
// the await. Everything the awaited expression produced is a temporary of
// the region's own block, so without this the value is released the moment
// the region ends - before the awaiting function has read the slot. It read
// correctly at -O0 and garbage at -O3, which is only ever a matter of what
// reused the block first.
//
// Same two cases as a local's declaration: a value that already carries a
// reference hands it over, anything else is retained. Either way the slot
// is the owner from here, and the awaiting scope gives that reference back.
if (compileOptions.isRefCounted() && mth.ownsHeapMemory(location, resultType))
{
if (producesOwnedReference(value))
{
consumeOwnedReference(value);
}
else
{
builder.create<mlir_ts::RetainOp>(location, value);
}
slotOwnsResult = true;
}
builder.create<mlir_ts::StoreOp>(location, value, resultSlot);
}
builder.create<mlir::async::YieldOp>(location, mlir::ValueRange{});
}
});
EXIT_IF_FAILED_OR_NO_VALUE(result)
// Registered only now, and only if the store above actually happened: an owned slot is
// released at scope exit whatever is in it, and a slot nothing wrote holds whatever the
// frame held before. The attributes say the retain is elsewhere - inside the region, beside
// the store - so the verifier does not go looking for one at the declaration.
if (slotOwnsResult && genContext.ownedVars != nullptr)
{
auto varOp = resultSlot.getDefiningOp<mlir_ts::VariableOp>();
varOp->setAttr(OWNED_LOCAL_ATTR_NAME, builder.getUnitAttr());
varOp->setAttr(OWNED_LOCAL_CONSUMED_ATTR_NAME, builder.getUnitAttr());
genContext.ownedVars->push_back(resultSlot);
}
builder.create<mlir::async::AwaitOp>(location, asyncExecOp.getToken());
if (resultSlot)
{
return V(builder.create<mlir_ts::LoadOp>(location, resultType, resultSlot));
}
return mlir::success();
#else
return mlirGen(awaitExpressionAST->expression, genContext);
#endif
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(UnaryExpression unaryExpressionAST, const GenContext &genContext)
{
return mlirGen(unaryExpressionAST.as<Expression>(), genContext);
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(LeftHandSideExpression leftHandSideExpressionAST, const GenContext &genContext)
{
return mlirGen(leftHandSideExpressionAST.as<Expression>(), genContext);
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(PrefixUnaryExpression prefixUnaryExpressionAST, const GenContext &genContext)
{
auto location = loc(prefixUnaryExpressionAST);
auto opCode = prefixUnaryExpressionAST->_operator;
auto expression = prefixUnaryExpressionAST->operand;
auto result = mlirGen(expression, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
auto expressionValue = V(result);
// special case "-" for literal value
if (opCode == SyntaxKind::PlusToken || opCode == SyntaxKind::MinusToken || opCode == SyntaxKind::TildeToken || opCode == SyntaxKind::ExclamationToken)
{
if (auto constantOp = expressionValue.getDefiningOp<mlir_ts::ConstantOp>())
{
auto res = mlirGenPrefixUnaryExpression(location, opCode, constantOp, genContext);
EXIT_IF_FAILED(res)
if (res.value)
{
return res.value;
}
}
}
switch (opCode)
{
case SyntaxKind::ExclamationToken:
{
auto boolValue = expressionValue;
if (expressionValue.getType() != getBooleanType())
{
CAST(boolValue, location, getBooleanType(), expressionValue, genContext);
}
return V(builder.create<mlir_ts::ArithmeticUnaryOp>(location, getBooleanType(),
builder.getI32IntegerAttr((int)opCode), boolValue));
}
case SyntaxKind::TildeToken:
{
// `~` always yields a 32-bit int result per JS ToInt32 semantics - a raw
// float type (e.g. `f64`/`f32`) satisfies isIntOrIndexOrFloat() just like an
// int does, but still needs truncating to i32 the same way mlir_ts::NumberType
// already does below; only a value that's already int/index can skip the cast.
auto numberValue = expressionValue;
if (!expressionValue.getType().isIntOrIndex())
{
CAST(numberValue, location, builder.getI32Type(), expressionValue, genContext);
}
return V(builder.create<mlir_ts::ArithmeticUnaryOp>(
location, numberValue.getType(), builder.getI32IntegerAttr((int)opCode), numberValue));
}
case SyntaxKind::PlusToken:
case SyntaxKind::MinusToken:
{
auto numberValue = expressionValue;
if (expressionValue.getType() != getNumberType() && !expressionValue.getType().isIntOrIndexOrFloat())
{
CAST(numberValue, location, getNumberType(), expressionValue, genContext);
}
return V(builder.create<mlir_ts::ArithmeticUnaryOp>(
location, numberValue.getType(), builder.getI32IntegerAttr((int)opCode), numberValue));
}
case SyntaxKind::PlusPlusToken:
case SyntaxKind::MinusMinusToken:
return V(builder.create<mlir_ts::PrefixUnaryOp>(location, expressionValue.getType(),
builder.getI32IntegerAttr((int)opCode), expressionValue));
default:
// `+ - ~ ! ++ --` are the complete set of TS prefix-unary operators, all handled
// above; fail cleanly instead of crashing if that ever stops being true.
emitError(location, "unsupported prefix unary operator");
return ValueOrLogicalResult(mlir::failure());
}
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(PostfixUnaryExpression postfixUnaryExpressionAST, const GenContext &genContext)
{
auto location = loc(postfixUnaryExpressionAST);
auto opCode = postfixUnaryExpressionAST->_operator;
auto expression = postfixUnaryExpressionAST->operand;
auto result = mlirGen(expression, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
auto expressionValue = V(result);
switch (opCode)
{
case SyntaxKind::PlusPlusToken:
case SyntaxKind::MinusMinusToken:
return V(builder.create<mlir_ts::PostfixUnaryOp>(location, expressionValue.getType(),
builder.getI32IntegerAttr((int)opCode), expressionValue));
default:
// `++ --` are the complete set of TS postfix-unary operators, both handled above;
// fail cleanly instead of crashing if that ever stops being true.
emitError(location, "unsupported postfix unary operator");
return ValueOrLogicalResult(mlir::failure());
}
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(ConditionalExpression conditionalExpressionAST, const GenContext &genContext)
{
auto location = loc(conditionalExpressionAST);
// condition
auto condExpression = conditionalExpressionAST->condition;
auto result = mlirGen(condExpression, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
auto condValue = V(result);
// only the branch that runs is generated when the condition is known, see mlirGenSkippedBranch
auto staticCondition = getStaticBoolean(condValue);
if (condValue.getType() != getBooleanType())
{
CAST(condValue, location, getBooleanType(), condValue, genContext);
}
// detect value type
// TODO: sync types for 'when' and 'else'
auto ifOp = builder.create<mlir_ts::IfOp>(location, mlir::TypeRange{getVoidType()}, condValue, true);
builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
auto whenTrueExpression = conditionalExpressionAST->whenTrue;
ElseSafeCase elseSafeCase;
mlir::Value resultTrue;
if (staticCondition.value_or(true))
{
// check if we do safe-cast here
SymbolTableScopeT varScope(symbolTable);
SafeTypesMapScopeT safeTypesMapScope(safeTypesMap);
checkSafeCast(conditionalExpressionAST->condition, V(result), &elseSafeCase, genContext);
auto result = mlirGen(whenTrueExpression, genContext);
if (!genContext.allowPartialResolve)
{
EXIT_IF_FAILED_OR_NO_VALUE(result)
}
resultTrue = V(result);
}
else
{
resultTrue = mlirGenSkippedBranch(location, whenTrueExpression, [&](const GenContext &evalGenContext) {
checkSafeCast(conditionalExpressionAST->condition, V(result), nullptr, evalGenContext);
}, genContext);
}
builder.setInsertionPointToStart(&ifOp.getElseRegion().front());
auto whenFalseExpression = conditionalExpressionAST->whenFalse;
mlir::Value resultFalse;
if (!staticCondition.value_or(false))
{
SymbolTableScopeT varScope(symbolTable);
SafeTypesMapScopeT safeTypesMapScope(safeTypesMap);
if (elseSafeCase.safeType)
{
addSafeCastStatement(elseSafeCase.expr, elseSafeCase.safeType, false, nullptr, genContext);
}
auto result2 = mlirGen(whenFalseExpression, genContext);
if (!genContext.allowPartialResolve)
{
EXIT_IF_FAILED_OR_NO_VALUE(result2)
}
resultFalse = V(result2);
}
else
{
resultFalse = mlirGenSkippedBranch(location, whenFalseExpression, [&](const GenContext &evalGenContext) {
if (elseSafeCase.safeType)
{
addSafeCastStatement(elseSafeCase.expr, elseSafeCase.safeType, false, nullptr, evalGenContext);
}
}, genContext);
}
if (resultTrue && resultFalse)
{
auto defaultUnionType = getUnionType(location, resultTrue.getType(), resultFalse.getType());
auto merged = false;
auto resultType = mth.findBaseType(resultTrue.getType(), resultFalse.getType(), merged, defaultUnionType);
ifOp.getResult(0).setType(resultType);
CAST_A(falseRes, location, resultType, resultFalse, genContext)
builder.create<mlir_ts::ResultOp>(location, mlir::ValueRange{falseRes});
// finish type of IfOp and WhenTrue clause
builder.setInsertionPointToEnd(&ifOp.getThenRegion().back());
CAST_A(trueRes, location, resultType, resultTrue, genContext);
builder.create<mlir_ts::ResultOp>(location, mlir::ValueRange{trueRes});
}
else
{
// to support partial result
auto partialResult = resultTrue ? resultTrue : resultFalse;
if (partialResult)
{
ifOp.getResult(0).setType(partialResult.getType());
}
else
{
return mlir::failure();
}
}
builder.setInsertionPointAfter(ifOp);
return ifOp.getResult(0);
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(BinaryExpression binaryExpressionAST, const GenContext &genContext)
{
auto location = loc(binaryExpressionAST);
auto opCode = (SyntaxKind)binaryExpressionAST->operatorToken;
auto saveResult = MLIRLogicHelper::isNeededToSaveData(opCode);
auto leftExpression = binaryExpressionAST->left;
auto rightExpression = binaryExpressionAST->right;
if (opCode == SyntaxKind::AmpersandAmpersandToken || opCode == SyntaxKind::BarBarToken)
{
return mlirGenAndOrLogic(binaryExpressionAST, genContext, opCode == SyntaxKind::AmpersandAmpersandToken,
saveResult);
}
if (opCode == SyntaxKind::QuestionQuestionToken)
{
return mlirGenQuestionQuestionLogic(binaryExpressionAST, saveResult, genContext);
}
if (opCode == SyntaxKind::InKeyword)
{
return mlirGenInLogic(binaryExpressionAST, genContext);
}
if (opCode == SyntaxKind::InstanceOfKeyword)
{
return mlirGenInstanceOfLogic(binaryExpressionAST, genContext);
}
if (opCode == SyntaxKind::EqualsToken)
{
return mlirGenSaveLogic(binaryExpressionAST, genContext);
}
auto result = mlirGen(leftExpression, genContext);
if (opCode == SyntaxKind::CommaToken)
{
//in case of "comma" op the result of left op can be "nothing"
EXIT_IF_FAILED(result)
}
else
{
EXIT_IF_FAILED_OR_NO_VALUE(result)
}
auto leftExpressionValue = V(result);
auto result2 = mlirGen(rightExpression, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result2)
auto rightExpressionValue = V(result2);
// `typeof x === "name"` where x has a type known at compile time: the descriptor's name is
// known now, and the run-time compare is a plain string compare, so fold it. The boolean
// literal lets `if` skip a branch that can never run - in a generic specialised for an array,
// such a branch can hold casts an array cannot take, which crash LLVM lowering.
if (auto folded = foldStaticTypeOfCompare(location, opCode, leftExpressionValue, rightExpressionValue))
{
return *folded;
}
// check if const expr.
if (genContext.allowConstEval)
{
LLVM_DEBUG(llvm::dbgs() << "Evaluate const: '" << leftExpressionValue << "' and '" << rightExpressionValue << "'\n";);
auto leftConstOp = dyn_cast<mlir_ts::ConstantOp>(leftExpressionValue.getDefiningOp());
auto rightConstOp = dyn_cast<mlir_ts::ConstantOp>(rightExpressionValue.getDefiningOp());
if (leftConstOp && rightConstOp)
{
// try to evaluate
return evaluateBinaryOp(location, opCode, leftConstOp, rightConstOp, genContext);
}
}
auto resultReturnUnions =
binaryOpLogicForUnions(location, opCode, leftExpressionValue, rightExpressionValue, genContext);
if (resultReturnUnions.value || resultReturnUnions.failed())
{
return resultReturnUnions;
}
auto leftExpressionValueBeforeCast = leftExpressionValue;
auto rightExpressionValueBeforeCast = rightExpressionValue;
if (mlir::failed(unwrapForBinaryOp(location, opCode, leftExpressionValue, rightExpressionValue, genContext)))
{
return mlir::failure();
}
if (mlir::failed(instantiateGenericsForBinaryOp(location, leftExpressionValue, rightExpressionValue, genContext)))
{
return mlir::failure();
}
if (mlir::failed(adjustTypesForBinaryOp(location, opCode, leftExpressionValue, rightExpressionValue, genContext)))
{
return mlir::failure();
}
auto resultReturn = binaryOpLogic(location, opCode, leftExpressionValue, rightExpressionValue, genContext);
if (saveResult)
{
return mlirGenSaveLogicOneItem(location, leftExpressionValueBeforeCast, resultReturn, genContext);
}
return resultReturn;
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(SpreadElement spreadElement, const GenContext &genContext)
{
return mlirGen(spreadElement->expression, genContext);
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(ParenthesizedExpression parenthesizedExpression, const GenContext &genContext)
{
return mlirGen(parenthesizedExpression->expression, genContext);
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(QualifiedName qualifiedName, const GenContext &genContext)
{
auto location = loc(qualifiedName);
auto expression = qualifiedName->left;
auto result = mlirGenModuleReference(expression, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
auto expressionValue = V(result);
auto name = MLIRHelper::getName(qualifiedName->right);
return mlirGenPropertyAccessExpression(location, expressionValue, name, genContext);
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(PropertyAccessExpression propertyAccessExpression, const GenContext &genContext)
{
auto location = loc(propertyAccessExpression);
auto expression = propertyAccessExpression->expression.as<Expression>();
auto result = mlirGen(expression, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
auto expressionValue = V(result);
auto namePtr = MLIRHelper::getName(propertyAccessExpression->name, stringAllocator);
auto propAccessStrRef = mlir::StringRef(print(propertyAccessExpression)).copy(stringAllocator);
auto fieldResult = mlirGenPropertyAccessExpression(location, expressionValue, namePtr,
!!propertyAccessExpression->questionDotToken, genContext);
// a narrowed field: read as it is now, cast to the type the test narrowed it to
auto safeType = safeTypesMap.lookup({ expressionValue.getType(), propAccessStrRef });
if (safeType && !fieldResult.failed_or_no_value() && V(fieldResult).getType() != safeType)
{
LLVM_DEBUG(llvm::dbgs() << "\n\t...safe type fieldname: \t "
<< propAccessStrRef << "." << namePtr << "type: " << expressionValue.getType() << " = " << safeType;);
auto fieldValue = V(fieldResult);
auto castValue = castToNarrowedType(location, fieldValue, safeType, genContext);
if (!castValue)
{
return mlir::failure();
}
return V(builder.create<mlir_ts::SafeCastOp>(location, safeType, castValue, fieldValue));
}
return fieldResult;
}
ValueOrLogicalResult MLIRGenImpl::mlirGenAssignedPropertyAccess(PropertyAccessExpression propertyAccessExpression, const GenContext &genContext)
{
// what an assignment writes is the field itself, never the value a narrowing cast from it
auto location = loc(propertyAccessExpression);
auto result = mlirGen(propertyAccessExpression->expression.as<Expression>(), genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
auto namePtr = MLIRHelper::getName(propertyAccessExpression->name, stringAllocator);
return mlirGenPropertyAccessExpression(location, V(result), namePtr,
!!propertyAccessExpression->questionDotToken, genContext);
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(ElementAccessExpression elementAccessExpression, const GenContext &genContext)
{
auto location = loc(elementAccessExpression);
auto conditinalAccess = !!elementAccessExpression->questionDotToken;
auto result = mlirGen(elementAccessExpression->expression.as<Expression>(), genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
auto expression = V(result);
// default access <array>[index]
if (!conditinalAccess)
{
auto result2 = mlirGen(elementAccessExpression->argumentExpression.as<Expression>(), genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result2)
auto argumentExpression = V(result2);
return mlirGenElementAccess(location, expression, argumentExpression, conditinalAccess, genContext);
}
// <array>?.[index] access
CAST_A(condValue, location, getBooleanType(), expression, genContext);
return conditionalValue(location, condValue,
[&]() {
auto result2 = mlirGen(elementAccessExpression->argumentExpression.as<Expression>(), genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result2)
auto argumentExpression = V(result2);
// conditinalAccess should be false here
auto result3 = mlirGenElementAccess(location, expression, argumentExpression, false, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result3)
auto value = V(result3);
auto optValue =
isa<mlir_ts::OptionalType>(value.getType())
? value
: builder.create<mlir_ts::OptionalValueOp>(location, getOptionalType(value.getType()), value);
return ValueOrLogicalResult(optValue);
},
[&](mlir::Type trueValueType) {
auto optUndefValue = builder.create<mlir_ts::OptionalUndefOp>(location, trueValueType);
return ValueOrLogicalResult(optUndefValue);
});
}
ValueOrLogicalResult MLIRGenImpl::mlirGen(CallExpression callExpression, const GenContext &genContext)
{
auto location = loc(callExpression);
auto callExpr = callExpression->expression.as<Expression>();
auto result = mlirGen(callExpr, genContext);
// in case of detecting value for recursive calls we need to ignore failed calls
// last condition we need to reduce posobilities to ignore legitimate failure
// TODO: register dummy function declaration at the begginnning of detecting function output
if (result.failed_or_no_value() && genContext.allowPartialResolve &&
(callExpr == SyntaxKind::Identifier || callExpr == SyntaxKind::PropertyAccessExpression))
{
// The callee is not resolvable yet, but the arguments still have to be walked - this
// is the same gap section 9.55 closed on `new`, in the other place a discovery pass
// gives up early. Discovery is where a lambda's captures are found, so an expression
// it never visits contributes none: `this.testRay({ start: pos, dir: livec }, scene)`
// inside a closure, with `scene` read nowhere else in it, left `scene` uncaptured and
// the real pass then read the enclosing function's own value from inside the lambda -
// "'ts.Load' op using value defined outside the region".
//
// Errors are ignored for the same reason they are ignored there: the callee failing is
// this branch's own premise, so its arguments can fail with it, and discovery is