agwat.pas 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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. interface
  21. uses
  22. cclasses,systems, cgutils,
  23. globtype,globals,
  24. symconst,symbase,symdef,symsym, symtype,symcpu,
  25. aasmbase,aasmtai,aasmdata,aasmcpu,
  26. assemble
  27. ,cutils
  28. ,cpubase
  29. ,fmodule
  30. ,verbose, itcpuwasm;
  31. type
  32. TWatInstrWriter = class;
  33. {# This is a derived class which is used to write
  34. Binaryen-styled assembler.
  35. }
  36. { TWatAssembler }
  37. { TWabtTextAssembler }
  38. TWabtTextAssembler=class(texternalassembler)
  39. protected
  40. procedure WriteInstruction(hp: tai);
  41. procedure WriteProcDef(pd: tprocdef);
  42. procedure WriteProcParams(pd: tprocdef);
  43. procedure WriteProcResult(pd: tprocdef);
  44. procedure WriteSymtableProcdefs(st: TSymtable);
  45. procedure WriteTempAlloc(p:TAsmList);
  46. public
  47. constructor CreateWithWriter(info: pasminfo; wr: TExternalAssemblerOutputFile; freewriter, smart: boolean); override;
  48. procedure WriteTree(p:TAsmList);override;
  49. procedure WriteAsmList;override;
  50. end;
  51. {# This is the base class for writing instructions.
  52. The WriteInstruction() method must be overridden
  53. to write a single instruction to the assembler
  54. file.
  55. }
  56. { TBinaryenInstrWriter }
  57. { TWatInstrWriter }
  58. TWatInstrWriter = class
  59. constructor create(_owner: TWabtTextAssembler);
  60. procedure WriteInstruction(hp : tai); virtual;
  61. protected
  62. owner: TWabtTextAssembler;
  63. end;
  64. implementation
  65. type
  66. t64bitarray = array[0..7] of byte;
  67. t32bitarray = array[0..3] of byte;
  68. const
  69. line_length = 70;
  70. {****************************************************************************}
  71. { Support routines }
  72. {****************************************************************************}
  73. function fixline(s:string):string;
  74. {
  75. return s with all leading and ending spaces and tabs removed
  76. }
  77. var
  78. i,j,k : integer;
  79. begin
  80. i:=length(s);
  81. while (i>0) and (s[i] in [#9,' ']) do
  82. dec(i);
  83. j:=1;
  84. while (j<i) and (s[j] in [#9,' ']) do
  85. inc(j);
  86. for k:=j to i do
  87. if s[k] in [#0..#31,#127..#255] then
  88. s[k]:='.';
  89. fixline:=Copy(s,j,i-j+1);
  90. end;
  91. function GetWasmName(const st: TSymStr): ansistring;
  92. begin
  93. Result := '$'+st;
  94. Replace(Result, '(','');
  95. Replace(Result, ')','');
  96. end;
  97. function getreferencestring(var ref : treference) : ansistring;
  98. begin
  99. if (ref.arrayreftype<>art_none) or
  100. (ref.index<>NR_NO) then
  101. internalerror(2010122809);
  102. if assigned(ref.symbol) then
  103. begin
  104. // global symbol or field -> full type and name
  105. // ref.base can be <> NR_NO in case an instance field is loaded.
  106. // This register is not part of this instruction, it will have
  107. // been placed on the stack by the previous one.
  108. if (ref.offset<>0) then
  109. internalerror(2010122811);
  110. result:=GetWasmName(ref.symbol.name);
  111. end
  112. else
  113. begin
  114. // local symbol -> stack slot, stored in offset
  115. if ref.base<>NR_STACK_POINTER_REG then
  116. internalerror(2010122810);
  117. result:=tostr(ref.offset);
  118. end;
  119. end;
  120. function constsingle(s: single): ansistring;
  121. begin
  122. result:='0fx'+hexstr(longint(t32bitarray(s)),8);
  123. end;
  124. function constdouble(d: double): ansistring;
  125. begin
  126. // force interpretation as double (since we write it out as an
  127. // integer, we never have to swap the endianess). We have to
  128. // include the sign separately because of the way Java parses
  129. // hex numbers (0x8000000000000000 is not a valid long)
  130. result:=hexstr(abs(int64(t64bitarray(d))),16);
  131. if int64(t64bitarray(d))<0 then
  132. result:='-'+result;
  133. result:='0dx'+result;
  134. end;
  135. function getopstr(const o:toper) : ansistring;
  136. var
  137. d: double;
  138. s: single;
  139. begin
  140. case o.typ of
  141. top_reg:
  142. // should have been translated into a memory location by the
  143. // register allocator)
  144. if (cs_no_regalloc in current_settings.globalswitches) then
  145. getopstr:=std_regname(o.reg)
  146. else
  147. internalerror(2010122803);
  148. top_const:
  149. str(o.val,result);
  150. top_ref:
  151. getopstr:=getreferencestring(o.ref^);
  152. top_single:
  153. begin
  154. result:=constsingle(o.sval);
  155. end;
  156. top_double:
  157. begin
  158. result:=constdouble(o.dval);
  159. end;
  160. {top_string:
  161. begin
  162. result:=constastr(o.pcval,o.pcvallen);
  163. end;
  164. top_wstring:
  165. begin
  166. result:=constwstr(o.pwstrval^.data,getlengthwidestring(o.pwstrval));
  167. end}
  168. else
  169. internalerror(2010122802);
  170. end;
  171. end;
  172. { TWabtTextAssembler }
  173. procedure TWabtTextAssembler.WriteInstruction(hp: tai);
  174. var
  175. cpu : taicpu;
  176. i : integer;
  177. const
  178. ExplicitOffset = [a_i32_load, a_i32_store];
  179. begin
  180. //writer.AsmWriteLn('instr');
  181. //writeln('>',taicpu(hp).opcode);
  182. cpu := taicpu(hp);
  183. writer.AsmWrite(#9);
  184. writer.AsmWrite(wasm_op2str[cpu.opcode] );
  185. cpu := taicpu(hp);
  186. if cpu.ops<>0 then
  187. begin
  188. for i:=0 to cpu.ops-1 do
  189. begin
  190. writer.AsmWrite(#9);
  191. if (cpu.oper[i]^.typ = top_ref) and
  192. (cpu.opcode in ExplicitOffset) then begin
  193. writer.AsmWrite('offset=');
  194. writer.AsmWrite(tostr(cpu.oper[i]^.ref^.offset));
  195. writer.AsmWrite(' ;;');
  196. writer.AsmWrite('alignment=');
  197. writer.AsmWrite(tostr(cpu.oper[i]^.ref^.alignment));
  198. end else
  199. writer.AsmWrite(getopstr(cpu.oper[i]^));
  200. end;
  201. end;
  202. writer.AsmLn;
  203. end;
  204. procedure TWabtTextAssembler.WriteProcDef(pd: tprocdef);
  205. var
  206. i : integer;
  207. begin
  208. if not assigned(tcpuprocdef(pd).exprasmlist) and
  209. not(po_abstractmethod in pd.procoptions) and
  210. (not is_javainterface(pd.struct) or
  211. (pd.proctypeoption in [potype_unitinit,potype_unitfinalize])) then
  212. begin
  213. //writeln('mordoy ne vyshel! ',pd.procsym.RealName );
  214. exit;
  215. end;
  216. writer.AsmWrite('(func ');
  217. writer.AsmWrite( GetWasmName( pd.procsym.RealName ));
  218. //writer.AsmWriteln(MethodDefinition(pd));
  219. {if jvmtypeneedssignature(pd) then
  220. begin
  221. writer.AsmWrite('.signature "');
  222. writer.AsmWrite(tcpuprocdef(pd).jvmmangledbasename(true));
  223. writer.AsmWriteln('"');
  224. end;}
  225. writer.AsmLn;
  226. WriteProcParams(tcpuprocdef(pd));
  227. WriteProcResult(tcpuprocdef(pd));
  228. WriteTempAlloc(tcpuprocdef(pd).exprasmlist);
  229. WriteTree(tcpuprocdef(pd).exprasmlist);
  230. writer.AsmWriteln(')');
  231. writer.AsmLn;
  232. end;
  233. procedure TWabtTextAssembler.WriteProcParams(pd: tprocdef);
  234. var
  235. i : integer;
  236. prm : tcpuparavarsym;
  237. begin
  238. if not Assigned(pd) or
  239. not Assigned(pd.paras) or
  240. (pd.paras.Count=0) then
  241. exit;
  242. for i:=0 to pd.paras.Count-1 do
  243. begin
  244. prm := tcpuparavarsym(pd.paras[i]);
  245. writer.AsmWrite(#9'(param'#9);
  246. case prm.getsize of
  247. 1..4: writer.AsmWrite('i32');
  248. 8: writer.AsmWrite('i64');
  249. end;
  250. writer.AsmWrite(')');
  251. writer.AsmLn;
  252. end;
  253. end;
  254. procedure TWabtTextAssembler.WriteProcResult(pd: tprocdef);
  255. begin
  256. if not assigned(pd) or
  257. not Assigned(pd.returndef) or
  258. (pd.returndef.size = 0)
  259. then exit;
  260. writer.AsmWrite(#9'(result'#9);
  261. case pd.returndef.size of
  262. 1..4: writer.AsmWrite('i32');
  263. 8: writer.AsmWrite('i64');
  264. end;
  265. writer.AsmWrite(')');
  266. writer.AsmLn;
  267. end;
  268. procedure TWabtTextAssembler.WriteTree(p: TAsmList);
  269. var
  270. ch : char;
  271. hp : tai;
  272. hp1 : tailineinfo;
  273. s : ansistring;
  274. i,pos : longint;
  275. InlineLevel : longint;
  276. do_line : boolean;
  277. begin
  278. if not assigned(p) then
  279. exit;
  280. InlineLevel:=0;
  281. { lineinfo is only needed for al_procedures (PFV) }
  282. do_line:=(cs_asm_source in current_settings.globalswitches);
  283. hp:=tai(p.first);
  284. while assigned(hp) do
  285. begin
  286. prefetch(pointer(hp.next)^);
  287. if not(hp.typ in SkipLineInfo) then
  288. begin
  289. hp1 := hp as tailineinfo;
  290. current_filepos:=hp1.fileinfo;
  291. { no line info for inlined code }
  292. if do_line and (inlinelevel=0) then
  293. begin
  294. { load infile }
  295. if lastfileinfo.fileindex<>hp1.fileinfo.fileindex then
  296. begin
  297. infile:=current_module.sourcefiles.get_file(hp1.fileinfo.fileindex);
  298. if assigned(infile) then
  299. begin
  300. { open only if needed !! }
  301. if (cs_asm_source in current_settings.globalswitches) then
  302. infile.open;
  303. end;
  304. { avoid unnecessary reopens of the same file !! }
  305. lastfileinfo.fileindex:=hp1.fileinfo.fileindex;
  306. { be sure to change line !! }
  307. lastfileinfo.line:=-1;
  308. end;
  309. { write source }
  310. if (cs_asm_source in current_settings.globalswitches) and
  311. assigned(infile) then
  312. begin
  313. if (infile<>lastinfile) then
  314. begin
  315. writer.AsmWriteLn(asminfo^.comment+'['+infile.name+']');
  316. if assigned(lastinfile) then
  317. lastinfile.close;
  318. end;
  319. if (hp1.fileinfo.line<>lastfileinfo.line) and
  320. ((hp1.fileinfo.line<infile.maxlinebuf) or (InlineLevel>0)) then
  321. begin
  322. if (hp1.fileinfo.line<>0) and
  323. ((infile.linebuf^[hp1.fileinfo.line]>=0) or (InlineLevel>0)) then
  324. writer.AsmWriteLn(asminfo^.comment+'['+tostr(hp1.fileinfo.line)+'] '+
  325. fixline(infile.GetLineStr(hp1.fileinfo.line)));
  326. { set it to a negative value !
  327. to make that is has been read already !! PM }
  328. if (infile.linebuf^[hp1.fileinfo.line]>=0) then
  329. infile.linebuf^[hp1.fileinfo.line]:=-infile.linebuf^[hp1.fileinfo.line]-1;
  330. end;
  331. end;
  332. lastfileinfo:=hp1.fileinfo;
  333. lastinfile:=infile;
  334. end;
  335. end;
  336. case hp.typ of
  337. ait_comment :
  338. Begin
  339. writer.AsmWrite(asminfo^.comment);
  340. writer.AsmWritePChar(tai_comment(hp).str);
  341. writer.AsmLn;
  342. End;
  343. ait_regalloc :
  344. begin
  345. if (cs_asm_regalloc in current_settings.globalswitches) then
  346. begin
  347. writer.AsmWrite(#9+asminfo^.comment+'Register ');
  348. repeat
  349. writer.AsmWrite(std_regname(Tai_regalloc(hp).reg));
  350. if (hp.next=nil) or
  351. (tai(hp.next).typ<>ait_regalloc) or
  352. (tai_regalloc(hp.next).ratype<>tai_regalloc(hp).ratype) then
  353. break;
  354. hp:=tai(hp.next);
  355. writer.AsmWrite(',');
  356. until false;
  357. writer.AsmWrite(' ');
  358. writer.AsmWriteLn(regallocstr[tai_regalloc(hp).ratype]);
  359. end;
  360. end;
  361. ait_tempalloc :
  362. begin
  363. if (cs_asm_tempalloc in current_settings.globalswitches) then
  364. begin
  365. {$ifdef EXTDEBUG}
  366. if assigned(tai_tempalloc(hp).problem) then
  367. writer.AsmWriteLn(asminfo^.comment+'Temp '+tostr(tai_tempalloc(hp).temppos)+','+
  368. tostr(tai_tempalloc(hp).tempsize)+' '+tai_tempalloc(hp).problem^)
  369. else
  370. {$endif EXTDEBUG}
  371. end;
  372. end;
  373. ait_align :
  374. begin
  375. end;
  376. ait_section :
  377. begin
  378. end;
  379. ait_datablock :
  380. begin
  381. // internalerror(2010122701);
  382. end;
  383. ait_const:
  384. begin
  385. writer.AsmWriteln('constant');
  386. // internalerror(2010122702);
  387. end;
  388. ait_realconst :
  389. begin
  390. internalerror(2010122703);
  391. end;
  392. ait_string :
  393. begin
  394. pos:=0;
  395. for i:=1 to tai_string(hp).len do
  396. begin
  397. if pos=0 then
  398. begin
  399. writer.AsmWrite(#9'strconst: '#9'"');
  400. pos:=20;
  401. end;
  402. ch:=tai_string(hp).str[i-1];
  403. case ch of
  404. #0, {This can't be done by range, because a bug in FPC}
  405. #1..#31,
  406. #128..#255 : s:='\'+tostr(ord(ch) shr 6)+tostr((ord(ch) and 63) shr 3)+tostr(ord(ch) and 7);
  407. '"' : s:='\"';
  408. '\' : s:='\\';
  409. else
  410. s:=ch;
  411. end;
  412. writer.AsmWrite(s);
  413. inc(pos,length(s));
  414. if (pos>line_length) or (i=tai_string(hp).len) then
  415. begin
  416. writer.AsmWriteLn('"');
  417. pos:=0;
  418. end;
  419. end;
  420. end;
  421. ait_label :
  422. begin
  423. if (tai_label(hp).labsym.is_used) then
  424. begin
  425. writer.AsmWrite(tai_label(hp).labsym.name);
  426. writer.AsmWriteLn(':');
  427. end;
  428. end;
  429. ait_symbol :
  430. begin
  431. if (tai_symbol(hp).sym.typ = AT_FUNCTION) then
  432. begin
  433. end
  434. else
  435. begin
  436. writer.AsmWrite('data symbol: ');
  437. writer.AsmWriteln(tai_symbol(hp).sym.name);
  438. // internalerror(2010122706);
  439. end;
  440. end;
  441. ait_symbol_end :
  442. begin
  443. end;
  444. ait_instruction :
  445. begin
  446. WriteInstruction(hp);
  447. end;
  448. ait_force_line,
  449. ait_function_name : ;
  450. ait_cutobject :
  451. begin
  452. end;
  453. ait_marker :
  454. if tai_marker(hp).kind=mark_NoLineInfoStart then
  455. inc(InlineLevel)
  456. else if tai_marker(hp).kind=mark_NoLineInfoEnd then
  457. dec(InlineLevel);
  458. ait_directive :
  459. begin
  460. { the CPU directive is probably not supported by the JVM assembler,
  461. so it's commented out }
  462. //todo:
  463. writer.AsmWrite(asminfo^.comment);
  464. if tai_directive(hp).directive=asd_cpu then
  465. writer.AsmWrite(asminfo^.comment);
  466. writer.AsmWrite('.'+directivestr[tai_directive(hp).directive]+' ');
  467. if tai_directive(hp).name<>'' then
  468. writer.AsmWrite(tai_directive(hp).name);
  469. writer.AsmLn;
  470. end;
  471. else
  472. internalerror(2010122707);
  473. end;
  474. hp:=tai(hp.next);
  475. end;
  476. end;
  477. procedure TWabtTextAssembler.WriteAsmList;
  478. var
  479. hal : tasmlisttype;
  480. begin
  481. if current_module.is_unit then begin
  482. writer.AsmWriteLn('(module)');
  483. exit;
  484. end;
  485. writer.MarkEmpty;
  486. writer.AsmWriteLn('(module ');
  487. { print all global variables }
  488. //WriteSymtableVarSyms(current_module.globalsymtable);
  489. //WriteSymtableVarSyms(current_module.localsymtable);
  490. //writer.AsmLn;
  491. { print all global procedures/functions }
  492. WriteSymtableProcdefs(current_module.globalsymtable);
  493. WriteSymtableProcdefs(current_module.localsymtable);
  494. //WriteSymtableStructDefs(current_module.globalsymtable);
  495. //WriteSymtableStructDefs(current_module.localsymtable);
  496. //writer.decorator.LinePrefix := '';
  497. writer.AsmWriteLn(')');
  498. writer.AsmLn;
  499. end;
  500. constructor TWabtTextAssembler.CreateWithWriter(info: pasminfo;
  501. wr: TExternalAssemblerOutputFile; freewriter, smart: boolean);
  502. begin
  503. inherited CreateWithWriter(info, wr, freewriter, smart);
  504. end;
  505. procedure TWabtTextAssembler.WriteSymtableProcdefs(st: TSymtable);
  506. var
  507. i : longint;
  508. def : tdef;
  509. begin
  510. if not assigned(st) then
  511. exit;
  512. for i:=0 to st.DefList.Count-1 do
  513. begin
  514. def:=tdef(st.DefList[i]);
  515. case def.typ of
  516. procdef :
  517. begin
  518. { methods are also in the static/globalsymtable of the unit
  519. -> make sure they are only written for the objectdefs that
  520. own them }
  521. if (not(st.symtabletype in [staticsymtable,globalsymtable]) or
  522. (def.owner=st)) and
  523. not(df_generic in def.defoptions) then
  524. begin
  525. WriteProcDef(tprocdef(def));
  526. if assigned(tprocdef(def).localst) then
  527. WriteSymtableProcdefs(tprocdef(def).localst);
  528. end;
  529. end;
  530. else
  531. ;
  532. end;
  533. end;
  534. end;
  535. procedure TWabtTextAssembler.WriteTempAlloc(p: TAsmList);
  536. var
  537. hp: tai;
  538. tmp: array of tai_tempalloc;
  539. mx : integer;
  540. i : integer;
  541. begin
  542. if not assigned(p) then
  543. exit;
  544. mx := -1;
  545. hp:=tai(p.first);
  546. while assigned(hp) do
  547. begin
  548. //prefetch(pointer(hp.next)^);
  549. if (hp.typ = ait_tempalloc) and
  550. tai_tempalloc(hp).allocation and
  551. (tai_tempalloc(hp).temppos >= mx) then
  552. mx := tai_tempalloc(hp).temppos+1;
  553. hp:=tai(hp.next);
  554. end;
  555. if (mx <= 0) then exit; // no temp allocations used
  556. SetLength(tmp, mx);
  557. hp:=tai(p.first);
  558. while assigned(hp) do
  559. begin
  560. //prefetch(pointer(hp.next)^);
  561. if (hp.typ = ait_tempalloc) and
  562. (tai_tempalloc(hp).allocation) and
  563. (tmp[ tai_tempalloc(hp).temppos ] = nil) then
  564. begin
  565. tmp[ tai_tempalloc(hp).temppos ] := tai_tempalloc(hp);
  566. dec(mx);
  567. if mx = 0 then break;
  568. end;
  569. hp:=tai(hp.next);
  570. end;
  571. for i:=0 to length(tmp)-1 do
  572. begin
  573. if tmp[i] = nil then continue;
  574. writer.AsmWrite(#9'(local'#9);
  575. if tmp[i].tempsize<=4 then writer.AsmWrite('i32')
  576. else if tmp[i].tempsize = 8 then writer.AsmWrite('i64');
  577. writer.AsmWrite(')');
  578. writer.AsmWrite(#9+asminfo^.comment+'Temp '+tostr(tmp[i].temppos)+','+
  579. tostr(tmp[i].tempsize)+' '+tempallocstr[tmp[i].allocation]);
  580. writer.AsmLn;
  581. end;
  582. end;
  583. { TWatInstrWriter }
  584. constructor TWatInstrWriter.create(_owner: TWabtTextAssembler);
  585. begin
  586. inherited create;
  587. owner := _owner;
  588. end;
  589. procedure TWatInstrWriter.WriteInstruction(hp: tai);
  590. begin
  591. end;
  592. const
  593. as_wasm_wabt_info : tasminfo =
  594. (
  595. id : as_wasm_wabt;
  596. idtxt : 'Wabt';
  597. asmbin : 'wat2wasm';
  598. asmcmd : '$ASM $EXTRAOPT';
  599. supported_targets : [system_wasm_wasm32];
  600. flags : [];
  601. labelprefix : 'L';
  602. comment : ';; ';
  603. dollarsign : '$';
  604. );
  605. initialization
  606. RegisterAssembler(as_wasm_wabt_info, TWabtTextAssembler);
  607. end.