2
0

agwat.pas 34 KB

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