agjasmin.pas 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. {
  2. Copyright (c) 1998-2010 by the Free Pascal team
  3. This unit implements the Jasmin assembler writer
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. { Unit for writing Jasmin assembler (JVM bytecode) output.
  18. }
  19. unit agjasmin;
  20. {$i fpcdefs.inc}
  21. interface
  22. uses
  23. cclasses,
  24. globtype,globals,
  25. symconst,symbase,symdef,symsym,
  26. aasmbase,aasmtai,aasmdata,aasmcpu,
  27. assemble;
  28. type
  29. TJasminInstrWriter = class;
  30. {# This is a derived class which is used to write
  31. Jasmin-styled assembler.
  32. }
  33. { TJasminAssembler }
  34. TJasminAssembler=class(texternalassembler)
  35. protected
  36. jasminjar: tcmdstr;
  37. asmfiles: TCmdStrList;
  38. procedure WriteExtraHeader(obj: tabstractrecorddef);
  39. procedure WriteInstruction(hp: tai);
  40. procedure NewAsmFileForStructDef(obj: tabstractrecorddef);
  41. function VisibilityToStr(vis: tvisibility): string;
  42. function MethodDefinition(pd: tprocdef): string;
  43. function ConstValue(csym: tconstsym): ansistring;
  44. function ConstAssignmentValue(csym: tconstsym): ansistring;
  45. function ConstDefinition(sym: tconstsym): string;
  46. function FieldDefinition(sym: tabstractvarsym): string;
  47. function InnerStructDef(obj: tabstractrecorddef): string;
  48. procedure WriteProcDef(pd: tprocdef);
  49. procedure WriteFieldSym(sym: tabstractvarsym);
  50. procedure WriteConstSym(sym: tconstsym);
  51. procedure WriteSymtableVarSyms(st: TSymtable);
  52. procedure WriteSymtableProcdefs(st: TSymtable);
  53. procedure WriteSymtableStructDefs(st: TSymtable);
  54. public
  55. constructor Create(smart: boolean); override;
  56. function MakeCmdLine: TCmdStr;override;
  57. procedure WriteTree(p:TAsmList);override;
  58. procedure WriteAsmList;override;
  59. destructor destroy; override;
  60. protected
  61. InstrWriter: TJasminInstrWriter;
  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. { TJasminInstrWriter }
  69. TJasminInstrWriter = class
  70. constructor create(_owner: TJasminAssembler);
  71. procedure WriteInstruction(hp : tai); virtual;
  72. protected
  73. owner: TJasminAssembler;
  74. end;
  75. implementation
  76. uses
  77. SysUtils,
  78. cutils,cfileutl,systems,script,
  79. fmodule,finput,verbose,
  80. symtype,symtable,jvmdef,
  81. itcpujas,cpubase,cpuinfo,cgutils,
  82. widestr
  83. ;
  84. const
  85. line_length = 70;
  86. type
  87. t64bitarray = array[0..7] of byte;
  88. t32bitarray = array[0..3] of byte;
  89. {****************************************************************************}
  90. { Support routines }
  91. {****************************************************************************}
  92. function fixline(s:string):string;
  93. {
  94. return s with all leading and ending spaces and tabs removed
  95. }
  96. var
  97. i,j,k : integer;
  98. begin
  99. i:=length(s);
  100. while (i>0) and (s[i] in [#9,' ']) do
  101. dec(i);
  102. j:=1;
  103. while (j<i) and (s[j] in [#9,' ']) do
  104. inc(j);
  105. for k:=j to i do
  106. if s[k] in [#0..#31,#127..#255] then
  107. s[k]:='.';
  108. fixline:=Copy(s,j,i-j+1);
  109. end;
  110. function constastr(p: pchar; len: longint): ansistring;
  111. var
  112. i,runstart,runlen: longint;
  113. procedure flush;
  114. begin
  115. if runlen>0 then
  116. begin
  117. setlength(result,length(result)+runlen);
  118. move(p[runstart],result[length(result)-runlen+1],runlen);
  119. runlen:=0;
  120. end;
  121. end;
  122. begin
  123. result:='"';
  124. runlen:=0;
  125. runstart:=0;
  126. for i:=0 to len-1 do
  127. begin
  128. { escape control codes }
  129. case p[i] of
  130. { LF and CR must be escaped specially, because \uXXXX parsing
  131. happens in the pre-processor, so it's the same as actually
  132. inserting a newline in the middle of a string constant }
  133. #10:
  134. begin
  135. flush;
  136. result:=result+'\n';
  137. end;
  138. #13:
  139. begin
  140. flush;
  141. result:=result+'\r';
  142. end;
  143. '"','\':
  144. begin
  145. flush;
  146. result:=result+'\'+p[i];
  147. end
  148. else if p[i]<#32 then
  149. begin
  150. flush;
  151. result:=result+'\u'+hexstr(ord(p[i]),4);
  152. end
  153. else if p[i]<#127 then
  154. begin
  155. if runlen=0 then
  156. runstart:=i;
  157. inc(runlen);
  158. end
  159. else
  160. // since Jasmin expects an UTF-16 string, we can't safely
  161. // have high ASCII characters since they'll be
  162. // re-interpreted as utf-16 anyway
  163. internalerror(2010122808);
  164. end;
  165. end;
  166. flush;
  167. result:=result+'"';
  168. end;
  169. function constwstr(w: pcompilerwidechar; len: longint): ansistring;
  170. var
  171. i: longint;
  172. begin
  173. result:='"';
  174. for i:=0 to len-1 do
  175. begin
  176. { escape control codes }
  177. case w[i] of
  178. 10:
  179. result:=result+'\n';
  180. 13:
  181. result:=result+'\r';
  182. ord('"'),ord('\'):
  183. result:=result+'\'+chr(w[i]);
  184. else if (w[i]<32) or
  185. (w[i]>127) then
  186. result:=result+'\u'+hexstr(w[i],4)
  187. else
  188. result:=result+char(w[i]);
  189. end;
  190. end;
  191. result:=result+'"';
  192. end;
  193. function constsingle(s: single): string;
  194. begin
  195. result:='0fx'+hexstr(longint(t32bitarray(s)),8);
  196. end;
  197. function constdouble(d: double): string;
  198. begin
  199. // force interpretation as double (since we write it out as an
  200. // integer, we never have to swap the endianess). We have to
  201. // include the sign separately because of the way Java parses
  202. // hex numbers (0x8000000000000000 is not a valid long)
  203. result:=hexstr(abs(int64(t64bitarray(d))),16);
  204. if int64(t64bitarray(d))<0 then
  205. result:='-'+result;
  206. result:='0dx'+result;
  207. end;
  208. {****************************************************************************}
  209. { Jasmin Assembler writer }
  210. {****************************************************************************}
  211. destructor TJasminAssembler.Destroy;
  212. begin
  213. InstrWriter.free;
  214. asmfiles.free;
  215. inherited destroy;
  216. end;
  217. procedure TJasminAssembler.WriteTree(p:TAsmList);
  218. var
  219. ch : char;
  220. hp : tai;
  221. hp1 : tailineinfo;
  222. s : string;
  223. i,pos : longint;
  224. InlineLevel : longint;
  225. do_line : boolean;
  226. begin
  227. if not assigned(p) then
  228. exit;
  229. InlineLevel:=0;
  230. { lineinfo is only needed for al_procedures (PFV) }
  231. do_line:=(cs_asm_source in current_settings.globalswitches);
  232. hp:=tai(p.first);
  233. while assigned(hp) do
  234. begin
  235. prefetch(pointer(hp.next)^);
  236. if not(hp.typ in SkipLineInfo) then
  237. begin
  238. hp1 := hp as tailineinfo;
  239. current_filepos:=hp1.fileinfo;
  240. { no line info for inlined code }
  241. if do_line and (inlinelevel=0) then
  242. begin
  243. { load infile }
  244. if lastfileinfo.fileindex<>hp1.fileinfo.fileindex then
  245. begin
  246. infile:=current_module.sourcefiles.get_file(hp1.fileinfo.fileindex);
  247. if assigned(infile) then
  248. begin
  249. { open only if needed !! }
  250. if (cs_asm_source in current_settings.globalswitches) then
  251. infile.open;
  252. end;
  253. { avoid unnecessary reopens of the same file !! }
  254. lastfileinfo.fileindex:=hp1.fileinfo.fileindex;
  255. { be sure to change line !! }
  256. lastfileinfo.line:=-1;
  257. end;
  258. { write source }
  259. if (cs_asm_source in current_settings.globalswitches) and
  260. assigned(infile) then
  261. begin
  262. if (infile<>lastinfile) then
  263. begin
  264. AsmWriteLn(target_asm.comment+'['+infile.name^+']');
  265. if assigned(lastinfile) then
  266. lastinfile.close;
  267. end;
  268. if (hp1.fileinfo.line<>lastfileinfo.line) and
  269. ((hp1.fileinfo.line<infile.maxlinebuf) or (InlineLevel>0)) then
  270. begin
  271. if (hp1.fileinfo.line<>0) and
  272. ((infile.linebuf^[hp1.fileinfo.line]>=0) or (InlineLevel>0)) then
  273. AsmWriteLn(target_asm.comment+'['+tostr(hp1.fileinfo.line)+'] '+
  274. fixline(infile.GetLineStr(hp1.fileinfo.line)));
  275. { set it to a negative value !
  276. to make that is has been read already !! PM }
  277. if (infile.linebuf^[hp1.fileinfo.line]>=0) then
  278. infile.linebuf^[hp1.fileinfo.line]:=-infile.linebuf^[hp1.fileinfo.line]-1;
  279. end;
  280. end;
  281. lastfileinfo:=hp1.fileinfo;
  282. lastinfile:=infile;
  283. end;
  284. end;
  285. case hp.typ of
  286. ait_comment :
  287. Begin
  288. AsmWrite(target_asm.comment);
  289. AsmWritePChar(tai_comment(hp).str);
  290. AsmLn;
  291. End;
  292. ait_regalloc :
  293. begin
  294. if (cs_asm_regalloc in current_settings.globalswitches) then
  295. begin
  296. AsmWrite(#9+target_asm.comment+'Register ');
  297. repeat
  298. AsmWrite(std_regname(Tai_regalloc(hp).reg));
  299. if (hp.next=nil) or
  300. (tai(hp.next).typ<>ait_regalloc) or
  301. (tai_regalloc(hp.next).ratype<>tai_regalloc(hp).ratype) then
  302. break;
  303. hp:=tai(hp.next);
  304. AsmWrite(',');
  305. until false;
  306. AsmWrite(' ');
  307. AsmWriteLn(regallocstr[tai_regalloc(hp).ratype]);
  308. end;
  309. end;
  310. ait_tempalloc :
  311. begin
  312. if (cs_asm_tempalloc in current_settings.globalswitches) then
  313. begin
  314. {$ifdef EXTDEBUG}
  315. if assigned(tai_tempalloc(hp).problem) then
  316. AsmWriteLn(target_asm.comment+'Temp '+tostr(tai_tempalloc(hp).temppos)+','+
  317. tostr(tai_tempalloc(hp).tempsize)+' '+tai_tempalloc(hp).problem^)
  318. else
  319. {$endif EXTDEBUG}
  320. AsmWriteLn(target_asm.comment+'Temp '+tostr(tai_tempalloc(hp).temppos)+','+
  321. tostr(tai_tempalloc(hp).tempsize)+' '+tempallocstr[tai_tempalloc(hp).allocation]);
  322. end;
  323. end;
  324. ait_align :
  325. begin
  326. end;
  327. ait_section :
  328. begin
  329. end;
  330. ait_datablock :
  331. begin
  332. internalerror(2010122701);
  333. end;
  334. ait_const:
  335. begin
  336. AsmWriteln('constant');
  337. // internalerror(2010122702);
  338. end;
  339. ait_real_64bit :
  340. begin
  341. internalerror(2010122703);
  342. end;
  343. ait_real_32bit :
  344. begin
  345. internalerror(2010122703);
  346. end;
  347. ait_comp_64bit :
  348. begin
  349. internalerror(2010122704);
  350. end;
  351. ait_string :
  352. begin
  353. pos:=0;
  354. for i:=1 to tai_string(hp).len do
  355. begin
  356. if pos=0 then
  357. begin
  358. AsmWrite(#9'strconst: '#9'"');
  359. pos:=20;
  360. end;
  361. ch:=tai_string(hp).str[i-1];
  362. case ch of
  363. #0, {This can't be done by range, because a bug in FPC}
  364. #1..#31,
  365. #128..#255 : s:='\'+tostr(ord(ch) shr 6)+tostr((ord(ch) and 63) shr 3)+tostr(ord(ch) and 7);
  366. '"' : s:='\"';
  367. '\' : s:='\\';
  368. else
  369. s:=ch;
  370. end;
  371. AsmWrite(s);
  372. inc(pos,length(s));
  373. if (pos>line_length) or (i=tai_string(hp).len) then
  374. begin
  375. AsmWriteLn('"');
  376. pos:=0;
  377. end;
  378. end;
  379. end;
  380. ait_label :
  381. begin
  382. if (tai_label(hp).labsym.is_used) then
  383. begin
  384. AsmWrite(tai_label(hp).labsym.name);
  385. AsmWriteLn(':');
  386. end;
  387. end;
  388. ait_symbol :
  389. begin
  390. if (tai_symbol(hp).sym.typ = AT_FUNCTION) then
  391. begin
  392. end
  393. else
  394. begin
  395. AsmWrite('data symbol: ');
  396. AsmWriteln(tai_symbol(hp).sym.name);
  397. // internalerror(2010122706);
  398. end;
  399. end;
  400. ait_symbol_end :
  401. begin
  402. end;
  403. ait_instruction :
  404. begin
  405. WriteInstruction(hp);
  406. end;
  407. ait_force_line,
  408. ait_function_name : ;
  409. ait_cutobject :
  410. begin
  411. end;
  412. ait_marker :
  413. if tai_marker(hp).kind=mark_NoLineInfoStart then
  414. inc(InlineLevel)
  415. else if tai_marker(hp).kind=mark_NoLineInfoEnd then
  416. dec(InlineLevel);
  417. ait_directive :
  418. begin
  419. AsmWrite('.'+directivestr[tai_directive(hp).directive]+' ');
  420. if assigned(tai_directive(hp).name) then
  421. AsmWrite(tai_directive(hp).name^);
  422. AsmLn;
  423. end;
  424. ait_jvar:
  425. begin
  426. AsmWrite('.var ');
  427. AsmWrite(tostr(tai_jvar(hp).stackslot));
  428. AsmWrite(' is ');
  429. AsmWrite(tai_jvar(hp).desc^);
  430. AsmWrite(' from ');
  431. AsmWrite(tai_jvar(hp).startlab.name);
  432. AsmWrite(' to ');
  433. AsmWriteLn(tai_jvar(hp).stoplab.name);
  434. end;
  435. ait_jcatch:
  436. begin
  437. AsmWrite('.catch ');
  438. AsmWrite(tai_jcatch(hp).name^);
  439. AsmWrite(' from ');
  440. AsmWrite(tai_jcatch(hp).startlab.name);
  441. AsmWrite(' to ');
  442. AsmWrite(tai_jcatch(hp).stoplab.name);
  443. AsmWrite(' using ');
  444. AsmWriteLn(tai_jcatch(hp).handlerlab.name);
  445. end;
  446. else
  447. internalerror(2010122707);
  448. end;
  449. hp:=tai(hp.next);
  450. end;
  451. end;
  452. procedure TJasminAssembler.WriteExtraHeader(obj: tabstractrecorddef);
  453. var
  454. superclass,
  455. intf: tobjectdef;
  456. n: string;
  457. i: longint;
  458. toplevelowner: tsymtable;
  459. begin
  460. { JVM 1.5+ }
  461. AsmWriteLn('.bytecode 49.0');
  462. // include files are not support by Java, and the directory of the main
  463. // source file must not be specified
  464. if assigned(current_module.mainsource) then
  465. n:=ExtractFileName(current_module.mainsource^)
  466. else
  467. n:=InputFileName;
  468. AsmWriteLn('.source '+ExtractFileName(n));
  469. { class/interface name }
  470. if not assigned(obj) then
  471. begin
  472. { fake class type for unit -> name=unitname and
  473. superclass=java.lang.object, make final so you cannot descend
  474. from it }
  475. AsmWrite('.class final public ');
  476. if assigned(current_module.namespace) then
  477. AsmWrite(current_module.namespace^+'.');
  478. AsmWriteln(current_module.realmodulename^);
  479. AsmWriteLn('.super java/lang/Object');
  480. end
  481. else
  482. begin
  483. toplevelowner:=obj.owner;
  484. while not(toplevelowner.symtabletype in [staticsymtable,globalsymtable]) do
  485. toplevelowner:=toplevelowner.defowner.owner;
  486. case obj.typ of
  487. recorddef:
  488. begin
  489. AsmWrite('.class ');
  490. if toplevelowner.symtabletype=globalsymtable then
  491. AsmWrite('public ');
  492. AsmWriteln(obj.jvm_full_typename(true));
  493. superclass:=java_fpcbaserecordtype;
  494. end;
  495. objectdef:
  496. begin
  497. case tobjectdef(obj).objecttype of
  498. odt_javaclass:
  499. begin
  500. AsmWrite('.class ');
  501. if toplevelowner.symtabletype=globalsymtable then
  502. AsmWrite('public ');
  503. AsmWriteln(obj.jvm_full_typename(true));
  504. superclass:=tobjectdef(obj).childof;
  505. end;
  506. odt_interfacejava:
  507. begin
  508. AsmWrite('.interface abstract ');
  509. if toplevelowner.symtabletype=globalsymtable then
  510. AsmWrite('public ');
  511. AsmWriteLn(obj.jvm_full_typename(true));
  512. { interfaces must always specify Java.lang.object as
  513. superclass }
  514. superclass:=java_jlobject;
  515. end
  516. else
  517. internalerror(2011010906);
  518. end;
  519. end;
  520. end;
  521. { superclass }
  522. if assigned(superclass) then
  523. begin
  524. AsmWrite('.super ');
  525. if assigned(superclass.import_lib) then
  526. AsmWrite(superclass.import_lib^+'/');
  527. AsmWriteln(superclass.objextname^);
  528. end;
  529. { implemented interfaces }
  530. if (obj.typ=objectdef) and
  531. assigned(tobjectdef(obj).ImplementedInterfaces) then
  532. begin
  533. for i:=0 to tobjectdef(obj).ImplementedInterfaces.count-1 do
  534. begin
  535. intf:=TImplementedInterface(tobjectdef(obj).ImplementedInterfaces[i]).IntfDef;
  536. AsmWrite('.implements ');
  537. if assigned(intf.import_lib) then
  538. AsmWrite(intf.import_lib^+'/');
  539. AsmWriteln(intf.objextname^);
  540. end;
  541. end;
  542. { in case of nested class: relation to parent class }
  543. if obj.owner.symtabletype in [objectsymtable,recordsymtable] then
  544. AsmWriteln(InnerStructDef(obj));
  545. { all all nested classes }
  546. for i:=0 to obj.symtable.deflist.count-1 do
  547. if is_java_class_or_interface(tdef(obj.symtable.deflist[i])) or
  548. (tdef(obj.symtable.deflist[i]).typ=recorddef) then
  549. AsmWriteln(InnerStructDef(tabstractrecorddef(obj.symtable.deflist[i])));
  550. end;
  551. AsmLn;
  552. end;
  553. procedure TJasminAssembler.WriteInstruction(hp: tai);
  554. begin
  555. InstrWriter.WriteInstruction(hp);
  556. end;
  557. function TJasminAssembler.MakeCmdLine: TCmdStr;
  558. const
  559. jasminjarname = 'jasmin.jar';
  560. var
  561. filenames: tcmdstr;
  562. jasminjarfound: boolean;
  563. begin
  564. if jasminjar='' then
  565. begin
  566. jasminjarfound:=false;
  567. if utilsdirectory<>'' then
  568. jasminjarfound:=FindFile(jasminjarname,utilsdirectory,false,jasminjar);
  569. if not jasminjarfound then
  570. jasminjarfound:=FindFileInExeLocations(jasminjarname,false,jasminjar);
  571. if (not jasminjarfound) and not(cs_asm_extern in current_settings.globalswitches) then
  572. begin
  573. Message1(exec_e_assembler_not_found,jasminjarname);
  574. current_settings.globalswitches:=current_settings.globalswitches+[cs_asm_extern];
  575. end;
  576. if jasminjarfound then
  577. Message1(exec_t_using_assembler,jasminjar);
  578. end;
  579. result:=target_asm.asmcmd;
  580. filenames:=maybequoted(ScriptFixFileName(AsmFileName));
  581. while not asmfiles.empty do
  582. filenames:=filenames+' '+asmfiles.GetFirst;
  583. Replace(result,'$ASM',filenames);
  584. if (path<>'') then
  585. Replace(result,'$OBJDIR',maybequoted(ScriptFixFileName(path)))
  586. else
  587. Replace(result,'$OBJDIR','.');
  588. Replace(result,'$JASMINJAR',maybequoted(ScriptFixFileName(jasminjar)));
  589. end;
  590. procedure TJasminAssembler.NewAsmFileForStructDef(obj: tabstractrecorddef);
  591. begin
  592. if AsmSize<>AsmStartSize then
  593. begin
  594. AsmClose;
  595. asmfiles.Concat(maybequoted(ScriptFixFileName(AsmFileName)));
  596. end
  597. else
  598. AsmClear;
  599. AsmFileName:=obj.jvm_full_typename(false);
  600. AsmFileName:=Path+FixFileName(AsmFileName)+target_info.asmext;
  601. AsmCreate(cut_normal);
  602. end;
  603. function TJasminAssembler.VisibilityToStr(vis: tvisibility): string;
  604. begin
  605. case vis of
  606. vis_hidden,
  607. vis_strictprivate:
  608. result:='private ';
  609. vis_strictprotected:
  610. result:='protected ';
  611. vis_protected,
  612. vis_private:
  613. { pick default visibility = "package" visibility; required because
  614. other classes in the same unit can also access these symbols }
  615. result:='';
  616. vis_public:
  617. result:='public '
  618. else
  619. internalerror(2010122609);
  620. end;
  621. end;
  622. function TJasminAssembler.MethodDefinition(pd: tprocdef): string;
  623. begin
  624. result:=VisibilityToStr(pd.visibility);
  625. if (pd.procsym.owner.symtabletype in [globalsymtable,staticsymtable,localsymtable]) or
  626. (po_staticmethod in pd.procoptions) then
  627. result:=result+'static ';
  628. if is_javainterface(tdef(pd.owner.defowner)) then
  629. result:=result+'abstract ';
  630. if (pd.procsym.owner.symtabletype in [globalsymtable,staticsymtable,localsymtable]) or
  631. (po_finalmethod in pd.procoptions) or
  632. (not(po_virtualmethod in pd.procoptions) and
  633. not(pd.proctypeoption in [potype_constructor,potype_class_constructor])) then
  634. result:=result+'final ';
  635. result:=result+pd.jvmmangledbasename;
  636. end;
  637. function TJasminAssembler.ConstValue(csym: tconstsym): ansistring;
  638. begin
  639. case csym.consttyp of
  640. constord:
  641. { always interpret as signed value, because the JVM does not
  642. support unsigned 64 bit values }
  643. result:=tostr(csym.value.valueord.svalue);
  644. conststring:
  645. result:=constastr(pchar(csym.value.valueptr),csym.value.len);
  646. constreal:
  647. case tfloatdef(csym.constdef).floattype of
  648. s32real:
  649. result:=constsingle(pbestreal(csym.value.valueptr)^);
  650. s64real:
  651. result:=constdouble(pbestreal(csym.value.valueptr)^);
  652. else
  653. internalerror(2011021204);
  654. end;
  655. constset:
  656. result:='TODO: add support for constant sets';
  657. constpointer:
  658. { can only be null, but that's the default value and should not
  659. be written; there's no primitive type that can hold nill }
  660. internalerror(2011021201);
  661. constnil:
  662. internalerror(2011021202);
  663. constresourcestring:
  664. result:='TODO: add support for constant resource strings';
  665. constwstring:
  666. result:=constwstr(pcompilerwidestring(csym.value.valueptr)^.data,pcompilerwidestring(csym.value.valueptr)^.len);
  667. constguid:
  668. result:='TODO: add support for constant guids';
  669. else
  670. internalerror(2011021205);
  671. end;
  672. end;
  673. function TJasminAssembler.ConstAssignmentValue(csym: tconstsym): ansistring;
  674. begin
  675. { nil is the default value -> don't write explicitly }
  676. case csym.consttyp of
  677. constpointer:
  678. begin
  679. if csym.value.valueordptr<>0 then
  680. internalerror(2011021206);
  681. result:='';
  682. end;
  683. constnil:
  684. result:='';
  685. else
  686. result:=' = '+ConstValue(csym)
  687. end;
  688. end;
  689. function TJasminAssembler.ConstDefinition(sym: tconstsym): string;
  690. begin
  691. result:=VisibilityToStr(sym.visibility);
  692. { formal constants are always class-level, not instance-level }
  693. result:=result+'static final ';
  694. result:=result+jvmmangledbasename(sym);
  695. result:=result+ConstAssignmentValue(tconstsym(sym));
  696. end;
  697. function TJasminAssembler.FieldDefinition(sym: tabstractvarsym): string;
  698. var
  699. vissym: tabstractvarsym;
  700. begin
  701. vissym:=sym;
  702. { static field definition -> get original field definition for
  703. visibility }
  704. if (sym.typ=staticvarsym) and
  705. (sym.owner.symtabletype=objectsymtable) then
  706. begin
  707. vissym:=tabstractvarsym(
  708. tabstractrecorddef(sym.owner.defowner).symtable.find(
  709. internal_static_field_name(sym.name)));
  710. if not assigned(vissym) then
  711. vissym:=tabstractvarsym(
  712. tabstractrecorddef(sym.owner.defowner).symtable.find(
  713. generate_nested_name(sym.owner,'_')+'_'+sym.name));
  714. if not assigned(vissym) or
  715. not(vissym.typ in [fieldvarsym,absolutevarsym]) then
  716. internalerror(2011011501);
  717. end;
  718. case vissym.typ of
  719. staticvarsym:
  720. begin
  721. if vissym.owner.symtabletype=globalsymtable then
  722. result:='public '
  723. else
  724. { package visbility }
  725. result:='';
  726. end;
  727. fieldvarsym,
  728. absolutevarsym:
  729. result:=VisibilityToStr(tstoredsym(vissym).visibility);
  730. else
  731. internalerror(2011011204);
  732. end;
  733. if (sym.typ=staticvarsym) or
  734. (sp_static in sym.symoptions) then
  735. result:=result+'static ';
  736. if sym.varspez=vs_const then
  737. result:=result+'final ';
  738. result:=result+jvmmangledbasename(sym);
  739. end;
  740. function TJasminAssembler.InnerStructDef(obj: tabstractrecorddef): string;
  741. var
  742. extname: pshortstring;
  743. kindname: string;
  744. begin
  745. if not(obj.owner.defowner.typ in [objectdef,recorddef]) then
  746. internalerror(2011021701);
  747. case obj.typ of
  748. recorddef:
  749. begin
  750. kindname:='class ';
  751. extname:=obj.symtable.realname;
  752. end;
  753. objectdef:
  754. begin
  755. extname:=tobjectdef(obj).objextname;
  756. case tobjectdef(obj).objecttype of
  757. odt_javaclass:
  758. kindname:='class ';
  759. odt_interfacejava:
  760. kindname:='interface ';
  761. else
  762. internalerror(2011021702);
  763. end;
  764. end;
  765. else
  766. internalerror(2011032809);
  767. end;
  768. result:=
  769. '.inner '+
  770. kindname+
  771. VisibilityToStr(obj.typesym.visibility)+
  772. { Nested classes in the Pascal sense are equivalent to "static"
  773. inner classes in Java -- will be changed when support for
  774. Java-style non-static classes is added }
  775. ' static '+
  776. extname^+
  777. ' inner '+
  778. obj.jvm_full_typename(true)+
  779. ' outer '+
  780. tabstractrecorddef(obj.owner.defowner).jvm_full_typename(true);
  781. end;
  782. procedure TJasminAssembler.WriteProcDef(pd: tprocdef);
  783. begin
  784. if not assigned(pd.exprasmlist) and
  785. (not is_javainterface(pd.struct) or
  786. (pd.proctypeoption in [potype_unitinit,potype_unitfinalize])) then
  787. exit;
  788. AsmWrite('.method ');
  789. AsmWriteln(MethodDefinition(pd));
  790. WriteTree(pd.exprasmlist);
  791. AsmWriteln('.end method');
  792. AsmLn;
  793. end;
  794. procedure TJasminAssembler.WriteFieldSym(sym: tabstractvarsym);
  795. begin
  796. { internal static field definition alias -> skip }
  797. if sp_static in sym.symoptions then
  798. exit;
  799. AsmWrite('.field ');
  800. AsmWriteln(FieldDefinition(sym));
  801. end;
  802. procedure TJasminAssembler.WriteConstSym(sym: tconstsym);
  803. begin
  804. AsmWrite('.field ');
  805. AsmWriteln(ConstDefinition(sym));
  806. end;
  807. procedure TJasminAssembler.WriteSymtableVarSyms(st: TSymtable);
  808. var
  809. sym : tsym;
  810. i,j : longint;
  811. begin
  812. if not assigned(st) then
  813. exit;
  814. for i:=0 to st.SymList.Count-1 do
  815. begin
  816. sym:=tsym(st.SymList[i]);
  817. case sym.typ of
  818. staticvarsym,
  819. fieldvarsym:
  820. begin
  821. WriteFieldSym(tabstractvarsym(sym));
  822. if (sym.typ=staticvarsym) and
  823. assigned(tstaticvarsym(sym).defaultconstsym) then
  824. WriteFieldSym(tabstractvarsym(tstaticvarsym(sym).defaultconstsym));
  825. end;
  826. constsym:
  827. begin
  828. WriteConstSym(tconstsym(sym));
  829. end;
  830. procsym:
  831. begin
  832. for j:=0 to tprocsym(sym).procdeflist.count-1 do
  833. WriteSymtableVarSyms(tprocdef(tprocsym(sym).procdeflist[j]).localst);
  834. end;
  835. end;
  836. end;
  837. end;
  838. procedure TJasminAssembler.WriteSymtableProcdefs(st: TSymtable);
  839. var
  840. i : longint;
  841. def : tdef;
  842. begin
  843. if not assigned(st) then
  844. exit;
  845. for i:=0 to st.DefList.Count-1 do
  846. begin
  847. def:=tdef(st.DefList[i]);
  848. case def.typ of
  849. procdef :
  850. begin
  851. { methods are also in the static/globalsymtable of the unit
  852. -> make sure they are only written for the objectdefs that
  853. own them }
  854. if not(st.symtabletype in [staticsymtable,globalsymtable]) or
  855. (def.owner=st) then
  856. begin
  857. WriteProcDef(tprocdef(def));
  858. if assigned(tprocdef(def).localst) then
  859. WriteSymtableProcdefs(tprocdef(def).localst);
  860. end;
  861. end;
  862. end;
  863. end;
  864. end;
  865. procedure TJasminAssembler.WriteSymtableStructDefs(st: TSymtable);
  866. var
  867. i : longint;
  868. def : tdef;
  869. obj : tabstractrecorddef;
  870. nestedstructs: tfpobjectlist;
  871. begin
  872. if not assigned(st) then
  873. exit;
  874. nestedstructs:=tfpobjectlist.create(false);
  875. for i:=0 to st.DefList.Count-1 do
  876. begin
  877. def:=tdef(st.DefList[i]);
  878. case def.typ of
  879. objectdef:
  880. if not(oo_is_external in tobjectdef(def).objectoptions) then
  881. nestedstructs.add(def);
  882. recorddef:
  883. nestedstructs.add(def);
  884. end;
  885. end;
  886. for i:=0 to nestedstructs.count-1 do
  887. begin
  888. obj:=tabstractrecorddef(nestedstructs[i]);
  889. NewAsmFileForStructDef(obj);
  890. WriteExtraHeader(obj);
  891. WriteSymtableVarSyms(obj.symtable);
  892. AsmLn;
  893. WriteSymtableProcDefs(obj.symtable);
  894. WriteSymtableStructDefs(obj.symtable);
  895. end;
  896. nestedstructs.free;
  897. end;
  898. constructor TJasminAssembler.Create(smart: boolean);
  899. begin
  900. inherited create(smart);
  901. InstrWriter:=TJasminInstrWriter.Create(self);
  902. asmfiles:=TCmdStrList.Create;
  903. end;
  904. procedure TJasminAssembler.WriteAsmList;
  905. begin
  906. {$ifdef EXTDEBUG}
  907. if assigned(current_module.mainsource) then
  908. Comment(V_Debug,'Start writing Jasmin-styled assembler output for '+current_module.mainsource^);
  909. {$endif}
  910. AsmStartSize:=AsmSize;
  911. WriteExtraHeader(nil);
  912. (*
  913. for hal:=low(TasmlistType) to high(TasmlistType) do
  914. begin
  915. AsmWriteLn(target_asm.comment+'Begin asmlist '+AsmlistTypeStr[hal]);
  916. writetree(current_asmdata.asmlists[hal]);
  917. AsmWriteLn(target_asm.comment+'End asmlist '+AsmlistTypeStr[hal]);
  918. end;
  919. *)
  920. { print all global variables }
  921. WriteSymtableVarSyms(current_module.globalsymtable);
  922. WriteSymtableVarSyms(current_module.localsymtable);
  923. AsmLn;
  924. { print all global procedures/functions }
  925. WriteSymtableProcdefs(current_module.globalsymtable);
  926. WriteSymtableProcdefs(current_module.localsymtable);
  927. WriteSymtableStructDefs(current_module.globalsymtable);
  928. WriteSymtableStructDefs(current_module.localsymtable);
  929. AsmLn;
  930. {$ifdef EXTDEBUG}
  931. if assigned(current_module.mainsource) then
  932. Comment(V_Debug,'Done writing gas-styled assembler output for '+current_module.mainsource^);
  933. {$endif EXTDEBUG}
  934. end;
  935. {****************************************************************************}
  936. { Jasmin Instruction Writer }
  937. {****************************************************************************}
  938. constructor TJasminInstrWriter.create(_owner: TJasminAssembler);
  939. begin
  940. inherited create;
  941. owner := _owner;
  942. end;
  943. function getreferencestring(var ref : treference) : string;
  944. begin
  945. if (ref.arrayreftype<>art_none) or
  946. (ref.index<>NR_NO) then
  947. internalerror(2010122809);
  948. if assigned(ref.symbol) then
  949. begin
  950. // global symbol or field -> full type and name
  951. // ref.base can be <> NR_NO in case an instance field is loaded.
  952. // This register is not part of this instruction, it will have
  953. // been placed on the stack by the previous one.
  954. if (ref.offset<>0) then
  955. internalerror(2010122811);
  956. result:=ref.symbol.name;
  957. end
  958. else
  959. begin
  960. // local symbol -> stack slot, stored in offset
  961. if ref.base<>NR_STACK_POINTER_REG then
  962. internalerror(2010122810);
  963. result:=tostr(ref.offset);
  964. end;
  965. end;
  966. function getopstr(const o:toper) : ansistring;
  967. var
  968. d: double;
  969. s: single;
  970. begin
  971. case o.typ of
  972. top_reg:
  973. // should have been translated into a memory location by the
  974. // register allocator)
  975. if (cs_no_regalloc in current_settings.globalswitches) then
  976. getopstr:=std_regname(o.reg)
  977. else
  978. internalerror(2010122803);
  979. top_const:
  980. str(o.val,result);
  981. top_ref:
  982. getopstr:=getreferencestring(o.ref^);
  983. top_single:
  984. begin
  985. result:=constsingle(o.sval);
  986. end;
  987. top_double:
  988. begin
  989. result:=constdouble(o.dval);
  990. end;
  991. top_string:
  992. begin
  993. result:=constastr(o.pcval,o.pcvallen);
  994. end;
  995. top_wstring:
  996. begin
  997. result:=constwstr(o.pwstrval^.data,getlengthwidestring(o.pwstrval));
  998. end
  999. else
  1000. internalerror(2010122802);
  1001. end;
  1002. end;
  1003. procedure TJasminInstrWriter.WriteInstruction(hp: tai);
  1004. var
  1005. s: ansistring;
  1006. i: byte;
  1007. sep: string[3];
  1008. begin
  1009. s:=#9+jas_op2str[taicpu(hp).opcode];
  1010. if taicpu(hp).ops<>0 then
  1011. begin
  1012. sep:=#9;
  1013. for i:=0 to taicpu(hp).ops-1 do
  1014. begin
  1015. s:=s+sep+getopstr(taicpu(hp).oper[i]^);
  1016. sep:=' ';
  1017. end;
  1018. end;
  1019. owner.AsmWriteLn(s);
  1020. end;
  1021. {****************************************************************************}
  1022. { Jasmin Instruction Writer }
  1023. {****************************************************************************}
  1024. const
  1025. as_jvm_jasmin_info : tasminfo =
  1026. (
  1027. id : as_jvm_jasmin;
  1028. idtxt : 'Jasmin';
  1029. asmbin : 'java';
  1030. asmcmd : '-jar $JASMINJAR $ASM -d $OBJDIR';
  1031. supported_targets : [system_jvm_java32];
  1032. flags : [];
  1033. labelprefix : 'L';
  1034. comment : ' ; ';
  1035. );
  1036. begin
  1037. RegisterAssembler(as_jvm_jasmin_info,TJasminAssembler);
  1038. end.