agwat.pas 21 KB

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