summaryrefslogtreecommitdiff
path: root/Source/JavaScriptCore/b3/air/opcode_generator.rb
blob: d14240515051c7ff68375264acc67ec28e2d3088 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
#!/usr/bin/env ruby

# Copyright (C) 2015-2016 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE.

require "pathname"

class Opcode
    attr_reader :name, :custom, :overloads
    attr_reader :attributes

    def initialize(name, custom)
        @name = name
        @custom = custom
        @attributes = {}
        unless custom
            @overloads = []
        end
    end

    def masmName
        name[0].downcase + name[1..-1]
    end
end

class Arg
    attr_reader :role, :type, :width

    def initialize(role, type, width)
        @role = role
        @type = type
        @width = width
    end

    def widthCode
        if width == "Ptr"
            "Arg::pointerWidth()"
        else
            "Arg::Width#{width}"
        end
    end
end

class Overload
    attr_reader :signature, :forms

    def initialize(signature, forms)
        @signature = signature
        @forms = forms
    end
end

class Kind
    attr_reader :name
    attr_accessor :custom

    def initialize(name)
        @name = name
        @custom = false
    end

    def ==(other)
        if other.is_a? String
            @name == other
        else
            @name == other.name and @custom == other.custom
        end
    end

    def Kind.argKinds(kind)
        if kind == "Addr"
            ["Addr", "Stack", "CallArg"]
        else
            [kind]
        end
    end

    def argKinds
        Kind.argKinds(kind)
    end
end

class Form
    attr_reader :kinds, :altName, :archs

    def initialize(kinds, altName, archs)
        @kinds = kinds
        @altName = altName
        @archs = archs
    end
end

class Origin
    attr_reader :fileName, :lineNumber
    
    def initialize(fileName, lineNumber)
        @fileName = fileName
        @lineNumber = lineNumber
    end
    
    def to_s
        "#{fileName}:#{lineNumber}"
    end
end

class Token
    attr_reader :origin, :string
    
    def initialize(origin, string)
        @origin = origin
        @string = string
    end
    
    def ==(other)
        if other.is_a? Token
            @string == other.string
        else
            @string == other
        end
    end
    
    def =~(other)
        @string =~ other
    end
    
    def to_s
        "#{@string.inspect} at #{origin}"
    end
    
    def parseError(*comment)
        if comment.empty?
            raise "Parse error: #{to_s}"
        else
            raise "Parse error: #{to_s}: #{comment[0]}"
        end
    end
end

def lex(str, fileName)
    fileName = Pathname.new(fileName)
    result = []
    lineNumber = 1
    while not str.empty?
        case str
        when /\A\#([^\n]*)/
            # comment, ignore
        when /\A\n/
            # newline, ignore
            lineNumber += 1
        when /\A([a-zA-Z0-9_]+)/
            result << Token.new(Origin.new(fileName, lineNumber), $&)
        when /\A([ \t\r]+)/
            # whitespace, ignore
        when /\A[,:*\/]/
            result << Token.new(Origin.new(fileName, lineNumber), $&)
        else
            raise "Lexer error at #{Origin.new(fileName, lineNumber).to_s}, unexpected sequence #{str[0..20].inspect}"
        end
        str = $~.post_match
    end
    result
end

def isRole(token)
    token =~ /\A((U)|(D)|(UD)|(ZD)|(UZD)|(UA)|(S))\Z/
end

def isGF(token)
    token =~ /\A((G)|(F))\Z/
end

def isKind(token)
    token =~ /\A((Tmp)|(Imm)|(BigImm)|(BitImm)|(BitImm64)|(Addr)|(Index)|(RelCond)|(ResCond)|(DoubleCond))\Z/
end

def isArch(token)
    token =~ /\A((x86)|(x86_32)|(x86_64)|(arm)|(armv7)|(arm64)|(32)|(64))\Z/
end

def isWidth(token)
    token =~ /\A((8)|(16)|(32)|(64)|(Ptr))\Z/
end

def isKeyword(token)
    isRole(token) or isGF(token) or isKind(token) or isArch(token) or isWidth(token) or
        token == "custom" or token == "as"
end

