-
Notifications
You must be signed in to change notification settings - Fork 32
/
ObLjbcGen.cpp
2907 lines (2591 loc) · 100 KB
/
ObLjbcGen.cpp
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
/*
* Copyright 2019, 2020 Rochus Keller <mailto:me@rochus-keller.ch>
*
* This file is part of the Oberon parser/code model library.
*
* The following is the license that applies to this copy of the
* library. For a license to use the library under conditions
* other than those described here, please email to me@rochus-keller.ch.
*
* GNU General Public License Usage
* This file may be used under the terms of the GNU General Public
* License (GPL) versions 2.0 or 3.0 as published by the Free Software
* Foundation and appearing in the file LICENSE.GPL included in
* the packaging of this file. Please review the following information
* to ensure GNU General Public Licensing requirements will be met:
* http://www.fsf.org/licensing/licenses/info/GPLv2.html and
* http://www.gnu.org/copyleft/gpl.html.
*/
#include "ObLjbcGen.h"
#include "ObAst.h"
#include "ObErrors.h"
#include "ObAstEval.h"
#include "ObLexer.h"
#include <LjTools/LuaJitComposer.h>
#include <QBitArray>
#include <QDir>
#include <QFile>
#include <QtDebug>
using namespace Ob;
using namespace Ob::Ast;
using namespace Lua;
struct LjbcGenImp : public AstVisitor
{
struct NoMoreFreeSlots {};
struct Ctx
{
Scope* scope;
JitComposer::SlotPool pool;
typedef QHash<Named*,quint16> Upvals;
Upvals upvals;
bool returnFound;
Ctx(Scope* s = 0):returnFound(false),scope(s) { }
int buySlots(int len = 1, bool call = false )
{
const int tmp = JitComposer::nextFreeSlot(pool,len, call );
if( tmp < 0 )
throw NoMoreFreeSlots();
return tmp;
}
void sellSlots(quint8 base, int len = 1 )
{
// qDebug() << "sell" << base << len;
JitComposer::releaseSlot(pool,base, len );
}
quint16 resolveUpval(Named* n)
{
Upvals::const_iterator i = upvals.find(n);
if( i != upvals.end() )
return i.value();
const int nr = upvals.size();
upvals[ n ] = nr;
return nr;
}
};
QList<Ctx> ctx;
JitComposer bc;
Errors* err;
Module* mod;
quint8 modSlot; // NOTE: never accessed from sub proc, so no uv management needed
bool ownsErr;
typedef QHash<Scope*,Import*> Imps;
Imps d_imps;
Ref<Import> obnlj;
QList<NamedType*> deferred;
struct Value
{
enum { None, Ref, Tmp, Uv, Ref2, Tmp2, Ref2v, Tmp2v, Pre, Val, Jump, Sold };
uint d_slot : 16; // Ref, Tmp, Pre, Uv, Ref2, Tmp2
uint d_idx : 8; // Ref2, Tmp2
uint d_kind : 4;
uint d_isVarParam : 1;
uint d_isParam : 1;
uint notUsed : 2;
QVariant d_val; // Val, Tmp2v, Ref2v
QList<quint32> trueList, falseList; // Jump
Type* d_type; // optional, for special assignments
Value():d_slot(0),d_idx(0),d_kind(None),d_type(0),d_isVarParam(0),d_isParam(0),notUsed(0){}
bool isVar() const { return d_kind > None && d_kind < Val; }
bool isConst() const { return d_kind == Val; }
Value( const Value& rhs ) { *this = rhs; }
Value& operator=( const Value& )
{
qWarning() << "dont copy Value";
return *this;
}
};
void sell( Value& v )
{
switch( v.d_kind )
{
case Value::Sold:
qWarning() << "try to double sell slot" << v.d_slot;
break;
case Value::Tmp:
case Value::Tmp2v:
ctx.back().sellSlots( v.d_slot );
v.d_kind = Value::Sold;
break;
case Value::Tmp2:
ctx.back().sellSlots( v.d_slot );
ctx.back().sellSlots( v.d_idx );
v.d_kind = Value::Sold;
break;
}
}
static QualiType::ModItem getQuali( Expression* e )
{
QualiType::ModItem res;
res.second = e->getIdent();
if( res.second )
{
if( e->getTag() == Thing::T_IdentSel )
{
IdentSel* sel = thing_cast<IdentSel*>(e);
Q_ASSERT( sel->d_sub->getTag() == Thing::T_IdentLeaf );
res.first = sel->d_sub->getIdent();
}
if( res.second->d_type->getTag() == Thing::T_Pointer )
{
Pointer* p = Ast::thing_cast<Pointer*>(res.second->d_type.data());
if( p->d_to->getTag() == Thing::T_QualiType )
{
QualiType::ModItem res2 = findClass( p->d_to.data() );
if( res2.first == 0 )
res2.first = res.first;
return res2;
}
// else
Q_ASSERT( p->d_to->getTag() == Thing::T_Record &&
p->d_to->d_ident == 0 );
}
}
return res;
}
static QualiType::ModItem findClass( Type* t )
{
if( t->getTag() == Thing::T_Pointer )
{
Pointer* p = Ast::thing_cast<Pointer*>(t);
if( p->d_to->getTag() == Thing::T_QualiType )
return findClass( p->d_to.data() );
Q_ASSERT( p->d_to->getTag() == Thing::T_Record &&
p->d_to->d_ident == 0 );
// since QualiType type aliasses are no longer shortcutted, but there is an instance of
// QualiType wherever there is no inplace type declaration after TO. But the latter has
// no d_ident by definition.
}else if( t->getTag() == Thing::T_QualiType )
{
QualiType* q = Ast::thing_cast<QualiType*>( t );
QualiType::ModItem res = q->getQuali();
if( res.first )
return res; // quali points to an import, that's where we find a class for sure
Q_ASSERT( res.second );
return findClass( res.second->d_type.data() );
}
Q_ASSERT( t->getTag() != Thing::T_QualiType && t == t->derefed() );
QualiType::ModItem res;
res.second = t->d_ident;
if( res.second == 0 )
{
if( t->getTag() == Thing::T_Record )
{
Record* r = Ast::thing_cast<Record*>( t );
if( r->d_binding )
res.second = r->d_binding->d_ident;
}
}
return res;
}
void fetchClass( QualiType::ModItem quali, Value& out, const RowCol& loc )
{
Q_ASSERT( quali.second != 0 );
const quint32 rowCol = loc.packed();
quint8 to;
if( out.d_kind == Value::Pre )
to = out.d_slot;
else
{
out.d_slot = ctx.back().buySlots(1);
out.d_kind = Value::Tmp;
to = out.d_slot;
}
if( quali.first == mod )
quali.first = 0;
if( quali.first )
{
// class lives in another module
// the type is declared in an imported module
// quali.first is the Import symbol
Q_ASSERT( quali.first->getTag() == Thing::T_Import );
if( quali.first->d_scope == mod )
{
// The import symbol is in this module and is supposed to have a slot already
if( !quali.first->d_slotValid )
err->error(Errors::Generator, mod->d_file, loc.d_row, loc.d_col,
QString("accessing import '%1' which has no allocated slot").arg(quali.first->d_name.constData()) );
if( ctx.back().scope != quali.first->d_scope )
{
// resolve upvalue
bc.UGET( to, resolveUpval( quali.first, loc ), rowCol );
bc.TGET(to, to, quali.second->d_name, rowCol );
}else
{
// Module level
bc.TGET(to, quali.first->d_slot, quali.second->d_name, rowCol );
}
}else
{
// The import symbol is in another module so we cannot directly access it here
// Example: TextFrames -> Texts -> Files.Rider where Files is not in import list of TextFrames
bc.GGET( to, quali.first->d_name, rowCol);
bc.TGET(to, to, quali.second->d_name, rowCol );
}
}else
{
// class lives in this module
if( !quali.second->d_slotValid )
{
err->error(Errors::Generator, mod->d_file, loc.d_row, loc.d_col,
QString("accessing local symbol '%1' which has no allocated slot").arg(quali.second->d_name.constData()) );
}
if( ctx.back().scope != quali.second->d_scope )
{
// resolve upvalue
bc.UGET( to, resolveUpval( quali.second, loc ), rowCol );
}else
{
// Module level
bc.MOV(to,quali.second->d_slot,rowCol);
}
}
}
void fetchClass( Type* t, Value& out, const RowCol& loc )
{
fetchClass( findClass(t), out, loc );
}
void visit( NamedType* t )
{
if( isNamedTypeWithSlot(t) && ( isLive(t) || isDurable(t) ) )
{
// create a slot representing the record (or pointer to record if latter anonymous)
Q_ASSERT( t->d_slotValid );
bc.TNEW( t->d_slot, 0, 0, t->d_loc.packed() );
// export it if public by copy to module table
if( t->d_scope == mod && t->d_public )
bc.TSET( t->d_slot, modSlot, t->d_name, t->d_loc.packed() );
Record* r = Model::toRecord( t->d_type.data() );
if( !r->d_base.isNull() )
{
// set the super class if there is one
// super classes are implemented by meta tables
quint8 base = ctx.back().buySlots(3,true);
bc.GGET(base, "setmetatable", t->d_loc.packed() );
bc.MOV(base+1,t->d_slot,t->d_loc.packed() );
Value v;
v.d_slot = base+2;
v.d_kind = Value::Pre;
fetchClass( findClass(r->d_base.data()),v,t->d_loc);
bc.CALL(base,0, 2, t->d_loc.packed());
ctx.back().sellSlots(base,3);
}
}else if( Model::toRecord(t->d_type.data()) != 0 && t->d_scope == mod && t->d_public )
{
// if the type points to a record (directly or indirectly) and is publicly visible
// on module level then copy its slot to the module table
if( t->d_type->getTag() == Thing::T_Pointer )
deferred << t; // Pointer can point to something which is created later, so defer it
else
publishTypeRef(t);
}
}
void publishTypeRef( NamedType* t )
{
Value v;
fetchClass(findClass(t->d_type.data()),v,t->d_loc);
bc.TSET( v.d_slot, modSlot, t->d_name, t->d_loc.packed() );
sell(v);
}
void publishDeferred()
{
foreach( NamedType* t, deferred )
publishTypeRef(t);
deferred.clear();
}
quint16 resolveUpval( Named* n, const RowCol& loc )
{
Q_ASSERT( n->d_scope != ctx.back().scope );
// get the upval id from the present context
const quint16 res = ctx.back().resolveUpval(n);
bool foundHome = false;
// now register the upval in all upper contexts too up to but not including the
// one where the symbol was defined
for( int i = ctx.size() - 2; i >= 0; i-- )
{
if( n->d_scope == ctx[i].scope )
{
foundHome = true;
break;
}else
ctx[i].resolveUpval(n);
}
if( !foundHome )
err->error(Errors::Generator, mod->d_file, loc.d_row, loc.d_col,
QString("cannot find module level symbol for upvalue '%1'").arg(n->d_name.constData()) );
return res;
}
void genArray( int len, quint8 out, const RowCol& loc )
{
quint8 tmp = ctx.back().buySlots(2,true);
fetchObnljMember(tmp,"Arr",loc);
bc.KSET(tmp+1, len,loc.packed() );
bc.CALL(tmp,1,1,loc.packed());
bc.MOV(out,tmp,loc.packed());
ctx.back().sellSlots(tmp,2);
}
void initMatrix( const QList<Array*>& dims, quint8 table, int curDim, const RowCol& loc )
{
// We need to create the arrays for each matrix dimension besides the highest one, unless it is of record value.
// If a matrix has only one dimension (i.e. it is an array), no initialization is required, unless it is of record value
// Each matrix dimension is created in a recursive call of this method.
// Examples:
// ARRAY n OF INTEGER
// -> obnlj.Arr(n)
// ARRAY n OF CHAR
// -> obnlj.Str(n)
// ARRAY n, m OF INTEGER
// -> for i=1,n do A[i] = obnlj.Arr(m) end
// ARRAY n, m OF RECORD END
// -> for i=1,n do A[i] = obnlj.Arr(m)
// for j=1,m do A[i][j] = initRecord() end end
if( curDim == dims.size() - 1 )
{
// we're at the highest dimension
if( isString( dims[curDim] ) )
{
// out << " = obnlj.Str(" << dims[curDim]->d_len << ")";
quint8 tmp = ctx.back().buySlots(2,true);
fetchObnljMember(tmp,"Str",loc);
bc.KSET(tmp+1, dims[curDim]->d_len, loc.packed() );
bc.CALL(tmp,1,1,loc.packed());
bc.MOV(table,tmp,loc.packed());
ctx.back().sellSlots(tmp,2);
}else if( dims[curDim]->d_type->derefed()->getTag() == Thing::T_Record )
{
// initHelper( dims[curDim], curDim, name, rec );
genArray( dims[curDim]->d_len, table, loc );
quint8 base = ctx.back().buySlots(4);
quint8 elem = ctx.back().buySlots(1);
bc.KSET(base,1,loc.packed());
bc.KSET(base+1,dims[curDim]->d_len,loc.packed());
bc.KSET(base+2,1,loc.packed());
bc.FORI(base,0,loc.packed());
const quint32 pc = bc.getCurPc();
// done within initRecord: bc.TNEW( elem, 0, 0, loc.packed() );
initRecord( dims[curDim]->d_type.data(), elem, loc );
bc.TSET(elem,table,base+3, loc.packed());
bc.FORL(base, pc - bc.getCurPc() - 1,loc.packed());
bc.patch(pc,bc.getCurPc() - pc);
ctx.back().sellSlots(elem);
ctx.back().sellSlots(base,4);
}else
genArray( dims[curDim]->d_len, table, loc );
// out << " = obnlj.Arr(" << dims[curDim]->d_len << ")";
}else
{
// we're at a lower dimension
//initHelper( dims[curDim], curDim, table, line );
genArray( dims[curDim]->d_len, table, loc );
quint8 base = ctx.back().buySlots(4);
quint8 elem = ctx.back().buySlots(1);
bc.KSET(base,1,loc.packed());
bc.KSET(base+1,dims[curDim]->d_len,loc.packed());
bc.KSET(base+2,1,loc.packed());
bc.FORI(base,0,loc.packed());
const quint32 pc = bc.getCurPc();
initMatrix( dims, elem, curDim + 1, loc );
bc.TSET(elem,table,base+3, loc.packed());
bc.FORL(base, pc - bc.getCurPc() - 1,loc.packed());
bc.patch(pc,bc.getCurPc() - pc);
ctx.back().sellSlots(elem);
ctx.back().sellSlots(base,4);
}
}
static bool isString( Type* t )
{
if( t && t->getTag() == Thing::T_Array )
{
Array* a = Ast::thing_cast<Array*>(t);
Type* td = a->d_type->derefed();
if( td->getTag() == Thing::T_BaseType &&
Ast::thing_cast<BaseType*>( td )->d_type == BaseType::CHAR )
return true;
}
return false;
}
void initArray(Array* arr, quint8 table, const RowCol& loc )
{
// table is the slot where the new array will be stored
// provide the code right of the '=' with all the necessary initialization
Array* curDim = arr;
QList<Array*> dims;
dims << curDim;
Type* td = curDim->d_type->derefed();
while( td->getTag() == Thing::T_Array )
{
curDim = Ast::thing_cast<Array*>( td );
dims << curDim;
td = curDim->d_type->derefed();
}
initMatrix( dims, table, 0, loc );
}
bool initScalar( BaseType* t, quint8 slot, const RowCol& loc )
{
switch( t->d_type )
{
case BaseType::BOOLEAN:
bc.KSET(slot,false,loc.packed());
return true;
case BaseType::INTEGER:
case BaseType::REAL:
case BaseType::BYTE:
bc.KSET(slot,0.0,loc.packed());
return true;
case BaseType::CHAR:
{
quint8 tmp = ctx.back().buySlots(2,true);
fetchObnljMember(tmp,"Str",loc);
bc.KSET(tmp+1, 2, loc.packed() );
bc.CALL(tmp,1,1,loc.packed());
bc.MOV(slot,tmp,loc.packed());
ctx.back().sellSlots(tmp,2);
}
return true;
case BaseType::SET:
{
// don't directly use slot for CALL because there are succeeding slots in use
quint8 tmp = ctx.back().buySlots(1,true);
fetchObnljMember(tmp,"SET",loc);
bc.CALL(tmp,1,0,loc.packed());
bc.MOV(slot,tmp,loc.packed());
ctx.back().sellSlots(tmp,1);
}
return true;
}
return false;
}
void initRecord( Type* rt, quint8 table, const RowCol& loc )
{
Q_ASSERT( rt != 0 );
QualiType::ModItem quali = findClass(rt);
if( quali.second )
{
if( quali.second->d_isDef )
{
// Special instantiation for tables in Def modules which could be userdata.
// The record table is supposed to have a function "__new" which generates the table or userdata
Q_ASSERT( quali.first );
quint8 base = ctx.back().buySlots(1,true);
Value v;
v.d_slot = base;
v.d_kind = Value::Pre;
fetchClass(quali,v, loc);
bc.TGET(base,base, QByteArray("__new"), loc.packed() );
bc.CALL(base,1, 0, loc.packed());
bc.MOV(table,base,loc.packed() );
ctx.back().sellSlots(base,1);
return;
}else
{
bc.TNEW( table, 0, 0, loc.packed() );
quint8 base = ctx.back().buySlots(3,true);
bc.GGET(base, "setmetatable", loc.packed() );
bc.MOV(base+1,table,loc.packed() );
Value v;
v.d_slot = base+2;
v.d_kind = Value::Pre;
fetchClass(quali,v, loc);
bc.CALL(base,0, 2, loc.packed());
ctx.back().sellSlots(base,3);
}
}else
bc.TNEW( table, 0, 0, loc.packed() );
Record* r = Model::toRecord(rt);
QList<Record*> topDown;
topDown << r;
Record* base = r->getBaseRecord();
while( base )
{
topDown.prepend(base);
base = base->getBaseRecord();
}
for( int j = 0; j < topDown.size(); j++ )
{
// go from top to bottom through inheritance hierarchy and initialize members
Record* rec = topDown[j];
for( int i = 0; i < rec->d_fields.size(); i++ )
{
Type* t = rec->d_fields[i]->d_type.data();
Type* td = t->derefed();
quint8 field = ctx.back().buySlots(1);
switch( td->getTag() )
{
case Thing::T_Record:
// done within initRecord: bc.TNEW( field, 0, 0, loc.packed() );
initRecord( t, field, loc );
bc.TSET(field, table, rec->d_fields[i]->d_name, loc.packed() );
break;
case Thing::T_Array:
// out << ws() << field;
initArray( Ast::thing_cast<Array*>(td), field, loc );
bc.TSET(field, table, rec->d_fields[i]->d_name, loc.packed() );
break;
case Thing::T_BaseType:
if( initScalar( thing_cast<BaseType*>(td), field, loc) )
bc.TSET(field, table, rec->d_fields[i]->d_name, loc.packed() );
break;
}
ctx.back().sellSlots(field);
}
}
}
void emitVariable( Named* v )
{
if( !v->d_slotValid )
return; // Var not used
Q_ASSERT( v->d_slotValid );
Type* td = v->d_type->derefed();
switch( td->getTag() )
{
case Thing::T_Record:
// done within initRecord: bc.TNEW( v->d_slot, 0, 0, v->d_loc.packed() );
initRecord( v->d_type.data(), v->d_slot, v->d_loc );
break;
case Thing::T_Array:
initArray( Ast::thing_cast<Array*>( td ), v->d_slot, v->d_loc );
break;
case Thing::T_BaseType:
initScalar( thing_cast<BaseType*>(td), v->d_slot, v->d_loc );
break;
default:
break;
// unneccessary, already nil: bc.KNIL(v->d_slot, 1, v->d_loc.packed() );
}
if( v->d_scope == mod && v->d_public )
{
if( v->d_type->isStructured() )
{
bc.TSET( v->d_slot, modSlot, v->d_name, v->d_loc.packed() );
}else
{
// out << "module" << "." << name << " = function() return " << name << " end" << endl;
const int tmp = ctx.back().buySlots(1);
const int func = bc.openFunction(0,v->d_name,v->d_loc.packed(), v->d_loc.packed() );
bc.UGET(0,0, v->d_loc.packed());
bc.RET(0,1, v->d_loc.packed());
JitComposer::Upval uv;
uv.d_isLocal = true;
uv.d_isRo = true;
uv.d_name = v->d_name;
Q_ASSERT( v->d_slotValid );
uv.d_uv = v->d_slot;
bc.setUpvals(JitComposer::UpvalList() << uv);
bc.closeFunction(1);
bc.FNEW(tmp,func,v->d_loc.packed());
bc.TSET( tmp,modSlot, v->d_name, v->d_loc.packed() );
ctx.back().sellSlots(tmp);
}
}
}
void visit( Variable* v )
{
emitVariable(v);
}
void visit( LocalVar* v )
{
emitVariable(v);
}
void visit( Const* c )
{
if( c->d_public )
{
Q_ASSERT( !c->d_constExpr.isNull() );
Value out;
fetchValue( c->d_val, out, c->d_constExpr->d_loc );
storeConst(out, c->d_constExpr->d_loc );
Q_ASSERT( out.d_kind == Value::Tmp );
bc.TSET( out.d_slot, modSlot, c->d_name, c->d_loc.packed() );
ctx.back().sellSlots(out.d_slot);
}
}
int emitImport( const QByteArray& modName, const RowCol& loc )
{
int tmp = ctx.back().buySlots(2,true);
bc.GGET( tmp, "require", loc.packed() );
bc.KSET( tmp+1, modName, loc.packed() );
bc.CALL( tmp, 1, 1, loc.packed() );
ctx.back().sellSlots(tmp+1); // keep tmp+0 as fixed import slot, release the other
return tmp;
}
void visit( Import* i )
{
// local imported = require 'module'
if( i->d_mod->d_name == "SYSTEM" )
return;
i->d_slot = emitImport( i->d_mod.isNull() ? i->d_name : i->d_mod->d_name, i->d_loc );
i->d_slotValid = true;
d_imps.insert(i->d_mod.data(), i );
}
bool inline isDurable( Named* n )
{
return n->d_usedFromSubs || n->d_usedFromLive || ( n->d_scope == mod && n->d_public );
}
bool inline isLive( Named* n )
{
return n->d_liveFrom > 0;
}
static bool inline isNamedTypeWithSlot( Named* nt )
{
if( nt->getTag() != Thing::T_NamedType )
return false;
// we only consider original named type declarations here, i.e. no aliasses.
if( nt->d_type->d_ident != nt )
return false;
const int tag = nt->d_type->getTag();
// In case of type aliasses which point to record types (wheter in this or another module), we at least
// put a copy of the original named type table to the module table of the present module,
// but we don't allocate a new slot.
if( tag == Thing::T_QualiType )
return false;
// We need a table for a named record type so it can be used as metatable for the
// instance of the record and a base for subrecords.
if( tag == Thing::T_Record )
return true;
if( tag == Thing::T_Pointer )
{
Pointer* p = Ast::thing_cast<Pointer*>(nt->d_type.data());
Q_ASSERT( p->d_to->derefed()->getTag() == Thing::T_Record );
Record* r = Ast::thing_cast<Record*>(p->d_to->derefed());
// A pointer to an anonymous record declared for the pointer is treatet the
// same way as a named Record declaration
if( r->d_binding == p )
return true;
}
return false;
}
bool allocateLocals( Scope* s )
{
JitComposer::Intervals vals;
Ctx& c = ctx.back();
for( int i = 0; i < s->d_order.size(); i++ )
{
const int tag = s->d_order[i]->getTag();
if( tag == Thing::T_Parameter )
{
Parameter* p = Ast::thing_cast<Parameter*>( s->d_order[i] );
p->d_slot = c.buySlots();
p->d_slotValid = true;
}else if( tag == Thing::T_Variable || tag == Thing::T_LocalVar || tag == Thing::T_Procedure ||
isNamedTypeWithSlot( s->d_order[i] ) )
{
Named* n = s->d_order[i];
const bool durable = isDurable(n);
if( isLive(n) || durable )
{
// public module vars need a slot even if not used in module statement sequence
if( true ) // if( durable )
// NOTE: we don't reuse slots at the moment because it has a significant impact
// on initialization complexity which requires further investigation.
// So currently there is a dedicated slot for each symbol which is either
// effectively in use in the current scope or (potentially) used in other scopes.
{
const int slot = c.buySlots();
if( slot < 0 )
return error( s->d_loc, QString("out of free slots") );
n->d_slot = slot;
n->d_slotValid = true;
}else
vals << JitComposer::Interval( n->d_liveFrom, n->d_liveTo, n );
}
}
}
if( JitComposer::allocateWithLinearScan(c.pool,vals,1) )
{
foreach( const JitComposer::Interval& val, vals )
{
Named* rb = static_cast<Named*>( val.d_payload );
rb->d_slot = val.d_slot;
rb->d_slotValid = true;
}
const int max = JitComposer::highestUsedSlot(c.pool) + 1;
if( !vals.isEmpty() && max > c.pool.d_frameSize )
c.pool.d_frameSize = max;
}else
return error( s->d_loc, QString("out of free slots") );
return true;
}
bool inline error( const RowCol& l, const QString& msg )
{
err->error(Errors::Semantics, mod->d_file, l.d_row, l.d_col, msg );
return false;
}
void visit( Procedure* p)
{
if( !p->d_slotValid )
return; // nobody seems to use this function
ctx.push_back( Ctx(p) );
const int id = bc.openFunction(Ast::thing_cast<ProcType*>(p->d_type.data())->d_formals.size(),
p->d_name,p->d_loc.packed(), p->d_end.packed() );
Q_ASSERT( id >= 0 );
allocateLocals(p);
if( p->d_type->d_ident == 0 )
p->d_type->accept(this);
for( int i = 0; i < p->d_order.size(); i++ )
{
const int tag = p->d_order[i]->getTag();
Q_ASSERT( tag != Thing::T_Variable );
if( tag == Thing::T_Procedure || tag == Thing::T_LocalVar )
publishDeferred();
p->d_order[i]->accept(this);
}
publishDeferred();
for( int i = 0; i < p->d_body.size(); i++ )
p->d_body[i]->accept(this);
if( !ctx.back().returnFound )
{
Q_ASSERT( p->d_type->getTag() == Thing::T_ProcType );
ProcType* pt = Ast::thing_cast<ProcType*>( p->d_type.data() );
QList<quint8> vars;
for( int i = 0; i < pt->d_formals.size(); i++ )
{
if( pt->d_formals[i]->d_var )
vars.append(i);
}
if( vars.isEmpty() )
bc.RET(p->d_end.packed());
else
{
quint8 tmp = ctx.back().buySlots(vars.size());
for( int i = 0; i < vars.size(); i++ )
bc.MOV(tmp+i,vars[i],p->d_end.packed());
bc.RET(tmp,vars.size(),p->d_end.packed());
ctx.back().sellSlots(tmp);
}
}
JitComposer::VarNameList sn = getSlotNames(p);
bc.setVarNames( sn );
bc.setUpvals( getUpvals() );
bc.closeFunction(ctx.back().pool.d_frameSize);
ctx.pop_back();
Q_ASSERT( p->d_slotValid );
bc.FNEW( p->d_slot, id, p->d_end.packed() );
if( p->d_scope == mod && p->d_public )
bc.TSET( p->d_slot, modSlot, p->d_name, p->d_end.packed() );
}
JitComposer::VarNameList getSlotNames( Scope* m )
{
JitComposer::VarNameList vnl(ctx.back().pool.d_frameSize);
for( int i = 0; i < m->d_order.size(); i++ )
{
if( m->d_order[i]->d_slotValid )
{
Named* n = m->d_order[i];
JitComposer::VarName& vn = vnl[n->d_slot];
Q_ASSERT( vn.d_name.isEmpty() );
vn.d_name = n->d_name;
// we currently don't reuse slots, so they're valid over the whole body
vn.d_from = 0; // n->d_liveFrom;
vn.d_to = bc.getCurPc(); // n->d_liveTo;
}
}
for( int i = 0; i < vnl.size(); i++ )
{
if( vnl[i].d_name.isEmpty() )
vnl[i].d_name = "";
}
return vnl;
}
JitComposer::UpvalList getUpvals()
{
JitComposer::UpvalList uvl(ctx.back().upvals.size());
Ctx::Upvals::const_iterator i;
for( i = ctx.back().upvals.begin(); i != ctx.back().upvals.end(); ++i )
{
JitComposer::Upval u;
u.d_name = i.key()->d_name;
// if( i.key()->d_uvRo )
// u.d_isRo = true; // TODO
if( i.key()->d_scope == ctx.back().scope->d_scope )
{
u.d_uv = i.key()->d_slot;
u.d_isLocal = true;
}else if( ctx.size() > 1 )
{
u.d_uv = ctx[ ctx.size() - 2 ].resolveUpval(i.key());
}else
error( i.key()->d_loc, QString("cannot compose upvalue list because of '%1'").arg(u.d_name.constData() ) );
uvl[i.value()] = u;
}
return uvl;
}
void addSlot( JitComposer::VarNameList& sn, quint8 slot, const char* name )
{
JitComposer::VarName& vn = sn[slot];
Q_ASSERT( vn.d_name.isEmpty() );
vn.d_name = name;
vn.d_from = 0;
vn.d_to = bc.getCurPc();
}
void visit( Module* m )
{
ctx.push_back( Ctx(m) );
bc.openFunction(0,m->d_file.toUtf8(),m->d_loc.packed(), m->d_end.packed() );
modSlot = ctx.back().buySlots(1);
// NOTE: if not modSlot is at slot 0 but a module var instead, upvalue access to the var at
// slot 0 doesn't work, i.e. renders a constant floating point number instead of the true value.
allocateLocals(m);
bc.TNEW( modSlot, 0, 0, m->d_loc.packed() ); // local module = {}
// local obnlj = require 'obnlj'
Named* lib = m->find("obnlj");
if( lib == 0 || lib->getTag() != Thing::T_Import )
{
obnlj = new Import();
obnlj->d_name = Lexer::getSymbol("obnlj");
obnlj->d_synthetic = true;
obnlj->d_loc = m->d_loc;
obnlj->d_slot = emitImport( obnlj->d_name, m->d_loc );
obnlj->d_slotValid = true;
obnlj->d_scope = mod;
}else
obnlj = Ast::thing_cast<Import*>( lib );
for( int i = 0; i < m->d_order.size(); i++ )
{
const int tag = m->d_order[i]->getTag();
Q_ASSERT( tag != Thing::T_LocalVar );
if( tag == Thing::T_Procedure || tag == Thing::T_Variable )
publishDeferred();
m->d_order[i]->accept(this);
}
publishDeferred();
for( int i = 0; i < m->d_body.size(); i++ )
m->d_body[i]->accept(this);
bc.UCLO( modSlot, 0, m->d_end.packed() );
// make Module table a global variable (because of fetchClass)
bc.GSET( modSlot, m->d_name, m->d_end.packed() );
bc.RET( modSlot, 1, m->d_end.packed() ); // return module
JitComposer::VarNameList sn = getSlotNames(m);
addSlot(sn,modSlot,"_mod_");
addSlot(sn,obnlj->d_slot,"obnlj");
bc.setVarNames( sn );
bc.setUpvals( getUpvals() );
bc.closeFunction(ctx.back().pool.d_frameSize);
ctx.pop_back();
}
void visit( Call* c )
{
Value v;
process( c->d_what.data(), v );
sell(v);
}
void visit( Return* r )
{
Q_ASSERT( ctx.back().scope->getTag() == Thing::T_Procedure &&
ctx.back().scope->d_type->getTag() == Thing::T_ProcType );
ProcType* pt = Ast::thing_cast<ProcType*>( ctx.back().scope->d_type.data() );
QList<quint8> vars;
for( int i = 0; i < pt->d_formals.size(); i++ )
{
if( pt->d_formals[i]->d_var )
vars.append(i);
}
ctx.back().returnFound = true;
Value ret;
ret.d_slot = ctx.back().buySlots( 1 + vars.size() );
ret.d_kind = Value::Tmp;
ret.d_type = pt->d_return.data();
assignExpr( ret, r->d_what.data() );
for( int i = 0; i < vars.size(); i++ )
bc.MOV( ret.d_slot + 1, vars[i], r->d_loc.packed() );
bc.RET(ret.d_slot, 1 + vars.size(), r->d_loc.packed());
ctx.back().sellSlots( ret.d_slot, 1 + vars.size() );
}
static bool isStructuredAssigByValue( const Value& v )
{
if( v.d_type == 0 || v.d_isVarParam || v.d_isParam )
return false;
const int tag = v.d_type->derefed()->getTag();
if( tag == Thing::T_Record || tag == Thing::T_Array )