agwat.pas 33 KB

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