def isIdentifier(token)
    token =~ /\A([a-zA-Z0-9_]+)\Z/ and not isKeyword(token)
end

class Parser
    def initialize(data, fileName)
        @tokens = lex(data, fileName)
        @idx = 0
    end

    def token
        @tokens[@idx]
    end

    def advance
        @idx += 1
    end

    def parseError(*comment)
        if token
            token.parseError(*comment)
        else
            if comment.empty?
                raise "Parse error at end of file"
            else
                raise "Parse error at end of file: #{comment[0]}"
            end
        end
    end

    def consume(string)
        parseError("Expected #{string}") unless token == string
        advance
    end

    def consumeIdentifier
        result = token.string
        parseError("Expected identifier") unless isIdentifier(result)
        advance
        result
    end

    def consumeRole
        result = token.string
        parseError("Expected role (U, D, UD, ZD, UZD, UA, or S)") unless isRole(result)
        advance
        result
    end

    def consumeType
        result = token.string
        parseError("Expected type (G or F)") unless isGF(result)
        advance
        result
    end

    def consumeKind
        result = token.string
        parseError("Expected kind (Imm, BigImm, BitImm, BitImm64, Tmp, Addr, Index, RelCond, ResCond, or DoubleCond)") unless isKind(result)
        advance
        result
    end

    def consumeWidth
        result = token.string
        parseError("Expected width (8, 16, 32, or 64)") unless isWidth(result)
        advance
        result
    end

    def parseArchs
        return nil unless isArch(token)

        result = []
        while isArch(token)
            case token.string
            when "x86"
                result << "X86"
                result << "X86_64"
            when "x86_32"
                result << "X86"
            when "x86_64"
                result << "X86_64"
            when "arm"
                result << "ARMv7"
                result << "ARM64"
            when "armv7"
                result << "ARMv7"
            when "arm64"
                result << "ARM64"
            when "32"
                result << "X86"
                result << "ARMv7"
            when "64"
                result << "X86_64"
                result << "ARM64"
            else
                raise token.string
            end
            advance
        end

        consume(":")
        @lastArchs = result
    end

    def consumeArchs
        result = @lastArchs
        @lastArchs = nil
        result
    end

    def parseAndConsumeArchs
        parseArchs
        consumeArchs
    end

    def intersectArchs(left, right)
        return left unless right
        return right unless left

        left.select {
            | value |
            right.find {
                | otherValue |
                value == otherValue
            }
        }
    end

    def parse
        result = {}
        
        loop {
            break if @idx >= @tokens.length

            if token == "custom"
                consume("custom")
                opcodeName = consumeIdentifier

                parseError("Cannot overload a custom opcode") if result[opcodeName]

                result[opcodeName] = Opcode.new(opcodeName, true)
            else
                opcodeArchs = parseAndConsumeArchs

                opcodeName = consumeIdentifier

                if result[opcodeName]
                    opcode = result[opcodeName]
                    parseError("Cannot overload a custom opcode") if opcode.custom
                else
                    opcode = Opcode.new(opcodeName, false)
                    result[opcodeName] = opcode
                end

                signature = []
                forms = []
                
                if isRole(token)
                    loop {
                        role = consumeRole
                        consume(":")
                        type = consumeType
                        consume(":")
                        width = consumeWidth
                        
                        signature << Arg.new(role, type, width)
                        
                        break unless token == ","
                        consume(",")
                    }
                end

                while token == "/"
                    consume("/")
                    case token.string
                    when "branch"
                        opcode.attributes[:branch] = true
                        opcode.attributes[:terminal] = true
                    when "terminal"
                        opcode.attributes[:terminal] = true
                    when "effects"
                        opcode.attributes[:effects] = true
                    when "return"
                        opcode.attributes[:return] = true
                        opcode.attributes[:terminal] = true
                    else
                        parseError("Bad / directive")
                    end
                    advance
                end

                parseArchs
                if isKind(token)
                    loop {
                        kinds = []
                        altName = nil
                        formArchs = consumeArchs
                        loop {
                            kinds << Kind.new(consumeKind)

                            if token == "*"
                                parseError("Can only apply * to Tmp") unless kinds[-1].name == "Tmp"
                                kinds[-1].custom = true
                                consume("*")
                            end

                            break unless token == ","
                            consume(",")
                        }

                        if token == "as"
                            consume("as")
                            altName = consumeIdentifier
                        end

                        parseError("Form has wrong number of arguments for overload") unless kinds.length == signature.length
                        kinds.each_with_index {
                            | kind, index |
                            if kind.name == "Imm" or kind.name == "BigImm" or kind.name == "BitImm" or kind.name == "BitImm64"
                                if signature[index].role != "U"
                                    parseError("Form has an immediate for a non-use argument")
                                end
                                if signature[index].type != "G"
                                    parseError("Form has an immediate for a non-general-purpose argument")
                                end
                            end
                        }
                        forms << Form.new(kinds, altName, intersectArchs(opcodeArchs, formArchs))

                        parseArchs
                        break unless isKind(token)
                    }
                end

                if signature.length == 0
                    raise unless forms.length == 0
                    forms << Form.new([], nil, opcodeArchs)
                end

                opcode.overloads << Overload.new(signature, forms)
            end
        }

        result
    end
