agwasa.pas 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. {
  2. Copyright (c) 1998-2010 by the Free Pascal team
  3. This unit implements the WebAssembly text assembler
  4. The text is in S-expression format and should be consumable
  5. By either Binaryen or Wabt
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program; if not, write to the Free Software
  16. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17. ****************************************************************************
  18. }
  19. unit agwasa;
  20. {$i fpcdefs.inc}
  21. interface
  22. uses
  23. cclasses,systems, cgutils,
  24. globtype,globals,
  25. symconst,symbase,symdef,symsym, symtype,symcpu,
  26. aasmbase,aasmtai,aasmdata,aasmcpu,
  27. assemble
  28. ,cutils
  29. ,cpubase, cgbase
  30. ,fmodule
  31. ,verbose, itcpuwasm
  32. ,cfileutl, tgcpu;
  33. type
  34. TWatInstrWriter = class;
  35. {# This is a derived class which is used to write
  36. Binaryen-styled assembler.
  37. }
  38. { TWatAssembler }
  39. { TWasaTextAssembler }
  40. TWasaTextAssembler=class(texternalassembler)
  41. protected
  42. dataofs : integer;
  43. procedure WriteOutGlobalInt32(const aname: string; val: integer; isconst: boolean = true);
  44. procedure WriteInstruction(hp: tai);
  45. procedure WriteProcDef(pd: tprocdef; stub: Boolean = false; stubUnreachable: Boolean = true);
  46. procedure WriteProcParams(pd: tprocdef);
  47. procedure WriteProcResult(pd: tprocdef);
  48. procedure WriteSymtableProcdefs(st: TSymtable);
  49. procedure WriteSymtableVarSyms(st: TSymtable);
  50. procedure WriteTempAlloc(p:TAsmList);
  51. procedure WriteExports(p: TAsmList);
  52. procedure WriteUnitExports(st: TSymtable);
  53. procedure WriteImports;
  54. procedure WriteOutPChar(p: pchar; ofs, len: integer);
  55. procedure WriteOutPChar(p: TByteDynArray; ofs, len: integer);
  56. procedure WriteOutPChar(p: TAnsicharDynArray; ofs, len: integer);
  57. procedure WriteConstString(lbl: tai_label; str: tai_string);
  58. procedure WriteConstants(p: TAsmList);
  59. public
  60. constructor CreateWithWriter(info: pasminfo; wr: TExternalAssemblerOutputFile; freewriter, smart: boolean); override;
  61. procedure WriteTree(p:TAsmList);override;
  62. procedure WriteAsmList;override;
  63. Function DoAssemble:boolean;override;
  64. end;
  65. {# This is the base class for writing instructions.
  66. The WriteInstruction() method must be overridden
  67. to write a single instruction to the assembler
  68. file.
  69. }
  70. { TBinaryenInstrWriter }
  71. { TWatInstrWriter }
  72. TWatInstrWriter = class
  73. constructor create(_owner: TWasaTextAssembler);
  74. procedure WriteInstruction(hp : tai); virtual;
  75. protected
  76. owner: TWasaTextAssembler;
  77. end;
  78. implementation
  79. type
  80. t64bitarray = array[0..7] of byte;
  81. t32bitarray = array[0..3] of byte;
  82. const
  83. line_length = 70;
  84. {****************************************************************************}
  85. { Support routines }
  86. {****************************************************************************}
  87. function fixline(s:string):string;
  88. {
  89. return s with all leading and ending spaces and tabs removed
  90. }
  91. var
  92. i,j,k : integer;
  93. begin
  94. i:=length(s);
  95. while (i>0) and (s[i] in [#9,' ']) do
  96. dec(i);
  97. j:=1;
  98. while (j<i) and (s[j] in [#9,' ']) do
  99. inc(j);
  100. for k:=j to i do
  101. if s[k] in [#0..#31,#127..#255] then
  102. s[k]:='.';
  103. fixline:=Copy(s,j,i-j+1);
  104. end;
  105. function GetWasmName(const st: TSymStr): ansistring;
  106. begin
  107. Result := '$'+st;
  108. Replace(Result, '(','');
  109. Replace(Result, ')','');
  110. end;
  111. function getreferencestring(var ref : treference) : ansistring;
  112. begin
  113. if (ref.index<>NR_NO) then
  114. internalerror(2010122809);
  115. if assigned(ref.symbol) then
  116. begin
  117. // global symbol or field -> full type and name
  118. // ref.base can be <> NR_NO in case an instance field is loaded.
  119. // This register is not part of this instruction, it will have
  120. // been placed on the stack by the previous one.
  121. result:=GetWasmName(ref.symbol.name);
  122. end
  123. else
  124. begin
  125. // local symbol -> stack slot, stored in offset
  126. if ref.base<>NR_STACK_POINTER_REG then
  127. internalerror(2010122810);
  128. result:=tostr(ref.offset);
  129. end;
  130. end;
  131. function constsingle(s: single): ansistring;
  132. begin
  133. // wat2wasm is using strtof() internally
  134. str(s, result); //'0x'+hexstr(longint(t32bitarray(s)),8);
  135. end;
  136. function constdouble(d: double): ansistring;
  137. begin
  138. // force interpretation as double (since we write it out as an
  139. // integer, we never have to swap the endianess). We have to
  140. // include the sign separately because of the way Java parses
  141. // hex numbers (0x8000000000000000 is not a valid long)
  142. //result:=hexstr(abs(int64(t64bitarray(d))),16);
  143. //if int64(t64bitarray(d))<0 then
  144. // result:='-'+result;
  145. //result:='0dx'+result;
  146. str(d, result);
  147. end;
  148. function getopstr(const o:toper) : ansistring;
  149. var
  150. d: double;
  151. s: single;
  152. begin
  153. case o.typ of
  154. top_reg:
  155. // should have been translated into a memory location by the
  156. // register allocator)
  157. if (cs_no_regalloc in current_settings.globalswitches) then
  158. getopstr:=std_regname(o.reg)
  159. else
  160. internalerror(2010122803);
  161. top_const:
  162. str(o.val,result);
  163. top_ref:
  164. getopstr:=getreferencestring(o.ref^);
  165. top_single:
  166. begin
  167. result:=constsingle(o.sval);
  168. end;
  169. top_double:
  170. begin
  171. result:=constdouble(o.dval);
  172. end;
  173. {top_string:
  174. begin
  175. result:=constastr(o.pcval,o.pcvallen);
  176. end;
  177. top_wstring:
  178. begin
  179. result:=constwstr(o.pwstrval^.data,getlengthwidestring(o.pwstrval));
  180. end}
  181. else
  182. internalerror(2010122802);
  183. end;
  184. end;
  185. { TWasaTextAssembler }
  186. procedure TWasaTextAssembler.WriteOutGlobalInt32(const aname: string;
  187. val: integer; isconst: boolean);
  188. begin
  189. writer.AsmWrite(#9);
  190. writer.AsmWrite('(global $');
  191. writer.AsmWrite(aname);
  192. if not isconst then
  193. writer.AsmWrite(' (mut i32)')
  194. else
  195. writer.AsmWrite(' i32');
  196. writer.AsmWrite(' (i32.const ');
  197. writer.AsmWrite( tostr(val));
  198. writer.AsmWrite(')');
  199. writer.AsmWriteLn(')');
  200. end;
  201. procedure TWasaTextAssembler.WriteInstruction(hp: tai);
  202. var
  203. cpu : taicpu;
  204. i : integer;
  205. isprm : boolean;
  206. begin
  207. //writer.AsmWriteLn('instr');
  208. cpu := taicpu(hp);
  209. writer.AsmWrite(#9#9);
  210. writer.AsmWrite(wasm_op2str[cpu.opcode] );
  211. if (cpu.opcode = a_call_indirect) then begin
  212. // special wat2wasm syntax "call_indirect (type x)"
  213. writer.AsmWrite(#9);
  214. // todo: fix
  215. //isprm := true;
  216. //for i:=1 to length(cpu.typecode) do
  217. // if cpu.typecode[i]=':' then
  218. // isprm:=false
  219. // else begin
  220. // if isprm then writer.AsmWrite('(param ')
  221. // else writer.AsmWrite('(result ');
  222. // case cpu.typecode[i] of
  223. // 'i': writer.AsmWrite('i32');
  224. // 'I': writer.AsmWrite('i64');
  225. // 'f': writer.AsmWrite('f32');
  226. // 'F': writer.AsmWrite('f64');
  227. // end;
  228. // writer.AsmWrite(')');
  229. // end;
  230. writer.AsmLn;
  231. exit;
  232. end;
  233. if (cpu.opcode = a_if) then
  234. writer.AsmWrite(' (result i32)') //todo: this is a hardcode, but shouldn't
  235. else
  236. cpu := taicpu(hp);
  237. if cpu.ops<>0 then
  238. begin
  239. for i:=0 to cpu.ops-1 do
  240. begin
  241. writer.AsmWrite(#9);
  242. if (cpu.opcode in AsmOp_LoadStore) and (cpu.oper[i]^.typ = top_ref) then
  243. writer.AsmWrite('offset='+tostr( cpu.oper[i]^.ref^.offset))
  244. else
  245. writer.AsmWrite(getopstr(cpu.oper[i]^));
  246. end;
  247. end;
  248. if (cpu.opcode = a_call_indirect) then
  249. // special wat2wasm syntax "call_indirect (type x)"
  250. writer.AsmWrite(')');
  251. writer.AsmLn;
  252. end;
  253. procedure TWasaTextAssembler.WriteProcDef(pd: tprocdef; stub: Boolean; stubUnreachable: Boolean);
  254. var
  255. i : integer;
  256. begin
  257. if not assigned(tcpuprocdef(pd).exprasmlist) and
  258. not(po_abstractmethod in pd.procoptions) and
  259. ((pd.proctypeoption in [potype_unitinit,potype_unitfinalize])) then
  260. begin
  261. exit;
  262. end;
  263. writer.AsmWriteLn('');
  264. if stub and stubUnreachable then begin
  265. writer.AsmWriteLn(#9';;.weak');
  266. end;
  267. writer.AsmWrite(#9'(func ');
  268. writer.AsmWrite( GetWasmName( pd.mangledname ));
  269. //procsym.RealName ));
  270. //writer.AsmWriteln(MethodDefinition(pd));
  271. {if jvmtypeneedssignature(pd) then
  272. begin
  273. writer.AsmWrite('.signature "');
  274. writer.AsmWrite(tcpuprocdef(pd).jvmmangledbasename(true));
  275. writer.AsmWriteln('"');
  276. end;}
  277. writer.AsmLn;
  278. WriteProcParams(pd);
  279. WriteProcResult(pd);
  280. if not stub then begin
  281. //WriteTempAlloc(tcpuprocdef(pd).exprasmlist);
  282. WriteTree(tcpuprocdef(pd).exprasmlist);
  283. end else begin
  284. if stubUnreachable then
  285. writer.AsmWriteLn(#9#9'unreachable');
  286. end;
  287. writer.AsmWriteln(#9')');
  288. writer.AsmLn;
  289. end;
  290. procedure TWasaTextAssembler.WriteProcParams(pd: tprocdef);
  291. var
  292. i : integer;
  293. prm : tcpuparavarsym;
  294. begin
  295. if not Assigned(pd) or
  296. not Assigned(pd.paras) or
  297. (pd.paras.Count=0) then
  298. exit;
  299. for i:=0 to pd.paras.Count-1 do
  300. begin
  301. prm := tcpuparavarsym(pd.paras[i]);
  302. writer.AsmWrite(#9#9'(param'#9);
  303. case prm.paraloc[callerside].Size of
  304. OS_8..OS_32, OS_S8..OS_S32:
  305. writer.AsmWrite('i32');
  306. OS_64, OS_S64:
  307. writer.AsmWrite('i64');
  308. OS_F32:
  309. writer.AsmWrite('f32');
  310. OS_F64:
  311. writer.AsmWrite('f64');
  312. else
  313. // unsupported calleeside parameter type
  314. Internalerror(2019093001);
  315. end;
  316. writer.AsmWrite(')');
  317. writer.AsmLn;
  318. end;
  319. end;
  320. procedure TWasaTextAssembler.WriteProcResult(pd: tprocdef);
  321. var
  322. bt : TWasmBasicType;
  323. begin
  324. if not assigned(pd) or
  325. not Assigned(pd.returndef) or
  326. (pd.returndef.size = 0)
  327. then exit;
  328. if not defToWasmBasic(pd.returndef, bt) then
  329. bt := wbt_i32;
  330. writer.AsmWrite(#9#9'(result'#9);
  331. case bt of
  332. wbt_i64: writer.AsmWrite('i64');
  333. wbt_f32: writer.AsmWrite('f32');
  334. wbt_f64: writer.AsmWrite('f64');
  335. else
  336. writer.AsmWrite('i32');
  337. end;
  338. writer.AsmWrite(')');
  339. writer.AsmLn;
  340. end;
  341. procedure TWasaTextAssembler.WriteTree(p: TAsmList);
  342. var
  343. ch : char;
  344. hp : tai;
  345. hp1 : tailineinfo;
  346. s : ansistring;
  347. i,pos : longint;
  348. InlineLevel : longint;
  349. do_line : boolean;
  350. t: TWasmBasicType;
  351. const
  352. WasmBasicTypeStr : array [TWasmBasicType] of string = ('unknown','i32','i64','f32','f64','funcref','externref','v128');
  353. begin
  354. if not assigned(p) then
  355. exit;
  356. InlineLevel:=0;
  357. { lineinfo is only needed for al_procedures (PFV) }
  358. do_line:=(cs_asm_source in current_settings.globalswitches);
  359. hp:=tai(p.first);
  360. while assigned(hp) do
  361. begin
  362. prefetch(pointer(hp.next)^);
  363. if not(hp.typ in SkipLineInfo) then
  364. begin
  365. hp1 := hp as tailineinfo;
  366. current_filepos:=hp1.fileinfo;
  367. { no line info for inlined code }
  368. if do_line and (inlinelevel=0) then
  369. begin
  370. { load infile }
  371. if lastfileinfo.fileindex<>hp1.fileinfo.fileindex then
  372. begin
  373. infile:=current_module.sourcefiles.get_file(hp1.fileinfo.fileindex);
  374. if assigned(infile) then
  375. begin
  376. { open only if needed !! }
  377. if (cs_asm_source in current_settings.globalswitches) then
  378. infile.open;
  379. end;
  380. { avoid unnecessary reopens of the same file !! }
  381. lastfileinfo.fileindex:=hp1.fileinfo.fileindex;
  382. { be sure to change line !! }
  383. lastfileinfo.line:=-1;
  384. end;
  385. { write source }
  386. if (cs_asm_source in current_settings.globalswitches) and
  387. assigned(infile) then
  388. begin
  389. if (infile<>lastinfile) then
  390. begin
  391. writer.AsmWriteLn(asminfo^.comment+'['+infile.name+']');
  392. if assigned(lastinfile) then
  393. lastinfile.close;
  394. end;
  395. if (hp1.fileinfo.line<>lastfileinfo.line) and
  396. ((hp1.fileinfo.line<infile.maxlinebuf) or (InlineLevel>0)) then
  397. begin
  398. if (hp1.fileinfo.line<>0) and
  399. ((infile.linebuf[hp1.fileinfo.line]>=0) or (InlineLevel>0)) then
  400. writer.AsmWriteLn(asminfo^.comment+'['+tostr(hp1.fileinfo.line)+'] '+
  401. fixline(infile.GetLineStr(hp1.fileinfo.line)));
  402. { set it to a negative value !
  403. to make that is has been read already !! PM }
  404. if (infile.linebuf[hp1.fileinfo.line]>=0) then
  405. infile.linebuf[hp1.fileinfo.line]:=-infile.linebuf[hp1.fileinfo.line]-1;
  406. end;
  407. end;
  408. lastfileinfo:=hp1.fileinfo;
  409. lastinfile:=infile;
  410. end;
  411. end;
  412. case hp.typ of
  413. ait_comment :
  414. Begin
  415. writer.AsmWrite(asminfo^.comment);
  416. writer.AsmWritePChar(tai_comment(hp).str);
  417. writer.AsmLn;
  418. End;
  419. ait_regalloc :
  420. begin
  421. if (cs_asm_regalloc in current_settings.globalswitches) then
  422. begin
  423. writer.AsmWrite(#9+asminfo^.comment+'Register ');
  424. repeat
  425. writer.AsmWrite(std_regname(Tai_regalloc(hp).reg));
  426. if (hp.next=nil) or
  427. (tai(hp.next).typ<>ait_regalloc) or
  428. (tai_regalloc(hp.next).ratype<>tai_regalloc(hp).ratype) then
  429. break;
  430. hp:=tai(hp.next);
  431. writer.AsmWrite(',');
  432. until false;
  433. writer.AsmWrite(' ');
  434. writer.AsmWriteLn(regallocstr[tai_regalloc(hp).ratype]);
  435. end;
  436. end;
  437. ait_tempalloc :
  438. begin
  439. if (cs_asm_tempalloc in current_settings.globalswitches) then
  440. begin
  441. {$ifdef EXTDEBUG}
  442. if assigned(tai_tempalloc(hp).problem) then
  443. writer.AsmWriteLn(asminfo^.comment+'Temp '+tostr(tai_tempalloc(hp).temppos)+','+
  444. tostr(tai_tempalloc(hp).tempsize)+' '+tai_tempalloc(hp).problem^)
  445. else
  446. {$endif EXTDEBUG}
  447. end;
  448. end;
  449. ait_align :
  450. begin
  451. end;
  452. ait_section :
  453. begin
  454. end;
  455. ait_datablock :
  456. begin
  457. // internalerror(2010122701);
  458. end;
  459. ait_const:
  460. begin
  461. writer.AsmWriteln('constant');
  462. // internalerror(2010122702);
  463. end;
  464. ait_realconst :
  465. begin
  466. internalerror(2010122703);
  467. end;
  468. ait_string :
  469. begin
  470. pos:=0;
  471. for i:=1 to tai_string(hp).len do
  472. begin
  473. if pos=0 then
  474. begin
  475. writer.AsmWrite(#9'strconst: '#9'"');
  476. pos:=20;
  477. end;
  478. ch:=tai_string(hp).str[i-1];
  479. case ch of
  480. #0, {This can't be done by range, because a bug in FPC}
  481. #1..#31,
  482. #128..#255 : s:='\'+tostr(ord(ch) shr 6)+tostr((ord(ch) and 63) shr 3)+tostr(ord(ch) and 7);
  483. '"' : s:='\"';
  484. '\' : s:='\\';
  485. else
  486. s:=ch;
  487. end;
  488. writer.AsmWrite(s);
  489. inc(pos,length(s));
  490. if (pos>line_length) or (i=tai_string(hp).len) then
  491. begin
  492. writer.AsmWriteLn('"');
  493. pos:=0;
  494. end;
  495. end;
  496. end;
  497. ait_label :
  498. begin
  499. // don't write any labels. Wasm don't support it
  500. // labels are only allowed with the respective block structures
  501. end;
  502. ait_symbol :
  503. begin
  504. if (tai_symbol(hp).sym.typ = AT_FUNCTION) then
  505. begin
  506. end
  507. else
  508. begin
  509. writer.AsmWrite('data symbol: ');
  510. writer.AsmWriteln(tai_symbol(hp).sym.name);
  511. // internalerror(2010122706);
  512. end;
  513. end;
  514. ait_symbol_end :
  515. begin
  516. end;
  517. ait_instruction :
  518. begin
  519. WriteInstruction(hp);
  520. end;
  521. ait_force_line,
  522. ait_function_name : ;
  523. ait_cutobject :
  524. begin
  525. end;
  526. ait_marker :
  527. if tai_marker(hp).kind=mark_NoLineInfoStart then
  528. inc(InlineLevel)
  529. else if tai_marker(hp).kind=mark_NoLineInfoEnd then
  530. dec(InlineLevel);
  531. ait_directive :
  532. begin
  533. { the CPU directive is probably not supported by the JVM assembler,
  534. so it's commented out }
  535. //todo:
  536. writer.AsmWrite(asminfo^.comment);
  537. if tai_directive(hp).directive=asd_cpu then
  538. writer.AsmWrite(asminfo^.comment);
  539. writer.AsmWrite('.'+directivestr[tai_directive(hp).directive]+' ');
  540. if tai_directive(hp).name<>'' then
  541. writer.AsmWrite(tai_directive(hp).name);
  542. writer.AsmLn;
  543. end;
  544. ait_local :
  545. begin
  546. for t in tai_local(hp).locals do
  547. begin
  548. writer.AsmWrite(#9#9'(local ');
  549. writer.AsmWrite( WasmBasicTypeStr[ t ] );
  550. writer.AsmWrite(')');
  551. writer.AsmLn;
  552. end;
  553. end;
  554. else
  555. internalerror(2010122707);
  556. end;
  557. hp:=tai(hp.next);
  558. end;
  559. end;
  560. procedure TWasaTextAssembler.WriteAsmList;
  561. var
  562. hal : tasmlisttype;
  563. begin
  564. writer.MarkEmpty;
  565. writer.AsmWriteLn('(module ');
  566. writer.AsmWriteLn('(import "env" "memory" (memory 0)) ;;');
  567. WriteImports;
  568. WriteConstants(current_asmdata.asmlists[al_const]);
  569. WriteConstants(current_asmdata.asmlists[al_typedconsts]);
  570. //current_asmdata.CurrAsmList.labe
  571. { print all global variables }
  572. //current_asmdata.AsmSymbolDict
  573. // for every unit __stack_top is a weak symbol
  574. // __stack_top is strong only for libraries or programs.
  575. if current_module.is_unit then
  576. writer.AsmWriteLn(#9';;.weak');
  577. writer.AsmWrite(#9'(global $__stack_top (mut i32) (i32.const ');
  578. writer.AsmWrite(tostr(globals.stacksize));
  579. writer.AsmWriteLn('))');
  580. WriteSymtableVarSyms(current_module.globalsymtable);
  581. WriteSymtableVarSyms(current_module.localsymtable);
  582. //writer.AsmLn;
  583. { print all global procedures/functions }
  584. WriteSymtableProcdefs(current_module.globalsymtable);
  585. WriteSymtableProcdefs(current_module.localsymtable);
  586. if current_module.islibrary then begin
  587. WriteExports(current_asmdata.asmlists[al_exports]);
  588. end else
  589. WriteUnitExports(current_module.globalsymtable);
  590. //WriteSymtableStructDefs(current_module.globalsymtable);
  591. //WriteSymtableStructDefs(current_module.localsymtable);
  592. //writer.decorator.LinePrefix := '';
  593. writer.AsmWriteLn(')');
  594. writer.AsmLn;
  595. end;
  596. function TWasaTextAssembler.DoAssemble: boolean;
  597. var
  598. t : tcmdstr;
  599. begin
  600. Result:=inherited DoAssemble;
  601. // the tool updates the symbol flags, so the linker
  602. // is capable of producing an executable
  603. if Result then
  604. if FindExe('wasmtool',true,t) then begin
  605. if current_module.is_unit then
  606. // making "common" global variables a week reference
  607. RequotedExecuteProcess(t,' --weak "$__stack_top" --symbolauto '+ObjFileName)
  608. else
  609. RequotedExecuteProcess(t,' --symbolauto '+ObjFileName)
  610. end
  611. else
  612. Message1(exec_e_util_not_found,'wasmtool');
  613. end;
  614. constructor TWasaTextAssembler.CreateWithWriter(info: pasminfo;
  615. wr: TExternalAssemblerOutputFile; freewriter, smart: boolean);
  616. begin
  617. inherited CreateWithWriter(info, wr, freewriter, smart);
  618. end;
  619. procedure TWasaTextAssembler.WriteSymtableProcdefs(st: TSymtable);
  620. var
  621. i : longint;
  622. def : tdef;
  623. begin
  624. if not assigned(st) then
  625. exit;
  626. for i:=0 to st.DefList.Count-1 do
  627. begin
  628. def:=tdef(st.DefList[i]);
  629. case def.typ of
  630. procdef :
  631. begin
  632. { methods are also in the static/globalsymtable of the unit
  633. -> make sure they are only written for the objectdefs that
  634. own them }
  635. if (not(st.symtabletype in [staticsymtable,globalsymtable]) or
  636. (def.owner=st)) and
  637. not(df_generic in def.defoptions) and
  638. not (po_external in tprocdef(def).procoptions)
  639. then
  640. begin
  641. WriteProcDef(tprocdef(def));
  642. if assigned(tprocdef(def).localst) then
  643. WriteSymtableProcdefs(tprocdef(def).localst);
  644. end;
  645. end;
  646. else
  647. ;
  648. end;
  649. end;
  650. end;
  651. procedure TWasaTextAssembler.WriteSymtableVarSyms(st: TSymtable);
  652. var
  653. i : integer;
  654. sym : tsym;
  655. begin
  656. if not assigned(st) then
  657. exit;
  658. for i:=0 to st.SymList.Count-1 do
  659. begin
  660. sym:=tsym(st.SymList[i]);
  661. case sym.typ of
  662. staticvarsym:
  663. begin
  664. //WriteFieldSym(tabstractvarsym(sym));
  665. //if (sym.typ=staticvarsym) and
  666. // assigned(tstaticvarsym(sym).defaultconstsym) then
  667. // WriteFieldSym(tabstractvarsym(tstaticvarsym(sym).defaultconstsym));
  668. WriteOutGlobalInt32(tcpustaticvarsym(sym).mangledname, dataofs);
  669. inc(dataofs, tcpustaticvarsym(sym).getsize);
  670. end;
  671. fieldvarsym:
  672. begin
  673. writer.AsmWriteLn(';; field');
  674. end;
  675. constsym:
  676. begin
  677. //if (sym.typ=staticvarsym) and
  678. // assigned(tstaticvarsym(sym).defaultconstsym) then
  679. // WriteFieldSym(tabstractvarsym(tstaticvarsym(sym).defaultconstsym));
  680. //{ multiple procedures can have constants with the same name }
  681. //if not assigned(sym.owner.defowner) or
  682. // (tdef(sym.owner.defowner).typ<>procdef) then
  683. // WriteConstSym(tconstsym(sym));
  684. writer.AsmWriteLn(';; constant');
  685. end;
  686. {procsym:
  687. begin
  688. for j:=0 to tprocsym(sym).procdeflist.count-1 do
  689. if not(df_generic in tprocdef(tprocsym(sym).procdeflist[j]).defoptions) then
  690. WriteSymtableVarSyms(tprocdef(tprocsym(sym).procdeflist[j]).localst);
  691. end;}
  692. else
  693. ;
  694. end;
  695. end;
  696. end;
  697. procedure TWasaTextAssembler.WriteTempAlloc(p: TAsmList);
  698. var
  699. hp: tai;
  700. tmp: array of tai_tempalloc;
  701. mx : integer;
  702. i : integer;
  703. begin
  704. if not assigned(p) then
  705. exit;
  706. mx := -1;
  707. hp:=tai(p.first);
  708. while assigned(hp) do
  709. begin
  710. //prefetch(pointer(hp.next)^);
  711. if (hp.typ = ait_tempalloc) and
  712. tai_tempalloc(hp).allocation and
  713. (tai_tempalloc(hp).temppos >= mx) then
  714. mx := tai_tempalloc(hp).temppos+1;
  715. hp:=tai(hp.next);
  716. end;
  717. if (mx <= 0) then exit; // no temp allocations used
  718. SetLength(tmp, mx);
  719. hp:=tai(p.first);
  720. while assigned(hp) do
  721. begin
  722. //prefetch(pointer(hp.next)^);
  723. if (hp.typ = ait_tempalloc) and
  724. (tai_tempalloc(hp).allocation) and
  725. (tmp[ tai_tempalloc(hp).temppos ] = nil) then
  726. begin
  727. tmp[ tai_tempalloc(hp).temppos ] := tai_tempalloc(hp);
  728. dec(mx);
  729. if mx = 0 then break;
  730. end;
  731. hp:=tai(hp.next);
  732. end;
  733. for i:=0 to length(tmp)-1 do
  734. begin
  735. if tmp[i] = nil then continue;
  736. writer.AsmWrite(#9'(local'#9);
  737. if tmp[i].tempsize<=4 then writer.AsmWrite('i32')
  738. else if tmp[i].tempsize = 8 then writer.AsmWrite('i64');
  739. writer.AsmWrite(')');
  740. writer.AsmWrite(#9+asminfo^.comment+'Temp '+tostr(tmp[i].temppos)+','+
  741. tostr(tmp[i].tempsize)+' '+tempallocstr[tmp[i].allocation]);
  742. writer.AsmLn;
  743. end;
  744. end;
  745. procedure TWasaTextAssembler.WriteExports(p: TAsmList);
  746. var
  747. hp: tai;
  748. x: tai_export_name;
  749. cnt: integer;
  750. begin
  751. if not Assigned(p) then Exit;
  752. hp:=tai(p.First);
  753. if not Assigned(hp) then Exit;
  754. cnt := 0;
  755. while Assigned(hp) do begin
  756. case hp.typ of
  757. ait_export_name:
  758. inc(cnt);
  759. else
  760. ;
  761. end;
  762. hp := tai_export_name(hp.Next);
  763. end;
  764. // writting out table, so wat2wasm can create reallocation symbols
  765. writer.AsmWrite(#9'(table ');
  766. writer.AsmWrite(tostr(cnt));
  767. writer.AsmWrite(' anyfunc)');
  768. writer.AsmWriteLn(#9'(elem 0 (i32.const 0) ');
  769. hp:=tai(p.First);
  770. while Assigned(hp) do begin
  771. case hp.typ of
  772. ait_export_name:
  773. begin
  774. x:=tai_export_name(hp);
  775. writer.AsmWrite(#9#9);
  776. writer.AsmWriteLn(GetWasmName(x.intname));
  777. end;
  778. else
  779. ;
  780. end;
  781. hp := tai_export_name(hp.Next);
  782. end;
  783. writer.AsmWriteLn(#9') ');
  784. // writing export sections
  785. hp:=tai(p.First);
  786. while Assigned(hp) do begin
  787. case hp.typ of
  788. ait_export_name:
  789. begin
  790. x:=tai_export_name(hp);
  791. writer.AsmWrite(#9#9'(export "');
  792. writer.AsmWrite(x.extname);
  793. writer.AsmWrite('" (');
  794. case x.symstype of
  795. ie_Func: writer.AsmWrite('func');
  796. else
  797. ;
  798. end;
  799. writer.AsmWrite(' ');
  800. writer.AsmWrite(GetWasmName(x.intname));
  801. writer.AsmWrite('))');
  802. writer.AsmLn;
  803. end;
  804. else
  805. ;
  806. end;
  807. hp := tai_export_name(hp.Next);
  808. end;
  809. end;
  810. procedure TWasaTextAssembler.WriteUnitExports(st: TSymtable);
  811. var
  812. i : longint;
  813. def : tdef;
  814. begin
  815. if not assigned(st) then
  816. exit;
  817. writer.AsmWrite(#9'(table 0 funcref)');
  818. writer.AsmWriteLn(#9'(elem 0 (i32.const 0) ');
  819. for i:=0 to st.DefList.Count-1 do
  820. begin
  821. def:=tdef(st.DefList[i]);
  822. case def.typ of
  823. procdef :
  824. begin
  825. { methods are also in the static/globalsymtable of the unit
  826. -> make sure they are only written for the objectdefs that
  827. own them }
  828. if
  829. not (po_external in tprocdef(def).procoptions)
  830. then
  831. begin
  832. writer.AsmWrite(#9#9'$');
  833. writer.AsmWriteLn(tprocdef(def).mangledname);
  834. end;
  835. end;
  836. else
  837. ;
  838. end;
  839. end;
  840. writer.AsmWriteLn(#9') ');
  841. end;
  842. procedure TWasaTextAssembler.WriteImports;
  843. var
  844. i : integer;
  845. def : tdef;
  846. proc : tprocdef;
  847. sym : tsym;
  848. j : integer;
  849. psym : tprocsym;
  850. begin
  851. for i:=0 to current_module.deflist.Count-1 do begin
  852. def:=tdef(current_module.deflist[i]);
  853. { since commit 48986 deflist might have NIL entries }
  854. if assigned(def) and (def.typ=procdef) then begin
  855. proc := tprocdef(def);
  856. if (po_external in proc.procoptions) and assigned(proc.import_dll) then begin
  857. writer.AsmWrite(#9'(import "');
  858. writer.AsmWrite(proc.import_dll^);
  859. writer.AsmWrite('" "');
  860. writer.AsmWrite(proc.import_name^);
  861. writer.AsmWrite('" ');
  862. WriteProcDef(proc);
  863. writer.AsmWriteLn(')');
  864. end;
  865. end;
  866. end;
  867. // any symbol used from another unit must be fully declared in .wat
  868. // (reference by symbol name only doesn't work in Wasm)
  869. // the entire entry should declared (as imported) symbol.
  870. // The wasm-import name (name of exernal module and name)
  871. // is not important, as the linker would be using the symbol name
  872. // while linking.
  873. for i:=0 to current_module.unitimportsyms.Count-1 do begin
  874. sym := tsym(current_module.unitimportsyms[i]);
  875. if sym.typ = procsym then begin
  876. psym := tprocsym(sym);
  877. if psym.ProcdefList.Count>0 then
  878. proc := tprocdef(psym.ProcdefList[0])
  879. else
  880. proc := nil;
  881. if proc<>nil then begin
  882. {writer.AsmWrite(#9'(import "_fpc_use" "');
  883. writer.AsmWrite(proc.mangledname);
  884. writer.AsmWrite('" ');}
  885. WriteProcDef(proc, true);
  886. //writer.AsmWrite(')');
  887. end;
  888. end;
  889. end;
  890. end;
  891. procedure TWasaTextAssembler.WriteOutPChar(p: pchar; ofs, len: integer);
  892. var
  893. i : integer;
  894. s : string;
  895. ch : char;
  896. begin
  897. for i:=ofs to ofs+len-1 do begin
  898. ch:=p[i];
  899. case ch of
  900. #0, {This can't be done by range, because a bug in FPC}
  901. #1..#31,
  902. #128..#255 : s:='\'+tostr(ord(ch) shr 6)+tostr((ord(ch) and 63) shr 3)+tostr(ord(ch) and 7);
  903. '"' : s:='\"';
  904. '\' : s:='\\';
  905. else
  906. s:=ch;
  907. end;
  908. writer.AsmWrite(s);
  909. end;
  910. end;
  911. procedure TWasaTextAssembler.WriteOutPChar(p: TByteDynArray; ofs, len: integer);
  912. begin
  913. WriteOutPChar(PAnsiChar(p),ofs,len);
  914. end;
  915. procedure TWasaTextAssembler.WriteOutPChar(p: TAnsicharDynArray; ofs, len: integer);
  916. begin
  917. WriteOutPChar(PAnsiChar(p),ofs,len);
  918. end;
  919. procedure TWasaTextAssembler.WriteConstString(lbl: tai_label;
  920. str: tai_string);
  921. var
  922. i : integer;
  923. ch : char;
  924. s : string;
  925. begin
  926. WriteOutGlobalInt32(lbl.labsym.Name, dataofs);
  927. // (data (get_global $test) "00")
  928. writer.AsmWrite(#9);
  929. writer.AsmWrite('(data (i32.const ');
  930. writer.AsmWrite(tostr(dataOfs));
  931. writer.AsmWrite(') "');
  932. // can be broken apart in multiple data() if needs to be
  933. WriteOutPChar(str.str, 0, str.len);
  934. writer.AsmWrite('"');
  935. writer.AsmWriteLn(') ;; value of '+ lbl.labsym.Name);
  936. inc(dataofs, str.len);
  937. end;
  938. procedure TWasaTextAssembler.WriteConstants(p: TAsmList);
  939. var
  940. i : integer;
  941. hp : tai;
  942. dt : tai;
  943. begin
  944. //WriteTree(p);
  945. hp:=tai(p.First);
  946. while Assigned(hp) do begin
  947. if (hp.typ = ait_label) then begin
  948. dt:=tai(hp.Next);
  949. if Assigned(dt) then begin
  950. case dt.typ of
  951. ait_string:
  952. begin
  953. WriteConstString(tai_label(hp), tai_string(dt));
  954. hp:=dt;
  955. end;
  956. else
  957. ;
  958. end;
  959. end;
  960. end;
  961. hp:=tai(hp.Next);
  962. end;
  963. end;
  964. { TWatInstrWriter }
  965. constructor TWatInstrWriter.create(_owner: TWasaTextAssembler);
  966. begin
  967. inherited create;
  968. owner := _owner;
  969. end;
  970. procedure TWatInstrWriter.WriteInstruction(hp: tai);
  971. begin
  972. end;
  973. const
  974. as_wasm_wasa_info : tasminfo =
  975. (
  976. id : as_wasm32_wasa;
  977. idtxt : 'WASA';
  978. asmbin : 'wasa';
  979. asmcmd : '-r --no-canonicalize-leb128s -o $OBJ $EXTRAOPT $ASM';
  980. supported_targets : [system_wasm32_embedded,system_wasm32_wasip1,system_wasm32_wasip1threads,system_wasm32_wasip2];
  981. flags : [];
  982. labelprefix : 'L';
  983. labelmaxlen : -1;
  984. comment : ';; ';
  985. dollarsign : '$';
  986. );
  987. initialization
  988. RegisterAssembler(as_wasm_wasa_info, TWasaTextAssembler);
  989. end.