agwat.pas 34 KB

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