-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathmirgen.nim
2918 lines (2596 loc) · 96.8 KB
/
mirgen.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
## Implements the translation from AST to the MIR. The input AST is expected
## to have already been transformed by ``transf``.
##
## How It Works
## ------------
##
## In terms of operation, the input AST is traversed via recursion, with
## declarative constructs not relevant to the MIR being ignored.
##
## None of the MIR operations that imply structured control-flow produce a
## value, so the input expression that do (``if``, ``case``, ``block``, and
## ``try``) are translated into statements where the last expression in each
## clause is turned into an assignment to, depending on the context where
## they're used, either a temporary or existing lvalue expression. The latter
## are forwarded to the generation procedures via ``Destination``.
##
## For efficiency, ``MirBuilder``'s double-buffering functionality is used for
## emitting the trees. Statements are directly emitted into the final buffer
## (after all their operands were emitted), while expressions are first
## emitted into the staging buffer, with the callsite then deciding what to
## do with them.
##
## When translating expressions, they're first translated to the `proto-MIR <proto_mir.html>`_,
## and then the proto-MIR expression is translated to the MIR. This allows
## the translation of expressions (besides calls) to focus only on syntax,
## leaving the semantics-related decision-making to the proto-MIR construction.
##
## For arguments, the translation uses temporaries (both owning and non-owning)
## to make sure that the following invariants are true:
## * normal argument expressions are pure (the expression always evaluates to
## the same value)
## * lvalue argument expressions are stable (the expression always has the
## same address)
## * sink arguments are always moveable
## * index and dereference targets are always pure
##
## These guarantees make the following analysis and transformation a lot
## easier.
##
## Origin information
## ------------------
##
## Each produced ``MirNode`` is associated with the ``PNode`` it originated
## from (referred to as "source information"). The ``PNode`` is registered in
## the ``SourceMap``, with the resulting ``SourceId`` then assigned to the
## nodes associated with the AST.
##
## In order to reduce the amount manual bookkeeping and to improve the
## ergonomics of producing MIR node sequences, assigning the ``SourceId``
## is decoupled from the initial production. ``SourceProvider`` keeps track of
## the currently processed AST node and manages setting the ``info`` field on
## nodes.
##
## Changing the active AST node is done via calling the ``useSource`` routine,
## which will apply the previous AST node as the origin to all MIR nodes
## added to a ``MirBuffer`` since the last call to ``useSource``. When
## the scope ``useSource`` is called in is exited, the previous AST node is
## restored as the active origin, allowing for arbitrary nesting.
##
import
std/[
tables
],
compiler/ast/[
ast,
astalgo,
astmsgs, # for generating the field error message
idents,
trees,
types,
wordrecg
],
compiler/mir/[
datatables,
mirbodies,
mirconstr,
mirenv,
mirgen_blocks,
mirtrees,
mirtypes,
proto_mir,
sourcemaps
],
compiler/modules/[
magicsys,
modulegraphs
],
compiler/front/[
options
],
compiler/sem/[
ast_analysis
],
compiler/utils/[
containers,
idioms,
tracer
]
import std/options as std_options
when defined(nimCompilerStacktraceHints):
import compiler/utils/debugutils
from compiler/front/msgs import unquotedFilename, toLinenumber
type
DestFlag = enum
## Extra information about an assignment destination. The flags are used to
## decide which kind of assignment to use
dfEmpty ## the destination doesn't store a value yet
dfOwns ## the destination is an owning location
Destination = object
## Stores the information necessary to generate the code for an assignment
## to some destination.
case isSome: bool
of false: discard
of true: val: Value
flags: set[DestFlag]
SourceProvider = object
## Stores the active origin and the in-progress database of origin
## ``PNode``s. Both are needed together in most cases, hence their bundling
## into an object
active: tuple[n: PNode, id: SourceId]
## the ``PNode`` to use as the origin for emitted ``MirNode``s (if none
## is explicitly provided). If `id` is 'none', no database entry exists
## for the ``PNode`` yet
map: SourceMap
## the in-progress database of origin ``PNode``s
GenOption* = enum
goIsNimvm ## choose the ``nimvm`` branch for ``when nimvm`` statements
goGenTypeExpr ## don't omit type expressions
goIsCompileTime ## whether the code is meant to be run at compile-time.
## Affects handling of ``.compileTime`` globals
goTailCallElim ## enables elimination of eligible `.tailcall` calls
TranslationConfig* = object
## Extra configuration for the AST -> MIR translation.
options*: set[GenOption]
magicsToKeep*: set[TMagic]
## magic procedures that need to be referenced via their symbols, either
## because they're not really magic or because the symbol has
## additional information
TCtx = object
# working state:
env: MirEnv
## for convenience and safety, `TCtx` temporarily assumes full
## ownership of the environment
builder: MirBuilder ## the builder for generating the MIR trees
blocks: BlockCtx
localsMap: Table[int, LocalId]
## maps symbol IDs of locals to the corresponding ``LocalId``
sp: SourceProvider
scopeDepth: int ## the current amount of scope nesting
inLoop: int
## > 0 if the current statement/expression is part of a loop
injectDestructors: bool
## whether injection of destroy operations is enabled
# input:
userOptions: set[TOption]
graph: ModuleGraph
owner: PSym
config: TranslationConfig
PMirExpr = seq[ProtoItem]
## Convenience alias.
const
ComplexExprs = {nkIfExpr, nkCaseStmt, nkBlockExpr, nkTryStmt}
## The expression that are treated as complex and which are transformed
## into assignments-to-temporaries
func tailCallElimActive(c: TCtx): bool =
## Whether tail-call elimination is enabled in the current context.
c.owner != nil and c.owner.kind in routineKinds and
c.owner.typ.callConv == ccTailcall and
goTailCallElim in c.config.options
func isHandleLike(t: PType): bool =
t.skipTypes(abstractInst).kind in {tyPtr, tyRef, tyLent, tyVar, tyOpenArray}
# XXX: copied from ``injectdestructors``. Move somewhere common
proc isCursor(n: PNode): bool =
## Computes whether the expression `n` names a location that is a cursor
case n.kind
of nkSym:
sfCursor in n.sym.flags
of nkDotExpr:
isCursor(n[1])
of nkCheckedFieldExpr:
isCursor(n[0])
else:
false
template doesReturn(n: PNode): bool =
## Returns whether `n` is a statement with a structured exit.
mixin c
n.typ != c.graph.noreturnType
func initDestination(v: sink Value, isFirst, sink: bool): Destination =
var flags: set[DestFlag]
if isFirst:
flags.incl dfEmpty
if sink:
flags.incl dfOwns
Destination(isSome: true, val: v, flags: flags)
proc typeToMir(c: var TCtx, t: PType): TypeId =
## Turns `t` into a MIR type and returns the latter's ID.
if t.isNil: VoidType
else: c.env.types.add(t)
# ----------- SourceProvider API -------------
template useSource(bu: var MirBuilder, sp: var SourceProvider,
origin: PNode) =
## Pushes `origin` to be used as the source for the rest of the scope that
## ``useSource`` is used inside. When the scope is exited, the previous
## origin is restored.
let x = origin
var prev =
if sp.active.n != x: (x, sp.map.add(x))
else: (x, sp.active.id)
# set the new source information on the builder and make it the
# active one:
bu.setSource(prev[1])
swap(prev, sp.active)
defer:
# switch back to the previous source information:
bu.setSource(prev[1])
swap(prev, sp.active)
# -------------- Symbol translation --------------
proc localToMir(c: var TCtx, s: PSym): Local =
Local(typ: c.env.types.add(s.typ),
flags: s.flags,
isImmutable: s.kind in {skLet, skForVar},
name: s.name,
alignment:
if s.kind in {skVar, skLet, skForVar}:
s.alignment.uint32
else:
0
)
template paramToMir(c: var TCtx, s: PSym): Local =
localToMir(c, s)
# -------------- builder/convenience routines -------------
template add(c: var TCtx, n: MirNode) =
c.builder.add n
template subTree(c: var TCtx, k: MirNodeKind, body: untyped) =
c.builder.subTree MirNode(kind: k):
body
template subTree(c: var TCtx, n: MirNode, body: untyped) =
c.builder.subTree n:
body
template scope(c: var TCtx, exits: bool, body: untyped) =
## `exits` signals whether the body of the scope has a structured control-
## flow exit.
let e = exits
inc c.scopeDepth
c.builder.scope:
let prev = c.blocks.startScope()
body
c.blocks.closeScope(c.builder, prev, e)
dec c.scopeDepth
template use(c: var TCtx, val: Value) =
c.builder.use(val)
template join(c: var TCtx, label: LabelId) =
c.builder.join(label)
template emitByVal(c: var TCtx, val: Value) =
## Emits a pass-by-value argument sub-tree with `val`.
c.builder.emitByVal(val)
template emitByName(c: var TCtx, eff: EffectKind, body: untyped) =
## Emits a pass-by-name argument sub-tree with `val`.
c.builder.emitByName(eff, body)
template addLocal(c: var TCtx, local: Local): LocalId =
c.builder.addLocal(local)
proc addLocal(c: var TCtx, s: PSym): LocalId =
## Translates `s` to its MIR representation, registers it with body, and
## establishes a mapping.
assert s.id notin c.localsMap
result = c.addLocal(localToMir(c, s))
c.localsMap[s.id] = result
proc empty(c: var TCtx, n: PNode): MirNode =
MirNode(kind: mnkNone, typ: c.typeToMir(n.typ))
func intLiteral(env: var MirEnv, val: BiggestInt, typ: TypeId): Value =
literal(mnkIntLit, env.getOrIncl(val), typ)
func uintLiteral(env: var MirEnv, val: BiggestUInt, typ: TypeId): Value =
literal(mnkUIntLit, env.getOrIncl(val), typ)
func floatLiteral(env: var MirEnv, val: BiggestFloat, typ: TypeId): Value =
literal(mnkFloatLit, env.getOrIncl(val), typ)
proc astLiteral(env: var MirEnv, val: PNode, typ: PType): Value =
literal(env.asts.add(val), env.types.add(typ))
proc toIntLiteral(env: var MirEnv, val: Int128, typ: PType): Value =
## Interprets `val` based on `typ`.
if isUnsigned(typ):
uintLiteral(env, val.toUInt, env.types.add(typ))
else:
intLiteral(env, val.toInt, env.types.add(typ))
proc toIntLiteral(env: var MirEnv, n: PNode): Value =
## Translates an integer value (represented by `n`) to its MIR
## counterpart.
assert n.kind in nkIntLiterals
let typ = env.types.add(n.typ)
# use the type for deciding what whether it's a signed or unsigned value
case n.typ.skipTypes(abstractRange + {tyEnum}).kind
of tyInt..tyInt64, tyBool:
intLiteral(env, n.intVal, typ)
of tyUInt..tyUInt64, tyChar, tyPtr, tyPointer, tyProc:
uintLiteral(env, cast[BiggestUInt](n.intVal), typ)
else:
unreachable()
proc toFloatLiteral(env: var MirEnv, n: PNode): Value =
## Translates a float value (represented by `n`) to its MIR
## counterpart.
assert n.kind in nkFloatLiterals
var val = n.floatVal
case n.typ.skipTypes(abstractRange).kind
of tyFloat, tyFloat64:
discard "nothing to adjust"
of tyFloat32:
# all code-generators would have to narrow the value at some point, so we
# help them by doing it here
val = val.float32.float64
else:
unreachable()
floatLiteral(env, val, env.types.add(n.typ))
func strLiteral(env: var MirEnv, str: string, typ: TypeId): Value =
literal(env.getOrIncl(str), typ)
template labelNode(lbl: LabelId): MirNode =
MirNode(kind: mnkLabel, label: lbl)
template newLabelNode(c: var TCtx): MirNode =
labelNode(c.builder.allocLabel())
proc nameNode(c: var TCtx, s: PSym): MirNode =
let t = c.typeToMir(s.typ)
case s.kind
of skTemp:
# temporaries are always locals, even if marked with the ``sfGlobal``
# flag
MirNode(kind: mnkLocal, typ: t, local: c.localsMap[s.id])
of skConst:
MirNode(kind: mnkConst, typ: t, cnst: c.env.constants.add(s))
of skParam:
MirNode(kind: mnkParam, typ: t, local: LocalId(1 + s.position))
of skResult:
MirNode(kind: mnkLocal, typ: t, local: c.localsMap[s.id])
of skVar, skLet, skForVar:
if sfGlobal in s.flags:
MirNode(kind: mnkGlobal, typ: t, global: c.env.globals.add(s))
else:
MirNode(kind: mnkLocal, typ: t, local: c.localsMap[s.id])
else:
unreachable(s.kind)
proc genLocation(c: var TCtx, n: PNode): Value =
let f = c.builder.push: c.builder.add(nameNode(c, n.sym))
c.builder.popSingle(f)
template allocTemp(c: var TCtx, typ: TypeId; alias=false): Value =
## Allocates a new ID for a temporary and returns the name.
c.builder.allocTemp(typ, alias)
template allocLabel(c: var TCtx): LabelId =
c.builder.allocLabel()
proc gen(c: var TCtx; n: PNode)
proc genx(c: var TCtx; e: PMirExpr, i: int; fromMove = false)
proc genComplexExpr(c: var TCtx, n: PNode, dest: Destination)
proc genAsgn(c: var TCtx, dest: Destination, rhs: PNode)
proc genWithDest(c: var TCtx; n: PNode; dest: Destination)
proc exprToPmir(c: var TCtx, n: PNode, sink, mutable: bool): PMirExpr =
exprToPmir(c.userOptions, c.graph.config, goIsNimvm in c.config.options,
n, sink, mutable)
proc genx(c: var TCtx, n: PNode; consume: bool = false) =
when defined(nimCompilerStacktraceHints):
frameMsg(c.graph.config, n)
let e = exprToPmir(c, n, consume, false)
genx(c, e, e.high)
func getTemp(c: var TCtx, typ: TypeId): Value =
## Allocates a new temporary and emits a definition for it into the
## final buffer.
assert typ != VoidType
result = c.allocTemp(typ)
withFront c.builder:
c.subTree mnkDef:
c.use result
c.add MirNode(kind: mnkNone)
template raiseExit(c: var TCtx) =
raiseExit(c.blocks, c.builder)
template buildStmt(c: var TCtx, k: MirNodeKind, body: untyped) =
c.builder.buildStmt(k, body)
template buildMagicCall(c: var TCtx, m: TMagic, t: TypeId, body: untyped) =
c.builder.buildMagicCall(m, t, body)
template buildCheckedMagicCall(c: var TCtx, m: TMagic, t: TypeId,
body: untyped) =
c.builder.rawBuildCall mnkCheckedCall, t, false:
c.add MirNode(kind: mnkMagic, magic: m)
body
raiseExit(c)
template buildDefectMagicCall(c: var TCtx, m: TMagic, t: TypeId,
body: untyped) =
## Builds and emits a call to the `m` magic with return type `t`. The call
## is only marked as potentially raising if panics are not enabled.
##
## This template is meant to be used for ``Defect``-raising magic
## procedures.
let kind =
if optPanics in c.graph.config.globalOptions:
mnkCall
else:
mnkCheckedCall
c.builder.rawBuildCall kind, t, false: # no side-effects
c.add MirNode(kind: mnkMagic, magic: m)
body
if kind == mnkCheckedCall:
raiseExit(c)
template buildIf(c: var TCtx, cond, body: untyped) =
let label = c.builder.allocLabel()
c.buildStmt mnkIf:
cond
c.add labelNode(label)
body
c.buildStmt mnkEndStruct:
c.add labelNode(label)
proc register(c: var TCtx, loc: Value) =
## If `loc` has a destructor and destroy injection is enabled for the
## current context, registers `loc` for destruction at the end of the
## current scope.
if c.injectDestructors and c.env[loc.typ].hasDestructor():
c.blocks.register(loc)
proc singleToValue(c: var TCtx, e: PMirExpr, i: int): Value =
c.builder.useSource(c.sp, e[i].orig)
let f = c.builder.push: genx(c, e, i)
result = c.builder.popSingle(f)
proc toValue(c: var TCtx, e: PMirExpr, i: int, def: MirNodeKind): Value =
## Generates the MIR code for the given expression and turns it into a
## ``Value``, using a `def` statement for creating the necessary
## temporary.
c.builder.useSource(c.sp, e[i].orig)
let f = c.builder.push: genx(c, e, i)
if c.builder.staging[f.pos].kind in Atoms:
# can be turned into a ``Value`` directly
result = c.builder.popSingle(f)
else:
# needs a temporary
result = c.allocTemp(c.typeToMir(e[i].typ), def in {mnkBind, mnkBindMut})
withFront c.builder:
c.subTree def:
c.use result
c.builder.pop(f)
if def == mnkDef:
c.register(result)
proc toValue(c: var TCtx, e: PMirExpr, i: int): Value =
## Generates the MIR code for the given expression and turns it into a
## ``Value``.
case classify(e, i)
of Lvalue:
case e[i].keep
of kDontCare: toValue(c, e, i, mnkDefCursor)
of kLvalue: toValue(c, e, i, mnkBind)
of kMutLvalue: toValue(c, e, i, mnkBindMut)
of Rvalue: toValue(c, e, i, mnkDefCursor)
of OwnedRvalue: toValue(c, e, i, mnkDef)
of Literal: singleToValue(c, e, i)
proc genUse(c: var TCtx, n: PNode): Value =
## Generates the MIR code for expression `n` and returns it as a ``Value``.
## The expression is not guaranteed to be pure.
var e = exprToPmir(c, n, false, false)
toValue(c, e, e.high)
proc genRd(c: var TCtx, n: PNode): Value =
## Generates the MIR code for expression `n` and returns it as a pure
## ``Value``.
var e = exprToPmir(c, n, false, false)
wantPure(e)
toValue(c, e, e.high)
proc genAlias(c: var TCtx, n: PNode, mutable: bool): Value =
## Generates the MIR code for lvalue expression `n`, and creates an alias
## (run-time reference) for it. `mutable` indicates whether the alias
## needs to support direct assignments through it.
var e = exprToPmir(c, n, false, mutable)
toValue(c, e, e.high)
proc genOperand(c: var TCtx, n: PNode) =
## Generates and emits the MIR code for expression `n`, using temporaries to
## make sure the emitted MIR expression is valid in an operand position.
var e = exprToPmir(c, n, false, false)
wantValue(e)
genx(c, e, e.high)
proc genOp(c: var TCtx, k: MirNodeKind, t: TypeId, n: PNode) =
c.subTree MirNode(kind: k, typ: t):
genOperand(c, n)
template buildOp(c: var TCtx, k: MirNodeKind, t: TypeId, body: untyped) =
c.subTree MirNode(kind: k, typ: t):
body
template wrapTemp(c: var TCtx, t: TypeId, body: untyped): Value =
## Assigns the expression emitted by `body` to a temporary and
## returns the name of the latter.
assert t != VoidType
let res = c.allocTemp(t)
c.buildStmt mnkDef:
c.use res
body
res
template wrapAndUse(c: var TCtx, t: TypeId, body: untyped) =
## Assigns the expression emitted by `body` to a temporary
## and immediately emits a use thereof.
let tmp = c.wrapTemp(t):
body
c.use tmp
template buildTree(c: var TCtx, k: MirNodeKind, t: TypeId, body: untyped) =
c.subTree MirNode(kind: k, typ: t):
body
proc genAndOr(c: var TCtx, n: PNode, dest: Destination) =
## Generates the code for an ``and|or`` operation:
##
## .. code-block:: nim
##
## dest = a
##
## # for `or`:
## if not dest:
## dest = b
##
## # for `and`:
## if dest:
## dest = b
##
# TODO: inefficient code is generated for nested ``and|or`` operations, e.g.
# ``a or b or c``. Sequences of the same operation should be merged
# into a single one before and the logic here adjusted to handle them.
# With the aforementioned transformation, the previously mentioned
# example would become: ``or(a, b, c)``
genAsgn(c, dest, n[1]) # the left-hand side
# condition:
var v = dest.val
if n[0].sym.magic == mOr:
v = c.wrapTemp BoolType:
c.buildMagicCall mNot, BoolType:
c.emitByVal v
c.buildIf (c.use v;):
genAsgn(c, dest, n[2]) # the right-hand side
proc genFieldCheck(c: var TCtx, access: Value, call: PNode, inverted: bool,
field: string) =
## Generates and emits a field check.
let
conf = c.graph.config
discr = call[2].sym
c.buildStmt mnkVoid:
c.buildDefectMagicCall mChckField, VoidType:
# set operand:
c.emitByVal c.genRd(call[1])
# discriminator value operand:
c.subTree mnkArg:
c.builder.pathNamed c.typeToMir(discr.typ), discr.position.int32:
c.use access
# inverted flag:
c.emitByVal intLiteral(c.env, ord(inverted), BoolType)
# error message operand:
c.emitByVal strLiteral(c.env, genFieldDefect(conf, field, discr),
StringType)
proc genCheckedVariantAccess(c: var TCtx, variant: Value, name: PIdent,
check: PNode): PSym =
## Generates and emits the field check. `variant` is the variant-object
## value the discriminator field is part of, `name` is the name to
## put into the error message, and `check` is the check-AST coming from an
## ``nkCheckedFieldExpr`` expression.
## The symbol of the discriminator field, as taken from `check`, is
## returned.
assert check.kind in nkCallKinds
let
inverted = check[0].sym.magic == mNot
call =
if inverted: check[1]
else: check
genFieldCheck(c, variant, call, inverted, name.s)
result = call[2].sym
proc genTypeExpr(c: var TCtx, n: PNode): Value =
## Generates the code for an expression that yields a type. These are only
## valid in metaprogramming contexts. If it's a static type expression, we
## evaluate it directly and store the result as a type literal in the MIR
assert n.typ.kind == tyTypeDesc
c.builder.useSource(c.sp, n)
case n.kind
of nkStmtListExpr:
# FIXME: a ``nkStmtListExpr`` shouldn't reach here, but it does. See
# ``tests/lang_callable/generics/t18859.nim`` for a case where it
# does
genTypeExpr(c, n.lastSon)
of nkSym:
case n.sym.kind
of skType:
typeLit c.typeToMir(n.sym.typ)
of skVar, skLet, skForVar, skTemp, skParam:
# a first-class type value stored in a location
genLocation(c, n)
else:
unreachable()
of nkBracketExpr:
# the type description of a generic type, e.g. ``seq[int]``
typeLit c.typeToMir(n.typ)
of nkTupleTy, nkStaticTy, nkRefTy, nkPtrTy, nkVarTy, nkDistinctTy, nkProcTy,
nkIteratorTy, nkSharedTy, nkTupleConstr:
typeLit c.typeToMir(n.typ)
of nkTypeOfExpr, nkType:
typeLit c.typeToMir(n.typ)
else:
unreachable("not a type expression")
proc genArgExpression(c: var TCtx, n: PNode, sink: bool) =
## Generates and emits the code for an expression appearing in a call or
## construction argument position.
c.builder.useSource(c.sp, n)
var e = exprToPmir(c, n, sink, false)
if sink:
wantConsumeable(e)
else:
wantValue(e)
wantPure(e)
genx(c, e, e.high)
proc emitOperandTree(c: var TCtx, n: PNode, sink: bool) =
## Generates and emits the MIR tree for a call or construction argument.
c.subTree (if sink: mnkConsume else: mnkArg):
genArgExpression(c, n, sink)
proc genLvalueOperand(c: var TCtx, n: PNode; mutable = true) =
## Generates the code for lvalue expression `n`. If the expression is either
## not pure or has side-effects, its address/name is captured, with
## `mutable` denoting whether the address is going to be used for mutation
## of the underlying location.
let n = if n.kind == nkHiddenAddr: n[0] else: n
var e = exprToPmir(c, n, false, mutable)
wantStable(e)
genx(c, e, e.high)
proc genCallee(c: var TCtx, n: PNode) =
## Generates and emits the code for a callee expression.
if n.kind == nkSym and n.sym.kind in routineKinds:
c.builder.useSource(c.sp, n)
let s = n.sym
if s.magic == mNone or s.magic in c.config.magicsToKeep:
# reference the procedure by symbol
c.add procNode(c.env.procedures.add(s))
else:
# don't use a symbol
c.add MirNode(kind: mnkMagic, magic: s.magic)
else:
# an indirect call
genArgExpression(c, n, false)
proc genArg(c: var TCtx, formal: PType, n: PNode) =
## Generates and emits the MIR code for an argument expression, with the
## MIR expression being wrapped in the correct argument node. The `formal`
## type is needed for figuring out how the argument is passed.
case formal.skipTypes(abstractRange-{tySink}).kind
of tyVar:
if formal.base.kind in {tyOpenArray, tyVarargs}:
# it's not a pass-by-name parameter
c.emitOperandTree n, false
else:
c.emitByName ekMutate, genLvalueOperand(c, n, true)
of tySink:
c.emitOperandTree n, true
else:
c.emitOperandTree n, false
proc genArgs(c: var TCtx, n: PNode) =
## Emits the MIR code for the argument expressions (including the
## argument node), but without a wrapping ``mnkArgBlock``.
let fntyp = skipTypes(n[0].typ, abstractInst)
for i in 1..<n.len:
# for procedures with unsafe varargs, the type of the argument expression
# is used as the formal type (because it's the only type-related
# information about the argument we have access to here)
let t =
if i < fntyp.len: fntyp[i]
else: n[i].typ
if t.kind == tyTypeDesc and goGenTypeExpr in c.config.options:
# generation of type expressions is requested. It's important that this
# branch comes before the ``isCompileTimeOnly`` one, as a ``tyTypeDesc``
# is treated as a compile-time-only type and would be omitted then
# FIXME: some argument expressions seem to reach here incorrectly
# typed (i.e., not as a typedesc). Figure out why, resolve
# the issues, and then remove the workaround here
if n[i].typ.kind == tyTypeDesc:
c.emitByVal genTypeExpr(c, n[i])
else:
c.emitByVal typeLit(c.typeToMir(n[i].typ))
elif t.isCompileTimeOnly:
# don't translate arguments to compile-time-only parameters. To ease the
# translation to ``CgNode``, we don't omit them completely but only
# replace them with a node holding their type
c.subTree mnkArg:
c.add empty(c, n[i])
elif t.kind == tyVoid:
# a ``void`` argument. We can't just generate an ``mnkNone`` node, as the
# statement used as the argument can still have side-effects
withFront c.builder:
gen(c, n[i])
c.subTree mnkArg:
c.add empty(c, n[i])
elif i == 1 and not fntyp[0].isEmptyType() and
not isHandleLike(t) and
classifyViewType(fntyp[0]) == immutableView:
# the procedure returns a view, but the first parameter is not something
# that resembles a handle. We need to make sure that the first argument
# (which the view could be created from), is passed by reference
c.builder.emitByName ekNone:
var e = exprToPmir(c, n[i], false, false)
wantStable(e)
genx(c, e, e.high)
elif fntyp.callConv == ccTailcall and
t.kind notin {tySink, tyVar} and
i < fntyp.len and # ignore the env argument
isPassByRef(c.graph.config, fntyp.n[i].sym, fntyp):
# pass-by-reference needs to be enforced early for tailcall calls.
# Temporary copies must not happen under any circumstance
c.builder.emitByName ekNone:
var e = exprToPmir(c, n[i], false, false)
wantStable(e)
genx(c, e, e.high)
else:
genArg(c, t, n[i])
proc callKind(c: TCtx, n: PNode): range[mnkCall..mnkCheckedCall] =
if canRaise(optPanics in c.graph.config.globalOptions, n):
mnkCheckedCall
else:
mnkCall
proc genCall(c: var TCtx, n: PNode) =
## Generates and emits the MIR code for a call expression.
let fntyp = n[0].typ.skipTypes(abstractInst)
let kind = callKind(c, n[0])
# the correct return type for .tailcall routines is that of the call, not
# that from the proc type:
let rettype =
if fntyp.callConv == ccTailcall:
n.typ
else:
fntyp[0]
let hasSideEffect = tfNoSideEffect notin fntyp.flags
c.builder.rawBuildCall kind, c.typeToMir(rettype), hasSideEffect:
genCallee(c, n[0])
genArgs(c, n)
if kind == mnkCheckedCall:
raiseExit(c)
proc genMacroCallArgs(c: var TCtx, n: PNode, kind: TSymKind, fntyp: PType) =
## Generates the arguments for a macro/template call expression. `n` is
## expected to be a ``getAst`` expression that has been transformed to the
## internal representation. `kind` is the meta-routine's kind, and `fntyp`
## its signature.
case kind
of skMacro:
genCallee(c, n[1])
of skTemplate:
# for late template invocations, the callee template is an argument
c.emitByVal literal(c.env.asts.add(n[1]), VoidType)
else:
unreachable(kind)
for i in 2..<n.len:
let
it = n[i]
argTyp = it.typ.skipTypes(abstractInst - {tyTypeDesc})
if argTyp.kind == tyTypeDesc:
# the expression is a type expression, explicitly handle it there so that
# ``genx`` doesn't have to
c.emitByVal genTypeExpr(c, it)
elif kind == skMacro:
# we can extract the formal types from the signature
genArg(c, fntyp[i - 1], it)
elif kind == skTemplate:
# we have to treat the arguments as normal expressions
c.emitByVal genRd(c, it)
else:
unreachable()
proc genSetConstr(c: var TCtx, n: PNode)
proc genInSetOp(c: var TCtx, n: PNode) =
## Generates and emits the IR for the ``mInSet`` magic call `n`. If
## the element operand is a range check, it is integrated into the
## operation, meaning that no defect will be raised if the operand is
## not in the expected range.
case n[2].kind
of nkChckRange, nkChckRange64:
# turn
# chkRange(a, b, c) in d
# into
# b <= a and a <= c and a in d
# but make sure that 'd' is still always evaluated
let
se = n[1]
x = n[2]
elemTyp = x.typ.skipTypes(abstractRange)
leOp = getMagicLeForType(elemTyp) # less-equal op
res = getTemp(c, BoolType) # the temporary to write the result to
# the evaluation order is reversed here: the second operand comes
# first
let
val = genRd(c, x[0])
a = genRd(c, x[1])
b = genRd(c, x[2])
c.builder.buildStmt:
let
label1 = c.allocLabel()
label2 = c.allocLabel()
c.subTree mnkIf:
# condition: ``a <= x:``
c.wrapAndUse(BoolType):
c.buildMagicCall leOp, BoolType:
c.emitByVal a
c.emitByVal val
c.add labelNode(label1)
c.subTree mnkIf:
# condition: ``x <= b:``
c.wrapAndUse(BoolType):
c.buildMagicCall leOp, BoolType:
c.emitByVal val
c.emitByVal b
c.add labelNode(label2)
var sv: Value
if se.kind == nkCurly and not isDeepConstExpr(se):
sv = c.allocTemp(c.typeToMir(se.typ))
c.subTree mnkDef:
c.use sv
genSetConstr(c, se)
else:
sv = genRd(c, se)
c.subTree mnkInit:
c.use res
c.buildMagicCall mInSet, BoolType:
c.emitByVal sv
c.emitByVal val
# close the if statements:
c.subTree mnkEndStruct:
c.add labelNode(label2)
c.subTree mnkEndStruct:
c.add labelNode(label1)
c.use res
else:
# the operation is not eligible for being turned into an ``if`` chain. Emit a
# generic magic call
genCall(c, n)
proc genMagic(c: var TCtx, n: PNode; m: TMagic) =
## Generates the MIR code for the magic call expression/statement `n`. `m` is
## the magic's enum value and must match with that of the callee.
##
## Some magics are inserted by the compiler, in which case the corresponding
## symbols are incomplete: only the ``magic`` and ``name`` field can be
## treated as valid. These magic calls are manually translated and don't go
## through ``genCall``
c.builder.useSource(c.sp, n)
template arg(n: PNode) =
c.emitOperandTree n, false
let rtyp = c.typeToMir(n.typ) ## call's return type
case m
of mAnd, mOr:
let tmp = getTemp(c, rtyp)
withFront c.builder:
genAndOr(c, n, Destination(isSome: true, val: tmp, flags: {dfOwns}))
c.use tmp
of mDefault:
# use the canonical form:
c.buildMagicCall mDefault, rtyp:
discard
of mNew:
# ``new`` has 2 variants. The standard one with zero arguments, and the
# unsafe version that takes a ``size`` argument
assert n.len == 1 or n.len == 2
c.buildMagicCall m, rtyp:
if n.len == 2:
# the size argument
arg n[1]
of mWasMoved:
# ``wasMoved`` has an effect that is not encoded by the parameter's type
# (it kills the location), so we need to manually translate it
c.buildMagicCall m, VoidType:
c.emitByName ekKill, genLvalueOperand(c, n[1])
of mConStrStr:
# the `mConStrStr` magic is very special. Nested calls to it are flattened
# into a single call in ``transf``. It can't be passed on to ``genCall``
# since the number of arguments doesn't match with the number of parameters
c.buildMagicCall m, rtyp:
for i in 1..<n.len:
arg n[i]
of mInSet:
genInSetOp(c, n)
of mEcho:
# forward the wrapped arguments to the call; don't emit the intermediate array
let x = n[1].skipConv
assert x.kind == nkBracket
c.buildCheckedMagicCall m, rtyp:
# for the convenience of later transformations, the type of the would-be
# array is passed along as the first argument
if x.len > 0:
c.emitByVal typeLit(c.typeToMir(x.typ))
for it in x.items:
arg it
of mOffsetOf:
# an offsetOf call that has to be evaluated by the backend
c.buildMagicCall mOffsetOf, rtyp:
c.builder.emitByName ekNone:
# prevent all checks and make sure that the original lvalue
# expression reaches the code generators
# XXX: this is a brittle and problematic hack. The type plus field