-
Notifications
You must be signed in to change notification settings - Fork 3
/
Instruction.cs
1549 lines (1395 loc) · 40 KB
/
Instruction.cs
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
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
namespace Wasm2CIL {
public class WebassemblyCodeParser
{
public readonly bool ElseTerminated;
public WebassemblyInstruction [] body;
private bool finished;
public int ParamCount;
public void Emit (ILGenerator ilgen, int num_params)
{
Console.WriteLine ("Emitting the following instructions");
foreach (var instr in body)
Console.WriteLine (instr.ToString ());
this.ParamCount = num_params;
var iter = BodyBuilder.GetEnumerator ();
while (true) {
var valid = iter.MoveNext ();
if (!valid)
break;
((WebassemblyInstruction) iter.Current).Emit (iter, ilgen, this);
}
}
public void Add (WebassemblyInstruction instr, ref int depth) {
if (instr == null)
throw new Exception ("Cannot add null instructions");
BodyBuilder.Add (instr);
var brancher = instr as WebassemblyControlInstruction;
if (brancher == null)
return;
if (brancher.EndsBlock ()) {
//Console.WriteLine ("End block");
// Tracks whether we've hit the extra 0x0b that marks end-of-function
depth -= 1;
if (depth != -1)
LabelStack.RemoveAt (LabelStack.Count - 1);
}
if (brancher.StartsBlock ()) {
//Console.WriteLine ("Start block");
depth += 1;
LabelStack.Add (brancher);
}
}
private int CurrLabel; // Incremented by control instructions
private List<WebassemblyInstruction> BodyBuilder;
private List<WebassemblyControlInstruction> LabelStack;
public WebassemblyCodeParser () {
BodyBuilder = new List<WebassemblyInstruction> ();
LabelStack = new List<WebassemblyControlInstruction> ();
CurrLabel = 0;
}
public WebassemblyCodeParser (BinaryReader reader): this () {
ParseExpression (reader);
FinishParsing ();
}
public WebassemblyInstruction Current ()
{
return this.BodyBuilder [this.BodyBuilder.Count - 1];
}
public void ParseExpression (BinaryReader reader)
{
int start = BodyBuilder.Count;
if (this.finished)
throw new Exception ("Expression block has already been finalized.");
// The "depth" is used to find the extra 0x0B at the end of an expression.
// When we see it and depth != 0, then it ends a block, not the function
//
// We make the nested blocks in if/else bodies without labels parse with
// the included logic as well, so an Else can also end this block
int depth = 0;
while (depth >= 0 && (reader.BaseStream.Position != reader.BaseStream.Length)) {
if (depth > LabelStack.Count)
throw new Exception (String.Format ("Depth {0} exceeds number of labels on stack {1}", depth, LabelStack.Count));
Console.WriteLine ("Depth {0} and number of labels on stack {1}", depth, LabelStack.Count);
WebassemblyInstruction result = null;
byte opcode = reader.ReadByte ();
if (opcode <= WebassemblyControlInstruction.UpperBound ()) {
// The appending is done inside the control instruction so that it can ensure ordering
// So we don't assign to result
new WebassemblyControlInstruction (opcode, reader, LabelStack, ref CurrLabel, this, ref depth);
} else if (opcode <= WebassemblyParametricInstruction.UpperBound ()) {
result = new WebassemblyParametricInstruction (opcode, reader);
} else if (opcode <= WebassemblyVariableInstruction.UpperBound ()) {
result = new WebassemblyVariableInstruction (opcode, reader);
} else if (opcode <= WebassemblyMemoryInstruction.UpperBound ()) {
result = new WebassemblyMemoryInstruction (opcode, reader);
} else if (opcode <= WebassemblyNumericInstruction.UpperBound ()) {
result = new WebassemblyNumericInstruction (opcode, reader);
} else {
throw new Exception (String.Format ("Illegal instruction {0:X}", opcode));
}
if (result != null) {
Add (result, ref depth);
}
}
Console.WriteLine ("Parsed {0} wasm instructions", BodyBuilder.Count - start);
}
public void FinishParsing ()
{
this.body = BodyBuilder.ToArray ();
this.finished = true;
}
}
// Make parser return collection of basic blocks, not instructions
public abstract class WebassemblyInstruction
{
public const byte End = 0x0b;
public const byte Else = 0x05;
public readonly byte Opcode;
//public readonly WebassemblyValueType [] StackInput;
//public readonly WebassemblyValueType [] StackOutput;
public WebassemblyInstruction (byte opcode)
{
this.Opcode = opcode;
}
protected void ShiftThisArgToFront (ILGenerator ilgen, Type [] args)
{
// Right now, we have arguments on the top of the stack.
// We need to shift them back to pass the "this" argument first
// We are going to make a scope, to give the JIT maximum visibility
// into the lifetime of the temporaries needed to make this call.
ilgen.BeginScope ();
var locals = new List<LocalBuilder> ();
// Traverse backwards, as last arg is the one that is pushed onto stack
for (int i=args.Length - 1; i >= 0; i--) {
Type ty = args [i];
LocalBuilder myLocalBuilder = ilgen.DeclareLocal(ty);
// Add backwards
locals.Add (myLocalBuilder);
ilgen.Emit (OpCodes.Stloc, myLocalBuilder);
}
// Emit load of "this" arg
ilgen.Emit (OpCodes.Ldarg_0);
// Since we added the locals backwards, we traverse
// "backwards" again, to restore the stack with "this" before all
// the args
for (int i=args.Length - 1; i >= 0; i--) {
ilgen.Emit (OpCodes.Ldloc, locals [i]);
}
ilgen.EndScope ();
}
public override abstract string ToString ();
public abstract void Emit (IEnumerator<WebassemblyInstruction> cursor, ILGenerator ilgen, WebassemblyCodeParser top_level);
}
public class WebassemblyControlInstruction : WebassemblyInstruction
{
Label label;
public readonly int? LabelIndex;
WebassemblyControlInstruction [] table;
ulong index;
ulong default_target;
Type block_type;
ulong function_index;
ulong type_index;
public WebassemblyControlInstruction dest;
bool loops;
// These are the expressions that are the
public readonly WebassemblyControlInstruction if_block;
public readonly WebassemblyControlInstruction else_block;
public readonly WebassemblyControlInstruction fallthrough_block;
public override void Emit (IEnumerator<WebassemblyInstruction> cursor, ILGenerator ilgen, WebassemblyCodeParser top_level)
{
switch (Opcode) {
case 0x0: // unreachable
// Fixme: make this catchable / offer options at exception time
ilgen.ThrowException (typeof (System.ExecutionEngineException));
return;
case 0x01: // nop
ilgen.Emit (OpCodes.Nop);
return;
case 0x02: // block
label = ilgen.DefineLabel ();
ilgen.MarkLabel (label);
return;
case 0x03: // loop
label = ilgen.DefineLabel ();
ilgen.MarkLabel (label);
return;
case 0x04: // if
var fallthrough_label = ilgen.DefineLabel ();
WebassemblyInstruction curr = cursor.Current;
if (curr != this)
throw new Exception (String.Format ("Cursor has passed us while we were emitting instruction"));
if (curr != if_block)
throw new Exception (String.Format ("if block limits not correctly parsed"));
if (this.else_block != null) {
Label else_label = ilgen.DefineLabel ();
ilgen.Emit (OpCodes.Brfalse, else_label);
Console.WriteLine ("GREP: if: {0}", this.if_block.ToString ());
Console.WriteLine ("GREP: else: {0}", this.else_block.ToString ());
Console.WriteLine ("GREP: fallthrough: {0}", this.fallthrough_block.ToString ());
while (curr != this.else_block) {
var good = cursor.MoveNext ();
if (!good)
throw new Exception ("if/else block limits not correctly parsed");
curr = cursor.Current;
curr.Emit (cursor, ilgen, top_level);
}
if (if_block == else_block)
ilgen.Emit (OpCodes.Nop);
ilgen.Emit (OpCodes.Br, fallthrough_label);
// We emit the else block
ilgen.MarkLabel (else_label);
while (curr != this.fallthrough_block) {
var good = cursor.MoveNext ();
if (!good)
throw new Exception ("Else/fallthrough block limits not correctly parsed");
curr = cursor.Current;
curr.Emit (cursor, ilgen, top_level);
}
if (else_block == fallthrough_block)
ilgen.Emit (OpCodes.Nop);
// Falls through to fallthrough by default
} else {
// No else block
Console.WriteLine ("GREP: if: {0}", this.if_block.ToString ());
Console.WriteLine ("GREP: fallthrough: {0}", this.fallthrough_block.ToString ());
ilgen.Emit (OpCodes.Brfalse, fallthrough_label);
if (if_block == fallthrough_block)
ilgen.Emit (OpCodes.Nop);
while (curr != this.fallthrough_block) {
Console.WriteLine ("Between if and fallthrough: {0} < {1}", cursor.Current.ToString (), fallthrough_block.ToString ());
var good = cursor.MoveNext ();
if (!good)
throw new Exception ("if/fallthrough block limits not correctly parsed");
curr = cursor.Current;
curr.Emit (cursor, ilgen, top_level);
}
}
// Start fallthrough symbol, for rest of code
ilgen.MarkLabel (fallthrough_label);
return;
case 0x05: // Else
ilgen.Emit (OpCodes.Nop);
return;
case 0x0b: // End
// loops fall through
if (this.dest == null && !this.loops) {
// ends function body, has implicit return
ilgen.Emit (OpCodes.Ret);
}
//else {
//ilgen.Emit (OpCodes.Nop);
//}
return;
// Br
case 0x0c:
ilgen.Emit (OpCodes.Br, this.dest.GetLabel ());
return;
// Br_if
case 0x0d:
ilgen.Emit (OpCodes.Brtrue, this.dest.GetLabel ());
return;
// Br_table
case 0x0e:
Label defaultCase = ilgen.DefineLabel();
Label endOfBlock = ilgen.DefineLabel();
var jumpTable = new Label [this.table.Length];
for (int i=0; i < this.table.Length; i++) {
jumpTable [i] = ilgen.DefineLabel();
}
ilgen.Emit (OpCodes.Switch, jumpTable);
ilgen.Emit (OpCodes.Br_S, defaultCase);
for (int i=0; i < jumpTable.Length; i++) {
// Case incoming argument is equal to i
ilgen.MarkLabel (jumpTable [i]);
ilgen.Emit (OpCodes.Br_S, this.table[i].dest.GetLabel ());
}
ilgen.MarkLabel (defaultCase);
ilgen.Emit(OpCodes.Br_S, jumpTable [Convert.ToInt32 (this.default_target)]);
ilgen.MarkLabel(endOfBlock);
return;
case 0x0f:
ilgen.Emit (OpCodes.Ret);
return;
//// Call
case 0x10:
//ilgen.Emit (OpCodes.Nop);
//return;
//case 0x11:
//return ilgen.Emit (OpCodes.Nop);
default:
throw new Exception (String.Format("Should not be reached: {0:X}", Opcode));
}
return;
}
public override string ToString ()
{
switch (Opcode) {
case 0x0:
return "unreachable";
case 0x01:
return "nop";
case 0x02:
return String.Format ("block {0} {1}", block_type, GetLabelName ());
case 0x03:
return String.Format ("loop {0} {1}", block_type, GetLabelName ());
case 0x04:
var block_type_str = "";
if (block_type != null)
block_type_str = String.Format ("Type: {0}", block_type);
return String.Format ("if {0} {1}", block_type, GetLabelName ());
case 0x05:
return "else";
case 0x0b:
if (this.dest == null)
return String.Format ("end (Of Function)");
else
return String.Format ("end {0}", this.dest.GetLabelName ());
case 0x0c:
return String.Format ("br {0}", this.dest.GetLabelName ());
case 0x0d:
return String.Format ("br_if {0}", this.dest.GetLabelName ());
case 0x0e:
return "br_table";
case 0x0f:
return "return";
case 0x10:
return String.Format ("call {0}", this.function_index);
case 0x11:
return String.Format ("call_indirect {0}", this.type_index);
default:
throw new Exception (String.Format("Should not be reached: {0:X}", Opcode));
}
}
public string GetLabelName ()
{
if (!this.StartsBlock ())
throw new Exception ("Does not create label");
if (Opcode == 0x05) {
if (this.dest != null)
return this.dest.GetLabelName ();
else
return "";
}
if (this.LabelIndex == null)
throw new Exception (String.Format ("Did not create label for 0x{0:x}", Opcode));
return String.Format ("@{0}", this.LabelIndex);
}
public Label GetLabel ()
{
if (label == null && this.StartsBlock ())
throw new Exception ("Did not emit label when traversing this instruction");
else if (label == null)
throw new Exception ("Does not create label");
else
return label;
}
public bool StartsBlock ()
{
return Opcode == 0x02 || Opcode == 0x03 || Opcode == 0x04 || Opcode == 0x05;
}
public bool EndsBlock ()
{
return Opcode == 0x0b || Opcode == 0x05;
}
public static byte UpperBound ()
{
return 0x11;
}
public WebassemblyControlInstruction (byte opcode, BinaryReader reader, List<WebassemblyControlInstruction> labels, ref int labelIndex, WebassemblyCodeParser parser, ref int depth): base (opcode)
{
switch (this.Opcode) {
case 0x0B: // end
case 0x05: // else
// dest set by if statement
break;
case 0x0: // unreachable
case 0x1: // nop
case 0x0F: // return
// No args
break;
case 0x0C: // br
case 0x0D: // br_if
{
// So these indexes are labels
// each loop, block,
// All branching is to previous labels
// This means that the most foolproof way to emit things is
// to preverse all the ordering in the initial instruction stream.
// When we emit this instruction, dest will already have had a label emitted.
this.index = Parser.ParseLEBUnsigned (reader, 32);
Console.WriteLine ("index {0}", this.index);
if (labels.Count == 0)
throw new Exception ("Branching with empty label stack!");
int offset = (labels.Count - 1) - (int) this.index;
if (offset >= labels.Count || offset < 0)
throw new Exception (String.Format ("branch label of {0} {1} {2} not acceptable", labels.Count, this.index, offset));
this.dest = labels [offset];
if (this.dest == null)
throw new Exception ("Could not find destination of jump");
break;
}
case 0x02: // block
// need to make label
this.block_type = WebassemblyResult.Convert (reader);
this.LabelIndex = labelIndex++;
this.loops = false;
break;
case 0x03: // loop
// need to make label
this.block_type = WebassemblyResult.Convert (reader);
this.LabelIndex = labelIndex++;
this.loops = true;
break;
case 0x04: // if
// Ensure this opcode comes before nested/subsequent blocks
this.LabelIndex = labelIndex++;
parser.Add (this, ref depth);
this.block_type = WebassemblyResult.Convert (reader);
// We have a stack of "expressions" we are writing to
//public readonly WebassemblyInstruction [] body;
this.if_block = this;
parser.ParseExpression (reader);
if (parser.Current ().Opcode == 0x05) {
this.else_block = (WebassemblyControlInstruction) parser.Current ();
this.else_block.dest = this.if_block;
Console.WriteLine ("Else is {0}", this.else_block.ToString ());
parser.ParseExpression (reader);
}
this.fallthrough_block = (WebassemblyControlInstruction) parser.Current ();
if (this.fallthrough_block.Opcode != 0x0B)
throw new Exception (String.Format ("If statement terminated with illegal opcode 0x0{0:X}", parser.Current ().Opcode));
this.fallthrough_block.dest = this.if_block;
Console.WriteLine ("Fallthrough is {0}", this.fallthrough_block.ToString ());
return; // Don't double-add the instruction
case 0x0e: // br_table
// works by getting index from stack. If index is in range of table,
// we jump to the label at that index. Else go to default.
var jump_labels = Parser.ParseLEBUnsignedArray (reader);
this.table = new WebassemblyControlInstruction [jump_labels.Length];
if (labels.Count == 0)
throw new Exception ("Branching with empty label stack!");
for (int i=0; i < jump_labels.Length; i++) {
// The entry for the switch statement has an index that defines the
// label of the block to jump to there. It is a reverse count from
// the current block, much like all other BR opcodes
int offset = (labels.Count () - 1) - (int) jump_labels [i];
this.table [i] = labels [offset];
if (this.table [i] == null)
throw new Exception ("Could not find destination of jump table");
}
this.default_target = Parser.ParseLEBUnsigned (reader, 32);;
break;
case 0x10: //call
this.function_index = Parser.ParseLEBUnsigned (reader, 32);
break;
case 0x11: //call indirect
this.type_index = Parser.ParseLEBUnsigned (reader, 32);
var endcap = Parser.ParseLEBUnsigned (reader, 32);
if (endcap != 0x0)
throw new Exception ("Call indirect call not ended with 0x0");
break;
default:
throw new Exception (String.Format ("Control instruction out of range {0:X}", this.Opcode));
}
// Ensure this opcode comes before nested/subsequent blocks
parser.Add (this, ref depth);
}
}
public class WebassemblyParametricInstruction : WebassemblyInstruction
{
public static byte UpperBound ()
{
return 0x1B;
}
public override void Emit (IEnumerator<WebassemblyInstruction> cursor, ILGenerator ilgen, WebassemblyCodeParser top_level)
{
throw new Exception (String.Format("Should not be reached: {0:X}", Opcode));
}
public override string ToString ()
{
switch (Opcode) {
case 0x1a:
// CIL: pop
return "drop";
case 0x1b:
// CIL: dup + pop
return "select";
default:
throw new Exception (String.Format("Should not be reached: {0:X}", Opcode));
}
}
public WebassemblyParametricInstruction (byte opcode, BinaryReader reader): base (opcode)
{
if (this.Opcode != 0x1A && this.Opcode <= 0x1B) {
throw new Exception ("Parametric opcode out of range");
}
}
}
public class WebassemblyVariableInstruction : WebassemblyInstruction
{
// If the index is lower than the number of parameters, this is a
// local reference, else it is a parameter reference
ulong index;
void EmitGetter (ILGenerator ilgen, int num_params)
{
// Fixme: use packed encodings (_s) and the opcodes that mention the index
if ((int) index < num_params) {
Console.WriteLine ("ldarg {0}", index);
// The +1 is because the first argument is the "this" argument
switch (index) {
case 0:
ilgen.Emit (OpCodes.Ldarg_1);
break;
case 1:
ilgen.Emit (OpCodes.Ldarg_2);
break;
case 2:
ilgen.Emit (OpCodes.Ldarg_3);
break;
default:
throw new Exception ("Should not be reached");
break;
}
} else {
//Console.WriteLine ("ldloc {0}", labelIndex);
int labelIndex = (int) index - num_params;
switch (labelIndex) {
case 0:
ilgen.Emit (OpCodes.Ldloc_0);
break;
case 1:
ilgen.Emit (OpCodes.Ldloc_1);
break;
case 2:
ilgen.Emit (OpCodes.Ldloc_2);
break;
case 3:
ilgen.Emit (OpCodes.Ldloc_3);
break;
default:
ilgen.Emit (OpCodes.Ldloc, labelIndex);
break;
}
}
}
void EmitSetter (ILGenerator ilgen, int num_params)
{
// Fixme: use packed encodings (_s) and the opcodes that mention the index
if ((int) index < num_params) {
ilgen.Emit (OpCodes.Starg, index);
//Console.WriteLine ("starg {0}", index);
return;
} else {
//Console.WriteLine ("stloc {0}", labelIndex);
int labelIndex = (int) index - num_params;
ilgen.Emit (OpCodes.Stloc, labelIndex);
}
}
public override void Emit (IEnumerator<WebassemblyInstruction> cursor, ILGenerator ilgen, WebassemblyCodeParser top_level)
{
switch (Opcode) {
case 0x20:
EmitGetter (ilgen, top_level.ParamCount);
return;
case 0x21:
EmitSetter (ilgen, top_level.ParamCount);
return;
case 0x22:
EmitSetter (ilgen, top_level.ParamCount);
EmitGetter (ilgen, top_level.ParamCount);
return;
//case 0x23:
//return String.Format ("get_global {0}", index);
//case 0x24:
//return String.Format ("set_global {0}", index);
default:
throw new Exception (String.Format("Should not be reached: {0:X}", Opcode));
}
}
public override string ToString ()
{
switch (Opcode) {
case 0x20:
return String.Format ("get_local {0}", index);
case 0x21:
return String.Format ("set_local {0}", index);
case 0x22:
return String.Format ("tee_local {0}", index);
case 0x23:
return String.Format ("get_global {0}", index);
case 0x24:
return String.Format ("set_global {0}", index);
default:
throw new Exception (String.Format("Should not be reached: {0:X}", Opcode));
}
}
public static byte UpperBound ()
{
return 0x24;
}
public WebassemblyVariableInstruction (byte opcode, BinaryReader reader): base (opcode)
{
if (this.Opcode >= 0x20 && this.Opcode <= 0x24) {
this.index = Parser.ParseLEBUnsigned (reader, 32);
} else if (this.Opcode > 0x24) {
throw new Exception ("Variable opcode out of range");
}
}
}
public class WebassemblyMemoryInstruction : WebassemblyInstruction
{
ulong align;
ulong offset;
public override void Emit (IEnumerator<WebassemblyInstruction> cursor, ILGenerator ilgen, WebassemblyCodeParser top_level)
{
String method;
switch (Opcode) {
case 0x28:
method = "Load32BitAsSigned32";
break;
case 0x29:
method = "Load64BitAsSigned64";
break;
case 0x2a:
method = "LoadSingle";
break;
case 0x2b:
method = "LoadDouble";
break;
case 0x2c:
method = "LoadSigned8BitAsSigned32";
break;
case 0x2d:
method = "LoadUnsigned8BitAsSigned32";
break;
case 0x2e:
method = "LoadSigned16BitAsSigned32";
break;
case 0x2f:
method = "LoadUnsigned16BitAsSigned32";
break;
case 0x30:
method = "LoadSigned8BitAsSigned64";
break;
case 0x31:
method = "LoadUnsigned8BitAsSigned64";
break;
case 0x32:
method = "LoadSigned16BitAsSigned64";
break;
case 0x33:
method = "LoadUnsigned16BitAsSigned64";
break;
case 0x34:
method = "LoadSigned32BitAsSigned64";
break;
case 0x35:
method = "LoadUnsigned32BitAsSigned64";
break;
case 0x36:
method = "Store32BitFrom32";
break;
case 0x37:
method = "Store64BitFrom32";
break;
case 0x38:
method = "StoreSingle";
break;
case 0x39:
method = "StoreDouble";
break;
case 0x3a:
method = "Store8BitFrom32";
break;
case 0x3b:
method = "Store16BitFrom32";
break;
case 0x3c:
method = "Store8BitFrom64";
break;
case 0x3d:
method = "Store16BitFrom64";
break;
case 0x3e:
method = "Store32BitFrom64";
break;
case 0x3f:
method = "CurrentMemory";
break;
case 0x40:
method = "GrowMemory";
break;
default:
throw new Exception (String.Format("Should not be reached: {0:X}", Opcode));
}
// Our opcode has an offset to apply to this address on top of the stack
// FIXME: we ignore alignment
ilgen.Emit (OpCodes.Ldc_I4, Convert.ToInt32 (offset));
ilgen.Emit (OpCodes.Add);
// Now we want to set ourselves up for a call
var method_info = typeof (WebassemblyModule).GetMethod (method, BindingFlags.Instance | BindingFlags.NonPublic);
if (method_info == null)
throw new Exception (String.Format("Could not find {0} in runtime", method));
var call_types = new List<Type> ();
foreach (var param_info in method_info.GetParameters ())
call_types.Add (param_info.ParameterType);
ShiftThisArgToFront (ilgen, call_types.ToArray ());
ilgen.Emit(OpCodes.Call, method_info);
return;
}
public override string ToString ()
{
switch (Opcode) {
case 0x28:
return String.Format ("i32.load {0} {1}", this.align, this.offset);
case 0x29:
return String.Format ("i64.load {0} {1}", this.align, this.offset);
case 0x2a:
return String.Format ("f32.load {0} {1}", this.align, this.offset);
case 0x2b:
return String.Format ("f64.load {0} {1}", this.align, this.offset);
case 0x2c:
return String.Format ("i32.load8_s {0} {1}", this.align, this.offset);
case 0x2d:
return String.Format ("i32.load8_u {0} {1}", this.align, this.offset);
case 0x2e:
return String.Format ("i32.load16_s {0} {1}", this.align, this.offset);
case 0x2f:
return String.Format ("i32.load16_u {0} {1}", this.align, this.offset);
case 0x30:
return String.Format ("i64.load8_s {0} {1}", this.align, this.offset);
case 0x31:
return String.Format ("i64.load8_u {0} {1}", this.align, this.offset);
case 0x32:
return String.Format ("i64.load16_s {0} {1}", this.align, this.offset);
case 0x33:
return String.Format ("i64.load16_u {0} {1}", this.align, this.offset);
case 0x34:
return String.Format ("i64.load32_s {0} {1}", this.align, this.offset);
case 0x35:
return String.Format ("i64.load32_u {0} {1}", this.align, this.offset);
case 0x36:
return String.Format ("i32.store {0} {1}", this.align, this.offset);
case 0x37:
return String.Format ("i64.store {0} {1}", this.align, this.offset);
case 0x38:
return String.Format ("f32.store {0} {1}", this.align, this.offset);
case 0x39:
return String.Format ("f64.store {0} {1}", this.align, this.offset);
case 0x3a:
return String.Format ("i32.store8 {0} {1}", this.align, this.offset);
case 0x3b:
return String.Format ("i32.store16 {0} {1}", this.align, this.offset);
case 0x3c:
return String.Format ("i64.store8 {0} {1}", this.align, this.offset);
case 0x3d:
return String.Format ("i64.store16 {0} {1}", this.align, this.offset);
case 0x3e:
return String.Format ("i64.store32 {0} {1}", this.align, this.offset);
case 0x3f:
return "current_memory";
case 0x40:
return "grow_memory";
default:
throw new Exception (String.Format("Should not be reached: {0:X}", Opcode));
}
}
public static byte UpperBound ()
{
return 0x40;
}
public WebassemblyMemoryInstruction (byte opcode, BinaryReader reader): base (opcode)
{
if (this.Opcode >= 0x28 && this.Opcode <= 0x3E) {
this.align = Parser.ParseLEBUnsigned (reader, 32);
this.offset = Parser.ParseLEBUnsigned (reader, 32);
} else if (this.Opcode == 0x3F || this.Opcode == 0x40) {
var endcap = reader.ReadByte ();
if (endcap != 0x0)
throw new Exception ("Memory size instruction lackend null endcap");
} else if (this.Opcode > 0x40) {
throw new Exception ("Memory opcode out of range");
}
}
}
public class WebassemblyNumericInstruction : WebassemblyInstruction
{
public override void Emit (IEnumerator<WebassemblyInstruction> cursor, ILGenerator ilgen, WebassemblyCodeParser top_level)
{
switch (Opcode) {
case 0x41:
switch (operand_i32) {
case 0:
ilgen.Emit (OpCodes.Ldc_I4_0);
break;
case 1:
ilgen.Emit (OpCodes.Ldc_I4_1);
break;
case 2:
ilgen.Emit (OpCodes.Ldc_I4_2);
break;
case 3:
ilgen.Emit (OpCodes.Ldc_I4_3);
break;
case 4:
ilgen.Emit (OpCodes.Ldc_I4_4);
break;
case 5:
ilgen.Emit (OpCodes.Ldc_I4_5);
break;
case 6:
ilgen.Emit (OpCodes.Ldc_I4_6);
break;
case 7:
ilgen.Emit (OpCodes.Ldc_I4_7);
break;
case 8:
ilgen.Emit (OpCodes.Ldc_I4_8);
break;
default:
ilgen.Emit (OpCodes.Ldc_I4, operand_i32);
break;
}
return;
case 0x42:
ilgen.Emit (OpCodes.Ldc_I8, operand_i64);
return;
case 0x43:
ilgen.Emit (OpCodes.Ldc_R4, operand_f32);
return;
case 0x44:
ilgen.Emit (OpCodes.Ldc_R8, operand_f64);
return;
case 0x45:
ilgen.Emit (OpCodes.Ldc_I4_0);
ilgen.Emit (OpCodes.Ceq);
return;
case 0x46:
ilgen.Emit (OpCodes.Ceq);
return;
case 0x47:
ilgen.Emit (OpCodes.Ceq);
ilgen.Emit (OpCodes.Neg);
return;
case 0x48:
ilgen.Emit (OpCodes.Clt);
return;
case 0x49:
ilgen.Emit (OpCodes.Clt_Un);
return;
case 0x4a:
ilgen.Emit (OpCodes.Cgt);
return;
case 0x4b:
ilgen.Emit (OpCodes.Cgt_Un);
return;
//case 0x4c:
//// Less than or equal, signed
//// first - last > 0
//// sub.ovf.un
//return "i32.le_s";
//case 0x4d:
//// Less than or equal, unsigned
//// first - last > 0
//// sub.ovf.un
//return "i32.le_u";
//case 0x4e: