agwat.pas 18 KB

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