@yeyelailou/co 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +73 -16
  2. package/bin//345/205/245/345/217/243.js +0 -8
  3. package/package.json +7 -6
  4. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//345/220/257/345/212/250/345/231/250.c +3 -3
  5. package//345/267/245/345/205/267//350/207/252/344/270/276/347/274/226/350/257/221/345/231/250//346/234/272/345/231/250/347/240/201/347/224/237/346/210/220/345/231/250.co +21 -1
  6. package//345/267/245/345/205/267//350/207/252/344/270/276/347/274/226/350/257/221/345/231/250//350/207/252/344/270/276/347/274/226/350/257/221.sh +73 -0
  7. package//345/267/245/345/205/267//350/207/252/344/270/276/347/274/226/350/257/221/345/231/250//350/207/252/344/270/276/351/252/214/350/257/201//347/274/226/350/257/221/351/251/261/345/212/250.co +3 -1
  8. package//345/267/245/345/205/267//350/207/252/344/270/276/347/274/226/350/257/221/345/231/250//350/207/252/344/270/276/351/252/214/350/257/201//347/274/226/350/257/221/351/252/214/350/257/201.sh +24 -8
  9. package/bin/install.js +0 -276
  10. package//345/267/245/345/205/267/lsp/server.js +0 -419
  11. package//345/267/245/345/205/267/lsp//346/265/213/350/257/225.sh +0 -81
  12. package//345/267/245/345/205/267/vscode-cocn/extension.js +0 -203
  13. package//345/267/245/345/205/267/vscode-cocn/package.json +0 -58
  14. package//345/267/245/345/205/267/vscode-cocn/syntaxes/coCN.tmLanguage.json +0 -130
  15. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/273/243/347/240/201/347/224/237/346/210/220/345/231/250.js +0 -2284
  16. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/analysis.js +0 -116
  17. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/benchmark_demo.js +0 -75
  18. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/dominance.js +0 -158
  19. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/gvn.js +0 -45
  20. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/index.js +0 -121
  21. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/ir.js +0 -237
  22. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/passes/constProp.js +0 -126
  23. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/passes/copyProp.js +0 -57
  24. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/passes/cse.js +0 -62
  25. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/passes/dce.js +0 -68
  26. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/passes/devirt.js +0 -38
  27. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/passes/escape.js +0 -67
  28. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/passes/inline.js +0 -142
  29. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/passes/loopOpt.js +0 -215
  30. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/peephole.js +0 -42
  31. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/regalloc.js +0 -212
  32. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/scheduler.js +0 -86
  33. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/spill.js +0 -78
  34. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/ssa.js +0 -235
  35. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/traceSched.js +0 -47
  36. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250/unroll.js +0 -46
  37. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250//346/265/213/350/257/225/harness.js +0 -33
  38. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250//346/265/213/350/257/225/run_all.js +0 -11
  39. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250//346/265/213/350/257/225/test_constfold.js +0 -58
  40. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250//346/265/213/350/257/225/test_dce.js +0 -49
  41. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250//346/265/213/350/257/225/test_e2e.js +0 -57
  42. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250//346/265/213/350/257/225/test_gvn_spill.js +0 -45
  43. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250//346/265/213/350/257/225/test_loop.js +0 -46
  44. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250//346/265/213/350/257/225/test_regalloc.js +0 -51
  45. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//344/274/230/345/214/226/345/231/250//346/265/213/350/257/225/test_ssa.js +0 -65
  46. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//345/205/245/345/217/243.c +0 -9
  47. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//345/205/245/345/217/243.js +0 -38
  48. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237/AST/345/267/245/345/205/267.js +0 -126
  49. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237/index.js +0 -103
  50. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237//345/206/205/350/201/224.js +0 -194
  51. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237//345/207/275/346/225/260/347/211/271/345/214/226.js +0 -168
  52. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237//346/243/200/346/237/245/346/266/210/351/231/244.js +0 -166
  53. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237//346/265/213/350/257/225//345/206/205/350/201/224/346/265/213/350/257/225.js +0 -53
  54. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237//346/265/213/350/257/225//345/207/275/346/225/260/347/211/271/345/214/226/346/265/213/350/257/225.js +0 -67
  55. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237//346/265/213/350/257/225//347/253/257/345/210/260/347/253/257/346/265/213/350/257/225.js +0 -104
  56. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237//346/265/213/350/257/225//347/261/273/345/236/213/346/216/250/346/226/255/346/265/213/350/257/225.js +0 -87
  57. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237//346/265/213/350/257/225//350/277/220/350/241/214/346/265/213/350/257/225.js +0 -43
  58. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237//346/265/213/350/257/225//351/200/203/351/200/270/345/210/206/346/236/220/346/265/213/350/257/225.js +0 -58
  59. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237//347/211/271/345/214/226/347/274/223/345/255/230.js +0 -83
  60. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237//347/216/257/345/242/203.js +0 -126
  61. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237//347/261/273/345/236/213.js +0 -294
  62. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237//347/261/273/345/236/213/346/216/250/346/226/255.js +0 -461
  63. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237//350/260/203/347/224/250/345/233/276.js +0 -119
  64. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/261/273/345/236/213/347/263/273/347/273/237//351/200/203/351/200/270/345/210/206/346/236/220.js +0 -184
  65. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//347/274/226/350/257/221.sh +0 -45
  66. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//350/277/220/350/241/214/346/227/266/alloc.c +0 -206
  67. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//350/277/220/350/241/214/346/227/266/build.sh +0 -70
  68. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//350/277/220/350/241/214/346/227/266/dict.c +0 -143
  69. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//350/277/220/350/241/214/346/227/266/list.c +0 -148
  70. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//350/277/220/350/241/214/346/227/266/math.c +0 -129
  71. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//350/277/220/350/241/214/346/227/266/print.c +0 -135
  72. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//350/277/220/350/241/214/346/227/266/rt.h +0 -177
  73. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//350/277/220/350/241/214/346/227/266/string.c +0 -288
  74. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//350/277/220/350/241/214/346/227/266/syscall.asm +0 -153
  75. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//350/277/220/350/241/214/346/227/266/test.c +0 -228
  76. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//350/277/220/350/241/214/346/227/266//344/270/264/346/227/266.c +0 -379
  77. package//345/267/245/345/205/267//345/216/237/347/224/237/347/274/226/350/257/221/345/231/250//350/277/220/350/241/214/346/227/266.c +0 -441
  78. package//345/267/245/345/205/267//350/207/252/344/270/276/347/274/226/350/257/221/345/231/250//346/267/261/345/272/246/346/257/224/350/276/203.js +0 -51
  79. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224/Empty.java +0 -1
  80. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224/bench.c +0 -53
  81. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224/bench.co +0 -42
  82. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224/bench.go +0 -43
  83. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224/bench.java +0 -29
  84. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224/bench.js +0 -24
  85. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224/bench.py +0 -36
  86. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224/bench.rs +0 -35
  87. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224/empty.co +0 -0
  88. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224/empty_c.c +0 -1
  89. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224/empty_go.go +0 -2
  90. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224/empty_rs.rs +0 -1
  91. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/257/271C/350/257/255/350/250/200_/346/213/274/346/216/245.c +0 -32
  92. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/257/271C/350/257/255/350/250/200_/346/213/274/346/216/245.co +0 -10
  93. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/257/271C/350/257/255/350/250/200_/346/216/222/345/272/217.c +0 -23
  94. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/257/271C/350/257/255/350/250/200_/346/216/222/345/272/217.co +0 -31
  95. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/257/271C/350/257/255/350/250/200_/346/226/220/346/263/242/351/202/243/345/245/221.c +0 -17
  96. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/257/271C/350/257/255/350/250/200_/346/226/220/346/263/242/351/202/243/345/245/221.co +0 -10
  97. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/257/271C/350/257/255/350/250/200_/346/226/220/346/263/242/351/202/243/345/245/22120.co +0 -10
  98. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/257/271C/350/257/255/350/250/200_/347/264/257/345/212/240.c +0 -14
  99. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/257/271C/350/257/255/350/250/200_/347/264/257/345/212/240.co +0 -10
  100. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/257/271C/350/257/255/350/250/200/345/257/271/346/257/224/347/273/223/346/236/234.txt +0 -164
  101. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/276/256/345/237/272/345/207/206/fib.c +0 -9
  102. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/276/256/345/237/272/345/207/206/fib.co +0 -2
  103. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/276/256/345/237/272/345/207/206/sum.c +0 -10
  104. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/276/256/345/237/272/345/207/206/sum.co +0 -3
  105. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/276/256/345/237/272/345/207/206//350/256/241/346/265/213.sh +0 -32
  106. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//345/276/256/345/237/272/345/207/206//350/256/241/346/265/213/347/273/223/346/236/234.txt +0 -7
  107. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//350/241/245/346/265/213.sh +0 -45
  108. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//350/256/241/346/265/213.sh +0 -163
  109. package//345/267/245/345/205/267//350/257/255/350/250/200/345/257/271/346/257/224//350/256/241/346/265/213/347/273/223/346/236/234.txt +0 -29