end

$fileName = ARGV[0]

parser = Parser.new(IO::read($fileName), $fileName)
$opcodes = parser.parse

def writeH(filename)
    File.open("Air#{filename}.h", "w") {
        | outp |
        
        outp.puts "// Generated by opcode_generator.rb from #{$fileName} -- do not edit!"
        
        outp.puts "#ifndef Air#{filename}_h"
        outp.puts "#define Air#{filename}_h"

        yield outp
        
        outp.puts "#endif // Air#{filename}_h"
    }
end

writeH("Opcode") {
    | outp |
    outp.puts "namespace JSC { namespace B3 { namespace Air {"
    outp.puts "enum Opcode : int16_t {"
    $opcodes.keys.sort.each {
        | opcode |
        outp.puts "    #{opcode},"
    }
    outp.puts "};"

    outp.puts "static const unsigned numOpcodes = #{$opcodes.keys.size};"
    outp.puts "} } } // namespace JSC::B3::Air"
    
    outp.puts "namespace WTF {"
    outp.puts "class PrintStream;"
    outp.puts "JS_EXPORT_PRIVATE void printInternal(PrintStream&, JSC::B3::Air::Opcode);"
    outp.puts "} // namespace WTF"
}

# From here on, we don't try to emit properly indented code, since we're using a recursive pattern
# matcher.

def matchForms(outp, speed, forms, columnIndex, columnGetter, filter, callback)
    return if forms.length == 0

    if filter[forms]
        return
    end

    if columnIndex >= forms[0].kinds.length
        raise "Did not reduce to one form: #{forms.inspect}" unless forms.length == 1
        callback[forms[0]]
        outp.puts "break;"
        return
    end
    
    groups = {}
    forms.each {
        | form |
        kind = form.kinds[columnIndex].name
        if groups[kind]
            groups[kind] << form
        else
            groups[kind] = [form]
        end
    }

    if speed == :fast and groups.length == 1
        matchForms(outp, speed, forms, columnIndex + 1, columnGetter, filter, callback)
        return
    end

    outp.puts "switch (#{columnGetter[columnIndex]}) {"
    groups.each_pair {
        | key, value |
        outp.puts "#if USE(JSVALUE64)" if key == "BigImm" or key == "BitImm64"
        Kind.argKinds(key).each {
            | argKind |
            outp.puts "case Arg::#{argKind}:"
        }
        matchForms(outp, speed, value, columnIndex + 1, columnGetter, filter, callback)
        outp.puts "break;"
        outp.puts "#endif // USE(JSVALUE64)" if key == "BigImm" or key == "BitImm64"
    }
    outp.puts "default:"
    outp.puts "break;"
    outp.puts "}"
end

