-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
vm.nim
2553 lines (2422 loc) · 91 KB
/
vm.nim
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
#
#
# The Nim Compiler
# (c) Copyright 2015 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
## This file implements the new evaluation engine for Nim code.
## An instruction is 1-3 int32s in memory, it is a register based VM.
import semmacrosanity
import
std/[strutils, tables, parseutils],
msgs, vmdef, vmgen, nimsets, types,
parser, vmdeps, idents, trees, renderer, options, transf,
gorgeimpl, lineinfos, btrees, macrocacheimpl,
modulegraphs, sighashes, int128, vmprofiler
when defined(nimPreviewSlimSystem):
import std/formatfloat
import ast except getstr
from semfold import leValueConv, ordinalValToString
from evaltempl import evalTemplate
from magicsys import getSysType
const
traceCode = defined(nimVMDebug)
when hasFFI:
import evalffi
proc stackTraceAux(c: PCtx; x: PStackFrame; pc: int; recursionLimit=100) =
if x != nil:
if recursionLimit == 0:
var calls = 0
var x = x
while x != nil:
inc calls
x = x.next
msgWriteln(c.config, $calls & " calls omitted\n", {msgNoUnitSep})
return
stackTraceAux(c, x.next, x.comesFrom, recursionLimit-1)
var info = c.debug[pc]
# we now use a format similar to the one in lib/system/excpt.nim
var s = ""
# todo: factor with quotedFilename
if optExcessiveStackTrace in c.config.globalOptions:
s = toFullPath(c.config, info)
else:
s = toFilename(c.config, info)
var line = toLinenumber(info)
var col = toColumn(info)
if line > 0:
s.add('(')
s.add($line)
s.add(", ")
s.add($(col + ColOffset))
s.add(')')
if x.prc != nil:
for k in 1..max(1, 25-s.len): s.add(' ')
s.add(x.prc.name.s)
msgWriteln(c.config, s, {msgNoUnitSep})
proc stackTraceImpl(c: PCtx, tos: PStackFrame, pc: int,
msg: string, lineInfo: TLineInfo, infoOrigin: InstantiationInfo) {.noinline.} =
# noinline to avoid code bloat
msgWriteln(c.config, "stack trace: (most recent call last)", {msgNoUnitSep})
stackTraceAux(c, tos, pc)
let action = if c.mode == emRepl: doRaise else: doNothing
# XXX test if we want 'globalError' for every mode
let lineInfo = if lineInfo == TLineInfo.default: c.debug[pc] else: lineInfo
liMessage(c.config, lineInfo, errGenerated, msg, action, infoOrigin)
when not defined(nimHasCallsitePragma):
{.pragma: callsite.}
template stackTrace(c: PCtx, tos: PStackFrame, pc: int,
msg: string, lineInfo: TLineInfo = TLineInfo.default) {.callsite.} =
stackTraceImpl(c, tos, pc, msg, lineInfo, instantiationInfo(-2, fullPaths = true))
return
proc bailOut(c: PCtx; tos: PStackFrame) =
stackTrace(c, tos, c.exceptionInstr, "unhandled exception: " &
c.currentExceptionA[3].skipColon.strVal &
" [" & c.currentExceptionA[2].skipColon.strVal & "]")
when not defined(nimComputedGoto):
{.pragma: computedGoto.}
proc ensureKind(n: var TFullReg, k: TRegisterKind) {.inline.} =
if n.kind != k:
n = TFullReg(kind: k)
template ensureKind(k: untyped) {.dirty.} =
ensureKind(regs[ra], k)
template decodeB(k: untyped) {.dirty.} =
let rb = instr.regB
ensureKind(k)
template decodeBC(k: untyped) {.dirty.} =
let rb = instr.regB
let rc = instr.regC
ensureKind(k)
template declBC() {.dirty.} =
let rb = instr.regB
let rc = instr.regC
template decodeBImm(k: untyped) {.dirty.} =
let rb = instr.regB
let imm = instr.regC - byteExcess
ensureKind(k)
template decodeBx(k: untyped) {.dirty.} =
let rbx = instr.regBx - wordExcess
ensureKind(k)
template move(a, b: untyped) {.dirty.} =
when defined(gcArc) or defined(gcOrc) or defined(gcAtomicArc):
a = move b
else:
system.shallowCopy(a, b)
# XXX fix minor 'shallowCopy' overloading bug in compiler
proc derefPtrToReg(address: BiggestInt, typ: PType, r: var TFullReg, isAssign: bool): bool =
# nim bug: `isAssign: static bool` doesn't work, giving odd compiler error
template fun(field, typ, rkind) =
if isAssign:
cast[ptr typ](address)[] = typ(r.field)
else:
r.ensureKind(rkind)
let val = cast[ptr typ](address)[]
when typ is SomeInteger | char:
r.field = BiggestInt(val)
else:
r.field = val
return true
## see also typeinfo.getBiggestInt
case typ.kind
of tyChar: fun(intVal, char, rkInt)
of tyInt: fun(intVal, int, rkInt)
of tyInt8: fun(intVal, int8, rkInt)
of tyInt16: fun(intVal, int16, rkInt)
of tyInt32: fun(intVal, int32, rkInt)
of tyInt64: fun(intVal, int64, rkInt)
of tyUInt: fun(intVal, uint, rkInt)
of tyUInt8: fun(intVal, uint8, rkInt)
of tyUInt16: fun(intVal, uint16, rkInt)
of tyUInt32: fun(intVal, uint32, rkInt)
of tyUInt64: fun(intVal, uint64, rkInt) # note: differs from typeinfo.getBiggestInt
of tyFloat: fun(floatVal, float, rkFloat)
of tyFloat32: fun(floatVal, float32, rkFloat)
of tyFloat64: fun(floatVal, float64, rkFloat)
else: return false
proc createStrKeepNode(x: var TFullReg; keepNode=true) =
if x.node.isNil or not keepNode:
x.node = newNode(nkStrLit)
elif x.node.kind == nkNilLit and keepNode:
when defined(useNodeIds):
let id = x.node.id
x.node[] = TNode(kind: nkStrLit)
when defined(useNodeIds):
x.node.id = id
elif x.node.kind notin {nkStrLit..nkTripleStrLit} or
nfAllConst in x.node.flags:
# XXX this is hacky; tests/txmlgen triggers it:
x.node = newNode(nkStrLit)
# It not only hackey, it is also wrong for tgentemplate. The primary
# cause of bugs like these is that the VM does not properly distinguish
# between variable definitions (var foo = e) and variable updates (foo = e).
include vmhooks
template createStr(x) =
x.node = newNode(nkStrLit)
template createSet(x) =
x.node = newNode(nkCurly)
proc moveConst(x: var TFullReg, y: TFullReg) =
x.ensureKind(y.kind)
case x.kind
of rkNone: discard
of rkInt: x.intVal = y.intVal
of rkFloat: x.floatVal = y.floatVal
of rkNode: x.node = y.node
of rkRegisterAddr: x.regAddr = y.regAddr
of rkNodeAddr: x.nodeAddr = y.nodeAddr
# this seems to be the best way to model the reference semantics
# of system.NimNode:
template asgnRef(x, y: untyped) = moveConst(x, y)
proc copyValue(src: PNode): PNode =
if src == nil or nfIsRef in src.flags:
return src
result = newNode(src.kind)
result.info = src.info
result.typ() = src.typ
result.flags = src.flags * PersistentNodeFlags
result.comment = src.comment
when defined(useNodeIds):
if result.id == nodeIdToDebug:
echo "COMES FROM ", src.id
case src.kind
of nkCharLit..nkUInt64Lit: result.intVal = src.intVal
of nkFloatLit..nkFloat128Lit: result.floatVal = src.floatVal
of nkSym: result.sym = src.sym
of nkIdent: result.ident = src.ident
of nkStrLit..nkTripleStrLit: result.strVal = src.strVal
else:
newSeq(result.sons, src.len)
for i in 0..<src.len:
result[i] = copyValue(src[i])
proc asgnComplex(x: var TFullReg, y: TFullReg) =
x.ensureKind(y.kind)
case x.kind
of rkNone: discard
of rkInt: x.intVal = y.intVal
of rkFloat: x.floatVal = y.floatVal
of rkNode: x.node = copyValue(y.node)
of rkRegisterAddr: x.regAddr = y.regAddr
of rkNodeAddr: x.nodeAddr = y.nodeAddr
proc fastAsgnComplex(x: var TFullReg, y: TFullReg) =
x.ensureKind(y.kind)
case x.kind
of rkNone: discard
of rkInt: x.intVal = y.intVal
of rkFloat: x.floatVal = y.floatVal
of rkNode: x.node = y.node
of rkRegisterAddr: x.regAddr = y.regAddr
of rkNodeAddr: x.nodeAddr = y.nodeAddr
proc writeField(n: var PNode, x: TFullReg) =
case x.kind
of rkNone: discard
of rkInt:
if n.kind == nkNilLit:
n[] = TNode(kind: nkIntLit) # ideally, `nkPtrLit`
n.intVal = x.intVal
of rkFloat: n.floatVal = x.floatVal
of rkNode: n = copyValue(x.node)
of rkRegisterAddr: writeField(n, x.regAddr[])
of rkNodeAddr: n = x.nodeAddr[]
proc putIntoReg(dest: var TFullReg; n: PNode) =
case n.kind
of nkStrLit..nkTripleStrLit:
dest = TFullReg(kind: rkNode, node: newStrNode(nkStrLit, n.strVal))
of nkIntLit: # use `nkPtrLit` once this is added
if dest.kind == rkNode: dest.node = n
elif n.typ != nil and n.typ.kind in PtrLikeKinds:
dest = TFullReg(kind: rkNode, node: n)
else:
dest = TFullReg(kind: rkInt, intVal: n.intVal)
of {nkCharLit..nkUInt64Lit} - {nkIntLit}:
dest = TFullReg(kind: rkInt, intVal: n.intVal)
of nkFloatLit..nkFloat128Lit:
dest = TFullReg(kind: rkFloat, floatVal: n.floatVal)
else:
dest = TFullReg(kind: rkNode, node: n)
proc regToNode(x: TFullReg): PNode =
case x.kind
of rkNone: result = newNode(nkEmpty)
of rkInt: result = newNode(nkIntLit); result.intVal = x.intVal
of rkFloat: result = newNode(nkFloatLit); result.floatVal = x.floatVal
of rkNode: result = x.node
of rkRegisterAddr: result = regToNode(x.regAddr[])
of rkNodeAddr: result = x.nodeAddr[]
template getstr(a: untyped): untyped =
(if a.kind == rkNode: a.node.strVal else: $chr(int(a.intVal)))
proc pushSafePoint(f: PStackFrame; pc: int) =
f.safePoints.add(pc)
proc popSafePoint(f: PStackFrame) =
discard f.safePoints.pop()
type
ExceptionGoto = enum
ExceptionGotoHandler,
ExceptionGotoFinally,
ExceptionGotoUnhandled
proc findExceptionHandler(c: PCtx, f: PStackFrame, exc: PNode):
tuple[why: ExceptionGoto, where: int] =
let raisedType = exc.typ.skipTypes(abstractPtrs)
while f.safePoints.len > 0:
var pc = f.safePoints.pop()
var matched = false
var pcEndExcept = pc
# Scan the chain of exceptions starting at pc.
# The structure is the following:
# pc - opcExcept, <end of this block>
# - opcExcept, <pattern1>
# - opcExcept, <pattern2>
# ...
# - opcExcept, <patternN>
# - Exception handler body
# - ... more opcExcept blocks may follow
# - ... an optional opcFinally block may follow
#
# Note that the exception handler body already contains a jump to the
# finally block or, if that's not present, to the point where the execution
# should continue.
# Also note that opcFinally blocks are the last in the chain.
while c.code[pc].opcode == opcExcept:
# Where this Except block ends
pcEndExcept = pc + c.code[pc].regBx - wordExcess
inc pc
# A series of opcExcept follows for each exception type matched
while c.code[pc].opcode == opcExcept:
let excIndex = c.code[pc].regBx - wordExcess
let exceptType =
if excIndex > 0: c.types[excIndex].skipTypes(abstractPtrs)
else: nil
# echo typeToString(exceptType), " ", typeToString(raisedType)
# Determine if the exception type matches the pattern
if exceptType.isNil or inheritanceDiff(raisedType, exceptType) <= 0:
matched = true
break
inc pc
# Skip any further ``except`` pattern and find the first instruction of
# the handler body
while c.code[pc].opcode == opcExcept:
inc pc
if matched:
break
# If no handler in this chain is able to catch this exception we check if
# the "parent" chains are able to. If this chain ends with a `finally`
# block we must execute it before continuing.
pc = pcEndExcept
# Where the handler body starts
let pcBody = pc
if matched:
return (ExceptionGotoHandler, pcBody)
elif c.code[pc].opcode == opcFinally:
# The +1 here is here because we don't want to execute it since we've
# already pop'd this statepoint from the stack.
return (ExceptionGotoFinally, pc + 1)
return (ExceptionGotoUnhandled, 0)
proc cleanUpOnReturn(c: PCtx; f: PStackFrame): int =
# Walk up the chain of safepoints and return the PC of the first `finally`
# block we find or -1 if no such block is found.
# Note that the safepoint is removed once the function returns!
result = -1
# Traverse the stack starting from the end in order to execute the blocks in
# the intended order
for i in 1..f.safePoints.len:
var pc = f.safePoints[^i]
# Skip the `except` blocks
while c.code[pc].opcode == opcExcept:
pc += c.code[pc].regBx - wordExcess
if c.code[pc].opcode == opcFinally:
discard f.safePoints.pop
return pc + 1
proc opConv(c: PCtx; dest: var TFullReg, src: TFullReg, desttyp, srctyp: PType): bool =
result = false
if desttyp.kind == tyString:
dest.ensureKind(rkNode)
dest.node = newNode(nkStrLit)
let styp = srctyp.skipTypes(abstractRange)
case styp.kind
of tyEnum:
let n = styp.n
let x = src.intVal.int
if x <% n.len and (let f = n[x].sym; f.position == x):
dest.node.strVal = if f.ast.isNil: f.name.s else: f.ast.strVal
else:
for i in 0..<n.len:
if n[i].kind != nkSym: internalError(c.config, "opConv for enum")
let f = n[i].sym
if f.position == x:
dest.node.strVal = if f.ast.isNil: f.name.s else: f.ast.strVal
return
dest.node.strVal = styp.sym.name.s & " " & $x
of tyInt..tyInt64:
dest.node.strVal = $src.intVal
of tyUInt..tyUInt64:
dest.node.strVal = $uint64(src.intVal)
of tyBool:
dest.node.strVal = if src.intVal == 0: "false" else: "true"
of tyFloat..tyFloat128:
dest.node.strVal = $src.floatVal
of tyString:
dest.node.strVal = src.node.strVal
of tyCstring:
if src.node.kind == nkBracket:
# Array of chars
var strVal = ""
for son in src.node.sons:
let c = char(son.intVal)
if c == '\0': break
strVal.add(c)
dest.node.strVal = strVal
else:
dest.node.strVal = src.node.strVal
of tyChar:
dest.node.strVal = $chr(src.intVal)
else:
internalError(c.config, "cannot convert to string " & desttyp.typeToString)
else:
let desttyp = skipTypes(desttyp, abstractVarRange)
case desttyp.kind
of tyInt..tyInt64:
dest.ensureKind(rkInt)
case skipTypes(srctyp, abstractRange).kind
of tyFloat..tyFloat64:
dest.intVal = int(src.floatVal)
else:
dest.intVal = src.intVal
if toInt128(dest.intVal) < firstOrd(c.config, desttyp) or toInt128(dest.intVal) > lastOrd(c.config, desttyp):
return true
of tyUInt..tyUInt64:
dest.ensureKind(rkInt)
let styp = srctyp.skipTypes(abstractRange) # skip distinct types(dest type could do this too if needed)
case styp.kind
of tyFloat..tyFloat64:
dest.intVal = int(src.floatVal)
else:
let destSize = getSize(c.config, desttyp)
let destDist = (sizeof(dest.intVal) - destSize) * 8
var value = cast[BiggestUInt](src.intVal)
when false:
# this would make uint64(-5'i8) evaluate to 251
# but at runtime, uint64(-5'i8) is 18446744073709551611
# so don't do it
let srcSize = getSize(c.config, styp)
let srcDist = (sizeof(src.intVal) - srcSize) * 8
value = (value shl srcDist) shr srcDist
value = (value shl destDist) shr destDist
dest.intVal = cast[BiggestInt](value)
of tyBool:
dest.ensureKind(rkInt)
dest.intVal =
case skipTypes(srctyp, abstractRange).kind
of tyFloat..tyFloat64: int(src.floatVal != 0.0)
else: int(src.intVal != 0)
of tyFloat..tyFloat64:
dest.ensureKind(rkFloat)
let srcKind = skipTypes(srctyp, abstractRange).kind
case srcKind
of tyInt..tyInt64, tyUInt..tyUInt64, tyEnum, tyBool, tyChar:
dest.floatVal = toBiggestFloat(src.intVal)
elif src.kind == rkInt:
dest.floatVal = toBiggestFloat(src.intVal)
else:
dest.floatVal = src.floatVal
of tyObject:
if srctyp.skipTypes(abstractVarRange).kind != tyObject:
internalError(c.config, "invalid object-to-object conversion")
# A object-to-object conversion is essentially a no-op
moveConst(dest, src)
else:
asgnComplex(dest, src)
proc compile(c: PCtx, s: PSym): int =
result = vmgen.genProc(c, s)
when debugEchoCode: c.echoCode result
#c.echoCode
template handleJmpBack() {.dirty.} =
if c.loopIterations <= 0:
if allowInfiniteLoops in c.features:
c.loopIterations = c.config.maxLoopIterationsVM
else:
msgWriteln(c.config, "stack trace: (most recent call last)", {msgNoUnitSep})
stackTraceAux(c, tos, pc)
globalError(c.config, c.debug[pc], errTooManyIterations % $c.config.maxLoopIterationsVM)
dec(c.loopIterations)
proc recSetFlagIsRef(arg: PNode) =
if arg.kind notin {nkStrLit..nkTripleStrLit}:
arg.flags.incl(nfIsRef)
for i in 0..<arg.safeLen:
arg[i].recSetFlagIsRef
proc setLenSeq(c: PCtx; node: PNode; newLen: int; info: TLineInfo) =
let typ = node.typ.skipTypes(abstractInst+{tyRange}-{tyTypeDesc})
let oldLen = node.len
setLen(node.sons, newLen)
if oldLen < newLen:
for i in oldLen..<newLen:
node[i] = getNullValue(c, typ.elementType, info, c.config)
const
errNilAccess = "attempt to access a nil address"
errOverOrUnderflow = "over- or underflow"
errConstantDivisionByZero = "division by zero"
errIllegalConvFromXtoY = "illegal conversion from '$1' to '$2'"
errTooManyIterations = "interpretation requires too many iterations; " &
"if you are sure this is not a bug in your code, compile with `--maxLoopIterationsVM:number` (current value: $1)"
errFieldXNotFound = "node lacks field: "
template maybeHandlePtr(node2: PNode, reg: TFullReg, isAssign2: bool): bool =
let node = node2 # prevent double evaluation
if node.kind == nkNilLit:
stackTrace(c, tos, pc, errNilAccess)
let typ = node.typ
if nfIsPtr in node.flags or (typ != nil and typ.kind == tyPtr):
assert node.kind == nkIntLit, $(node.kind)
assert typ != nil
let typ2 = if typ.kind == tyPtr: typ.elementType else: typ
if not derefPtrToReg(node.intVal, typ2, reg, isAssign = isAssign2):
# tyObject not supported in this context
stackTrace(c, tos, pc, "deref unsupported ptr type: " & $(typeToString(typ), typ.kind))
true
else:
false
template takeAddress(reg, source) =
reg.nodeAddr = addr source
GC_ref source
proc takeCharAddress(c: PCtx, src: PNode, index: BiggestInt, pc: int): TFullReg =
let typ = newType(tyPtr, c.idgen, c.module.owner)
typ.add getSysType(c.graph, c.debug[pc], tyChar)
var node = newNodeIT(nkIntLit, c.debug[pc], typ) # xxx nkPtrLit
node.intVal = cast[int](src.strVal[index].addr)
node.flags.incl nfIsPtr
TFullReg(kind: rkNode, node: node)
proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg =
result = TFullReg(kind: rkNone)
var pc = start
var tos = tos
# Used to keep track of where the execution is resumed.
var savedPC = -1
var savedFrame: PStackFrame = nil
when defined(gcArc) or defined(gcOrc) or defined(gcAtomicArc):
template updateRegsAlias = discard
template regs: untyped = tos.slots
else:
template updateRegsAlias =
move(regs, tos.slots)
var regs: seq[TFullReg] # alias to tos.slots for performance
updateRegsAlias
#echo "NEW RUN ------------------------"
while true:
#{.computedGoto.}
let instr = c.code[pc]
let ra = instr.regA
when traceCode:
template regDescr(name, r): string =
let kind = if r < regs.len: $regs[r].kind else: ""
let ret = name & ": " & $r & " " & $kind
alignLeft(ret, 15)
echo "PC:$pc $opcode $ra $rb $rc" % [
"pc", $pc, "opcode", alignLeft($c.code[pc].opcode, 15),
"ra", regDescr("ra", ra), "rb", regDescr("rb", instr.regB),
"rc", regDescr("rc", instr.regC)]
if c.config.isVmTrace:
# unlike nimVMDebug, this doesn't require re-compiling nim and is controlled by user code
let info = c.debug[pc]
# other useful variables: c.loopIterations
echo "$# [$#] $#" % [c.config$info, $instr.opcode, c.config.sourceLine(info)]
c.profiler.enter(c, tos)
case instr.opcode
of opcEof: return regs[ra]
of opcRet:
let newPc = c.cleanUpOnReturn(tos)
# Perform any cleanup action before returning
if newPc < 0:
pc = tos.comesFrom
let retVal = regs[0]
tos = tos.next
if tos.isNil:
return retVal
updateRegsAlias
assert c.code[pc].opcode in {opcIndCall, opcIndCallAsgn}
if c.code[pc].opcode == opcIndCallAsgn:
regs[c.code[pc].regA] = retVal
else:
savedPC = pc
savedFrame = tos
# The -1 is needed because at the end of the loop we increment `pc`
pc = newPc - 1
of opcYldYoid: assert false
of opcYldVal: assert false
of opcAsgnInt:
decodeB(rkInt)
if regs[rb].kind == rkInt:
regs[ra].intVal = regs[rb].intVal
else:
stackTrace(c, tos, pc, "opcAsgnInt: got " & $regs[rb].kind)
of opcAsgnFloat:
decodeB(rkFloat)
regs[ra].floatVal = regs[rb].floatVal
of opcCastFloatToInt32:
let rb = instr.regB
ensureKind(rkInt)
regs[ra].intVal = cast[int32](float32(regs[rb].floatVal))
of opcCastFloatToInt64:
let rb = instr.regB
ensureKind(rkInt)
regs[ra].intVal = cast[int64](regs[rb].floatVal)
of opcCastIntToFloat32:
let rb = instr.regB
ensureKind(rkFloat)
regs[ra].floatVal = cast[float32](regs[rb].intVal)
of opcCastIntToFloat64:
let rb = instr.regB
ensureKind(rkFloat)
regs[ra].floatVal = cast[float64](regs[rb].intVal)
of opcCastPtrToInt: # RENAME opcCastPtrOrRefToInt
decodeBImm(rkInt)
case imm
of 1: # PtrLikeKinds
case regs[rb].kind
of rkNode:
regs[ra].intVal = cast[int](regs[rb].node.intVal)
of rkNodeAddr:
regs[ra].intVal = cast[int](regs[rb].nodeAddr)
of rkRegisterAddr:
regs[ra].intVal = cast[int](regs[rb].regAddr)
of rkInt:
regs[ra].intVal = regs[rb].intVal
else:
stackTrace(c, tos, pc, "opcCastPtrToInt: got " & $regs[rb].kind)
of 2: # tyRef
regs[ra].intVal = cast[int](regs[rb].node)
else: assert false, $imm
of opcCastIntToPtr:
let rb = instr.regB
let typ = regs[ra].node.typ
let node2 = newNodeIT(nkIntLit, c.debug[pc], typ)
case regs[rb].kind
of rkInt: node2.intVal = regs[rb].intVal
of rkNode:
if regs[rb].node.typ.kind notin PtrLikeKinds:
stackTrace(c, tos, pc, "opcCastIntToPtr: regs[rb].node.typ: " & $regs[rb].node.typ.kind)
node2.intVal = regs[rb].node.intVal
else: stackTrace(c, tos, pc, "opcCastIntToPtr: regs[rb].kind: " & $regs[rb].kind)
regs[ra].node = node2
of opcAsgnComplex:
asgnComplex(regs[ra], regs[instr.regB])
of opcFastAsgnComplex:
fastAsgnComplex(regs[ra], regs[instr.regB])
of opcAsgnRef:
asgnRef(regs[ra], regs[instr.regB])
of opcNodeToReg:
let ra = instr.regA
let rb = instr.regB
# opcLdDeref might already have loaded it into a register. XXX Let's hope
# this is still correct this way:
if regs[rb].kind != rkNode:
regs[ra] = regs[rb]
else:
assert regs[rb].kind == rkNode
let nb = regs[rb].node
if nb == nil:
stackTrace(c, tos, pc, errNilAccess)
else:
case nb.kind
of nkCharLit..nkUInt64Lit:
ensureKind(rkInt)
regs[ra].intVal = nb.intVal
of nkFloatLit..nkFloat64Lit:
ensureKind(rkFloat)
regs[ra].floatVal = nb.floatVal
else:
ensureKind(rkNode)
regs[ra].node = nb
of opcSlice:
# A bodge, but this takes in `toOpenArray(rb, rc, rc)` and emits
# nkTupleConstr(x, y, z) into the `regs[ra]`. These can later be used for calculating the slice we have taken.
decodeBC(rkNode)
let
collection = regs[ra].node
leftInd = regs[rb].intVal
rightInd = regs[rc].intVal
proc rangeCheck(left, right: BiggestInt, safeLen: BiggestInt) =
if left < 0:
stackTrace(c, tos, pc, formatErrorIndexBound(left, safeLen))
if right > safeLen:
stackTrace(c, tos, pc, formatErrorIndexBound(right, safeLen))
case collection.kind
of nkTupleConstr: # slice of a slice
let safeLen = collection[2].intVal - collection[1].intVal
rangeCheck(leftInd, rightInd, safeLen)
let
leftInd = leftInd + collection[1].intVal # Slice is from the start of the old
rightInd = rightInd + collection[1].intVal
regs[ra].node = newTree(
nkTupleConstr,
collection[0],
newIntNode(nkIntLit, BiggestInt leftInd),
newIntNode(nkIntLit, BiggestInt rightInd)
)
else:
let safeLen = safeArrLen(collection) - 1
rangeCheck(leftInd, rightInd, safeLen)
regs[ra].node = newTree(
nkTupleConstr,
collection,
newIntNode(nkIntLit, BiggestInt leftInd),
newIntNode(nkIntLit, BiggestInt rightInd)
)
of opcLdArr:
# a = b[c]
decodeBC(rkNode)
if regs[rc].intVal > high(int):
stackTrace(c, tos, pc, formatErrorIndexBound(regs[rc].intVal, high(int)))
let idx = regs[rc].intVal.int
let src = regs[rb].node
case src.kind
of nkTupleConstr: # refer to `of opcSlice`
let
left = src[1].intVal
right = src[2].intVal
realIndex = left + idx
if idx in 0..(right - left):
case src[0].kind
of nkStrKinds:
regs[ra].node = newIntNode(nkCharLit, ord src[0].strVal[int realIndex])
of nkBracket:
regs[ra].node = src[0][int realIndex]
else:
stackTrace(c, tos, pc, "opcLdArr internal error")
else:
stackTrace(c, tos, pc, formatErrorIndexBound(idx, int right))
of nkStrLit..nkTripleStrLit:
if idx <% src.strVal.len:
regs[ra].node = newNodeI(nkCharLit, c.debug[pc])
regs[ra].node.intVal = src.strVal[idx].ord
else:
stackTrace(c, tos, pc, formatErrorIndexBound(idx, src.strVal.len-1))
elif src.kind notin {nkEmpty..nkFloat128Lit} and idx <% src.len:
regs[ra].node = src[idx]
else:
stackTrace(c, tos, pc, formatErrorIndexBound(idx, src.safeLen-1))
of opcLdArrAddr:
# a = addr(b[c])
decodeBC(rkNodeAddr)
if regs[rc].intVal > high(int):
stackTrace(c, tos, pc, formatErrorIndexBound(regs[rc].intVal, high(int)))
let idx = regs[rc].intVal.int
let src = if regs[rb].kind == rkNode: regs[rb].node else: regs[rb].nodeAddr[]
case src.kind
of nkTupleConstr:
let
left = src[1].intVal
right = src[2].intVal
realIndex = left + idx
if idx in 0..(right - left): # Refer to `opcSlice`
case src[0].kind
of nkStrKinds:
regs[ra] = takeCharAddress(c, src[0], realIndex, pc)
of nkBracket:
takeAddress regs[ra], src.sons[0].sons[realIndex]
else:
stackTrace(c, tos, pc, "opcLdArrAddr internal error")
else:
stackTrace(c, tos, pc, formatErrorIndexBound(idx, int right))
else:
if src.kind notin {nkEmpty..nkTripleStrLit} and idx <% src.len:
takeAddress regs[ra], src.sons[idx]
elif src.kind in nkStrKinds and idx <% src.strVal.len:
regs[ra] = takeCharAddress(c, src, idx, pc)
else:
stackTrace(c, tos, pc, formatErrorIndexBound(idx, src.safeLen-1))
of opcLdStrIdx:
decodeBC(rkInt)
let idx = regs[rc].intVal.int
let s {.cursor.} = regs[rb].node.strVal
if idx <% s.len:
regs[ra].intVal = s[idx].ord
else:
stackTrace(c, tos, pc, formatErrorIndexBound(idx, s.len-1))
of opcLdStrIdxAddr:
# a = addr(b[c]); similar to opcLdArrAddr
decodeBC(rkNode)
if regs[rc].intVal > high(int):
stackTrace(c, tos, pc, formatErrorIndexBound(regs[rc].intVal, high(int)))
let idx = regs[rc].intVal.int
let s = regs[rb].node.strVal.addr # or `byaddr`
if idx <% s[].len:
regs[ra] = takeCharAddress(c, regs[rb].node, idx, pc)
else:
stackTrace(c, tos, pc, formatErrorIndexBound(idx, s[].len-1))
of opcWrArr:
# a[b] = c
decodeBC(rkNode)
let idx = regs[rb].intVal.int
assert regs[ra].kind == rkNode
let arr = regs[ra].node
case arr.kind
of nkTupleConstr: # refer to `opcSlice`
let
src = arr[0]
left = arr[1].intVal
right = arr[2].intVal
realIndex = left + idx
if idx in 0..(right - left):
case src.kind
of nkStrKinds:
src.strVal[int(realIndex)] = char(regs[rc].intVal)
of nkBracket:
if regs[rc].kind == rkInt:
src[int(realIndex)] = newIntNode(nkIntLit, regs[rc].intVal)
else:
assert regs[rc].kind == rkNode
src[int(realIndex)] = regs[rc].node
else:
stackTrace(c, tos, pc, "opcWrArr internal error")
else:
stackTrace(c, tos, pc, formatErrorIndexBound(idx, int right))
of {nkStrLit..nkTripleStrLit}:
if idx <% arr.strVal.len:
arr.strVal[idx] = chr(regs[rc].intVal)
else:
stackTrace(c, tos, pc, formatErrorIndexBound(idx, arr.strVal.len-1))
elif idx <% arr.len:
writeField(arr[idx], regs[rc])
else:
stackTrace(c, tos, pc, formatErrorIndexBound(idx, arr.safeLen-1))
of opcLdObj:
# a = b.c
decodeBC(rkNode)
if rb >= regs.len or regs[rb].kind == rkNone or
(regs[rb].kind == rkNode and regs[rb].node == nil) or
(regs[rb].kind == rkNodeAddr and regs[rb].nodeAddr[] == nil):
stackTrace(c, tos, pc, errNilAccess)
else:
let src = if regs[rb].kind == rkNode: regs[rb].node else: regs[rb].nodeAddr[]
case src.kind
of nkEmpty..nkNilLit:
# for nkPtrLit, this could be supported in the future, use something like:
# derefPtrToReg(src.intVal + offsetof(src.typ, rc), typ_field, regs[ra], isAssign = false)
# where we compute the offset in bytes for field rc
stackTrace(c, tos, pc, errNilAccess & " " & $("kind", src.kind, "typ", typeToString(src.typ), "rc", rc))
of nkObjConstr:
let n = src[rc + 1].skipColon
regs[ra].node = n
of nkTupleConstr:
let n = if src.typ != nil and tfTriggersCompileTime in src.typ.flags:
src[rc]
else:
src[rc].skipColon
regs[ra].node = n
else:
let n = src[rc]
regs[ra].node = n
of opcLdObjAddr:
# a = addr(b.c)
decodeBC(rkNodeAddr)
let src = if regs[rb].kind == rkNode: regs[rb].node else: regs[rb].nodeAddr[]
case src.kind
of nkEmpty..nkNilLit:
stackTrace(c, tos, pc, errNilAccess)
of nkObjConstr:
let n = src.sons[rc + 1]
if n.kind == nkExprColonExpr:
takeAddress regs[ra], n.sons[1]
else:
takeAddress regs[ra], src.sons[rc + 1]
else:
takeAddress regs[ra], src.sons[rc]
of opcWrObj:
# a.b = c
decodeBC(rkNode)
assert regs[ra].node != nil
let shiftedRb = rb + ord(regs[ra].node.kind == nkObjConstr)
let dest = regs[ra].node
if dest.kind == nkNilLit:
stackTrace(c, tos, pc, errNilAccess)
elif dest[shiftedRb].kind == nkExprColonExpr:
writeField(dest[shiftedRb][1], regs[rc])
dest[shiftedRb][1].flags.incl nfSkipFieldChecking
else:
writeField(dest[shiftedRb], regs[rc])
dest[shiftedRb].flags.incl nfSkipFieldChecking
of opcWrStrIdx:
decodeBC(rkNode)
let idx = regs[rb].intVal.int
if idx <% regs[ra].node.strVal.len:
regs[ra].node.strVal[idx] = chr(regs[rc].intVal)
else:
stackTrace(c, tos, pc, formatErrorIndexBound(idx, regs[ra].node.strVal.len-1))
of opcAddrReg:
decodeB(rkRegisterAddr)
regs[ra].regAddr = addr(regs[rb])
of opcAddrNode:
decodeB(rkNodeAddr)
case regs[rb].kind
of rkNode:
takeAddress regs[ra], regs[rb].node
of rkNodeAddr: # bug #14339
regs[ra].nodeAddr = regs[rb].nodeAddr
else:
stackTrace(c, tos, pc, "limited VM support for 'addr', got kind: " & $regs[rb].kind)
of opcLdDeref:
# a = b[]
let ra = instr.regA
let rb = instr.regB
case regs[rb].kind
of rkNodeAddr:
ensureKind(rkNode)
regs[ra].node = regs[rb].nodeAddr[]
of rkRegisterAddr:
ensureKind(regs[rb].regAddr.kind)
regs[ra] = regs[rb].regAddr[]
of rkNode:
if regs[rb].node.kind == nkRefTy:
regs[ra].node = regs[rb].node[0]
elif not maybeHandlePtr(regs[rb].node, regs[ra], false):
## e.g.: typ.kind = tyObject
ensureKind(rkNode)
regs[ra].node = regs[rb].node
else:
stackTrace(c, tos, pc, errNilAccess & " kind: " & $regs[rb].kind)
of opcWrDeref:
# a[] = c; b unused
let ra = instr.regA
let rc = instr.regC
case regs[ra].kind
of rkNodeAddr:
let n = regs[rc].regToNode
# `var object` parameters are sent as rkNodeAddr. When they are mutated
# vmgen generates opcWrDeref, which means that we must dereference
# twice.
# TODO: This should likely be handled differently in vmgen.
let nAddr = regs[ra].nodeAddr
if nAddr[] == nil: stackTrace(c, tos, pc, "opcWrDeref internal error") # refs bug #16613
if (nfIsRef notin nAddr[].flags and nfIsRef notin n.flags): nAddr[][] = n[]
else: nAddr[] = n
of rkRegisterAddr: regs[ra].regAddr[] = regs[rc]
of rkNode:
# xxx: also check for nkRefTy as in opcLdDeref?
if not maybeHandlePtr(regs[ra].node, regs[rc], true):
regs[ra].node[] = regs[rc].regToNode[]
regs[ra].node.flags.incl nfIsRef
else: stackTrace(c, tos, pc, errNilAccess)
of opcAddInt:
decodeBC(rkInt)
let
bVal = regs[rb].intVal
cVal = regs[rc].intVal
sum = bVal +% cVal
if (sum xor bVal) >= 0 or (sum xor cVal) >= 0:
regs[ra].intVal = sum
else:
stackTrace(c, tos, pc, errOverOrUnderflow)
of opcAddImmInt:
decodeBImm(rkInt)
#message(c.config, c.debug[pc], warnUser, "came here")
#debug regs[rb].node
let
bVal = regs[rb].intVal
cVal = imm
sum = bVal +% cVal
if (sum xor bVal) >= 0 or (sum xor cVal) >= 0:
regs[ra].intVal = sum
else:
stackTrace(c, tos, pc, errOverOrUnderflow)
of opcSubInt:
decodeBC(rkInt)
let
bVal = regs[rb].intVal
cVal = regs[rc].intVal
diff = bVal -% cVal