agwat.pas 32 KB

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