def matchInstOverload(outp, speed, inst)
    outp.puts "switch (#{inst}->kind.opcode) {"
    $opcodes.values.each {
        | opcode |
        outp.puts "case #{opcode.name}:"
        if opcode.custom
            yield opcode, nil
        else
            needOverloadSwitch = ((opcode.overloads.size != 1) or speed == :safe)
            outp.puts "switch (#{inst}->args.size()) {" if needOverloadSwitch
            opcode.overloads.each {
                | overload |
                outp.puts "case #{overload.signature.length}:" if needOverloadSwitch
                yield opcode, overload
                outp.puts "break;" if needOverloadSwitch
            }
            if needOverloadSwitch
                outp.puts "default:"
                outp.puts "break;"
                outp.puts "}"
            end
        end
        outp.puts "break;"
    }
    outp.puts "default:"
    outp.puts "break;"
    outp.puts "}"
end
    
def matchInstOverloadForm(outp, speed, inst)
    matchInstOverload(outp, speed, inst) {
        | opcode, overload |
        if opcode.custom
            yield opcode, nil, nil
        else
            columnGetter = proc {
                | columnIndex |
                "#{inst}->args[#{columnIndex}].kind()"
            }
            filter = proc { false }
            callback = proc {
                | form |
                yield opcode, overload, form
            }
            matchForms(outp, speed, overload.forms, 0, columnGetter, filter, callback)
        end
    }
end

def beginArchs(outp, archs)
    return unless archs
    if archs.empty?
        outp.puts "#if 0"
        return
    end
    outp.puts("#if " + archs.map {
                  | arch |
                  "CPU(#{arch})"
              }.join(" || "))
end

def endArchs(outp, archs)
    return unless archs
    outp.puts "#endif"
end

writeH("OpcodeUtils") {
    | outp |
    outp.puts "#include \"AirCustom.h\""
    outp.puts "#include \"AirInst.h\""
    outp.puts "namespace JSC { namespace B3 { namespace Air {"
    
    outp.puts "inline bool opgenHiddenTruth() { return true; }"
    outp.puts "template<typename T>"
    outp.puts "inline T* opgenHiddenPtrIdentity(T* pointer) { return pointer; }"
    outp.puts "#define OPGEN_RETURN(value) do {\\"
    outp.puts "    if (opgenHiddenTruth())\\"
    outp.puts "        return value;\\"
    outp.puts "} while (false)"

    outp.puts "template<typename Functor>"
    outp.puts "void Inst::forEachArg(const Functor& functor)"
    outp.puts "{"
    matchInstOverload(outp, :fast, "this") {
        | opcode, overload |
        if opcode.custom
            outp.puts "#{opcode.name}Custom::forEachArg(*this, functor);"
        else
            overload.signature.each_with_index {
                | arg, index |
                
                role = nil
                case arg.role
                when "U"
                    role = "Use"
                when "D"
                    role = "Def"
                when "ZD"
                    role = "ZDef"
                when "UD"
                    role = "UseDef"
                when "UZD"
                    role = "UseZDef"
                when "UA"
                    role = "UseAddr"
                when "S"
                    role = "Scratch"
                else
                    raise
                end

                outp.puts "functor(args[#{index}], Arg::#{role}, Arg::#{arg.type}P, #{arg.widthCode});"
            }
        end
    }
    outp.puts "}"

    outp.puts "template<typename... Arguments>"
    outp.puts "ALWAYS_INLINE bool isValidForm(Opcode opcode, Arguments... arguments)"
    outp.puts "{"
    outp.puts "Arg::Kind kinds[sizeof...(Arguments)] = { arguments... };"
    outp.puts "switch (opcode) {"
    $opcodes.values.each {
        | opcode |
        outp.puts "case #{opcode.name}:"
        if opcode.custom
            outp.puts "OPGEN_RETURN(#{opcode.name}Custom::isValidFormStatic(arguments...));"
        else
            outp.puts "switch (sizeof...(Arguments)) {"
            opcode.overloads.each {
                | overload |
                outp.puts "case #{overload.signature.length}:"
                columnGetter = proc { | columnIndex | "opgenHiddenPtrIdentity(kinds)[#{columnIndex}]" }
                filter = proc { false }
                callback = proc {
                    | form |
                    # This conservatively says that Stack is not a valid form for UseAddr,
                    # because it's only valid if it's not a spill slot. This is consistent with
                    # isValidForm() being conservative and it also happens to be practical since
                    # we don't really use isValidForm for deciding when Stack is safe.
                    overload.signature.length.times {
                        | index |
                        if overload.signature[index].role == "UA"
                            outp.puts "if (opgenHiddenPtrIdentity(kinds)[#{index}] == Arg::Stack)"
                            outp.puts "    return false;"
                        end
                    }
                    
                    notCustom = (not form.kinds.detect { | kind | kind.custom })
                    if notCustom
                        beginArchs(outp, form.archs)
                        outp.puts "OPGEN_RETURN(true);"
                        endArchs(outp, form.archs)
                    end
                }
                matchForms(outp, :safe, overload.forms, 0, columnGetter, filter, callback)
                outp.puts "break;"
            }
            outp.puts "default:"
            outp.puts "break;"
            outp.puts "}"
        end
        outp.puts "break;"
    }
    outp.puts "default:"
    outp.puts "break;"
    outp.puts "}"
    outp.puts "return false; "
    outp.puts "}"

    outp.puts "inline bool isDefinitelyTerminal(Opcode opcode)"
    outp.puts "{"
    outp.puts "switch (opcode) {"
    didFindTerminals = false
    $opcodes.values.each {
        | opcode |
        if opcode.attributes[:terminal]
            outp.puts "case #{opcode.name}:"
            didFindTerminals = true
        end
    }
    if didFindTerminals
        outp.puts "return true;"
    end
    outp.puts "default:"
    outp.puts "return false;"
    outp.puts "}"
    outp.puts "}"

    outp.puts "inline bool isReturn(Opcode opcode)"
    outp.puts "{"
    outp.puts "switch (opcode) {"
    didFindReturns = false
    $opcodes.values.each {
        | opcode |
        if opcode.attributes[:return]
            outp.puts "case #{opcode.name}:"
            didFindReturns = true
        end
    }
    if didFindReturns
        outp.puts "return true;"
    end
    outp.puts "default:"
    outp.puts "return false;"
    outp.puts "}"
    outp.puts "}"
    
    outp.puts "} } } // namespace JSC::B3::Air"
}