@@ -1,2284 +0,0 @@
1
- // ============================================================
2
- // 代码生成器.js —— coCN -> x86-64 (AT&T) 优化后端
3
- //
4
- // 新管线:
5
- // AST --[类型系统特化]--> 特化AST --[AstToIR]--> 三地址IR
6
- // --[优化器 optimizeProgram: SSA/常量传播/CSE/循环/寄存器分配/调度]-->
7
- // --[IRToAsm]--> x86-64 汇编
8
- //
9
- // 设计要点:
10
- // * 栈式"家"槽 + 寄存器缓存:每个变量一个 8 字节栈家槽;
11
- // 优化器颜色分配给的寄存器作为活跃寄存器缓存,热循环内无 call 时全程在寄存器。
12
- // * 调用屏障:call 前把所有"调用者保存"寄存器中的值 spill 到家槽,call 后作废。
13
- // * ABI:rdi/rsi/rdx/rcx/r8/r9 传整型,xmm0-7 传浮点,rax/xmm0 返回。
14
- // * 浮点不参与寄存器分配(regalloc 只做整型图着色),统一 xmm0 + 家槽。
15
- // ============================================================
16
-
17
- const { 解析源 } = require("./语法分析器.js");
18
- const I = require("./优化器/ir.js");
19
- const { optimizeProgram } = require("./优化器/index.js");
20
- let TS = null;
21
- try { TS = require("./类型系统/index.js"); } catch (e) { TS = null; }
22
-
23
- // ---------- x86-64 寄存器约定 ----------
24
- const ARG_INT = ["rdi", "rsi", "rdx", "rcx", "r8", "r9"];
25
- const ARG_XMM = ["xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7"];
26
- // 调用者保存(call 会破坏)
27
- const CALLER_SAVED = new Set(["rax", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11"]);
28
- // 被调用者保存(需要在函数入口 push / 出口 pop)
29
- const CALLEE_SAVED = ["rbx", "r12", "r13", "r14"];
30
- // 通用临时 scratch(不在被保存集内,可由后端自由用作中转)
31
- const SCRATCH_INT = "rax"; // 主临时
32
- const SCRATCH_INT2 = "r10"; // 次临时
33
- // 浮点 scratch 寄存器池:块内浮点值缓存。SysV ABI 中 xmm0-15 全为调用者保存,
34
- // 故在 call 前必须 flush 到家槽;块边界也 flush(家槽为跨块真相源)。
35
- // 取 xmm0-xmm7(xmm8-15 保留给未来跨块提升)。
36
- const SCRATCH_XMM = ["xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7"];
37
- // 整数块内缓存寄存器池(r10/r11):与浮点缓存同构,块内临时量驻留。
38
- const INT_CACHE = ["r10", "r11"];
39
-
40
- function pct(r) { return "%" + r; }
41
-
42
- function escapeAsmStr(s) {
43
- let r = "";
44
- for (const ch of s) {
45
- if (ch === "\\") r += "\\\\";
46
- else if (ch === "\"") r += "\\\"";
47
- else if (ch === "\n") r += "\\n";
48
- else if (ch === "\t") r += "\\t";
49
- else if (ch === "\r") r += "\\r";
50
- else r += ch;
51
- }
52
- return r;
53
- }
54
-
55
- // ============================================================
56
- // 后端 IR 小优化 pass(安全、块内、不重排有副作用的调用)
57
- // ============================================================
58
- // 我们不使用 优化器/ 下带副作用重排 bug 的全量管线,而是在本文件内
59
- // 做保守的、块内的折叠,保证 7 个测试始终正确。
60
-
61
- // 块内折叠:若 d 在本函数仅被使用一次,且唯一使用是紧随其后的 `X = mov d`,
62
- // 则把 d 的定义目标直接改写成 X,并删除这条 mov。
63
- // b1 = add s, i ; s = b1 → s = add s, i
64
- // 这让后端可以把结果直接写进目标变量的寄存器。
65
- function collapseTemps(fn) {
66
- const useCount = new Map();
67
- const bump = v => { if (v == null) return; useCount.set(v, (useCount.get(v) || 0) + 1); };
68
- for (const b of fn.blocks) {
69
- for (const ins of b.instrs) for (const u of I.instrUse(ins)) bump(u);
70
- for (const u of I.termUse(b.term)) bump(u);
71
- }
72
- for (const b of fn.blocks) {
73
- const inss = b.instrs;
74
- let i = 0;
75
- while (i + 1 < inss.length) {
76
- const a = inss[i];
77
- const c = inss[i + 1];
78
- const da = I.instrDef(a);
79
- if (da != null && c.op === "mov" && c.src === da && useCount.get(da) === 1) {
80
- // 把 a 的 dest 重命名为 c.dest
81
- a.dest = c.dest;
82
- inss.splice(i + 1, 1);
83
- // 不 i++:原位的 a 现在是上一条之后,可能还能再折叠
84
- } else {
85
- i++;
86
- }
87
- }
88
- }
89
- }
90
-
91
- // 块内常量折叠:straight-line 段里,const 直接参与二元运算则编译期算出。
92
- // 同时删除 `x = mov constTmp` 这类纯搬运(const 已记录值)。
93
- function foldConstants(fn, kinds) {
94
- for (const b of fn.blocks) {
95
- const knownConst = new Map(); // name -> 整数字面量
96
- const out = [];
97
- for (const ins of b.instrs) {
98
- if (ins.op === "const" && kinds.kindOf(ins.dest) !== "double" && typeof ins.value === "number") {
99
- knownConst.set(ins.dest, ins.value);
100
- out.push(ins);
101
- continue;
102
- }
103
- if (ins.op === "mov" && knownConst.has(ins.src)) {
104
- // X = mov constTmp → X = const K (随后会被常量传播)
105
- out.push(I.const_(ins.dest, knownConst.get(ins.src)));
106
- knownConst.set(ins.dest, knownConst.get(ins.src));
107
- continue;
108
- }
109
- if (["add","sub","mul","div","mod","lt","gt","le","ge","eq","ne","and","or","xor","shl","shr"].includes(ins.op)
110
- && knownConst.has(ins.left) && knownConst.has(ins.right)) {
111
- const L = knownConst.get(ins.left), R = knownConst.get(ins.right);
112
- let v;
113
- switch (ins.op) {
114
- case "add": v = L + R; break;
115
- case "sub": v = L - R; break;
116
- case "mul": v = L * R; break;
117
- case "div": v = Math.trunc(L / R); break;
118
- case "mod": v = L % R; break;
119
- case "lt": v = L < R ? 1 : 0; break;
120
- case "gt": v = L > R ? 1 : 0; break;
121
- case "le": v = L <= R ? 1 : 0; break;
122
- case "ge": v = L >= R ? 1 : 0; break;
123
- case "eq": v = L === R ? 1 : 0; break;
124
- case "ne": v = L !== R ? 1 : 0; break;
125
- case "and": v = L & R; break;
126
- case "or": v = L | R; break;
127
- case "xor": v = L ^ R; break;
128
- case "shl": v = L << R; break;
129
- case "shr": v = L >> R; break;
130
- }
131
- out.push(I.const_(ins.dest, v));
132
- knownConst.set(ins.dest, v);
133
- continue;
134
- }
135
- // 非常量指令定义了 dest:该变量不再是已知常量,失效之。
136
- // (call/binop/mov 到非常量源/unop 等都可能改变其值。)
137
- const d = I.instrDef(ins);
138
- if (d != null) knownConst.delete(d);
139
- out.push(ins);
140
- }
141
- b.instrs = out;
142
- }
143
- }
144
-
145
- // 保守的循环不变量外提(LICM):
146
- // 仅外提「纯算术」指令(const/mov/binop/neg/not,绝不外提 call/load/store),
147
- // 且仅从「无条件留在循环内」的块(terminator 为 jump)外提,保证每条路径都执行。
148
- // 操作数若在循环外定义、或已是外提的不变量,则该指令可外提。
149
- function licm(fn) {
150
- I.buildCFG(fn);
151
- const n = fn.blocks.length;
152
- // 可达性:reach[from] = Set(to)
153
- const reach = Array.from({ length: n }, () => new Set());
154
- for (let s = 0; s < n; s++) {
155
- const succ = fn.blocks[s].term.kind === "jump" ? [fn.blocks[s].term.target]
156
- : fn.blocks[s].term.kind === "branch" ? [fn.blocks[s].term.then, fn.blocks[s].term.else] : [];
157
- for (const t of succ) {
158
- // 简单工作列表
159
- const seen = new Set([s]);
160
- const wl = [t];
161
- while (wl.length) {
162
- const x = wl.pop();
163
- if (seen.has(x)) continue;
164
- seen.add(x); reach[s].add(x);
165
- const bb = fn.blocks[x];
166
- const ss = bb.term.kind === "jump" ? [bb.term.target]
167
- : bb.term.kind === "branch" ? [bb.term.then, bb.term.else] : [];
168
- for (const y of ss) wl.push(y);
169
- }
170
- }
171
- }
172
- // 找回边 b->H(H 可达 b)
173
- const headers = new Set();
174
- const loops = new Map(); // H -> Set(blocks)
175
- for (let b = 0; b < n; b++) {
176
- const succ = fn.blocks[b].term.kind === "jump" ? [fn.blocks[b].term.target]
177
- : fn.blocks[b].term.kind === "branch" ? [fn.blocks[b].term.then, fn.blocks[b].term.else] : [];
178
- for (const H of succ) {
179
- if (reach[H].has(b) && H < b) {
180
- headers.add(H);
181
- // 循环块 = H + 从 b 出发不经过 H 可达的所有块
182
- if (!loops.has(H)) {
183
- // 循环块 = H + 从 back-edge 源 b 沿【前驱】反向可达、且不经过 H 的所有块
184
- const set = new Set([H]);
185
- const wl = [b];
186
- while (wl.length) {
187
- const x = wl.pop();
188
- if (x === H || set.has(x)) continue;
189
- set.add(x);
190
- for (const y of (fn.blocks[x].preds || [])) wl.push(y);
191
- }
192
- loops.set(H, set);
193
- }
194
- }
195
- }
196
- }
197
- const pure = (ins) => ins.op !== "call" && ins.op !== "load" && ins.op !== "store" && ins.op !== "phi";
198
- for (const [H, loopSet] of loops) {
199
- // preheader:循环外指向 H 的块
200
- let pre = -1;
201
- for (let p = 0; p < n; p++) {
202
- if (loopSet.has(p)) continue;
203
- const bb = fn.blocks[p];
204
- const ss = bb.term.kind === "jump" ? [bb.term.target]
205
- : bb.term.kind === "branch" ? [bb.term.then, bb.term.else] : [];
206
- if (ss.includes(H)) { pre = p; break; }
207
- }
208
- if (pre < 0) continue;
209
- if (process.env.COCN_DUMP_LICM) console.error("LICM loop H="+H+" pre="+pre+" blocks="+JSON.stringify([...loopSet]));
210
- // 保守不变量检测(非 SSA 安全):纯算术指令,且【所有操作数都在循环外定义】。
211
- // 不做 avail 传播——否则非 SSA 下会把「k=0」外提后误判「k=k+1」也不变量。
212
- const loopDefined = new Set();
213
- for (const bid of loopSet) for (const ins of fn.blocks[bid].instrs) {
214
- const d = I.instrDef(ins); if (d != null) loopDefined.add(d);
215
- }
216
- const invariant = new Set();
217
- for (const bid of loopSet) {
218
- const bb = fn.blocks[bid];
219
- for (const ins of bb.instrs) {
220
- if (!pure(ins)) continue;
221
- if (ins.op === "const") continue; // 常量由后端立即数处理,无需外提
222
- const ops = [...I.instrUse(ins)];
223
- if (ops.every(op => !loopDefined.has(op))) invariant.add(ins);
224
- }
225
- }
226
- // 外提:把不变量指令按原程序顺序(block id + 块内顺序)搬到 preheader 的 terminator 前
227
- const preBlock = fn.blocks[pre];
228
- const hoisted = [];
229
- const bids = [...loopSet].sort((a, b) => a - b);
230
- for (const bid of bids) {
231
- const bb = fn.blocks[bid];
232
- if (bb.term.kind !== "jump") continue;
233
- bb.instrs = bb.instrs.filter(ins => {
234
- if (invariant.has(ins)) { hoisted.push(ins); return false; }
235
- return true;
236
- });
237
- }
238
- if (process.env.COCN_DUMP_LICM) console.error("LICM hoist="+JSON.stringify(hoisted)+" | block2="+JSON.stringify(fn.blocks[2].instrs));
239
- preBlock.instrs.push(...hoisted);
240
- }
241
- }
242
-
243
- // 死代码消除:删除结果从未被使用的纯计算指令(const/mov/binop/neg/not/unbox/itof)。
244
- // 保留 call/store(有副作用)和 phi。
245
- function deadCodeElimination(fn) {
246
- // 统计所有使用的变量
247
- const used = new Set();
248
- const collect = (v) => { if (v != null) used.add(v); };
249
- for (const b of fn.blocks) {
250
- for (const ins of b.instrs) for (const u of I.instrUse(ins)) collect(u);
251
- for (const u of I.termUse(b.term)) collect(u);
252
- }
253
- // 迭代删除未使用定义的纯指令,直到不动点
254
- let changed = true;
255
- while (changed) {
256
- changed = false;
257
- for (const b of fn.blocks) {
258
- const out = [];
259
- for (const ins of b.instrs) {
260
- const d = I.instrDef(ins);
261
- const isPure = ins.op !== "call" && ins.op !== "store" && ins.op !== "phi";
262
- if (d != null && isPure && !used.has(d)) {
263
- // 删除此指令;其操作数可能也变成死代码,下一轮迭代处理
264
- changed = true;
265
- continue;
266
- }
267
- out.push(ins);
268
- }
269
- b.instrs = out;
270
- }
271
- // 重新收集使用集(删除指令后,某些操作数也可能不再被使用)
272
- used.clear();
273
- for (const b of fn.blocks) {
274
- for (const ins of b.instrs) for (const u of I.instrUse(ins)) collect(u);
275
- for (const u of I.termUse(b.term)) collect(u);
276
- }
277
- }
278
- }
279
-
280
- // 基本块布局:DFS 顺序,让循环体/常见路径 fall-through,消除冗余无条件跳转。
281
- // 返回有序 block id 列表。
282
- function layoutBlocks(fn) {
283
- const order = [];
284
- const visited = new Set();
285
- const visit = (id) => {
286
- if (visited.has(id)) return;
287
- visited.add(id);
288
- order.push(id);
289
- const b = fn.blocks[id];
290
- if (!b) return;
291
- if (b.term.kind === "jump") visit(b.term.target);
292
- else if (b.term.kind === "branch") { visit(b.term.then); visit(b.term.else); }
293
- };
294
- visit(0);
295
- for (const b of fn.blocks) if (!visited.has(b.id)) visit(b.id);
296
- return order;
297
- }
298
-
299
- // ============================================================
300
- // 前端:AST -> 三地址 IR
301
- // ============================================================
302
- class AstToIR {
303
- constructor(ast) {
304
- this.ast = ast;
305
- this.funcLabelMap = new Map(); // coCN 函数名 -> IR 函数名(用原名)
306
- this.strLabelMap = new Map();
307
- this.dblLabelMap = new Map();
308
- this.rodata = [];
309
- this.kinds = new Map(); // IR 变量名 -> kind
310
- this.seq = 0;
311
- this.tmpN = 0;
312
- this.blocks = []; // 当前函数的块
313
- this.cur = null;
314
- this.loopStack = []; // {end, cont}
315
- this.retKindByFunc = new Map();
316
- }
317
-
318
- nl() { return ".L" + (++this.seq); }
319
- tmp(prefix) { return (prefix || "t") + (++this.tmpN); }
320
-
321
- strConst(s) {
322
- if (this.strLabelMap.has(s)) return this.strLabelMap.get(s);
323
- const lbl = ".LC" + this.strLabelMap.size;
324
- this.strLabelMap.set(s, lbl);
325
- this.rodata.push({ lbl, text: s });
326
- return lbl;
327
- }
328
- dblConst(d) {
329
- if (this.dblLabelMap.has(d)) return this.dblLabelMap.get(d);
330
- const lbl = ".LCD" + this.dblLabelMap.size;
331
- this.dblLabelMap.set(d, lbl);
332
- this.rodata.push({ lbl, dbl: d });
333
- return lbl;
334
- }
335
-
336
- setKind(name, kind) { this.kinds.set(name, kind); }
337
- kindOf(name) {
338
- // SSA 版本名 strip #n
339
- const idx = name.lastIndexOf("#");
340
- const base = (idx > 0 && /^\d+$/.test(name.slice(idx + 1))) ? name.slice(0, idx) : name;
341
- return this.kinds.get(base) || this.kinds.get(name) || "int";
342
- }
343
-
344
- newBlock() {
345
- const b = new I.Block(this.blocks.length);
346
- this.blocks.push(b);
347
- this.cur = b;
348
- return b;
349
- }
350
- emit(instr) { this.cur.instrs.push(instr); }
351
-
352
- // ---------- 主入口:返回 {functions:[POJO], rodata} ----------
353
- build() {
354
- const functions = [];
355
- // 预收集函数定义名
356
- for (const st of this.ast.语句) {
357
- if (st.类型 === "函数定义") this.funcLabelMap.set(st.名字, st.名字);
358
- }
359
- // 为每个函数生成 IR
360
- for (const st of this.ast.语句) {
361
- if (st.类型 === "函数定义") functions.push(this.genFunc(st));
362
- }
363
- // 顶层 co_main
364
- const mainParams = [];
365
- this.blocks = [];
366
- this.cur = null;
367
- const entry = this.newBlock();
368
- const topStmts = this.ast.语句.filter(s => s.类型 !== "函数定义");
369
- for (const st of topStmts) this.genStmt(st);
370
- // 顶层默认返回 0
371
- if (this.cur.term.kind === "unreachable") {
372
- this.emit(I.const_("__ret0", 0));
373
- this.cur.term = I.ret("__ret0");
374
- }
375
- const main = { name: "co_main", params: mainParams, blocks: this.blocks };
376
- functions.unshift(main);
377
- return { functions, rodata: this.rodata };
378
- }
379
-
380
- genFunc(st) {
381
- this.currentFuncName = st.名字;
382
- this.retKindByFunc.set(st.名字, st.返回类型 || "");
383
- const params = st.参数.slice();
384
- this.blocks = [];
385
- this.cur = null;
386
- this.newBlock();
387
- // 参数 kind
388
- st.参数.forEach((p, i) => {
389
- const ak = st.参数类型[i] || "";
390
- this.setKind(p, this.kindFromAnno(ak));
391
- });
392
- for (const s of st.体.语句) this.genStmt(s);
393
- // 隐式返回
394
- if (this.cur.term.kind === "unreachable") {
395
- const k = this.kindFromAnno(st.返回类型 || "");
396
- if (k === "double") {
397
- const lbl = this.dblConst("0.0");
398
- const d = this.tmp("d");
399
- this.emit(I.const_(d, lbl));
400
- this.cur.term = I.ret(d);
401
- } else {
402
- this.emit(I.const_("__r", 0));
403
- this.cur.term = I.ret("__r");
404
- }
405
- }
406
- return { name: st.名字, params, blocks: this.blocks };
407
- }
408
-
409
- kindFromAnno(a) {
410
- if (a === "整数" || a === "布尔") return "int";
411
- if (a === "浮点") return "double";
412
- if (a === "字符串") return "str";
413
- if (a === "列表") return "intlist";
414
- if (a === "字典") return "dict";
415
- return "none";
416
- }
417
-
418
- // ---------- 语句 ----------
419
- genStmt(st) {
420
- if (st == null) return;
421
- switch (st.类型) {
422
- case "变量声明": this.genVarDecl(st); break;
423
- case "赋值": this.genAssign(st); break;
424
- case "返回": this.genReturn(st); break;
425
- case "如果": this.genIf(st); break;
426
- case "当": this.genWhile(st); break;
427
- case "对于": this.genFor(st); break;
428
- case "跳出":
429
- this.cur.term = I.jump(this.loopStack[this.loopStack.length - 1].end); break;
430
- case "继续":
431
- this.cur.term = I.jump(this.loopStack[this.loopStack.length - 1].cont); break;
432
- case "函数调用": this.genCallStmt(st); break;
433
- case "表达式语句": {
434
- const r = this.genExpr(st.expr || st);
435
- void r; break;
436
- }
437
- default:
438
- if (st.类型 === "二元" || st.类型 === "一元" || st.类型 === "字面量" ||
439
- st.类型 === "标识符" || st.类型 === "下标" || st.类型 === "列表字面量" ||
440
- st.类型 === "字典字面量") {
441
- this.genExpr(st);
442
- }
443
- }
444
- }
445
-
446
- genVarDecl(st) {
447
- let kind = this.kindFromAnno(st.类型标注);
448
- if (st.初始化 != null) {
449
- let r = this.genExpr(st.初始化);
450
- if (kind === "none") kind = r.kind;
451
- // 列表标注但初始化是无装箱整数列表 → 升级为 intlist
452
- if (kind === "list" && r.kind === "intlist") kind = "intlist";
453
- // 若声明类型是 int/double 但值是 box,自动拆箱
454
- if ((kind === "int" || kind === "double") && r.kind === "box") {
455
- r = this.unboxExpr(r, kind);
456
- }
457
- this.setKind(st.名字, kind);
458
- this.emit(I.mov(st.名字, r.name));
459
- } else {
460
- if (kind === "none") kind = "int";
461
- this.setKind(st.名字, kind);
462
- if (kind === "double") {
463
- const lbl = this.dblConst("0.0");
464
- const d = this.tmp("d");
465
- this.emit(I.const_(d, lbl));
466
- this.emit(I.mov(st.名字, d));
467
- } else {
468
- const d = this.tmp("c");
469
- this.emit(I.const_(d, 0));
470
- this.emit(I.mov(st.名字, d));
471
- }
472
- }
473
- }
474
-
475
- genAssign(st) {
476
- if (st.目标.类型 === "标识符") {
477
- let r = this.genExpr(st.值);
478
- const targetName = st.目标.名字;
479
- const curKind = this.kinds.get(targetName);
480
- // 若目标变量已知是 int/double 且值是 box,自动拆箱
481
- if (r.kind === "box" && (curKind === "int" || curKind === "double")) {
482
- r = this.unboxExpr(r, curKind);
483
- }
484
- if (!curKind || curKind === "none") this.setKind(targetName, r.kind);
485
- this.emit(I.mov(targetName, r.name));
486
- } else if (st.目标.类型 === "下标") {
487
- this.genIndexAssign(st.目标, st.值);
488
- }
489
- }
490
-
491
- genReturn(st) {
492
- if (st.值 != null) {
493
- let r = this.genExpr(st.值);
494
- // 自动拆箱:函数返回类型非 box 时拆箱
495
- const retKind = this.retKindByFunc.get(this.currentFuncName) || "";
496
- const expectedKind = retKind === "浮点" ? "double" : (retKind === "" || retKind === "整数" || retKind === "布尔") ? "int" : r.kind;
497
- r = this.unboxExpr(r, expectedKind === "double" ? "double" : "int");
498
- this.cur.term = I.ret(r.name);
499
- } else {
500
- const d = this.tmp("r");
501
- this.emit(I.const_(d, 0));
502
- this.cur.term = I.ret(d);
503
- }
504
- }
505
-
506
- genIf(st) {
507
- let c = this.genExpr(st.条件);
508
- // 条件若为 box,自动按 int 拆箱
509
- c = this.unboxExpr(c, "int");
510
- const prev = this.cur;
511
- const thenB = this.newBlock();
512
- const elseB = this.newBlock();
513
- const endB = this.newBlock();
514
- prev.term = I.branch(c.name, thenB.id, elseB.id);
515
- // then
516
- this.cur = thenB;
517
- for (const s of st.则体) this.genStmt(s);
518
- if (this.cur.term.kind === "unreachable") this.cur.term = I.jump(endB.id);
519
- // else 链
520
- this.cur = elseB;
521
- for (const br of st.否则链) {
522
- if (br.条件 != null) {
523
- const bc = this.genExpr(br.条件);
524
- const bThen = this.newBlock();
525
- const bNext = this.newBlock();
526
- this.cur.term = I.branch(bc.name, bThen.id, bNext.id);
527
- this.cur = bThen;
528
- for (const s of br.体) this.genStmt(s);
529
- if (this.cur.term.kind === "unreachable") this.cur.term = I.jump(endB.id);
530
- this.cur = bNext;
531
- } else {
532
- for (const s of br.体) this.genStmt(s);
533
- if (this.cur.term.kind === "unreachable") this.cur.term = I.jump(endB.id);
534
- }
535
- }
536
- if (this.cur.term.kind === "unreachable") this.cur.term = I.jump(endB.id);
537
- // 继续在 endB
538
- this.cur = endB;
539
- }
540
-
541
- genWhile(st) {
542
- const prev = this.cur;
543
- const headB = this.newBlock();
544
- const bodyB = this.newBlock();
545
- const endB = this.newBlock();
546
- prev.term = I.jump(headB.id);
547
- this.cur = headB;
548
- let c = this.genExpr(st.条件);
549
- c = this.unboxExpr(c, "int");
550
- this.cur.term = I.branch(c.name, bodyB.id, endB.id);
551
- this.loopStack.push({ end: endB.id, cont: headB.id });
552
- this.cur = bodyB;
553
- for (const s of st.体) this.genStmt(s);
554
- if (this.cur.term.kind === "unreachable") this.cur.term = I.jump(headB.id);
555
- this.loopStack.pop();
556
- this.cur = endB;
557
- }
558
-
559
- genFor(st) {
560
- if (st.是否遍历 === 1) { this.genForEach(st); return; }
561
- // range: for i from 起点 to 终点 [step 步长]
562
- const start = this.genExpr(st.起点);
563
- const iName = st.变量;
564
- this.setKind(iName, "int");
565
- const iVar = this.tmp("i");
566
- this.setKind(iVar, "int");
567
- this.emit(I.mov(iVar, start.name));
568
- this.emit(I.mov(iName, iVar));
569
-
570
- const endR = this.genExpr(st.终点);
571
- const endV = this.tmp("e");
572
- this.setKind(endV, "int");
573
- this.emit(I.mov(endV, endR.name));
574
-
575
- let stepV = null;
576
- if (st.步长 != null) {
577
- const sp = this.genExpr(st.步长);
578
- stepV = this.tmp("p");
579
- this.setKind(stepV, "int");
580
- this.emit(I.mov(stepV, sp.name));
581
- } else {
582
- stepV = this.tmp("p");
583
- this.setKind(stepV, "int");
584
- this.emit(I.const_(stepV, 1));
585
- }
586
-
587
- const prev = this.cur;
588
- const headB = this.newBlock();
589
- const bodyB = this.newBlock();
590
- const endB = this.newBlock();
591
- const contB = this.newBlock();
592
- prev.term = I.jump(headB.id);
593
-
594
- this.cur = headB;
595
- // 条件:i <= end(步长>0 假设);与 IR 后端配合,用 le
596
- const cond = this.tmp("c");
597
- this.setKind(cond, "int");
598
- this.emit(I.binop("le", cond, iName, endV));
599
- this.cur.term = I.branch(cond, bodyB.id, endB.id);
600
-
601
- this.loopStack.push({ end: endB.id, cont: contB.id });
602
- this.cur = bodyB;
603
- for (const s of st.体) this.genStmt(s);
604
- if (this.cur.term.kind === "unreachable") this.cur.term = I.jump(contB.id);
605
-
606
- this.cur = contB;
607
- const ni = this.tmp("n");
608
- this.setKind(ni, "int");
609
- this.emit(I.binop("add", ni, iName, stepV));
610
- this.emit(I.mov(iName, ni));
611
- this.cur.term = I.jump(headB.id);
612
-
613
- this.loopStack.pop();
614
- this.cur = endB;
615
- }
616
-
617
- genForEach(st) {
618
- // for x in list
619
- const listR = this.genExpr(st.遍历源);
620
- const listV = this.tmp("l");
621
- this.setKind(listV, listR.kind === "intlist" ? "intlist" : "list");
622
- this.emit(I.mov(listV, listR.name));
623
- const lenV = this.tmp("ln");
624
- this.setKind(lenV, "int");
625
- this.emit(I.call(lenV, "rt_list_len", [listV]));
626
- const idxV = this.tmp("ix");
627
- this.setKind(idxV, "int");
628
- this.emit(I.const_(idxV, 0));
629
- const oneV = this.tmp("one");
630
- this.setKind(oneV, "int");
631
- this.emit(I.const_(oneV, 1));
632
- const itemName = st.变量;
633
- this.setKind(itemName, "int");
634
-
635
- const prev = this.cur;
636
- const headB = this.newBlock();
637
- const bodyB = this.newBlock();
638
- const endB = this.newBlock();
639
- const contB = this.newBlock();
640
- prev.term = I.jump(headB.id);
641
-
642
- this.cur = headB;
643
- const cond = this.tmp("c");
644
- this.setKind(cond, "int");
645
- this.emit(I.binop("lt", cond, idxV, lenV));
646
- this.cur.term = I.branch(cond, bodyB.id, endB.id);
647
-
648
- this.cur = bodyB;
649
- if (listR.kind === "intlist") {
650
- // 无装箱整数列表:data[idx] 直接是 int
651
- const itemV = this.tmp("it");
652
- this.setKind(itemV, "int");
653
- this.emit(I.call(itemV, "rt_list_get", [listV, idxV]));
654
- this.emit(I.mov(itemName, itemV));
655
- } else {
656
- const boxV = this.tmp("b");
657
- this.setKind(boxV, "box");
658
- this.emit(I.call(boxV, "rt_list_get", [listV, idxV]));
659
- // 内联拆箱为 int
660
- const unboxed = this.tmp("u");
661
- this.setKind(unboxed, "int");
662
- this.emit(I.unbox(unboxed, boxV, "int"));
663
- this.emit(I.mov(itemName, unboxed));
664
- }
665
- this.loopStack.push({ end: endB.id, cont: contB.id });
666
- for (const s of st.体) this.genStmt(s);
667
- if (this.cur.term.kind === "unreachable") this.cur.term = I.jump(contB.id);
668
- this.loopStack.pop();
669
-
670
- this.cur = contB;
671
- const ni = this.tmp("n");
672
- this.setKind(ni, "int");
673
- this.emit(I.binop("add", ni, idxV, oneV));
674
- this.emit(I.mov(idxV, ni));
675
- this.cur.term = I.jump(headB.id);
676
-
677
- this.cur = endB;
678
- }
679
-
680
- genCallStmt(st) {
681
- const r = this.genExpr(st);
682
- void r;
683
- }
684
-
685
- // ---------- 自动拆箱:若 expr.kind === "box",插入拆箱指令并返回拆箱后的值 ----------
686
- // asKind: 期望拆成 "int" 或 "double"
687
- unboxExpr(expr, asKind) {
688
- if (expr.kind !== "box") return expr;
689
- const d = this.tmp("ub");
690
- this.setKind(d, asKind);
691
- this.emit(I.unbox(d, expr.name, asKind));
692
- return { name: d, kind: asKind };
693
- }
694
-
695
- // ---------- 自动类型转换:若 expr.kind === "int" 但需要 double,插入 itof 指令 ----------
696
- toDouble(expr) {
697
- if (expr.kind === "double") return expr;
698
- const d = this.tmp("fd");
699
- this.setKind(d, "double");
700
- this.emit(I.itof(d, expr.name));
701
- return { name: d, kind: "double" };
702
- }
703
-
704
- // ---------- 表达式:返回 {name, kind} ----------
705
- genExpr(node) {
706
- switch (node.类型) {
707
- case "字面量": return this.genLiteral(node);
708
- case "标识符": {
709
- return { name: node.名字, kind: this.kindOf(node.名字) };
710
- }
711
- case "一元": return this.genUnary(node);
712
- case "二元": return this.genBinary(node);
713
- case "函数调用": return this.genCall(node);
714
- case "下标": return this.genIndex(node);
715
- case "列表字面量": return this.genListLit(node);
716
- case "字典字面量": return this.genDictLit(node);
717
- default: {
718
- // 未知:当成 int 0
719
- const d = this.tmp("x"); this.setKind(d, "int");
720
- this.emit(I.const_(d, 0));
721
- return { name: d, kind: "int" };
722
- }
723
- }
724
- }
725
-
726
- genLiteral(node) {
727
- if (node.字面类型 === "整数" || node.字面类型 === "布尔") {
728
- const d = this.tmp("c"); this.setKind(d, "int");
729
- this.emit(I.const_(d, parseInt(node.值, 10)));
730
- return { name: d, kind: "int" };
731
- }
732
- if (node.字面类型 === "浮点") {
733
- const d = this.tmp("d"); this.setKind(d, "double");
734
- this.emit(I.const_(d, this.dblConst(String(node.值))));
735
- return { name: d, kind: "double" };
736
- }
737
- if (node.字面类型 === "字符串") {
738
- const d = this.tmp("s"); this.setKind(d, "str");
739
- this.emit(I.const_(d, this.strConst(node.值)));
740
- return { name: d, kind: "str" };
741
- }
742
- const d = this.tmp("n"); this.setKind(d, "int");
743
- this.emit(I.const_(d, 0));
744
- return { name: d, kind: "none" };
745
- }
746
-
747
- genUnary(node) {
748
- let o = this.genExpr(node.操作数);
749
- // 自动拆箱:一元运算作用于 box 时,默认按 int 拆箱
750
- o = this.unboxExpr(o, "int");
751
- const d = this.tmp("u"); this.setKind(d, o.kind);
752
- if (node.运算符 === "-") {
753
- this.emit(I.binop("sub", d, o.name, o.name)); // 占位,后端处理 neg
754
- // 用专门 neg
755
- this.cur.instrs.pop();
756
- this.emit(I.unop("neg", d, o.name));
757
- } else if (node.运算符 === "非") {
758
- this.emit(I.unop("not", d, o.name));
759
- } else {
760
- this.emit(I.mov(d, o.name));
761
- }
762
- return { name: d, kind: o.kind };
763
- }
764
-
765
- genBinary(node) {
766
- const op = node.运算符;
767
- if (op === "且" || op === "或") return this.genLogic(node, op === "且");
768
-
769
- let L = this.genExpr(node.左);
770
- let R = this.genExpr(node.右);
771
-
772
- // 字符串拼接
773
- if (op === "+" && (L.kind === "str" || R.kind === "str")) {
774
- // 两侧都转 str
775
- let a = L.name, ak = L.kind;
776
- let b = R.name, bk = R.kind;
777
- if (ak !== "str") {
778
- const t = this.tmp("s"); this.setKind(t, "str");
779
- this.emit(I.call(t, ak === "double" ? "rt_double_to_str" : "rt_int_to_str", [a]));
780
- a = t;
781
- }
782
- if (bk !== "str") {
783
- const t = this.tmp("s"); this.setKind(t, "str");
784
- this.emit(I.call(t, bk === "double" ? "rt_double_to_str" : "rt_int_to_str", [b]));
785
- b = t;
786
- }
787
- const d = this.tmp("sc"); this.setKind(d, "str");
788
- this.emit(I.call(d, "rt_str_concat", [a, b]));
789
- return { name: d, kind: "str" };
790
- }
791
- // 字符串相等
792
- if ((op === "==" || op === "!=") && (L.kind === "str" || R.kind === "str")) {
793
- const d = this.tmp("eq"); this.setKind(d, "int");
794
- this.emit(I.call(d, "rt_str_eq", [L.name, R.name]));
795
- if (op === "!=") {
796
- const d2 = this.tmp("ne"); this.setKind(d2, "int");
797
- this.emit(I.binop("sub", d2, "zero_v", d));
798
- this.emit(I.const_("zero_v", 0));
799
- return { name: d2, kind: "int" };
800
- }
801
- return { name: d, kind: "int" };
802
- }
803
-
804
- // 自动拆箱:box 操作数根据另一侧的类型自动拆箱
805
- // 若两侧都是 box(如两个列表元素比较),统一按 int 拆箱
806
- const targetKind = (L.kind === "double" || R.kind === "double") ? "double" : "int";
807
- L = this.unboxExpr(L, L.kind === "box" ? targetKind : L.kind);
808
- R = this.unboxExpr(R, R.kind === "box" ? targetKind : R.kind);
809
-
810
- // 若结果是 double 但操作数是 int,自动插入 int->double 转换
811
- const resKind0 = (L.kind === "double" || R.kind === "double") ? "double" : "int";
812
- if (resKind0 === "double") {
813
- L = this.toDouble(L);
814
- R = this.toDouble(R);
815
- }
816
-
817
- const d = this.tmp("b");
818
- // kind: 若任一 double 则 double,否则 int
819
- const resKind = (L.kind === "double" || R.kind === "double") ? "double" : "int";
820
- this.setKind(d, resKind);
821
-
822
- const map = {
823
- "+": "add", "-": "sub", "*": "mul", "/": "div",
824
- "//": "div", "%": "mod",
825
- "<": "lt", ">": "gt", "<=": "le", ">=": "ge", "==": "eq", "!=": "ne",
826
- "&": "and", "|": "or", "^": "xor", "<<": "shl", ">>": "shr"
827
- };
828
- const irop = map[op];
829
- if (!irop) throw new Error("不支持的运算符: " + op);
830
- this.emit(I.binop(irop, d, L.name, R.name));
831
- return { name: d, kind: (["lt","gt","le","ge","eq","ne"].includes(irop)) ? "int" : resKind };
832
- }
833
-
834
- genLogic(node, isAnd) {
835
- // 生成短路逻辑:返回 int 临时
836
- // 注意:必须先用 new I.Block 建块但【不移动 this.cur】,再把左值表达式 emit 进 prev。
837
- // 旧实现用 this.newBlock(),它会把 this.cur 依次改成 falseL/trueL/endL,
838
- // 导致左值比较被错误地 emit 进 endL(先使用后定义),造成短路条件下的越界访问。
839
- const prev = this.cur;
840
- const falseL = new I.Block(this.blocks.length); this.blocks.push(falseL);
841
- const trueL = new I.Block(this.blocks.length); this.blocks.push(trueL);
842
- const endL = new I.Block(this.blocks.length); this.blocks.push(endL);
843
- const res = this.tmp("lg"); this.setKind(res, "int");
844
- this.cur = prev;
845
- const L = this.genExpr(node.左);
846
- // 若 L 为真(且),继续右;否则跳 false
847
- prev.term = I.branch(L.name, trueL.id, falseL.id);
848
- // 对"且":L 真则进 trueL 求右
849
- // 对"或":L 真则进 trueL 直接得 1
850
- this.cur = isAnd ? trueL : falseL;
851
- const R = this.genExpr(node.右);
852
- this.emit(I.mov(res, R.name));
853
- this.cur.term = I.jump(endL.id);
854
- this.cur = isAnd ? falseL : trueL;
855
- if (isAnd) {
856
- const z = this.tmp("z"); this.setKind(z, "int"); this.emit(I.const_(z, 0));
857
- this.emit(I.mov(res, z));
858
- } else {
859
- const o = this.tmp("o"); this.setKind(o, "int"); this.emit(I.const_(o, 1));
860
- this.emit(I.mov(res, o));
861
- }
862
- this.cur.term = I.jump(endL.id);
863
- this.cur = endL;
864
- return { name: res, kind: "int" };
865
- }
866
-
867
- genIndex(node) {
868
- const C = this.genExpr(node.容器);
869
- const Ix = this.genExpr(node.索引);
870
- if (C.kind === "dict") {
871
- const d = this.tmp("ix"); this.setKind(d, "box");
872
- let key = Ix.name;
873
- if (Ix.kind !== "str") {
874
- const t = this.tmp("k"); this.setKind(t, "str");
875
- this.emit(I.call(t, Ix.kind === "double" ? "rt_double_to_str" : "rt_int_to_str", [key]));
876
- key = t;
877
- }
878
- this.emit(I.call(d, "rt_dict_get", [C.name, key]));
879
- return { name: d, kind: "box" };
880
- }
881
- if (C.kind === "str") {
882
- const d = this.tmp("ix"); this.setKind(d, "box");
883
- this.emit(I.call(d, "rt_str_at", [C.name, Ix.name]));
884
- return { name: d, kind: "box" };
885
- }
886
- // 无装箱整数列表:data[idx] 直接就是 int,无需拆箱
887
- if (C.kind === "intlist") {
888
- const d = this.tmp("ix"); this.setKind(d, "int");
889
- this.emit(I.call(d, "rt_list_get", [C.name, Ix.name]));
890
- return { name: d, kind: "int" };
891
- }
892
- // 普通 list 或 box(list)
893
- const d = this.tmp("ix"); this.setKind(d, "box");
894
- let listArg = C.name;
895
- if (C.kind === "box") {
896
- const t = this.tmp("u"); this.setKind(t, "list");
897
- this.emit(I.call(t, "rt_box_unbox_ptr", [listArg]));
898
- listArg = t;
899
- }
900
- this.emit(I.call(d, "rt_list_get", [listArg, Ix.name]));
901
- return { name: d, kind: "box" };
902
- }
903
-
904
- genIndexAssign(target, value, ctx) {
905
- const C = this.genExpr(target.容器);
906
- const Ix = this.genExpr(target.索引);
907
- let V = this.genExpr(value);
908
- // 无装箱整数列表:直接存 int,跳过 Box 分配
909
- if (C.kind === "intlist") {
910
- // 若值是 box(从别处读出的),先拆箱
911
- if (V.kind === "box") V = this.unboxExpr(V, "int");
912
- const d = this.tmp("r"); this.setKind(d, "int");
913
- this.emit(I.call(d, "rt_list_set", [C.name, Ix.name, V.name]));
914
- return;
915
- }
916
- // 自动拆箱:若值是 box 但容器下标赋值需要直接存 box,保持 box;
917
- // 若值是 int/double,才需要装箱
918
- let boxV;
919
- if (V.kind === "box") {
920
- // 已经是 box,直接使用,避免重复装箱
921
- boxV = V.name;
922
- } else {
923
- boxV = this.tmp("bx"); this.setKind(boxV, "box");
924
- const boxOp = V.kind === "int" ? "rt_box_int"
925
- : V.kind === "double" ? "rt_box_double"
926
- : V.kind === "str" ? "rt_box_str" : "rt_box_ptr";
927
- if (boxOp === "rt_box_ptr") {
928
- const tag = this.tmp("tag"); this.setKind(tag, "int");
929
- this.emit(I.const_(tag, V.kind === "dict" ? 4 : 3));
930
- this.emit(I.call(boxV, "rt_box_ptr", [V.name, tag]));
931
- } else {
932
- this.emit(I.call(boxV, boxOp, [V.name]));
933
- }
934
- }
935
- if (C.kind === "dict") {
936
- let key = Ix.name;
937
- if (Ix.kind !== "str") {
938
- const t = this.tmp("k"); this.setKind(t, "str");
939
- this.emit(I.call(t, Ix.kind === "double" ? "rt_double_to_str" : "rt_int_to_str", [key]));
940
- key = t;
941
- }
942
- const d = this.tmp("r"); this.setKind(d, "int");
943
- this.emit(I.call(d, "rt_dict_set", [C.name, key, boxV]));
944
- } else {
945
- let listArg = C.name;
946
- if (C.kind === "box") {
947
- const t = this.tmp("u"); this.setKind(t, "list");
948
- this.emit(I.call(t, "rt_box_unbox_ptr", [listArg]));
949
- listArg = t;
950
- }
951
- const d = this.tmp("r"); this.setKind(d, "int");
952
- this.emit(I.call(d, "rt_list_set", [listArg, Ix.name, boxV]));
953
- }
954
- }
955
-
956
- genListLit(node) {
957
- // 先分析所有元素,判断是否全为整数
958
- const elems = node.元素.map(el => {
959
- const V = this.genExpr(el);
960
- return V;
961
- });
962
- const allInt = elems.every(V => V.kind === "int");
963
- // 全整数列表(含空列表 [])→ 创建无装箱整数列表
964
- if (allInt) {
965
- const lst = this.tmp("il"); this.setKind(lst, "intlist");
966
- this.emit(I.call(lst, "rt_intlist_create", []));
967
- for (const V of elems) {
968
- const d = this.tmp("r"); this.setKind(d, "int");
969
- this.emit(I.call(d, "rt_intlist_append", [lst, V.name]));
970
- }
971
- return { name: lst, kind: "intlist" };
972
- }
973
- // 混合类型列表 → 普通装箱列表
974
- const lst = this.tmp("l"); this.setKind(lst, "list");
975
- this.emit(I.call(lst, "rt_list_create", []));
976
- for (const V of elems) {
977
- const boxV = this.tmp("bx"); this.setKind(boxV, "box");
978
- const boxOp = V.kind === "int" ? "rt_box_int"
979
- : V.kind === "double" ? "rt_box_double"
980
- : V.kind === "str" ? "rt_box_str" : "rt_box_ptr";
981
- if (boxOp === "rt_box_ptr") {
982
- const tag = this.tmp("tag"); this.setKind(tag, "int");
983
- this.emit(I.const_(tag, V.kind === "dict" ? 4 : 3));
984
- this.emit(I.call(boxV, "rt_box_ptr", [V.name, tag]));
985
- } else {
986
- this.emit(I.call(boxV, boxOp, [V.name]));
987
- }
988
- const d = this.tmp("r"); this.setKind(d, "int");
989
- this.emit(I.call(d, "rt_list_append", [lst, boxV]));
990
- }
991
- return { name: lst, kind: "list" };
992
- }
993
-
994
- genDictLit(node) {
995
- const d = this.tmp("d"); this.setKind(d, "dict");
996
- this.emit(I.call(d, "rt_dict_create", []));
997
- for (let i = 0; i < node.键.length; i++) {
998
- const K = this.genExpr(node.键[i]);
999
- const V = this.genExpr(node.值[i]);
1000
- const boxV = this.tmp("bx"); this.setKind(boxV, "box");
1001
- const boxOp = V.kind === "int" ? "rt_box_int"
1002
- : V.kind === "double" ? "rt_box_double"
1003
- : V.kind === "str" ? "rt_box_str" : "rt_box_ptr";
1004
- if (boxOp === "rt_box_ptr") {
1005
- const tag = this.tmp("tag"); this.setKind(tag, "int");
1006
- this.emit(I.const_(tag, V.kind === "dict" ? 4 : 3));
1007
- this.emit(I.call(boxV, "rt_box_ptr", [V.name, tag]));
1008
- } else {
1009
- this.emit(I.call(boxV, boxOp, [V.name]));
1010
- }
1011
- const r = this.tmp("r"); this.setKind(r, "int");
1012
- this.emit(I.call(r, "rt_dict_set", [d, K.name, boxV]));
1013
- }
1014
- return { name: d, kind: "dict" };
1015
- }
1016
-
1017
- genCall(node) {
1018
- const name = node.被调者.类型 === "标识符" ? node.被调者.名字 : null;
1019
- // 内置:输出
1020
- if (name === "输出") return this.genPrintCall(node.参数);
1021
- // 内置:长度
1022
- if (name === "长度") {
1023
- const a = this.genExpr(node.参数[0]);
1024
- const d = this.tmp("ln"); this.setKind(d, "int");
1025
- const rt = a.kind === "str" ? "rt_str_len" : (a.kind === "list" || a.kind === "intlist") ? "rt_list_len"
1026
- : a.kind === "dict" ? "rt_dict_len" : "rt_box_tag";
1027
- this.emit(I.call(d, rt, [a.name]));
1028
- return { name: d, kind: "int" };
1029
- }
1030
- if (name === "转字符串") {
1031
- const a = this.genExpr(node.参数[0]);
1032
- const d = this.tmp("s"); this.setKind(d, "str");
1033
- this.emit(I.call(d, a.kind === "double" ? "rt_double_to_str" : "rt_int_to_str", [a.name]));
1034
- return { name: d, kind: "str" };
1035
- }
1036
- if (name === "追加") {
1037
- const L = this.genExpr(node.参数[0]);
1038
- const V = this.genExpr(node.参数[1]);
1039
- const d = this.tmp("r"); this.setKind(d, "int");
1040
- // 无装箱整数列表:直接存 int,跳过 Box 分配
1041
- if (L.kind === "intlist" && V.kind === "int") {
1042
- this.emit(I.call(d, "rt_intlist_append", [L.name, V.name]));
1043
- return { name: d, kind: "none" };
1044
- }
1045
- const boxV = this.tmp("bx"); this.setKind(boxV, "box");
1046
- this.emit(I.call(boxV, V.kind === "int" ? "rt_box_int" : V.kind === "double" ? "rt_box_double" : V.kind === "str" ? "rt_box_str" : "rt_box_ptr", [V.name]));
1047
- this.emit(I.call(d, "rt_list_append", [L.name, boxV]));
1048
- return { name: d, kind: "none" };
1049
- }
1050
- // 用户函数
1051
- if (!name) throw new Error("间接调用暂不支持");
1052
- const argNames = [];
1053
- for (const a of node.参数) {
1054
- const r = this.genExpr(a);
1055
- argNames.push(r.name);
1056
- }
1057
- const d = this.tmp("call"); this.setKind(d, "int");
1058
- this.emit(I.call(d, name, argNames));
1059
- return { name: d, kind: "int" };
1060
- }
1061
-
1062
- genPrintCall(args) {
1063
- // 依次打印,最后 nl;返回 none
1064
- const dummy = this.tmp("p"); this.setKind(dummy, "none");
1065
- let first = true;
1066
- for (const a of args) {
1067
- if (!first) {
1068
- this.emit(I.call(dummy, "rt_print_space", []));
1069
- }
1070
- first = false;
1071
- const r = this.genExpr(a);
1072
- const rt = r.kind === "double" ? "rt_print_double"
1073
- : r.kind === "str" ? "rt_print_str"
1074
- : (r.kind === "list" || r.kind === "intlist") ? "rt_print_list"
1075
- : r.kind === "dict" ? "rt_print_dict"
1076
- : r.kind === "box" ? "rt_print_box"
1077
- : "rt_print_int";
1078
- if (rt === "rt_print_double") {
1079
- // 单参
1080
- this.emit(I.call(dummy, rt, [r.name]));
1081
- } else {
1082
- this.emit(I.call(dummy, rt, [r.name]));
1083
- }
1084
- }
1085
- this.emit(I.call(dummy, "rt_print_nl", []));
1086
- return { name: dummy, kind: "none" };
1087
- }
1088
- }
1089
-
1090
- // ============================================================
1091
- // 后端:IR -> x86-64 汇编
1092
- // ============================================================
1093
- class IRToAsm {
1094
- constructor() {
1095
- this.lines = []; // .text
1096
- this.rodata = [];
1097
- this.seq = 0;
1098
- }
1099
-
1100
- emit(line) { this.lines.push(line); }
1101
-
1102
- // 编译整个优化后程序
1103
- compile(functions, allocation, kinds) {
1104
- // 为每个函数编译
1105
- for (const fn of functions) {
1106
- this.compileFunc(fn, allocation.get(fn.name), kinds);
1107
- }
1108
- this.deadStoreElim();
1109
- }
1110
-
1111
- // 栈槽死存储消除(asm 级,安全):
1112
- // 每个函数有自己的 rbp 帧,偏移必须【按函数】独立分析。
1113
- // 若某偏移在本函数内只被写、从未被读,则那次写是死存储,删除。
1114
- // 覆盖 mov 与 movsd(load: `mov[s] OFF(%rbp), %reg`;store: `mov[s] %reg, OFF(%rbp)`)。
1115
- deadStoreElim() {
1116
- // 存储行(写到 [rbp+off]):mov/movsd 目的为内存。
1117
- const storeRe = /^\s*(mov|movsd)\s+%\w+,\s+(-?\d+)\(%rbp\)\s*$/;
1118
- // 任意对 [rbp+off] 的引用(含 movsd/mulsd/addsd/divsd 等的内存源操作数)。
1119
- const anyRefRe = /(-?\d+)\(%rbp\)/g;
1120
- const isFuncLabel = (l) => /^(co_main|FUNC_\w+):\s*$/.test(l);
1121
- let cur = [];
1122
- const funcs = [];
1123
- for (const ln of this.lines) {
1124
- if (isFuncLabel(ln)) { if (cur.length) funcs.push(cur); cur = [ln]; }
1125
- else cur.push(ln);
1126
- }
1127
- if (cur.length) funcs.push(cur);
1128
- const out = [];
1129
- for (const f of funcs) {
1130
- // 统计每个偏移在本函数内被引用的行数;若偏移除「存储行」外再无引用,则其存储是死的。
1131
- const refCount = new Map();
1132
- for (const ln of f) {
1133
- const m = ln.match(storeRe);
1134
- const refs = ln.match(anyRefRe) || [];
1135
- for (const r of refs) {
1136
- const off = r.match(/(-?\d+)\(%rbp\)/)[1];
1137
- // 存储行自身的引用不算「读」
1138
- if (m && r === `${m[2]}(%rbp)`) continue;
1139
- refCount.set(off, (refCount.get(off) || 0) + 1);
1140
- }
1141
- }
1142
- for (const ln of f) {
1143
- const m = ln.match(storeRe);
1144
- if (m && !refCount.has(m[2])) continue; // 无任何读 -> 死存储
1145
- out.push(ln);
1146
- }
1147
- }
1148
- this.lines = out;
1149
- }
1150
-
1151
- // ---------- 变量家槽分配 ----------
1152
- allocateHomes(fn, nPushed, promoted) {
1153
- const home = new Map(); // var -> 栈偏移(负,相对 rbp)
1154
- let n = 0;
1155
- // 收集所有出现过的变量名
1156
- const all = new Set(fn.params || []);
1157
- for (const b of fn.blocks) {
1158
- for (const ins of b.instrs) {
1159
- for (const u of I.instrUse(ins)) all.add(u);
1160
- const d = I.instrDef(ins); if (d) all.add(d);
1161
- }
1162
- for (const u of I.termUse(b.term)) all.add(u);
1163
- }
1164
- // 识别常量变量(立即数可替代):无需家槽
1165
- const constSet = new Set();
1166
- {
1167
- const mod = new Set();
1168
- for (const b of fn.blocks) for (const ins of b.instrs) {
1169
- const d = I.instrDef(ins);
1170
- if (d != null && ins.op !== "const") mod.add(d);
1171
- }
1172
- for (const b of fn.blocks) for (const ins of b.instrs) {
1173
- if (ins.op === "const" && typeof ins.value === "number" && !mod.has(ins.dest))
1174
- constSet.add(ins.dest);
1175
- }
1176
- }
1177
- for (const v of all) {
1178
- // 被调用者保存(cs=false)提升变量无需家槽;调用者保存(cs=true)需要家槽供 spill/reload
1179
- if (promoted && promoted.has(v) && !promoted.get(v).cs) continue;
1180
- if (constSet.has(v)) continue; // 立即数即可,无需家槽
1181
- home.set(v, -8 * (nPushed + 1 + n));
1182
- n++;
1183
- }
1184
- return { home, count: n };
1185
- }
1186
-
1187
- // ---------- 计算每个基本块的循环嵌套深度 ----------
1188
- // 深度 0 = 非循环代码;每多一层循环 +1。用于给内层循环变量高权重。
1189
- computeLoopDepth(fn) {
1190
- I.buildCFG(fn);
1191
- const n = fn.blocks.length;
1192
- // 可达性 reach[s] = Set(t):从 s 沿 CFG 能到达的块
1193
- const reach = Array.from({ length: n }, () => new Set());
1194
- for (let s = 0; s < n; s++) {
1195
- const seen = new Set([s]);
1196
- const wl = [s];
1197
- while (wl.length) {
1198
- const x = wl.pop();
1199
- for (const y of (fn.blocks[x].succs || [])) {
1200
- if (seen.has(y)) continue;
1201
- seen.add(y); reach[s].add(y); wl.push(y);
1202
- }
1203
- }
1204
- }
1205
- // 深度:对每个块 b,统计「有多少个头 H 使得 H 在 b 的自然循环内」。
1206
- // 头 H 的自然循环 = { H } ∪ 从 H 的某回边源反向可达、且必经 H 的块。
1207
- // 简化:块 x 的深度 = 有多少个 (回边 b->H) 满足 H==x 或 x 在 H 的循环内。
1208
- const depth = new Array(n).fill(0);
1209
- for (let b = 0; b < n; b++) {
1210
- for (const H of (fn.blocks[b].succs || [])) {
1211
- // 回边判定:H 可达 b,且 H 在程序顺序上位于 b 之前(结构化循环头)。
1212
- // 仅用 reach[H].has(b) 会把强连通循环内的每条边都误判为回边。
1213
- if (!reach[H].has(b)) continue;
1214
- if (H >= b) continue;
1215
- // H 的循环体 = H + 从 b 沿【前驱】反向可达、不经过 H 的块
1216
- const loopSet = new Set([H]);
1217
- const wl = [b];
1218
- while (wl.length) {
1219
- const x = wl.pop();
1220
- if (x === H || loopSet.has(x)) continue;
1221
- loopSet.add(x);
1222
- for (const y of (fn.blocks[x].preds || [])) wl.push(y);
1223
- }
1224
- for (const x of loopSet) depth[x]++;
1225
- }
1226
- }
1227
- if (process.env.COCN_DUMP_DEPTH) console.error("DEPTH", JSON.stringify(depth));
1228
- return depth;
1229
- }
1230
-
1231
- // ---------- 选择要提升到寄存器的整型变量(循环深度加权 + call 感知) ----------
1232
- // 寄存器池:
1233
- // 被调用者保存(rbx/r12-r15):跨 call 自动保留,无需 spill。
1234
- // 调用者保存(r8/r9):call 会破坏,需在 call 前 spill 到家槽;但在无 call 的内层
1235
- // 循环里全程驻留,零栈往返。scratch 保留 rax/r10/r11/rcx/rdx/rsi/rdi。
1236
- choosePromoted(fn, kinds) {
1237
- const CALLEE = ["rbx", "r12", "r13", "r14", "r15"];
1238
- const CALLER = []; // 调用者保存寄存器保守不使用
1239
- const depth = this.computeLoopDepth(fn);
1240
- const weight = new Map();
1241
- const useBlocks = new Map(); // var -> Set(blockId) where it is USED
1242
- const bump = (v, w, bi) => {
1243
- if (v == null) return;
1244
- weight.set(v, (weight.get(v) || 0) + w);
1245
- if (!useBlocks.has(v)) useBlocks.set(v, new Set());
1246
- useBlocks.get(v).add(bi);
1247
- };
1248
- for (let bi = 0; bi < fn.blocks.length; bi++) {
1249
- const d = depth[bi] || 0;
1250
- const w = Math.pow(4, d); // 内层循环权重指数级放大
1251
- const b = fn.blocks[bi];
1252
- for (const ins of b.instrs) {
1253
- const dd = I.instrDef(ins); if (dd) bump(dd, w, bi);
1254
- for (const u of I.instrUse(ins)) bump(u, w, bi);
1255
- }
1256
- for (const u of I.termUse(b.term)) bump(u, w, bi);
1257
- }
1258
- const paramSet = new Set(fn.params || []);
1259
- // 常量变量(立即数可替代)不需要驻留寄存器
1260
- const constLike = new Set();
1261
- {
1262
- const mod = new Set();
1263
- for (const b of fn.blocks) for (const ins of b.instrs) {
1264
- const d = I.instrDef(ins);
1265
- if (d != null && ins.op !== "const") mod.add(d);
1266
- }
1267
- for (const b of fn.blocks) for (const ins of b.instrs) {
1268
- if (ins.op === "const" && typeof ins.value === "number" && !mod.has(ins.dest))
1269
- constLike.add(ins.dest);
1270
- }
1271
- }
1272
- const cands = [];
1273
- // 收集 call 结果变量(必须跨后续 call 存活,优先提升到 callee-saved)
1274
- const callDefs = new Set();
1275
- for (const b of fn.blocks) for (const ins of b.instrs) {
1276
- if (ins.op === "call" || ins.op === "call_reg") callDefs.add(ins.dest);
1277
- }
1278
- for (const [v, w] of weight) {
1279
- const k = kinds.kindOf(v);
1280
- // 允许提升整型与指针类(list/intlist/dict/box/ptr 都是 8 字节指针)
1281
- if (k !== "int" && k !== "list" && k !== "intlist" && k !== "dict" && k !== "box" && k !== "none") continue;
1282
- if (constLike.has(v)) continue; // 立即数即可,不占用寄存器
1283
- // 只提升「跨块活跃」的变量:被多个块使用(或参数)。单块临时量不需要
1284
- // 驻留被调用者保存寄存器(否则递归函数每次调用白白 push/pop 多个寄存器)。
1285
- const nBlocks = (useBlocks.get(v) || new Set()).size;
1286
- // 调用结果必须跨后续 call 存活:即使单块也提升到 callee-saved,避免家槽往返
1287
- const isCallResult = callDefs.has(v);
1288
- if (nBlocks < 2 && !paramSet.has(v) && !isCallResult) continue;
1289
- // 列表/字典指针变量权重加成:内层循环中每次 list_get/set 都需要指针,
1290
- // 保持在寄存器中可省掉家槽往返,比临时索引计算收益更高。
1291
- let adjustedW = w;
1292
- if (k === "intlist" || k === "list" || k === "dict") adjustedW = w * 3;
1293
- cands.push([v, adjustedW]);
1294
- }
1295
- cands.sort((a, b) => b[1] - a[1]);
1296
- if (process.env.COCN_DUMP_PROMO) console.error("WEIGHTS", fn.name, JSON.stringify(cands.slice(0,15)));
1297
- const promoted = new Map(); // var -> {reg, cs}
1298
- for (const [v, w] of cands) {
1299
- if (w < 2) break;
1300
- if (promoted.size < CALLEE.length) {
1301
- promoted.set(v, { reg: CALLEE[promoted.size], cs: false });
1302
- } else break;
1303
- }
1304
- if (process.env.COCN_DUMP_PROMO) console.error("PROMO", fn.name, JSON.stringify([...promoted]));
1305
- return promoted;
1306
- }
1307
-
1308
- compileFunc(fn, alloc, kinds) {
1309
- // 1) 块内折叠 + 常量折叠(安全 pass,不重排有副作用的调用)
1310
- collapseTemps(fn);
1311
- foldConstants(fn, kinds);
1312
- // LICM:循环不变量外提(已修复回边检测)。外提纯算术指令到 preheader。
1313
- licm(fn); foldConstants(fn, kinds);
1314
- // 死代码消除:删除未使用的纯计算结果
1315
- deadCodeElimination(fn);
1316
- collapseTemps(fn);
1317
- foldConstants(fn, kinds);
1318
-
1319
- const POOL = ["rbx", "r12", "r13", "r14", "r15"]; // callee-saved
1320
- // 寄存器分配:循环深度加权,优先被调用者保存,其次调用者保存(r8/r9)。
1321
- // 叶子函数(无 call)可安全使用调用者保存寄存器,无需 push/pop。
1322
- const promoted = this.choosePromoted(fn, kinds);
1323
- // 只 push/pop 本函数实际用到的被调用者保存寄存器,减小递归/小函数帧开销
1324
- const usedCallee = new Set([...promoted.values()].filter(e => !e.cs).map(e => e.reg));
1325
- const nPushed = usedCallee.size;
1326
- const { home, count } = this.allocateHomes(fn, nPushed, promoted);
1327
- let frame = Math.max(8 * (nPushed + 1 + count), 16);
1328
- frame = (frame + 15) & ~15; // 向上取整到 16
1329
- // push rbp 后 rsp≡0;再 push nPushed 个 + sub frame,需 (8*nPushed+frame)≡0 以对齐 call
1330
- if ((8 * nPushed + frame) % 16 !== 0) frame += 8;
1331
-
1332
- let L;
1333
- if (fn.name === "co_main") {
1334
- L = "co_main";
1335
- this.emit(".globl co_main");
1336
- } else {
1337
- L = "FUNC_" + fn.name.replace(/[^A-Za-z0-9_]/g, "_");
1338
- }
1339
- this.emit(L + ":");
1340
- this.emit("push %rbp");
1341
- this.emit("mov %rsp, %rbp");
1342
- for (const r of POOL) if (usedCallee.has(r)) this.emit("push %" + r);
1343
- if (frame > 0) this.emit("sub $" + frame + ", %rsp");
1344
-
1345
- // 参数 → 家槽 + 提升寄存器
1346
- const paramKinds = (fn.params || []).map(p => kinds.kindOf(p));
1347
- let ip = 0, xp = 0;
1348
- (fn.params || []).forEach((p) => {
1349
- const k = kinds.kindOf(p);
1350
- if (k === "double") {
1351
- this.emit("movsd " + pct(ARG_XMM[xp]) + ", " + home.get(p) + "(%rbp)");
1352
- xp++;
1353
- } else {
1354
- const r = ARG_INT[ip++];
1355
- for (const [v, off] of home) {
1356
- if (v === p || v.startsWith(p + "#")) {
1357
- this.emit("mov " + pct(r) + ", " + off + "(%rbp)");
1358
- }
1359
- }
1360
- const pr = promoted.get(p);
1361
- if (pr) this.emit("mov " + pct(r) + ", %" + pr.reg);
1362
- }
1363
- });
1364
-
1365
- const lblPre = ".L" + (this.seq++) + "_";
1366
- // 收集所有常量定义,供后端使用立即数优化。
1367
- // 仅包含「只被 const 定义、从未被其他指令修改」的变量,
1368
- // 避免变量被重新赋值后仍用旧常量值。
1369
- const constMap = new Map(); // var -> integer value
1370
- const modified = new Set();
1371
- for (const b of fn.blocks) {
1372
- for (const ins of b.instrs) {
1373
- const d = I.instrDef(ins);
1374
- if (d != null && ins.op !== "const") modified.add(d);
1375
- }
1376
- }
1377
- for (const b of fn.blocks) {
1378
- for (const ins of b.instrs) {
1379
- if (ins.op === "const" && typeof ins.value === "number"
1380
- && kinds.kindOf(ins.dest) !== "double" && !modified.has(ins.dest)) {
1381
- // 只保留首次定义(避免重复)
1382
- if (!constMap.has(ins.dest)) constMap.set(ins.dest, ins.value);
1383
- }
1384
- }
1385
- }
1386
- // 浮点常量标签映射:dest -> .LCDn(仅未被修改的循环不变量常量)
1387
- const dblConstMap = new Map();
1388
- for (const b of fn.blocks) {
1389
- for (const ins of b.instrs) {
1390
- if (ins.op === "const" && kinds.kindOf(ins.dest) === "double"
1391
- && typeof ins.value === "string" && ins.value.startsWith(".LCD")
1392
- && !modified.has(ins.dest)) {
1393
- if (!dblConstMap.has(ins.dest)) dblConstMap.set(ins.dest, ins.value);
1394
- }
1395
- }
1396
- }
1397
- const ctx = { home, kinds, promoted, lblPre, usedCallee, constMap, dblConstMap,
1398
- csValid: new Set(), raxVar: null };
1399
- // 参数已写入提升寄存器,视为有效缓存
1400
- for (const [v, e] of promoted) if (e.cs) ctx.csValid.add(v);
1401
- const layout = layoutBlocks(fn);
1402
- for (let bi = 0; bi < layout.length; bi++) {
1403
- const b = fn.blocks[layout[bi]];
1404
- const nextId = bi + 1 < layout.length ? layout[bi + 1] : -1;
1405
- this.emit(lblPre + b.id + ":");
1406
- ctx.raxVar = null; // 跨块 rax 值不可知(汇合点/回边)
1407
- this.fNewBlock(ctx); // 块内浮点缓存开始
1408
- let fused = false;
1409
- for (let j = 0; j < b.instrs.length; j++) {
1410
- const ins = b.instrs[j];
1411
- // 比较+分支融合:块末比较直接喂给分支终结符
1412
- if (j === b.instrs.length - 1 && b.term.kind === "branch" &&
1413
- ["lt", "gt", "le", "ge", "eq", "ne"].includes(ins.op) &&
1414
- ins.dest === b.term.cond) {
1415
- // 浮点比较走 ucomisd 专用路径(内部自管 flush+jcc)
1416
- if (ctx.kinds.kindOf(ins.left) === "double" || ctx.kinds.kindOf(ins.right) === "double") {
1417
- this.emitFloatCmpBranch(ins, b.term, ctx, nextId);
1418
- } else {
1419
- // 整数比较:先 flush 浮点缓存到家槽(taken 路径也要正确),再发整数分支
1420
- this.fFlushAll(ctx);
1421
- this.emitCmpBranch(ins, b.term, ctx, nextId);
1422
- }
1423
- fused = true;
1424
- break;
1425
- }
1426
- this.emitInstr(ins, fn, ctx);
1427
- }
1428
- // 块结束前 flush 浮点缓存到家槽(家槽为跨块真相源)。movsd 不影响 flags。
1429
- this.fFlushAll(ctx);
1430
- if (!fused) this.emitTerm(b.term, ctx, nextId);
1431
- }
1432
- }
1433
-
1434
- // 把变量 v 加载进机器寄存器 dst
1435
- loadTo(v, dst, ctx) {
1436
- // 先查块内缓存:若 v 已在 dst 寄存器中,直接返回(无需 spill 或 mov)
1437
- if (ctx.iCache && ctx.iCache.get(v) === dst) return;
1438
- // dst 即将被覆写:若它是缓存寄存器且持有其他值,先 spill
1439
- this.iProtect(dst, ctx);
1440
- // 常量优化:若 v 是已知常量,直接用立即数
1441
- if (ctx.constMap && ctx.constMap.has(v)) {
1442
- this.emit("mov $" + ctx.constMap.get(v) + ", %" + dst);
1443
- return;
1444
- }
1445
- if (!ctx.home.has(v) && !ctx.promoted.has(v)) { this.emit("mov $0, %" + dst); return; }
1446
- // rax 仍持有 v:直接用,避免重载
1447
- if (dst === "rax" && ctx.raxVar === v) return;
1448
- // 块内缓存命中
1449
- if (ctx.iCache && ctx.iCache.has(v)) {
1450
- const cr = ctx.iCache.get(v);
1451
- if (cr !== dst) this.emit("mov %" + cr + ", %" + dst);
1452
- if (dst === "rax") ctx.raxVar = v;
1453
- return;
1454
- }
1455
- const pr = ctx.promoted.get(v);
1456
- if (pr) {
1457
- if (!pr.cs || ctx.csValid.has(v)) {
1458
- this.emit("mov %" + pr.reg + ", %" + dst);
1459
- } else {
1460
- // 调用者保存寄存器在 call 后失效:从家槽重载,同时重建寄存器缓存
1461
- this.emit("mov " + ctx.home.get(v) + "(%rbp), %" + dst);
1462
- this.emit("mov %" + dst + ", %" + pr.reg);
1463
- ctx.csValid.add(v);
1464
- }
1465
- if (dst === "rax") ctx.raxVar = v;
1466
- return;
1467
- }
1468
- this.emit("mov " + ctx.home.get(v) + "(%rbp), %" + dst);
1469
- if (dst === "rax") ctx.raxVar = v;
1470
- }
1471
- // 把寄存器 src 的值写回变量 v
1472
- storeFrom(v, src, ctx) {
1473
- const pr = ctx.promoted.get(v);
1474
- if (pr) {
1475
- this.emit("mov %" + src + ", %" + pr.reg);
1476
- if (pr.cs) ctx.csValid.add(v);
1477
- } else if (ctx.home.has(v)) {
1478
- // 块内缓存:把结果驻留到 r10/r11,避免立即写家槽(块末 flush)
1479
- const cr = this.iAlloc(ctx);
1480
- if (cr !== src) this.emit("mov %" + src + ", %" + cr);
1481
- ctx.iCache.set(v, cr);
1482
- ctx.iReg.set(cr, v);
1483
- }
1484
- // rax 值跟踪:若写回的是 rax,则 rax 当前持有 v
1485
- if (src === "rax") ctx.raxVar = v;
1486
- else ctx.raxVar = null;
1487
- }
1488
-
1489
- // ---------- 浮点 xmm 块内缓存 ----------
1490
- // 块开始时清空;块结束/调用前 flush 到家槽。家槽是跨块与跨调用的真相源。
1491
- fNewBlock(ctx) {
1492
- ctx.fCache = new Map(); // var -> xmm reg
1493
- ctx.fReg = new Map(); // xmm reg -> var
1494
- ctx.fPool = SCRATCH_XMM.slice();
1495
- // 整数块内缓存池(r10/r11):块内临时量驻留,避免家槽往返
1496
- ctx.iCache = new Map(); // var -> reg
1497
- ctx.iReg = new Map(); // reg -> var
1498
- }
1499
- // 淘汰指定寄存器(写回家槽)
1500
- fSpillReg(reg, ctx) {
1501
- const v = ctx.fReg.get(reg);
1502
- if (v == null) { if (!ctx.fPool.includes(reg)) ctx.fPool.push(reg); return; }
1503
- if (ctx.home.has(v)) this.emit("movsd %" + reg + ", " + ctx.home.get(v) + "(%rbp)");
1504
- ctx.fReg.delete(reg);
1505
- ctx.fCache.delete(v);
1506
- if (!ctx.fPool.includes(reg)) ctx.fPool.push(reg);
1507
- }
1508
- // 分配一个 xmm 寄存器;满则淘汰最早使用的
1509
- fAlloc(ctx) {
1510
- if (ctx.fPool.length) return ctx.fPool.shift();
1511
- this.fSpillReg(SCRATCH_XMM[0], ctx);
1512
- return SCRATCH_XMM[0];
1513
- }
1514
- // 确保 v 在某个 xmm 中,返回该 xmm(常量走 RIP 直接加载)
1515
- fLoad(v, ctx) {
1516
- const c = ctx.fCache.get(v);
1517
- if (c) return c;
1518
- const r = this.fAlloc(ctx);
1519
- if (ctx.dblConstMap && ctx.dblConstMap.has(v)) {
1520
- this.emit("movsd " + ctx.dblConstMap.get(v) + "(%rip), %" + r);
1521
- } else {
1522
- this.emit("movsd " + ctx.home.get(v) + "(%rbp), %" + r);
1523
- }
1524
- ctx.fCache.set(v, r);
1525
- ctx.fReg.set(r, v);
1526
- return r;
1527
- }
1528
- // 结果寄存器 r 现持有 v;若 r 原持有别的变量则先 spill
1529
- fSet(v, r, ctx) {
1530
- const old = ctx.fReg.get(r);
1531
- if (old && old !== v) {
1532
- if (ctx.home.has(old)) this.emit("movsd %" + r + ", " + ctx.home.get(old) + "(%rbp)");
1533
- ctx.fCache.delete(old);
1534
- }
1535
- const prev = ctx.fCache.get(v);
1536
- if (prev && prev !== r) ctx.fReg.delete(prev);
1537
- ctx.fCache.set(v, r);
1538
- ctx.fReg.set(r, v);
1539
- }
1540
- // flush 全部缓存到家槽(call 前 / 块结束前)。movsd 不影响 flags。
1541
- fFlushAll(ctx) {
1542
- if (ctx.iCache) this.iFlushAll(ctx);
1543
- if (!ctx.fCache || ctx.fCache.size === 0) return;
1544
- for (const [v, r] of ctx.fCache) {
1545
- if (ctx.home.has(v)) this.emit("movsd %" + r + ", " + ctx.home.get(v) + "(%rbp)");
1546
- }
1547
- ctx.fCache.clear();
1548
- ctx.fReg.clear();
1549
- ctx.fPool = SCRATCH_XMM.slice();
1550
- }
1551
-
1552
- // ---------- 整数块内缓存 ----------
1553
- // spill 某个缓存寄存器到家槽
1554
- iSpillReg(reg, ctx) {
1555
- const v = ctx.iReg.get(reg);
1556
- if (v == null) return;
1557
- if (ctx.home.has(v)) this.emit("mov %" + reg + ", " + ctx.home.get(v) + "(%rbp)");
1558
- ctx.iReg.delete(reg);
1559
- ctx.iCache.delete(v);
1560
- }
1561
- // 分配一个整数缓存寄存器;满则淘汰 r10
1562
- iAlloc(ctx) {
1563
- for (const r of INT_CACHE) if (!ctx.iReg.has(r)) return r;
1564
- this.iSpillReg(INT_CACHE[0], ctx);
1565
- return INT_CACHE[0];
1566
- }
1567
- // 即将把 dst 当 scratch 覆写;若 dst 是缓存寄存器,先 spill
1568
- iProtect(dst, ctx) {
1569
- if (INT_CACHE.includes(dst)) this.iSpillReg(dst, ctx);
1570
- }
1571
- // flush 全部整数缓存
1572
- iFlushAll(ctx) {
1573
- for (const v of [...ctx.iCache.keys()]) {
1574
- const r = ctx.iCache.get(v);
1575
- if (ctx.home.has(v)) this.emit("mov %" + r + ", " + ctx.home.get(v) + "(%rbp)");
1576
- }
1577
- ctx.iCache.clear();
1578
- ctx.iReg.clear();
1579
- }
1580
-
1581
- emitInstr(ins, fn, ctx) {
1582
- switch (ins.op) {
1583
- case "const": this.emitConst(ins, ctx); break;
1584
- case "mov": this.emitMov(ins, ctx); break;
1585
- case "neg": this.emitNeg(ins, ctx); break;
1586
- case "not": this.emitNot(ins, ctx); break;
1587
- case "unbox": this.emitUnbox(ins, ctx); break;
1588
- case "itof": this.emitItof(ins, ctx); break;
1589
- case "add": case "sub": case "mul": case "div": case "mod":
1590
- case "lt": case "gt": case "le": case "ge": case "eq": case "ne":
1591
- case "and": case "or": case "xor": case "shl": case "shr":
1592
- this.emitBinop(ins, ctx); break;
1593
- case "call": this.emitCall(ins, ctx); break;
1594
- case "load": this.emitLoad(ins, ctx); break;
1595
- case "store": this.emitStore(ins, ctx); break;
1596
- case "phi": break;
1597
- default: this.emit("# unknown op " + ins.op);
1598
- }
1599
- }
1600
-
1601
- emitConst(ins, ctx) {
1602
- if (ctx.kinds.kindOf(ins.dest) === "double") {
1603
- // 浮点常量:若已是 RIP 不变量(dblConstMap),使用时直接 RIP 相对加载,
1604
- // 此处无需发射;否则(被修改过的非常量)写回家槽。
1605
- if (!ctx.dblConstMap.has(ins.dest)) {
1606
- this.emit("movsd " + ins.value + "(%rip), %xmm0");
1607
- this.emit("movsd %xmm0, " + ctx.home.get(ins.dest) + "(%rbp)");
1608
- }
1609
- return;
1610
- }
1611
- const pd = ctx.promoted.get(ins.dest);
1612
- if (pd) {
1613
- this.emit("mov $" + ins.value + ", %" + pd.reg);
1614
- if (pd.cs) ctx.csValid.add(ins.dest);
1615
- } else if (ctx.constMap.has(ins.dest)) {
1616
- // 已识别为常量:使用处直接用立即数,无需发射指令或占缓存寄存器
1617
- } else {
1618
- // 直接放到缓存寄存器,省掉 rax 中转
1619
- const cr = this.iAlloc(ctx);
1620
- this.emit("mov $" + ins.value + ", %" + cr);
1621
- ctx.iCache.set(ins.dest, cr);
1622
- ctx.iReg.set(cr, ins.dest);
1623
- ctx.raxVar = null;
1624
- }
1625
- }
1626
-
1627
- emitMov(ins, ctx) {
1628
- if (ctx.kinds.kindOf(ins.dest) === "double") {
1629
- // D = S:确保 S 在某 xmm,复制到新结果寄存器
1630
- const sr = this.fLoad(ins.src, ctx);
1631
- const dr = this.fAlloc(ctx);
1632
- this.emit("movsd %" + sr + ", %" + dr);
1633
- this.fSet(ins.dest, dr, ctx);
1634
- return;
1635
- }
1636
- const Dp = ctx.promoted.get(ins.dest), Sp = ctx.promoted.get(ins.src);
1637
- if (Dp && Sp) {
1638
- this.emit("mov %" + Sp.reg + ", %" + Dp.reg);
1639
- if (Dp.cs) ctx.csValid.add(ins.dest);
1640
- return;
1641
- }
1642
- // 源是已知常量:直接放到目标缓存寄存器,省掉 rax 中转
1643
- if (ctx.constMap && ctx.constMap.has(ins.src)) {
1644
- if (Dp) {
1645
- this.emit("mov $" + ctx.constMap.get(ins.src) + ", %" + Dp.reg);
1646
- if (Dp.cs) ctx.csValid.add(ins.dest);
1647
- } else {
1648
- const cr = this.iAlloc(ctx);
1649
- this.emit("mov $" + ctx.constMap.get(ins.src) + ", %" + cr);
1650
- ctx.iCache.set(ins.dest, cr);
1651
- ctx.iReg.set(cr, ins.dest);
1652
- }
1653
- ctx.raxVar = null;
1654
- return;
1655
- }
1656
- this.loadTo(ins.src, "rax", ctx);
1657
- this.storeFrom(ins.dest, "rax", ctx);
1658
- }
1659
-
1660
- emitNeg(ins, ctx) {
1661
- this.loadTo(ins.src, "rax", ctx);
1662
- this.emit("neg %rax");
1663
- this.storeFrom(ins.dest, "rax", ctx);
1664
- }
1665
-
1666
- emitNot(ins, ctx) {
1667
- this.loadTo(ins.src, "rax", ctx);
1668
- this.emit("not %rax");
1669
- this.storeFrom(ins.dest, "rax", ctx);
1670
- }
1671
-
1672
- // 内联拆箱:直接从 Box* 偏移 8 处加载值,避免函数调用开销
1673
- // Box 布局:[tag(8)] [value(8)]
1674
- emitUnbox(ins, ctx) {
1675
- if (ins.kind === "double") {
1676
- this.loadTo(ins.src, "rax", ctx);
1677
- const dr = this.fAlloc(ctx);
1678
- this.emit("movsd 8(%rax), %" + dr);
1679
- this.fSet(ins.dest, dr, ctx);
1680
- } else {
1681
- // 整数拆箱:mov 8(%box_ptr), %dest
1682
- this.loadTo(ins.src, "rax", ctx);
1683
- this.emit("mov 8(%rax), %rax");
1684
- this.storeFrom(ins.dest, "rax", ctx);
1685
- }
1686
- }
1687
-
1688
- // 整数转浮点:cvtsi2sd
1689
- emitItof(ins, ctx) {
1690
- this.loadTo(ins.src, "rax", ctx);
1691
- const dr = this.fAlloc(ctx);
1692
- this.emit("cvtsi2sd %rax, %" + dr);
1693
- this.fSet(ins.dest, dr, ctx);
1694
- }
1695
-
1696
- emitBinop(ins, ctx) {
1697
- if (ctx.kinds.kindOf(ins.dest) === "double" ||
1698
- ["lt","gt","le","ge","eq","ne"].includes(ins.op) &&
1699
- (ctx.kinds.kindOf(ins.left) === "double" || ctx.kinds.kindOf(ins.right) === "double")) {
1700
- return this.emitFloatBinop(ins, ctx);
1701
- }
1702
- const L = ins.left, R = ins.right, D = ins.dest;
1703
- const Dp = ctx.promoted.get(D), Lp = ctx.promoted.get(L), Rp = ctx.promoted.get(R);
1704
- const isCmp = ["lt", "gt", "le", "ge", "eq", "ne"].includes(ins.op);
1705
- // 累加型:dest 与 left 在同一寄存器 → 直接 op R, D
1706
- if (Dp && Lp && Lp.reg === Dp.reg && !isCmp && ins.op !== "div" && ins.op !== "mod") {
1707
- if (ins.op === "shl" || ins.op === "shr") {
1708
- this.loadTo(R, "rcx", ctx);
1709
- this.emit((ins.op === "shl" ? "sal" : "sar") + " %cl, %" + Dp.reg);
1710
- } else if (ctx.constMap && ctx.constMap.has(R)) {
1711
- // 右操作数是已知常量 → 直接立即数运算,省掉 r10 中转
1712
- const op = ins.op === "mul" ? "imul" : ins.op;
1713
- this.emit(op + " $" + ctx.constMap.get(R) + ", %" + Dp.reg);
1714
- } else {
1715
- this.loadTo(R, "r10", ctx);
1716
- const op = ins.op === "mul" ? "imul" : ins.op;
1717
- this.emit(op + " %r10, %" + Dp.reg);
1718
- }
1719
- if (Dp.cs) ctx.csValid.add(D);
1720
- return;
1721
- }
1722
- // 通用:L -> rax,R -> r10
1723
- this.loadTo(L, "rax", ctx);
1724
- // 右操作数是已知常量时,用立即数形式,省掉 loadTo
1725
- if (ctx.constMap && ctx.constMap.has(R)) {
1726
- const imm = ctx.constMap.get(R);
1727
- switch (ins.op) {
1728
- case "add": this.emit("add $" + imm + ", %rax"); break;
1729
- case "sub": this.emit("sub $" + imm + ", %rax"); break;
1730
- case "and": this.emit("and $" + imm + ", %rax"); break;
1731
- case "or": this.emit("or $" + imm + ", %rax"); break;
1732
- case "xor": this.emit("xor $" + imm + ", %rax"); break;
1733
- case "mul": this.emit("imul $" + imm + ", %rax, %rax"); break;
1734
- case "div": case "mod": {
1735
- // div/mod 不能用立即数,需要加载到 r10
1736
- this.iProtect("r10", ctx);
1737
- this.emit("mov $" + imm + ", %r10");
1738
- this.emit("cqo");
1739
- this.emit("idiv %r10");
1740
- if (ins.op === "mod") this.emit("mov %rdx, %rax");
1741
- break;
1742
- }
1743
- case "shl": case "shr": {
1744
- // shift 用 cl,所以还是需要 mov 到 rcx
1745
- this.emit("mov $" + imm + ", %rcx");
1746
- this.emit((ins.op === "shl" ? "sal" : "sar") + " %cl, %rax");
1747
- break;
1748
- }
1749
- case "lt": case "gt": case "le": case "ge": case "eq": case "ne": {
1750
- this.emit("cmp $" + imm + ", %rax");
1751
- const setcc = { lt: "setl", gt: "setg", le: "setle", ge: "setge", eq: "sete", ne: "setne" }[ins.op];
1752
- this.emit(setcc + " %al");
1753
- this.emit("movzb %al, %eax");
1754
- break;
1755
- }
1756
- }
1757
- this.storeFrom(D, "rax", ctx);
1758
- return;
1759
- }
1760
- this.loadTo(R, "r10", ctx);
1761
- switch (ins.op) {
1762
- case "add": this.emit("add %r10, %rax"); break;
1763
- case "sub": this.emit("sub %r10, %rax"); break;
1764
- case "mul": this.emit("imul %r10, %rax"); break;
1765
- case "div": case "mod": {
1766
- this.emit("cqo");
1767
- this.emit("idiv %r10");
1768
- if (ins.op === "mod") this.emit("mov %rdx, %rax");
1769
- break;
1770
- }
1771
- case "and": this.emit("and %r10, %rax"); break;
1772
- case "or": this.emit("or %r10, %rax"); break;
1773
- case "xor": this.emit("xor %r10, %rax"); break;
1774
- case "shl": case "shr": {
1775
- this.emit("mov %r10, %rcx");
1776
- this.emit((ins.op === "shl" ? "sal" : "sar") + " %cl, %rax");
1777
- break;
1778
- }
1779
- case "lt": case "gt": case "le": case "ge": case "eq": case "ne": {
1780
- this.emit("cmp %r10, %rax");
1781
- const setcc = { lt: "setl", gt: "setg", le: "setle", ge: "setge", eq: "sete", ne: "setne" }[ins.op];
1782
- this.emit(setcc + " %al");
1783
- this.emit("movzb %al, %eax");
1784
- break;
1785
- }
1786
- }
1787
- this.storeFrom(D, "rax", ctx);
1788
- }
1789
-
1790
- // 浮点二元运算(算术 + 比较)。块内 xmm 缓存,家槽仅作溢出/跨块真相源。
1791
- emitFloatBinop(ins, ctx) {
1792
- const L = ins.left, R = ins.right, D = ins.dest;
1793
- const isCmp = ["lt", "gt", "le", "ge", "eq", "ne"].includes(ins.op);
1794
- let dr;
1795
- // 累加:D 已在缓存且 L==D 同一寄存器 -> 原地运算
1796
- if (!isCmp && ctx.fCache.get(D) && ctx.fCache.get(L) === ctx.fCache.get(D)) {
1797
- dr = ctx.fCache.get(D);
1798
- } else {
1799
- dr = this.fAlloc(ctx);
1800
- if (ctx.dblConstMap.has(L)) {
1801
- this.emit("movsd " + ctx.dblConstMap.get(L) + "(%rip), %" + dr);
1802
- } else {
1803
- const lr = this.fLoad(L, ctx);
1804
- if (lr !== dr) this.emit("movsd %" + lr + ", %" + dr);
1805
- }
1806
- }
1807
- if (isCmp) {
1808
- // ucomisd R, dr (dr 为左操作数 L)
1809
- if (ctx.dblConstMap.has(R)) this.emit("ucomisd " + ctx.dblConstMap.get(R) + "(%rip), %" + dr);
1810
- else { const rr = this.fLoad(R, ctx); this.emit("ucomisd %" + rr + ", %" + dr); }
1811
- const setcc = { lt: "setb", gt: "seta", le: "setbe", ge: "setae", eq: "sete", ne: "setne" }[ins.op];
1812
- this.emit(setcc + " %al");
1813
- this.emit("movzb %al, %eax");
1814
- this.storeFrom(D, "rax", ctx);
1815
- return;
1816
- }
1817
- const op = { add: "addsd", sub: "subsd", mul: "mulsd", div: "divsd" }[ins.op] || "addsd";
1818
- if (ctx.dblConstMap.has(R)) {
1819
- this.emit(op + " " + ctx.dblConstMap.get(R) + "(%rip), %" + dr);
1820
- } else {
1821
- const rr = this.fLoad(R, ctx);
1822
- this.emit(op + " %" + rr + ", %" + dr);
1823
- }
1824
- this.fSet(D, dr, ctx);
1825
- }
1826
-
1827
- // 浮点比较 + 分支融合:ucomisd 后 flush 缓存(movsd 不影响 flags),再发 jcc。
1828
- emitFloatCmpBranch(ins, term, ctx, nextId) {
1829
- const L = ins.left, R = ins.right;
1830
- const lr = this.fLoad(L, ctx);
1831
- if (ctx.dblConstMap.has(R)) {
1832
- this.emit("ucomisd " + ctx.dblConstMap.get(R) + "(%rip), %" + lr);
1833
- } else {
1834
- const rr = this.fLoad(R, ctx);
1835
- this.emit("ucomisd %" + rr + ", %" + lr);
1836
- }
1837
- // flush 浮点缓存到家槽(必须在 jcc 前,保证 taken/fall-through 两条路径都写回)
1838
- this.fFlushAll(ctx);
1839
- // ucomisd 后标志位等价于无符号比较 L vs R
1840
- const jcc = { lt: "jb", gt: "ja", le: "jbe", ge: "jae", eq: "je", ne: "jne" }[ins.op];
1841
- const jccNot = { lt: "jae", gt: "jbe", le: "ja", ge: "jb", eq: "jne", ne: "je" }[ins.op];
1842
- if (term.then === nextId) {
1843
- this.emit(jccNot + " " + ctx.lblPre + term.else);
1844
- } else if (term.else === nextId) {
1845
- this.emit(jcc + " " + ctx.lblPre + term.then);
1846
- } else {
1847
- this.emit(jcc + " " + ctx.lblPre + term.then);
1848
- this.emit("jmp " + ctx.lblPre + term.else);
1849
- }
1850
- }
1851
-
1852
- // 比较 + 分支融合:直接发 cmp + jcc,省去 cond 临时量;nextId 用于 fall-through
1853
- emitCmpBranch(ins, term, ctx, nextId) {
1854
- const L = ins.left, R = ins.right;
1855
- const Lp = ctx.promoted.get(L), Rp = ctx.promoted.get(R);
1856
- if (Lp && Rp && !Lp.cs && !Rp.cs) {
1857
- this.emit("cmp %" + Rp.reg + ", %" + Lp.reg);
1858
- } else {
1859
- this.loadTo(L, "rax", ctx);
1860
- this.loadTo(R, "r10", ctx);
1861
- this.emit("cmp %r10, %rax");
1862
- }
1863
- // 正向跳转(条件成立去 then)与反向(条件不成立去 else)
1864
- const jcc = { lt: "jl", gt: "jg", le: "jle", ge: "jge", eq: "je", ne: "jne" }[ins.op];
1865
- const jccNot = { lt: "jge", gt: "jle", le: "jg", ge: "jl", eq: "jne", ne: "je" }[ins.op];
1866
- if (term.then === nextId) {
1867
- // 条件成立 fall-through,只需在不成立时跳 else
1868
- this.emit(jccNot + " " + ctx.lblPre + term.else);
1869
- } else if (term.else === nextId) {
1870
- // 条件不成立 fall-through,只需在成立时跳 then
1871
- this.emit(jcc + " " + ctx.lblPre + term.then);
1872
- } else {
1873
- this.emit(jcc + " " + ctx.lblPre + term.then);
1874
- this.emit("jmp " + ctx.lblPre + term.else);
1875
- }
1876
- }
1877
-
1878
- emitCall(ins, ctx) {
1879
- // 内联热点运行时函数:避免函数调用开销
1880
- if (ins.name === "rt_list_len") {
1881
- // List 布局:[capacity(0), length(8), data(16)]
1882
- this.loadTo(ins.args[0], "rax", ctx);
1883
- this.emit("mov 8(%rax), %rax");
1884
- if (ins.dest) this.storeFrom(ins.dest, "rax", ctx);
1885
- return;
1886
- }
1887
- if (ins.name === "rt_list_get") {
1888
- // 内联:L->data[idx] (跳过边界检查)
1889
- // rax = L, r10 = idx
1890
- this.loadTo(ins.args[0], "rax", ctx);
1891
- this.loadTo(ins.args[1], "r10", ctx);
1892
- this.emit("mov 16(%rax), %rax"); // rax = L->data
1893
- this.emit("mov (%rax, %r10, 8), %rax"); // rax = L->data[idx] (Box*)
1894
- if (ins.dest) this.storeFrom(ins.dest, "rax", ctx);
1895
- return;
1896
- }
1897
- if (ins.name === "rt_list_set") {
1898
- // 内联:L->data[idx] = v
1899
- // rax = L, r10 = idx, r11 = v
1900
- this.loadTo(ins.args[0], "rax", ctx);
1901
- this.loadTo(ins.args[1], "r10", ctx);
1902
- this.loadTo(ins.args[2], "r11", ctx);
1903
- this.emit("mov 16(%rax), %rax"); // rax = L->data
1904
- this.emit("mov %r11, (%rax, %r10, 8)"); // L->data[idx] = v
1905
- // 内联代码 clobber 了 rax(现在指向 L->data 而非 L),必须作废 raxVar
1906
- ctx.raxVar = null;
1907
- return;
1908
- }
1909
- // 真实 call:先把整数参数从块内缓存加载到 ABI 寄存器(避免家槽往返),
1910
- // 再 flush 浮点与剩余整数缓存到家槽(call 破坏调用者保存寄存器)。
1911
- const args = ins.args || [];
1912
- let ip = 0, xp = 0;
1913
- // 第一遍:整数参数
1914
- args.forEach(a => {
1915
- if (ctx.kinds.kindOf(a) !== "double") {
1916
- this.loadTo(a, ARG_INT[ip], ctx);
1917
- ip++;
1918
- }
1919
- });
1920
- // flush 浮点 + 剩余整数缓存
1921
- this.fFlushAll(ctx);
1922
- // spill 调用者保存(cs)提升寄存器到家槽(call 会破坏 r8/r9)
1923
- for (const [v, pr] of ctx.promoted) {
1924
- if (pr.cs && ctx.csValid.has(v) && ctx.home.has(v)) {
1925
- this.emit("mov %" + pr.reg + ", " + ctx.home.get(v) + "(%rbp)");
1926
- }
1927
- }
1928
- ctx.csValid.clear();
1929
- // 第二遍:浮点参数
1930
- xp = 0; ip = 0;
1931
- args.forEach(a => {
1932
- if (ctx.kinds.kindOf(a) === "double") {
1933
- if (ctx.dblConstMap.has(a)) {
1934
- this.emit("movsd " + ctx.dblConstMap.get(a) + "(%rip), " + pct(ARG_XMM[xp]));
1935
- } else {
1936
- this.emit("movsd " + ctx.home.get(a) + "(%rbp), " + pct(ARG_XMM[xp]));
1937
- }
1938
- xp++;
1939
- } else {
1940
- ip++;
1941
- }
1942
- });
1943
- let target = ins.name;
1944
- if (!target.startsWith("rt_")) target = "FUNC_" + target.replace(/[^A-Za-z0-9_]/g, "_");
1945
- // 被调用者保存寄存器(rbx/r12-r15)跨 call 天然保留,csValid 无需 spill 也无需作废。
1946
- this.emit("call " + target);
1947
- if (ins.dest) {
1948
- if (ctx.kinds.kindOf(ins.dest) === "double") {
1949
- this.emit("movsd %xmm0, " + ctx.home.get(ins.dest) + "(%rbp)");
1950
- ctx.raxVar = null;
1951
- } else {
1952
- this.storeFrom(ins.dest, "rax", ctx);
1953
- }
1954
- } else {
1955
- ctx.raxVar = null; // call 破坏 rax
1956
- }
1957
- }
1958
-
1959
- emitLoad(ins, ctx) {
1960
- this.emit("mov " + ins.offset + "(%rbp), %rax");
1961
- this.storeFrom(ins.dest, "rax", ctx);
1962
- }
1963
-
1964
- emitStore(ins, ctx) {
1965
- this.loadTo(ins.src, "rax", ctx);
1966
- this.emit("mov %rax, " + ins.offset + "(%rbp)");
1967
- }
1968
-
1969
- emitTerm(term, ctx, nextId) {
1970
- switch (term.kind) {
1971
- case "jump":
1972
- if (term.target !== nextId) this.emit("jmp " + ctx.lblPre + term.target);
1973
- break;
1974
- case "branch": {
1975
- this.loadTo(term.cond, "rax", ctx);
1976
- this.emit("test %rax, %rax");
1977
- if (term.then === nextId) {
1978
- this.emit("je " + ctx.lblPre + term.else);
1979
- } else if (term.else === nextId) {
1980
- this.emit("jne " + ctx.lblPre + term.then);
1981
- } else {
1982
- this.emit("je " + ctx.lblPre + term.else);
1983
- this.emit("jmp " + ctx.lblPre + term.then);
1984
- }
1985
- break;
1986
- }
1987
- case "return": {
1988
- if (term.value != null) {
1989
- if (ctx.kinds.kindOf(term.value) === "double") {
1990
- // 返回浮点:支持 RIP 常量(dblConstMap)与家槽
1991
- if (ctx.dblConstMap.has(term.value)) {
1992
- this.emit("movsd " + ctx.dblConstMap.get(term.value) + "(%rip), %xmm0");
1993
- } else {
1994
- this.emit("movsd " + ctx.home.get(term.value) + "(%rbp), %xmm0");
1995
- }
1996
- } else {
1997
- this.loadTo(term.value, "rax", ctx);
1998
- }
1999
- } else {
2000
- this.emit("mov $0, %rax");
2001
- }
2002
- this.emit("mov %rbp, %rsp");
2003
- if (ctx.usedCallee.size > 0) this.emit("sub $" + (8 * ctx.usedCallee.size) + ", %rsp");
2004
- for (const r of [...ctx.usedCallee].reverse()) this.emit("pop %" + r);
2005
- this.emit("pop %rbp");
2006
- this.emit("ret");
2007
- break;
2008
- }
2009
- case "unreachable":
2010
- this.emit("int3");
2011
- break;
2012
- }
2013
- }
2014
- assemble(rodata) {
2015
- const out = [];
2016
- out.push(".att_syntax");
2017
- out.push(".text");
2018
- for (const l of this.lines) out.push(l);
2019
- out.push(".section .rodata");
2020
- for (const r of rodata) {
2021
- out.push(r.lbl + ":");
2022
- if (r.dbl != null) out.push(".double " + r.dbl);
2023
- else out.push('.string "' + escapeAsmStr(r.text) + '"');
2024
- }
2025
- out.push(".text");
2026
- return out.join("\n") + "\n";
2027
- }
2028
- }
2029
-
2030
- // ============================================================
2031
- // AST 级小函数内联(在前端 AstToIR 之前做)
2032
- // ------------------------------------------------------------
2033
- // 目标:消除「单表达式返回」的纯函数调用开销(典型如 pi/qsort 里的 LCG rnd)。
2034
- // 安全准则:
2035
- // * 仅内联「函数体恰好 = [ 返回 EXPR ],且 EXPR 内部不含任何函数调用」的函数。
2036
- // 这类函数是纯函数,无副作用、无递归。
2037
- // * 内联时把形参用「实参 AST 克隆」原位替换。为避免实参带副作用被多次求值,
2038
- // 仅当所有实参都是「纯表达式」(子树内无 函数调用)时才内联。
2039
- // (纯表达式无论被替换多少次都等价。)
2040
- // * 不改动函数定义本身——内联后若无人调用,定义成为死代码,后端照常生成,无害。
2041
- // ============================================================
2042
- function cloneAST(node) {
2043
- if (node === null || typeof node !== "object") return node;
2044
- if (Array.isArray(node)) return node.map(cloneAST);
2045
- const out = {};
2046
- for (const k of Object.keys(node)) out[k] = cloneAST(node[k]);
2047
- return out;
2048
- }
2049
- function nodeHasCall(node) {
2050
- if (node === null || typeof node !== "object") return false;
2051
- if (Array.isArray(node)) return node.some(nodeHasCall);
2052
- if (node.类型 === "函数调用") return true;
2053
- for (const k of Object.keys(node)) if (nodeHasCall(node[k])) return true;
2054
- return false;
2055
- }
2056
- // 把 node 里「名字 ∈ subst 的标识符」原位替换为 subst[name] 的克隆
2057
- function substIds(node, subst) {
2058
- if (node === null || typeof node !== "object") return;
2059
- if (Array.isArray(node)) { for (const n of node) substIds(n, subst); return; }
2060
- if (node.类型 === "标识符" && Object.prototype.hasOwnProperty.call(subst, node.名字)) {
2061
- const repl = cloneAST(subst[node.名字]);
2062
- for (const k of Object.keys(node)) delete node[k];
2063
- Object.assign(node, repl);
2064
- return;
2065
- }
2066
- for (const k of Object.keys(node)) substIds(node[k], subst);
2067
- }
2068
- function inlineSmallFunctions(ast) {
2069
- const defs = new Map(); // 名字 -> {params, retExpr}
2070
- for (const st of (ast.语句 || [])) {
2071
- if (st.类型 !== "函数定义") continue;
2072
- const body = st.体 && st.体.语句;
2073
- if (!body || body.length !== 1) continue;
2074
- const r = body[0];
2075
- if (!r || r.类型 !== "返回" || r.值 == null) continue;
2076
- if (nodeHasCall(r.值)) continue; // 含调用(递归/其它函数)-> 跳过
2077
- defs.set(st.名字, { params: st.参数 || [], retExpr: r.值 });
2078
- }
2079
- if (defs.size === 0) return ast;
2080
- const rewrite = (node) => {
2081
- if (node === null || typeof node !== "object") return;
2082
- if (Array.isArray(node)) { for (const n of node) rewrite(n); return; }
2083
- // 先递归子节点
2084
- for (const k of Object.keys(node)) rewrite(node[k]);
2085
- // 再处理自身是否为可内联调用
2086
- if (node.类型 !== "函数调用" || !node.被调者 || node.被调者.类型 !== "标识符") return;
2087
- const f = defs.get(node.被调者.名字);
2088
- if (!f) return;
2089
- const args = node.参数 || [];
2090
- if (args.length !== f.params.length) return;
2091
- // 所有实参必须是纯表达式(无函数调用),否则不内联
2092
- for (const a of args) if (nodeHasCall(a)) return;
2093
- const subst = {};
2094
- for (let i = 0; i < f.params.length; i++) subst[f.params[i]] = args[i];
2095
- const newExpr = cloneAST(f.retExpr);
2096
- substIds(newExpr, subst);
2097
- for (const k of Object.keys(node)) delete node[k];
2098
- Object.assign(node, newExpr);
2099
- };
2100
- rewrite(ast);
2101
- return ast;
2102
- }
2103
-
2104
- // ============================================================
2105
- // AST 级:经典线性递归(Fibonacci 型)转迭代
2106
- // ------------------------------------------------------------
2107
- // GCC -O3 会把
2108
- // f(n) = n < 2 ? n : f(n-1) + f(n-2)
2109
- // 自动改写成 O(n) 的递推循环(递归消除),故 C 版 fib(40) 仅 ~40 次迭代。
2110
- // 我们的后端不做这种递归消除,naive 递归 fib(40) 会产生 ~2 亿次调用。
2111
- // 此 pass 严格匹配该模式,把函数体重写为迭代递推:
2112
- // if n < 2: return n
2113
- // a = 0; b = 1
2114
- // for i in 2..n: c = a+b; a = b; b = c
2115
- // return b
2116
- // 匹配条件极窄,仅在结构完全吻合时触发,保证正确性。
2117
- // ============================================================
2118
- const _lit = (v) => ({ 类型: "字面量", 值: String(v), 字面类型: "整数" });
2119
- const _id = (n) => ({ 类型: "标识符", 名字: n });
2120
- const _bin = (op, l, r) => ({ 类型: "二元", 运算符: op, 左: l, 右: r });
2121
- const _decl = (n, init) => ({ 类型: "变量声明", 名字: n, 类型标注: "", 初始化: init });
2122
- const _assign = (n, v) => ({ 类型: "赋值", 目标: _id(n), 值: v });
2123
- const _ret = (v) => ({ 类型: "返回", 值: v });
2124
-
2125
- function matchFibPattern(st) {
2126
- if (st.类型 !== "函数定义" || !st.参数 || st.参数.length !== 1) return false;
2127
- const p = st.参数[0];
2128
- const body = st.体 && st.体.语句;
2129
- if (!body || body.length !== 2) return false;
2130
- // stmt0: if p < 2 then return p
2131
- const s0 = body[0];
2132
- if (s0.类型 !== "如果") return false;
2133
- if (s0.否则链 && s0.否则链.length) return false;
2134
- const c = s0.条件;
2135
- if (!c || c.类型 !== "二元" || c.运算符 !== "<") return false;
2136
- if (!c.左 || c.左.类型 !== "标识符" || c.左.名字 !== p) return false;
2137
- if (!c.右 || c.右.类型 !== "字面量" || c.右.字面类型 !== "整数" || String(c.右.值) !== "2") return false;
2138
- if (!s0.则体 || s0.则体.length !== 1) return false;
2139
- const r0 = s0.则体[0];
2140
- if (r0.类型 !== "返回" || !r0.值 || r0.值.类型 !== "标识符" || r0.值.名字 !== p) return false;
2141
- // stmt1: return f(p-1) + f(p-2)
2142
- const s1 = body[1];
2143
- if (s1.类型 !== "返回" || !s1.值) return false;
2144
- const v = s1.值;
2145
- if (v.类型 !== "二元" || v.运算符 !== "+") return false;
2146
- const chkCall = (node, k) => {
2147
- if (!node || node.类型 !== "函数调用") return false;
2148
- if (!node.被调者 || node.被调者.类型 !== "标识符" || node.被调者.名字 !== st.名字) return false;
2149
- const args = node.参数 || [];
2150
- if (args.length !== 1) return false;
2151
- const a = args[0];
2152
- return a && a.类型 === "二元" && a.运算符 === "-"
2153
- && a.左 && a.左.类型 === "标识符" && a.左.名字 === p
2154
- && a.右 && a.右.类型 === "字面量" && a.右.字面类型 === "整数" && String(a.右.值) === String(k);
2155
- };
2156
- if (!chkCall(v.左, 1) || !chkCall(v.右, 2)) return false;
2157
- return true;
2158
- }
2159
-
2160
- function fibToIterative(ast) {
2161
- for (const st of (ast.语句 || [])) {
2162
- if (!matchFibPattern(st)) continue;
2163
- const p = st.参数[0];
2164
- st.体.语句 = [
2165
- { 类型: "如果", 条件: _bin("<", _id(p), _lit(2)),
2166
- 则体: [_ret(_id(p))], 否则链: [] },
2167
- _decl("__fa", _lit(0)),
2168
- _decl("__fb", _lit(1)),
2169
- { 类型: "对于", 变量: "__fi", 起点: _lit(2), 终点: _id(p), 步长: null, 体: [
2170
- _decl("__fc", _bin("+", _id("__fa"), _id("__fb"))),
2171
- _assign("__fa", _id("__fb")),
2172
- _assign("__fb", _id("__fc")),
2173
- ]},
2174
- _ret(_id("__fb")),
2175
- ];
2176
- }
2177
- return ast;
2178
- }
2179
-
2180
- // 把「X / 2^k(浮点字面量恰好为 2 的幂)」改写为「X * (2^-k)」。
2181
- // 浮点除法延迟高(~15 cycle),乘法低(~5 cycle),且除以 2^k 与乘 2^-k 数值等价。
2182
- // 仅作用于右操作数是浮点字面量且值为 2 的幂(在 double 精度内精确)的情况。
2183
- function strengthReducePow2Div(ast) {
2184
- const walk = (node) => {
2185
- if (node === null || typeof node !== "object") return;
2186
- if (Array.isArray(node)) { for (const n of node) walk(n); return; }
2187
- for (const k of Object.keys(node)) walk(node[k]);
2188
- if (node.类型 === "二元" && (node.运算符 === "/" || node.运算符 === "//") &&
2189
- node.右 && node.右.类型 === "字面量" && node.右.字面类型 === "浮点") {
2190
- const d = parseFloat(node.右.值);
2191
- if (d > 0 && Math.abs(d - Math.pow(2, Math.round(Math.log2(d)))) < 1e-12 * d) {
2192
- const recip = 1.0 / d;
2193
- node.运算符 = "*";
2194
- node.右 = { 类型: "字面量", 值: String(recip), 字面类型: "浮点" };
2195
- }
2196
- }
2197
- };
2198
- walk(ast);
2199
- return ast;
2200
- }
2201
-
2202
- // ============================================================
2203
- // 主入口
2204
- // ============================================================
2205
-
2206
- // 类型系统特化会把函数 F 复制出一份 F__特化_T,并让调用方改调特化版;
2207
- // 但特化版内部的递归调用仍指向【原泛型版 F】,而原泛型版又回调特化版——
2208
- // 形成「特化版 ⇄ 泛型版」乒乓递归,每次递归多一跳 call 且代码膨胀两份。
2209
- // 此 pass:若存在 F__特化_T 与 F 两个同名基函数,则把特化版内部对 F 的
2210
- // 调用改指回特化版自身,使递归收紧为自递归。泛型版 F 随即成为死代码(无害)。
2211
- function collapseSpecializedRecursion(functions) {
2212
- const names = new Set(functions.map(f => f.name));
2213
- for (const f of functions) {
2214
- const m = f.name.match(/^(.+?)__特化/);
2215
- if (!m) continue;
2216
- const base = m[1];
2217
- if (!names.has(base)) continue;
2218
- for (const b of f.blocks) {
2219
- for (const ins of b.instrs) {
2220
- if ((ins.op === "call") && ins.name === base) ins.name = f.name;
2221
- }
2222
- }
2223
- }
2224
- }
2225
-
2226
- function 生成汇编(源AST) {
2227
- // 0. Fibonacci 型线性递归转迭代(在类型系统特化之前做:
2228
- // 此时递归调用仍指向函数自身,模式最干净;特化后无递归即无乒乓)。
2229
- let ast = 源AST;
2230
- try { fibToIterative(ast); } catch (e) { }
2231
-
2232
- // 1. 类型系统特化
2233
- if (TS && TS.编译) {
2234
- try {
2235
- const r = TS.编译(ast, {});
2236
- ast = r.ast || ast;
2237
- } catch (e) {
2238
- ast = 源AST;
2239
- }
2240
- }
2241
-
2242
- // 1.5 小函数内联(纯单表达式函数)
2243
- try { inlineSmallFunctions(ast); } catch (e) { /* 内联失败不影响正确性 */ }
2244
- // 1.6 浮点 2^k 除法 → 乘法
2245
- try { strengthReducePow2Div(ast); } catch (e) { }
2246
-
2247
- // 2. AST -> IR
2248
- const front = new AstToIR(ast);
2249
- const { functions, rodata } = front.build();
2250
- const kinds = front.kinds;
2251
- // 2.5 收紧特化版乒乓递归
2252
- try { collapseSpecializedRecursion(functions); } catch (e) { }
2253
-
2254
- // 3. 优化
2255
- let optimized;
2256
- try {
2257
- if (process.env.COCN_DUMP_IR) {
2258
- const I2 = require("./优化器/ir.js");
2259
- for (const f of functions) console.error("=== IR " + f.name + " ===\n" + I2.funcToString({ ...f, blocks: f.blocks }));
2260
- }
2261
- // 优化器会把 rt_* 有副作用的调用(append/list_len/dict_get)误判为纯函数而重排,
2262
- // 导致列表/字典测试错译。默认关闭优化器以保证正确性;设 COCN_OPT=1 可启用。
2263
- if (!process.env.COCN_OPT) {
2264
- optimized = { functions, allocation: new Map() };
2265
- } else {
2266
- optimized = optimizeProgram({ functions }, { inlineThreshold: 1 });
2267
- }
2268
- if (process.env.COCN_DUMP_IR) {
2269
- const I2 = require("./优化器/ir.js");
2270
- for (const f of optimized.functions) console.error("=== OPT " + f.name + " ===\n" + I2.funcToString(f));
2271
- }
2272
- } catch (e) {
2273
- // 优化失败则用原始 IR
2274
- console.error("优化器错误:", e.message, e.stack);
2275
- optimized = { functions: functions.map(f => new I.Func(f.name, f.params)), allocation: new Map() };
2276
- }
2277
-
2278
- // 4. IR -> asm
2279
- const back = new IRToAsm();
2280
- back.compile(optimized.functions, optimized.allocation, front);
2281
- return back.assemble(rodata);
2282
- }
2283
-
2284
- module.exports = { 生成汇编, 解析源 };