-
-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathMLIRGenVariables.cpp
More file actions
1311 lines (1100 loc) · 51.4 KB
/
Copy pathMLIRGenVariables.cpp
File metadata and controls
1311 lines (1100 loc) · 51.4 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
// Variable declaration/binding and identifier resolution methods of MLIRGenImpl (see MLIRGenImpl.h).
#include "MLIRGenImpl.h"
namespace typescript
{
namespace mlirgen
{
ValueOrLogicalResult MLIRGenImpl::registerVariableInThisContext(mlir::Location location, StringRef name, mlir::Type type,
const GenContext &genContext)
{
if (genContext.passResult)
{
// create new type with added field
genContext.passResult->extraFieldsInThisContext.push_back(
{MLIRHelper::TupleFieldName(name, builder.getContext()), type, false, mlir_ts::AccessLevel::Public});
return mlir::Value();
}
// resolve object property
NodeFactory nf(NodeFactoryFlags::None);
// load this.<var name>
auto _this = nf.createToken(SyntaxKind::ThisKeyword);
auto _name = nf.createIdentifier(stows(std::string(name)));
auto _this_name = nf.createPropertyAccessExpression(_this, _name);
auto result = mlirGen(_this_name, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
auto thisVarValue = V(result);
assert(thisVarValue);
MLIRCodeLogic mcl(builder, compileOptions);
auto thisVarValueRef = mcl.GetReferenceFromValue(location, thisVarValue);
assert(thisVarValueRef);
return V(thisVarValueRef);
}
mlir::LogicalResult MLIRGenImpl::registerVariableDeclaration(mlir::Location location, VariableDeclarationDOM::TypePtr variableDeclaration, struct VariableDeclarationInfo &variableDeclarationInfo, bool showWarnings, const GenContext &genContext)
{
if (variableDeclarationInfo.deleted)
{
return mlir::success();
}
else if (!variableDeclarationInfo.isGlobal)
{
if (mlir::failed(declare(
location,
variableDeclaration,
variableDeclarationInfo.storage
? variableDeclarationInfo.storage
: variableDeclarationInfo.initial,
genContext,
showWarnings)))
{
return mlir::failure();
}
if (this->compileOptions.generateDebugInfo
&& variableDeclarationInfo.initial
&& !variableDeclarationInfo.storage
&& !mth.isGenericType(variableDeclarationInfo.initial.getType())
&& !mth.isAnyFunctionType(variableDeclarationInfo.initial.getType()))
{
// to show const values
MLIRDebugInfoHelper mti(builder, debugScope);
auto namedLoc = mti.combineWithCurrentScopeAndName(location, variableDeclarationInfo.variableName);
builder.create<mlir_ts::DebugVariableOp>(namedLoc, variableDeclarationInfo.initial);
}
}
else if (variableDeclarationInfo.isFullName)
{
fullNameGlobalsMap.insert(variableDeclarationInfo.fullName, variableDeclaration);
}
else
{
getGlobalsMap().insert({variableDeclarationInfo.variableName, variableDeclaration});
}
return mlir::success();
}
mlir::Type MLIRGenImpl::registerVariable(mlir::Location location, StringRef name, bool isFullName, VariableClass varClass,
TypeValueInitFuncType func, const GenContext &genContext, bool showWarnings, bool forceLocalVar)
{
struct VariableDeclarationInfo variableDeclarationInfo(
compileOptions, func, [this](StringRef name) { return getGlobalsFullNamespaceName(name); });
variableDeclarationInfo.detectFlags(isFullName, varClass, forceLocalVar, genContext);
variableDeclarationInfo.setName(name);
if (declarationMode)
variableDeclarationInfo.setExternal(true);
if (!variableDeclarationInfo.isGlobal)
{
if (variableDeclarationInfo.isConst) {
if (mlir::failed(variableDeclarationInfo.processConstRef(location, builder, genContext)))
return mlir::Type();
// a const binding that turns out to need identity storage (see
// processConstRef / hasBoundMethodField) falls through to the same
// real-storage path as `let` instead of staying a bare SSA value.
if (variableDeclarationInfo.needsIdentityStorage
&& mlir::failed(createLocalVariable(location, variableDeclarationInfo, genContext)))
return mlir::Type();
} else if (mlir::failed(createLocalVariable(location, variableDeclarationInfo, genContext)))
return mlir::Type();
}
else
{
variableDeclarationInfo.isSpecialization = genContext.specialization;
if (mlir::failed(createGlobalVariable(location, variableDeclarationInfo, genContext))) {
return mlir::Type();
}
if (mlir::succeeded(isGlobalConstLambda(location, variableDeclarationInfo, genContext)))
{
variableDeclarationInfo.globalOp->erase();
variableDeclarationInfo.deleted = true;
}
}
if (!variableDeclarationInfo.type)
{
emitError(location) << "type of variable '" << variableDeclarationInfo.variableName << "' is not valid";
return variableDeclarationInfo.type;
}
//LLVM_DEBUG(variableDeclarationInfo.printDebugInfo(););
auto varDecl = variableDeclarationInfo.createVariableDeclaration(location, genContext);
if (genContext.usingVars != nullptr && varDecl->getUsing())
{
genContext.usingVars->push_back(varDecl);
}
registerVariableDeclaration(location, varDecl, variableDeclarationInfo, showWarnings, genContext);
return varDecl->getType();
}
ValueOrLogicalResult MLIRGenImpl::processDeclarationArrayBindingPatternSubPath(
mlir::Location location, int index, mlir::Type type, mlir::Value init,
bool isDotDotDot, bool isIterator, bool isArrayLike, mlir::Value arrayLikeLengthValue, mlir::Type arrayLikeElementType, const GenContext &genContext)
{
MLIRPropertyAccessCodeLogic cl(compileOptions, builder, location, init, builder.getI32IntegerAttr(index));
mlir::Value subInit =
mlir::TypeSwitch<mlir::Type, mlir::Value>(type)
.template Case<mlir_ts::ConstTupleType>([&](auto constTupleType) {
if (isDotDotDot)
{
SmallVector<mlir::Value> arrayValues;
SmallVector<mlir_ts::FieldInfo> fieldInfos;
SmallVector<mlir_ts::FieldInfo> srcFieldInfos;
if (mlir::failed(mth.getFields(constTupleType, srcFieldInfos)))
{
return mlir::Value();
}
for (auto indexSpread = index; indexSpread < srcFieldInfos.size(); indexSpread++)
{
MLIRPropertyAccessCodeLogic cl(
compileOptions, builder, location, init, builder.getI32IntegerAttr(indexSpread));
auto value = cl.Tuple(constTupleType, true);
//fieldInfos.push_back({mlir::Attribute(), value.getType(), false, mlir_ts::AccessLevel::Public});
fieldInfos.push_back(srcFieldInfos[indexSpread]);
arrayValues.push_back(value);
}
return V(builder.create<mlir_ts::CreateTupleOp>(location, getTupleType(fieldInfos), arrayValues));
}
return cl.Tuple(constTupleType, true);
})
.template Case<mlir_ts::TupleType>([&](auto tupleType) {
if (isDotDotDot)
{
SmallVector<mlir::Value> arrayValues;
SmallVector<mlir_ts::FieldInfo> fieldInfos;
SmallVector<mlir_ts::FieldInfo> srcFieldInfos;
if (mlir::failed(mth.getFields(tupleType, srcFieldInfos)))
{
return mlir::Value();
}
for (auto indexSpread = index; indexSpread < srcFieldInfos.size(); indexSpread++)
{
MLIRPropertyAccessCodeLogic cl(
compileOptions, builder, location, init, builder.getI32IntegerAttr(indexSpread));
auto value = cl.Tuple(tupleType, true);
//fieldInfos.push_back({mlir::Attribute(), value.getType(), false, mlir_ts::AccessLevel::Public});
fieldInfos.push_back(srcFieldInfos[indexSpread]);
arrayValues.push_back(value);
}
return V(builder.create<mlir_ts::CreateTupleOp>(location, getTupleType(fieldInfos), arrayValues));
}
return cl.Tuple(tupleType, true);
})
.template Case<mlir_ts::ConstArrayType>([&](auto constArrayType) {
if (isDotDotDot)
{
auto indexType = builder.getIndexType();
auto arrayType = mth.removeConstType(constArrayType);
auto arrayValue = cast(location, arrayType, init, genContext);
if (!arrayValue)
{
return mlir::Value();
}
auto constIndex = builder.create<mlir_ts::ConstantOp>(
location, indexType, builder.getIndexAttr(index));
auto length = builder.create<mlir_ts::LengthOfOp>(location, indexType, arrayValue);
auto count = builder.create<mlir_ts::ArithmeticBinaryOp>(
location, indexType, builder.getI32IntegerAttr(static_cast<int32_t>(SyntaxKind::MinusToken)), length, constIndex);
mlir::Value arrayViewValue =
builder.create<mlir_ts::ArrayViewOp>(
location,
arrayType,
arrayValue,
constIndex,
count);
return arrayViewValue;
}
// TODO: unify it with ElementAccess
auto constIndex = builder.create<mlir_ts::ConstantOp>(location, builder.getI32Type(),
builder.getI32IntegerAttr(index));
auto elemRef = builder.create<mlir_ts::ElementRefOp>(
location, mlir_ts::RefType::get(constArrayType.getElementType()), init, constIndex);
return V(builder.create<mlir_ts::LoadOp>(location, constArrayType.getElementType(), elemRef));
})
.template Case<mlir_ts::ArrayType>([&](auto arrayType) {
if (isDotDotDot)
{
auto indexType = builder.getIndexType();
auto constIndex = builder.create<mlir_ts::ConstantOp>(
location, indexType, builder.getIndexAttr(index));
auto length = builder.create<mlir_ts::LengthOfOp>(location, indexType, init);
auto count = builder.create<mlir_ts::ArithmeticBinaryOp>(
location, indexType, builder.getI32IntegerAttr(static_cast<int32_t>(SyntaxKind::MinusToken)), length, constIndex);
mlir::Value arrayViewValue =
builder.create<mlir_ts::ArrayViewOp>(
location,
arrayType,
init,
constIndex,
count);
return arrayViewValue;
}
// TODO: unify it with ElementAccess
auto constIndex = builder.create<mlir_ts::ConstantOp>(location, builder.getI32Type(),
builder.getI32IntegerAttr(index));
auto elemRef = builder.create<mlir_ts::ElementRefOp>(
location, mlir_ts::RefType::get(arrayType.getElementType()), init, constIndex);
return V(builder.create<mlir_ts::LoadOp>(location, arrayType.getElementType(), elemRef));
})
.Default([&](auto type) {
if (isDotDotDot)
{
emitError(location) << "Array Binding Pattern: spread is not implemented for type: " << to_print(type);
return mlir::Value();
}
if (isIterator)
{
// seems it is "iterator"
auto nextProperty = init;
auto result = callIteratorNext(location, nextProperty, nullptr, genContext);
return V(result);
}
// add array like access
if (isArrayLike)
{
auto valueFactory =
(isa<mlir_ts::AnyType>(arrayLikeElementType))
? &MLIRGenImpl::anyOrUndefined
: &MLIRGenImpl::optionalValueOrUndefined;
auto indexVal = builder.create<mlir_ts::ConstantOp>(location, mth.getIndexType(),
mth.getIndexAttrValue(index));
// conditional expr: length > "spreadIndex" ? value[index] : undefined
auto inBoundsValue = V(builder.create<mlir_ts::LogicalBinaryOp>(location, getBooleanType(),
builder.getI32IntegerAttr((int)SyntaxKind::GreaterThanToken),
arrayLikeLengthValue,
indexVal));
auto spreadValue = (this->*valueFactory)(location, inBoundsValue,
[&](auto genContext) {
auto result = mlirGenElementAccess(location, init, indexVal, false, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
return result;
}, genContext);
//EXIT_IF_FAILED_OR_NO_VALUE(spreadValue)
return V(spreadValue);
}
emitError(location) << "Array Binding Pattern: not implemented for type: " << to_print(type);
return mlir::Value();
});
if (!subInit)
{
return mlir::failure();
}
return subInit;
}
mlir::LogicalResult MLIRGenImpl::processDeclarationArrayBindingPattern(mlir::Location location, ArrayBindingPattern arrayBindingPattern,
VariableClass varClass,
TypeValueInitFuncType func,
const GenContext &genContext)
{
auto [typeRef, initRef, typeProvidedRef] = func(location, genContext);
mlir::Type type = typeRef;
mlir::Value init = initRef;
//TypeProvided typeProvided = typeProvidedRef;
if (!init)
{
return mlir::failure();
}
mlir::Value arrayLikeLengthValue;
mlir::Type arrayLikeElementType;
auto isIterator = false;
auto isSourceArrayLike = false;
auto isArrayOrTuple = isa<mlir_ts::ArrayType>(typeRef)
|| isa<mlir_ts::TupleType>(typeRef)
|| isa<mlir_ts::ConstArrayType>(typeRef)
|| isa<mlir_ts::ConstTupleType>(typeRef);
if (!isArrayOrTuple)
{
if (auto iteratorType = evaluateProperty(location, init, SYMBOL_ITERATOR, genContext))
{
if (auto iteratorResult = mlirGenCallThisMethod(location, init, SYMBOL_ITERATOR, undefined, undefined, genContext))
{
auto iteratorValue = V(iteratorResult);
// request iterator
auto nextProperty = mlirGenPropertyAccessExpression(
location, iteratorValue, ITERATOR_NEXT, false, genContext);
if (nextProperty)
{
init = V(nextProperty);
isIterator = true;
}
}
}
else if (hasIterator(location, init, genContext))
{
// request iterator
auto nextProperty = mlirGenPropertyAccessExpression(
location, init, ITERATOR_NEXT, false, genContext);
if (nextProperty)
{
init = V(nextProperty);
isIterator = true;
}
}
else if (isArrayLike(location, init, genContext))
{
auto lengthValue = mlirGenPropertyAccessExpression(location, init, LENGTH_FIELD_NAME, false, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(lengthValue)
arrayLikeLengthValue = V(lengthValue);
CAST(arrayLikeLengthValue, location, builder.getIndexType(), arrayLikeLengthValue, genContext);
auto elementType = evaluateElementAccess(location, init, false, genContext);
if (elementType)
{
isSourceArrayLike = true;
arrayLikeElementType = elementType;
}
}
else
{
emitError(location) << "Array Binding Pattern: unsupported source of array data";
return mlir::failure();
}
}
for (auto [index, element] : enumerate(arrayBindingPattern->elements))
{
if (element == SyntaxKind::OmittedExpression)
{
continue;
}
if (element != SyntaxKind::BindingElement)
{
emitError(location) << "Array Binding Pattern: unsupported element";
return mlir::failure();
}
auto arrayBindingElement = element.as<BindingElement>();
auto subValueFunc = [&](mlir::Location location, const GenContext &genContext) {
auto result = processDeclarationArrayBindingPatternSubPath(
location, index, type, init, !!arrayBindingElement->dotDotDotToken, isIterator, isSourceArrayLike, arrayLikeLengthValue, arrayLikeElementType, genContext);
if (result.failed_or_no_value())
{
return std::make_tuple(mlir::Type(), mlir::Value(), TypeProvided::No);
}
auto value = V(result);
return std::make_tuple(value.getType(), value, TypeProvided::No);
};
if (mlir::failed(processDeclaration(
arrayBindingElement, varClass, subValueFunc, genContext)))
{
return mlir::failure();
}
}
return mlir::success();
}
ValueOrLogicalResult MLIRGenImpl::processDeclarationObjectBindingPatternSubPath(
mlir::Location location, BindingElement objectBindingElement, mlir::Type type, mlir::Value init, const GenContext &genContext)
{
auto fieldName = getFieldNameFromBindingElement(objectBindingElement);
auto isNumericAccess = isa<mlir::IntegerAttr>(fieldName);
LLVM_DEBUG(llvm::dbgs() << "ObjectBindingPattern:\n\t" << init << "\n\tprop: " << fieldName << "\n");
mlir::Value subInit;
mlir::Type subInitType;
mlir::Value value;
if (isNumericAccess)
{
MLIRPropertyAccessCodeLogic cl(compileOptions, builder, location, init, fieldName);
if (auto tupleType = dyn_cast<mlir_ts::TupleType>(type))
{
value = cl.Tuple(tupleType, true);
}
else if (auto constTupleType = dyn_cast<mlir_ts::ConstTupleType>(type))
{
value = cl.Tuple(constTupleType, true);
}
}
else
{
auto result = mlirGenPropertyAccessExpression(location, init, fieldName, false, genContext);
EXIT_IF_FAILED_OR_NO_VALUE(result)
value = V(result);
}
if (!value)
{
return mlir::failure();
}
if (objectBindingElement->initializer)
{
auto tupleType = mlir::cast<mlir_ts::TupleType>(type);
auto subType = mlir::cast<mlir_ts::OptionalType>(tupleType.getFieldInfo(tupleType.getIndex(fieldName)).type).getElementType();
auto res = optionalValueOrDefault(location, subType, value, objectBindingElement->initializer, genContext);
subInit = V(res);
subInitType = subInit.getType();
}
else
{
subInit = value;
subInitType = subInit.getType();
}
assert(subInit);
return subInit;
}
ValueOrLogicalResult MLIRGenImpl::processDeclarationObjectBindingPatternSubPathSpread(
mlir::Location location, ObjectBindingPattern objectBindingPattern, mlir::Type type, mlir::Value init, const GenContext &genContext)
{
mlir::Value subInit;
mlir::Type subInitType;
SmallVector<mlir::Attribute> names;
// take all used fields
for (auto objectBindingElement : objectBindingPattern->elements)
{
auto isSpreadBinding = !!objectBindingElement->dotDotDotToken;
if (isSpreadBinding)
{
continue;
}
auto fieldId = getFieldNameFromBindingElement(objectBindingElement);
names.push_back(fieldId);
}
// filter all fields
llvm::SmallVector<mlir_ts::FieldInfo> tupleFields;
llvm::SmallVector<mlir_ts::FieldInfo> destTupleFields;
if (mlir::succeeded(mth.getFields(init.getType(), tupleFields)))
{
for (auto fieldInfo : tupleFields)
{
if (std::find_if(names.begin(), names.end(), [&] (auto& item) { return item == fieldInfo.id; }) == names.end())
{
// filter;
destTupleFields.push_back(fieldInfo);
}
}
}
// create object
subInitType = getTupleType(destTupleFields);
CAST(subInit, location, subInitType, init, genContext);
assert(subInit);
return subInit;
}
mlir::LogicalResult MLIRGenImpl::processDeclarationObjectBindingPattern(mlir::Location location, ObjectBindingPattern objectBindingPattern,
VariableClass varClass,
TypeValueInitFuncType func,
const GenContext &genContext)
{
auto [typeRef, initRef, typeProvidedRef] = func(location, genContext);
mlir::Type type = typeRef;
mlir::Value init = initRef;
//TypeProvided typeProvided = typeProvidedRef;
for (auto objectBindingElement : objectBindingPattern->elements)
{
auto subValueFunc = [&] (mlir::Location location, const GenContext &genContext) {
auto isSpreadBinding = !!objectBindingElement->dotDotDotToken;
auto result = isSpreadBinding
? processDeclarationObjectBindingPatternSubPathSpread(location, objectBindingPattern, type, init, genContext)
: processDeclarationObjectBindingPatternSubPath(location, objectBindingElement, type, init, genContext);
if (result.failed_or_no_value())
{
return std::make_tuple(mlir::Type(), mlir::Value(), TypeProvided::No);
}
auto value = V(result);
return std::make_tuple(value.getType(), value, TypeProvided::No);
};
// nested obj, objectBindingElement->propertyName -> name
if (objectBindingElement->name == SyntaxKind::ObjectBindingPattern)
{
auto objectBindingPattern = objectBindingElement->name.as<ObjectBindingPattern>();
return processDeclarationObjectBindingPattern(
location, objectBindingPattern, varClass, subValueFunc, genContext);
}
if (mlir::failed(processDeclaration(
objectBindingElement, varClass, subValueFunc, genContext)))
{
return mlir::failure();
}
}
return mlir::success();;
}
mlir::LogicalResult MLIRGenImpl::processDeclarationName(DeclarationName name, VariableClass varClass,
TypeValueInitFuncType func, const GenContext &genContext, bool showWarnings)
{
auto location = loc(name);
if (name == SyntaxKind::ArrayBindingPattern)
{
auto arrayBindingPattern = name.as<ArrayBindingPattern>();
return processDeclarationArrayBindingPattern(location, arrayBindingPattern, varClass, func, genContext);
}
else if (name == SyntaxKind::ObjectBindingPattern)
{
auto objectBindingPattern = name.as<ObjectBindingPattern>();
return processDeclarationObjectBindingPattern(location, objectBindingPattern, varClass, func, genContext);
}
else
{
// name
auto nameStr = MLIRHelper::getName(name);
// register
auto varType = registerVariable(location, nameStr, false, varClass, func, genContext, showWarnings);
if (!varType)
{
return mlir::failure();
}
if (varClass.isExport)
{
auto isConst = varClass.type == VariableType::Const || varClass.type == VariableType::ConstRef;
addVariableDeclarationToExport(nameStr, currentNamespace, varType, isConst);
}
return mlir::success();
}
return mlir::failure();
}
mlir::LogicalResult MLIRGenImpl::processDeclaration(NamedDeclaration item, VariableClass varClass,
TypeValueInitFuncType func, const GenContext &genContext, bool showWarnings)
{
if (item == SyntaxKind::OmittedExpression)
{
return mlir::success();
}
item->name->parent = item;
return processDeclarationName(item->name, varClass, func, genContext, showWarnings);
}
mlir::LogicalResult MLIRGenImpl::mlirGen(VariableDeclaration item, VariableClass varClass, const GenContext &genContext)
{
auto location = loc(item);
#ifndef ANY_AS_DEFAULT
auto isExternal = varClass == VariableType::External;
if (declarationMode)
{
isExternal = true;
}
if (mth.isNoneType(item->type) && !item->initializer && !isExternal)
{
auto name = MLIRHelper::getName(item->name);
emitError(loc(item)) << "type of variable '" << name
<< "' is not provided, variable must have type or initializer";
return mlir::failure();
}
#endif
auto initFunc = [&](mlir::Location location, const GenContext &genContext) {
if (declarationMode)
{
auto [t, b, p] = evaluateTypeAndInit(item, genContext);
return std::make_tuple(t, mlir::Value(), p ? TypeProvided::Yes : TypeProvided::No);
}
auto typeAndInit = getTypeAndInit(item, genContext);
if (varClass.isDynamicImport)
{
auto nameStr = concatFullNamespaceName(MLIRHelper::getName(item->name));
auto fieldType = std::get<0>(typeAndInit);
if (fieldType)
{
auto dllVarName = V(mlirGenStringValue(location, nameStr, true));
auto referenceToStaticFieldOpaque = builder.create<mlir_ts::SearchForAddressOfSymbolOp>(
location, getOpaqueType(), dllVarName);
auto refToTyped = cast(location, mlir_ts::RefType::get(fieldType), referenceToStaticFieldOpaque, genContext);
auto valueOfField = builder.create<mlir_ts::LoadOp>(location, fieldType, refToTyped);
return std::make_tuple(valueOfField.getType(), V(valueOfField), TypeProvided::Yes);
}
}
return typeAndInit;
};
auto valClassItem = varClass;
if ((item->internalFlags & InternalFlags::ForceConst) == InternalFlags::ForceConst)
{
valClassItem = VariableType::Const;
}
if ((item->internalFlags & InternalFlags::ForceConstRef) == InternalFlags::ForceConstRef)
{
valClassItem = VariableType::ConstRef;
}
if (!genContext.funcOp && (item->name == SyntaxKind::ObjectBindingPattern || item->name == SyntaxKind::ArrayBindingPattern))
{
auto name = MLIRHelper::getAnonymousName(location, ".gc", "");
auto fullInitGlobalFuncName = getFullNamespaceName(name);
{
mlir::OpBuilder::InsertionGuard insertGuard(builder);
// create global construct
valClassItem = VariableType::Var;
auto funcType = getFunctionType({}, {}, false);
if (mlir::failed(mlirGenFunctionBody(location, name, fullInitGlobalFuncName, funcType,
[&](mlir::Location location, const GenContext &genContext) {
return processDeclaration(item, valClassItem, initFunc, genContext, true);
}, genContext)))
{
return mlir::failure();
}
addGlobalConstructor(location, fullInitGlobalFuncName);
}
}
else if (mlir::failed(processDeclaration(item, valClassItem, initFunc, genContext, true)))
{
return mlir::failure();
}
return mlir::success();
}
mlir::LogicalResult MLIRGenImpl::mlirGen(VariableDeclarationList variableDeclarationListAST, const GenContext &genContext)
{
auto isLet = (variableDeclarationListAST->flags & NodeFlags::Let) == NodeFlags::Let;
auto isConst = (variableDeclarationListAST->flags & NodeFlags::Const) == NodeFlags::Const;
auto isUsing = (variableDeclarationListAST->flags & NodeFlags::Using) == NodeFlags::Using;
auto isExternal = (variableDeclarationListAST->flags & NodeFlags::Ambient) == NodeFlags::Ambient;
VariableClass varClass = isExternal ? VariableType::External
: isLet ? VariableType::Let
: isConst || isUsing ? VariableType::Const
: VariableType::Var;
varClass.isUsing = isUsing;
if (variableDeclarationListAST->parent)
{
varClass.isPublic = hasModifier(variableDeclarationListAST->parent, SyntaxKind::ExportKeyword);
varClass.isExport = getExportModifier(variableDeclarationListAST->parent);
iterateDecorators(variableDeclarationListAST->parent, genContext, [&](StringRef name, SmallVector<StringRef> args) {
if (name == DLL_EXPORT)
{
varClass.isExport = true;
}
if (name == DLL_IMPORT)
{
varClass.type = isLet ? VariableType::Let : isConst || isUsing ? VariableType::Const : VariableType::Var;
varClass.isImport = true;
// it has parameter, means this is dynamic import, should point to dll path
// TODO: finish it, look at mlirGenCustomRTTIDynamicImport as example how to load it
if (args.size() > 0)
{
varClass.type = VariableType::Var;
varClass.isDynamicImport = true;
varClass.isImport = false;
}
}
if (name == "used") {
varClass.isUsed = true;
}
if (name == "atomic") {
varClass.atomic = true;
if (args.size() > 0)
{
auto ordering = 0;
if (llvm::to_integer(args[0], ordering))
{
varClass.ordering = ordering;
}
}
if (args.size() > 1)
varClass.syncscope = args[1];
}
if (name == "volatile") {
varClass.isVolatile = true;
}
if (name == "nontemporal") {
varClass.nonTemporal = true;
}
if (name == "invariant") {
varClass.invariant = true;
}
});
}
for (auto &item : variableDeclarationListAST->declarations)
{
// we need it for support "undefined type" in 'let' without initialization
item->parent = variableDeclarationListAST;
if (mlir::failed(mlirGen(item, varClass, genContext)))
{
return mlir::failure();
}
}
return mlir::success();
}
mlir::Type MLIRGenImpl::mlirGenParameterObjectOrArrayBinding(Node name, const GenContext &genContext)
{
// TODO: put it into function to support recursive call
if (name == SyntaxKind::ObjectBindingPattern)
{
SmallVector<mlir_ts::FieldInfo> fieldInfos;
// we need to construct object type
auto objectBindingPattern = name.as<ObjectBindingPattern>();
for (auto objectBindingElement : objectBindingPattern->elements)
{
mlirGenParameterBindingElement(objectBindingElement, fieldInfos, genContext);
}
return getTupleType(fieldInfos);
}
else if (name == SyntaxKind::ArrayBindingPattern)
{
SmallVector<mlir_ts::FieldInfo> fieldInfos;
// we need to construct object type
auto arrayBindingPattern = name.as<ArrayBindingPattern>();
for (auto arrayBindingElement : arrayBindingPattern->elements)
{
if (arrayBindingElement == SyntaxKind::OmittedExpression)
{
continue;
}
if (arrayBindingElement == SyntaxKind::BindingElement)
{
auto objectBindingElement = arrayBindingElement.as<BindingElement>();
mlirGenParameterBindingElement(objectBindingElement, fieldInfos, genContext);
}
}
return getTupleType(fieldInfos);
}
return mlir::Type();
}
mlir::Value MLIRGenImpl::resolveIdentifierAsVariable(mlir::Location location, StringRef name, const GenContext &genContext)
{
if (name.empty())
{
return mlir::Value();
}
auto value = symbolTable.lookup(name);
if (value.second && value.first)
{
//LLVM_DEBUG(dbgs() << "\n!! resolveIdentifierAsVariable: " << name << " type: " << value.second->getType() << " value: " << value.first;);
// begin of logic: outer vars
auto valueRegion = value.first.getParentRegion();
auto isOuterVar = false;
// TODO: review code "valueRegion && valueRegion->getParentOp()" is to support async.execute
if (genContext.funcOp && genContext.funcOp != tempFuncOp && valueRegion &&
valueRegion->getParentOp() /* && valueRegion->getParentOp()->getParentOp()*/)
{
mlir_ts::FuncOp contextFuncOp = genContext.funcOp;
auto funcRegion = contextFuncOp.getCallableRegion();
isOuterVar = !funcRegion->isAncestor(valueRegion);
// TODO: HACK
if (isOuterVar && value.second->getIgnoreCapturing())
{
// special case when "ForceConstRef" pointering to outer variable but it is not outer var
isOuterVar = false;
}
LLVM_DEBUG(if (isOuterVar) dbgs() << "\n!! outer var: [" << value.second->getName()
<< "] \n\n\tvalue region: " << *valueRegion->getParentOp()
<< " \n\n\tFuncOp: " << contextFuncOp << "";);
}
if (isOuterVar && genContext.passResult && !isGenericFunctionReference(value.first))
{
LLVM_DEBUG(dbgs() << "\n!! capturing var: [" << value.second->getName()
<< "] \n\tvalue pair: " << value.first << " \n\ttype: " << value.second->getType()
<< " \n\treadwrite: " << value.second->getReadWriteAccess() << "";);
// debug ref of ref
assert(!isa<mlir_ts::RefType>(value.second->getType()));
// valueRegion->viewGraph();
// special case, to prevent capturing ".a" because of reference to outer VaribleOp, which is hack (review
// solution for it)
genContext.passResult->outerVariables.insert({value.second->getName(), value.second});
}
// end of logic: outer vars
if (!value.second->getReadWriteAccess())
{
return value.first;
}
//LLVM_DEBUG(dbgs() << "\n!! variable: " << name << " type: " << value.first.getType() << "\n");
// load value if memref
auto valueType = mlir::cast<mlir_ts::RefType>(value.first.getType()).getElementType();
auto loadOp = builder.create<mlir_ts::LoadOp>(location, valueType, value.first);
if (value.second->getAtomic())
{
loadOp->setAttr(ATOMIC_ATTR_NAME, builder.getBoolAttr(true));
loadOp->setAttr(ORDERING_ATTR_NAME, builder.getI32IntegerAttr(value.second->getOrdering()));
loadOp->setAttr(SYNCSCOPE_ATTR_NAME, builder.getStringAttr(value.second->getSyncScope()));
}
if (value.second->getVolatile())
{
loadOp->setAttr(VOLATILE_ATTR_NAME, builder.getBoolAttr(true));
}
if (value.second->getNonTemporal())
{
loadOp->setAttr(NONTEMPORAL_ATTR_NAME, builder.getBoolAttr(true));
}
if (value.second->getInvariant())
{
loadOp->setAttr(INVARIANT_ATTR_NAME, builder.getBoolAttr(true));
}
return loadOp;
}
return mlir::Value();
}
mlir::Value MLIRGenImpl::resolveFunctionNameInNamespace(mlir::Location location, StringRef name, const GenContext &genContext)
{
// resolving function
auto fn = getFunctionMap().find(name);
if (fn != getFunctionMap().end())
{
auto &funcEntry = fn->getValue();
return resolveFunctionWithCapture(location, funcEntry.name, funcEntry.funcType, mlir::Value(), false, genContext);
}
return mlir::Value();
}
mlir::Type MLIRGenImpl::resolveTypeByNameInNamespace(mlir::Location location, StringRef name, const GenContext &genContext)
{
// support generic types
if (genContext.typeParamsWithArgs.size() > 0)
{
auto type = getResolveTypeParameter(name, false, genContext);
if (type)
{
return type;
}
}
if (genContext.typeAliasMap.count(name))
{
auto typeAliasInfo = genContext.typeAliasMap.lookup(name);
assert(typeAliasInfo);
return typeAliasInfo;
}
if (getTypeAliasMap().count(name))
{
auto typeAliasInfo = getTypeAliasMap().lookup(name);
if (typeAliasInfo.first)
{
return typeAliasInfo.first;
}
assert(typeAliasInfo.second);
GenContext typeAliasGenContext(genContext);
auto type = getType(typeAliasInfo.second, typeAliasGenContext);
if (!type)
{
typeAliasInfo.first = type;
}
return type;
}
if (getClassesMap().count(name))
{