writeH("OpcodeGenerated") {
    | outp |
    outp.puts "#include \"AirInstInlines.h\""
    outp.puts "#include \"wtf/PrintStream.h\""
    outp.puts "namespace WTF {"
    outp.puts "using namespace JSC::B3::Air;"
    outp.puts "void printInternal(PrintStream& out, Opcode opcode)"
    outp.puts "{"
    outp.puts "    switch (opcode) {"
    $opcodes.keys.each {
        | opcode |
        outp.puts "    case #{opcode}:"
        outp.puts "        out.print(\"#{opcode}\");"
        outp.puts "        return;"
    }
    outp.puts "    }"
    outp.puts "    RELEASE_ASSERT_NOT_REACHED();"
    outp.puts "}"
    outp.puts "} // namespace WTF"
    outp.puts "namespace JSC { namespace B3 { namespace Air {"
    outp.puts "bool Inst::isValidForm()"
    outp.puts "{"
    matchInstOverloadForm(outp, :safe, "this") {
        | opcode, overload, form |
        if opcode.custom
            outp.puts "OPGEN_RETURN(#{opcode.name}Custom::isValidForm(*this));"
        else
            beginArchs(outp, form.archs)
            needsMoreValidation = false
            overload.signature.length.times {
                | index |
                arg = overload.signature[index]
                kind = form.kinds[index]
                needsMoreValidation |= kind.custom

                # Some kinds of Args reqire additional validation.
                case kind.name
                when "Tmp"
                    outp.puts "if (!args[#{index}].tmp().is#{arg.type}P())"
                    outp.puts "OPGEN_RETURN(false);"
                when "Imm"
                    outp.puts "if (!Arg::isValidImmForm(args[#{index}].value()))"
                    outp.puts "OPGEN_RETURN(false);"
                when "BitImm"
                    outp.puts "if (!Arg::isValidBitImmForm(args[#{index}].value()))"
                    outp.puts "OPGEN_RETURN(false);"
                when "BitImm64"
                    outp.puts "if (!Arg::isValidBitImm64Form(args[#{index}].value()))"
                    outp.puts "OPGEN_RETURN(false);"
                when "Addr"
                    if arg.role == "UA"
                        outp.puts "if (args[#{index}].isStack() && args[#{index}].stackSlot()->isSpill())"
                        outp.puts "OPGEN_RETURN(false);"
                    end
                    
                    outp.puts "if (!Arg::isValidAddrForm(args[#{index}].offset()))"
                    outp.puts "OPGEN_RETURN(false);"
                when "Index"
                    outp.puts "if (!Arg::isValidIndexForm(args[#{index}].scale(), args[#{index}].offset(), #{arg.widthCode}))"
                    outp.puts "OPGEN_RETURN(false);"
                when "BigImm"
                when "RelCond"
                when "ResCond"
                when "DoubleCond"
                else
                    raise "Unexpected kind: #{kind.name}"
                end
            }
            if needsMoreValidation
                outp.puts "if (!is#{opcode.name}Valid(*this))"
                outp.puts "OPGEN_RETURN(false);"
            end
            outp.puts "OPGEN_RETURN(true);"
            endArchs(outp, form.archs)
        end
    }
    outp.puts "return false;"
    outp.puts "}"

    outp.puts "bool Inst::admitsStack(unsigned argIndex)"
    outp.puts "{"
    outp.puts "switch (kind.opcode) {"
    $opcodes.values.each {
        | opcode |
        outp.puts "case #{opcode.name}:"

        if opcode.custom
            outp.puts "OPGEN_RETURN(#{opcode.name}Custom::admitsStack(*this, argIndex));"
        else
            # Switch on the argIndex.
            outp.puts "switch (argIndex) {"

            numArgs = opcode.overloads.map {
                | overload |
                overload.signature.length
            }.max
            
            numArgs.times {
                | argIndex |
                outp.puts "case #{argIndex}:"

                # Check if all of the forms of all of the overloads either do, or don't, admit an address
                # at this index. We expect this to be a very common case.
                numYes = 0
                numNo = 0
                opcode.overloads.each {
                    | overload |
                    useAddr = (overload.signature[argIndex] and
                               overload.signature[argIndex].role == "UA")
                    overload.forms.each {
                        | form |
                        if form.kinds[argIndex] == "Addr" and not useAddr
                            numYes += 1
                        else
                            numNo += 1
                        end
                    }
                }

                # Note that we deliberately test numYes first because if we end up with no forms, we want
                # to say that Address is inadmissible.
                if numYes == 0
                    outp.puts "OPGEN_RETURN(false);"
                elsif numNo == 0
                    outp.puts "OPGEN_RETURN(true);"
                else
                    # Now do the full test.

                    needOverloadSwitch = (opcode.overloads.size != 1)

                    outp.puts "switch (args.size()) {" if needOverloadSwitch
                    opcode.overloads.each {
                        | overload |

                        useAddr = (overload.signature[argIndex] and
                                   overload.signature[argIndex].role == "UA")
                        
                        # Again, check if all of them do what we want.
                        numYes = 0
                        numNo = 0
                        overload.forms.each {
                            | form |
                            if form.kinds[argIndex] == "Addr" and not useAddr
                                numYes += 1
                            else
                                numNo += 1
                            end
                        }

                        if numYes == 0
                            # Don't emit anything, just drop to default.
                        elsif numNo == 0
                            outp.puts "case #{overload.signature.length}:" if needOverloadSwitch
                            outp.puts "OPGEN_RETURN(true);"
                            outp.puts "break;" if needOverloadSwitch
                        else
                            outp.puts "case #{overload.signature.length}:" if needOverloadSwitch

                            # This is how we test the hypothesis that changing this argument to an
                            # address yields a valid form.
                            columnGetter = proc {
                                | columnIndex |
                                if columnIndex == argIndex
                                    "Arg::Addr"
                                else
                                    "args[#{columnIndex}].kind()"
                                end
                            }
                            filter = proc {
                                | forms |
                                numYes = 0

                                forms.each {
                                    | form |
                                    if form.kinds[argIndex] == "Addr"
                                        numYes += 1
                                    end
                                }

                                if numYes == 0
                                    # Drop down, emit no code, since we cannot match.
                                    true
                                else
                                    # Keep going.
                                    false
                                end
                            }
                            callback = proc {
                                | form |
                                beginArchs(outp, form.archs)
                                outp.puts "OPGEN_RETURN(true);"
                                endArchs(outp, form.archs)
                            }
                            matchForms(outp, :safe, overload.forms, 0, columnGetter, filter, callback)

                            outp.puts "break;" if needOverloadSwitch
                        end
                    }
                    if needOverloadSwitch
                        outp.puts "default:"
                        outp.puts "break;"
                        outp.puts "}"
                    end
                end
                
                outp.puts "break;"
            }
            
            outp.puts "default:"
            outp.puts "break;"
            outp.puts "}"
        end
        
        outp.puts "break;"
    }
    outp.puts "default:";
    outp.puts "break;"
    outp.puts "}"
    outp.puts "return false;"
    outp.puts "}"

    outp.puts "bool Inst::isTerminal()"
    outp.puts "{"
    outp.puts "switch (kind.opcode) {"
    foundTrue = false
    $opcodes.values.each {
        | opcode |
        if opcode.attributes[:terminal]
            outp.puts "case #{opcode.name}:"
            foundTrue = true
        end
    }
    if foundTrue
        outp.puts "return true;"
    end
    $opcodes.values.each {
        | opcode |
        if opcode.custom
            outp.puts "case #{opcode.name}:"
            outp.puts "return #{opcode.name}Custom::isTerminal(*this);"
        end
    }
    outp.puts "default:"
    outp.puts "return false;"
    outp.puts "}"
    outp.puts "}"
    
    outp.puts "bool Inst::hasNonArgNonControlEffects()"
    outp.puts "{"
    outp.puts "if (kind.traps)"
    outp.puts "return true;"
    outp.puts "switch (kind.opcode) {"
    foundTrue = false
    $opcodes.values.each {
        | opcode |
        if opcode.attributes[:effects]
            outp.puts "case #{opcode.name}:"
            foundTrue = true
        end
    }
    if foundTrue
        outp.puts "return true;"
    end
    $opcodes.values.each {
        | opcode |
        if opcode.custom
            outp.puts "case #{opcode.name}:"
            outp.puts "return #{opcode.name}Custom::hasNonArgNonControlEffects(*this);"
        end
    }
    outp.puts "default:"
    outp.puts "return false;"
    outp.puts "}"
    outp.puts "}"
    
    outp.puts "bool Inst::hasNonArgEffects()"
    outp.puts "{"
    outp.puts "if (kind.traps)"
    outp.puts "return true;"
    outp.puts "switch (kind.opcode) {"
    foundTrue = false
    $opcodes.values.each {
        | opcode |
        if opcode.attributes[:terminal] or opcode.attributes[:effects]
            outp.puts "case #{opcode.name}:"
            foundTrue = true
        end
    }
    if foundTrue
        outp.puts "return true;"
    end
    $opcodes.values.each {
        | opcode |
        if opcode.custom
            outp.puts "case #{opcode.name}:"
            outp.puts "return #{opcode.name}Custom::hasNonArgEffects(*this);"
        end
    }
    outp.puts "default:"
    outp.puts "return false;"
    outp.puts "}"
    outp.puts "}"
    
    outp.puts "CCallHelpers::Jump Inst::generate(CCallHelpers& jit, GenerationContext& context)"
    outp.puts "{"
    outp.puts "UNUSED_PARAM(jit);"
    outp.puts "UNUSED_PARAM(context);"
    outp.puts "CCallHelpers::Jump result;"
    matchInstOverloadForm(outp, :fast, "this") {
        | opcode, overload, form |
        if opcode.custom
            outp.puts "OPGEN_RETURN(#{opcode.name}Custom::generate(*this, jit, context));"
        else
            beginArchs(outp, form.archs)
            if form.altName
                methodName = form.altName
            else
                methodName = opcode.masmName
            end
            if opcode.attributes[:branch]
                outp.print "result = "
            end
            outp.print "jit.#{methodName}("

            form.kinds.each_with_index {
                | kind, index |
                if index != 0
                    outp.print ", "
                end
                case kind.name
                when "Tmp"
                    if overload.signature[index].type == "G"
                        outp.print "args[#{index}].gpr()"
                    else
                        outp.print "args[#{index}].fpr()"
                    end
                when "Imm", "BitImm"
                    outp.print "args[#{index}].asTrustedImm32()"
                when "BigImm", "BitImm64"
                    outp.print "args[#{index}].asTrustedImm64()"
                when "Addr"
                    outp.print "args[#{index}].asAddress()"
                when "Index"
                    outp.print "args[#{index}].asBaseIndex()"
                when "RelCond"
                    outp.print "args[#{index}].asRelationalCondition()"
                when "ResCond"
                    outp.print "args[#{index}].asResultCondition()"
                when "DoubleCond"
                    outp.print "args[#{index}].asDoubleCondition()"
                end
            }

            outp.puts ");"
            outp.puts "OPGEN_RETURN(result);"
            endArchs(outp, form.archs)
        end
    }
    outp.puts "RELEASE_ASSERT_NOT_REACHED();"
    outp.puts "return result;"
    outp.puts "}"

    outp.puts "} } } // namespace JSC::B3::Air"
}

# This is a hack for JSAir. It's a joke.
File.open("JSAir_opcode.js", "w") {
    | outp |
    outp.puts "\"use strict\";"
    outp.puts "// Generated by opcode_generator.rb from #{$fileName} -- do not edit!"
    
    $opcodes.values.each {
        | opcode |
        outp.puts "const #{opcode.name} = Symbol(#{opcode.name.inspect});"
    }
    
    outp.puts "function Inst_forEachArg(inst, func)"
    outp.puts "{"
    outp.puts "let replacement;"
    outp.puts "switch (inst.opcode) {"
    $opcodes.values.each {
        | opcode |
        outp.puts "case #{opcode.name}:"
        if opcode.custom
            outp.puts "#{opcode.name}Custom.forEachArg(inst, func);"
        else
            needOverloadSwitch = opcode.overloads.size != 1
            outp.puts "switch (inst.args.length) {" if needOverloadSwitch
            opcode.overloads.each {
                | overload |
                outp.puts "case #{overload.signature.length}:" if needOverloadSwitch
                overload.signature.each_with_index {
                    | arg, index |
                    role = nil
                    case arg.role
                    when "U"
                        role = "Use"
                    when "D"
                        role = "Def"
                    when "ZD"
                        role = "ZDef"
                    when "UD"
                        role = "UseDef"
                    when "UZD"
                        role = "UseZDef"
                    when "UA"
                        role = "UseAddr"
                    when "S"
                        role = "Scratch"
                    else
                        raise
                    end
                    
                    outp.puts "inst.visitArg(#{index}, func, Arg.#{role}, #{arg.type}P, #{arg.width});"
                }
                outp.puts "break;"
            }
            if needOverloadSwitch
                outp.puts "default:"
                outp.puts "throw new Error(\"Bad overload\");"
                outp.puts "break;"
                outp.puts "}"
            end
        end
        outp.puts "break;"
    }
    outp.puts "default:"
    outp.puts "throw \"Bad opcode\";"
    outp.puts "}"
    outp.puts "}"
    
    outp.puts "function Inst_hasNonArgEffects(inst)"
    outp.puts "{"
    outp.puts "switch (inst.opcode) {"
    foundTrue = false
    $opcodes.values.each {
        | opcode |
        if opcode.attributes[:terminal] or opcode.attributes[:effects]
            outp.puts "case #{opcode.name}:"
            foundTrue = true
        end
    }
    if foundTrue
        outp.puts "return true;"
    end
    $opcodes.values.each {
        | opcode |
        if opcode.custom
            outp.puts "case #{opcode.name}:"
            outp.puts "return #{opcode.name}Custom.hasNonArgNonControlEffects(inst);"
        end
    }
    outp.puts "default:"
    outp.puts "return false;"
    outp.puts "}"
    outp.puts "}"
    
    outp.puts "function opcodeCode(opcode)"
    outp.puts "{"
    outp.puts "switch (opcode) {"
    $opcodes.keys.sort.each_with_index {
        | opcode, index |
        outp.puts "case #{opcode}:"
        outp.puts "return #{index}"
    }
    outp.puts "default:"
    outp.puts "throw new Error(\"bad opcode\");"
    outp.puts "}"
    outp.puts "}"
}