agjasmin.pas 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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 (vissym.typ=staticvarsym) and
  705. (vissym.owner.symtabletype=objectsymtable) then
  706. begin
  707. vissym:=tabstractvarsym(search_struct_member(
  708. tabstractrecorddef(vissym.owner.defowner),
  709. internal_static_field_name(vissym.name)));
  710. if not assigned(vissym) or
  711. (vissym.typ<>fieldvarsym) then
  712. internalerror(2011011501);
  713. end;
  714. case vissym.typ of
  715. staticvarsym:
  716. begin
  717. if vissym.owner.symtabletype=globalsymtable then
  718. result:='public '
  719. else
  720. { package visbility }
  721. result:='';
  722. end;
  723. fieldvarsym:
  724. result:=VisibilityToStr(tstoredsym(vissym).visibility);
  725. else
  726. internalerror(2011011204);
  727. end;
  728. if (sym.typ=staticvarsym) or
  729. (sp_static in sym.symoptions) then
  730. result:=result+'static ';
  731. result:=result+jvmmangledbasename(sym);
  732. end;
  733. function TJasminAssembler.InnerStructDef(obj: tabstractrecorddef): string;
  734. var
  735. extname: pshortstring;
  736. kindname: string;
  737. begin
  738. if not(obj.owner.defowner.typ in [objectdef,recorddef]) then
  739. internalerror(2011021701);
  740. case obj.typ of
  741. recorddef:
  742. begin
  743. kindname:='class ';
  744. extname:=obj.symtable.realname;
  745. end;
  746. objectdef:
  747. begin
  748. extname:=tobjectdef(obj).objextname;
  749. case tobjectdef(obj).objecttype of
  750. odt_javaclass:
  751. kindname:='class ';
  752. odt_interfacejava:
  753. kindname:='interface ';
  754. else
  755. internalerror(2011021702);
  756. end;
  757. end;
  758. else
  759. internalerror(2011032809);
  760. end;
  761. result:=
  762. '.inner '+
  763. kindname+
  764. VisibilityToStr(obj.typesym.visibility)+
  765. { Nested classes in the Pascal sense are equivalent to "static"
  766. inner classes in Java -- will be changed when support for
  767. Java-style non-static classes is added }
  768. ' static '+
  769. extname^+
  770. ' inner '+
  771. obj.jvm_full_typename(true)+
  772. ' outer '+
  773. tabstractrecorddef(obj.owner.defowner).jvm_full_typename(true);
  774. end;
  775. procedure TJasminAssembler.WriteProcDef(pd: tprocdef);
  776. begin
  777. if not assigned(pd.exprasmlist) and
  778. (not is_javainterface(pd.struct) or
  779. (pd.proctypeoption in [potype_unitinit,potype_unitfinalize])) then
  780. exit;
  781. AsmWrite('.method ');
  782. AsmWriteln(MethodDefinition(pd));
  783. WriteTree(pd.exprasmlist);
  784. AsmWriteln('.end method');
  785. AsmLn;
  786. end;
  787. procedure TJasminAssembler.WriteFieldSym(sym: tabstractvarsym);
  788. begin
  789. { internal static field definition alias -> skip }
  790. if sp_static in sym.symoptions then
  791. exit;
  792. AsmWrite('.field ');
  793. AsmWriteln(FieldDefinition(sym));
  794. end;
  795. procedure TJasminAssembler.WriteConstSym(sym: tconstsym);
  796. begin
  797. AsmWrite('.field ');
  798. AsmWriteln(ConstDefinition(sym));
  799. end;
  800. procedure TJasminAssembler.WriteSymtableVarSyms(st: TSymtable);
  801. var
  802. sym : tsym;
  803. i,j : longint;
  804. begin
  805. if not assigned(st) then
  806. exit;
  807. for i:=0 to st.SymList.Count-1 do
  808. begin
  809. sym:=tsym(st.SymList[i]);
  810. case sym.typ of
  811. staticvarsym,
  812. fieldvarsym:
  813. begin
  814. WriteFieldSym(tabstractvarsym(sym));
  815. if (sym.typ=staticvarsym) and
  816. assigned(tstaticvarsym(sym).defaultconstsym) then
  817. WriteFieldSym(tabstractvarsym(tstaticvarsym(sym).defaultconstsym));
  818. end;
  819. constsym:
  820. begin
  821. WriteConstSym(tconstsym(sym));
  822. end;
  823. procsym:
  824. begin
  825. for j:=0 to tprocsym(sym).procdeflist.count-1 do
  826. WriteSymtableVarSyms(tprocdef(tprocsym(sym).procdeflist[j]).localst);
  827. end;
  828. end;
  829. end;
  830. end;
  831. procedure TJasminAssembler.WriteSymtableProcdefs(st: TSymtable);
  832. var
  833. i : longint;
  834. def : tdef;
  835. begin
  836. if not assigned(st) then
  837. exit;
  838. for i:=0 to st.DefList.Count-1 do
  839. begin
  840. def:=tdef(st.DefList[i]);
  841. case def.typ of
  842. procdef :
  843. begin
  844. { methods are also in the static/globalsymtable of the unit
  845. -> make sure they are only written for the objectdefs that
  846. own them }
  847. if not(st.symtabletype in [staticsymtable,globalsymtable]) or
  848. (def.owner=st) then
  849. begin
  850. WriteProcDef(tprocdef(def));
  851. if assigned(tprocdef(def).localst) then
  852. WriteSymtableProcdefs(tprocdef(def).localst);
  853. end;
  854. end;
  855. end;
  856. end;
  857. end;
  858. procedure TJasminAssembler.WriteSymtableStructDefs(st: TSymtable);
  859. var
  860. i : longint;
  861. def : tdef;
  862. obj : tabstractrecorddef;
  863. nestedstructs: tfpobjectlist;
  864. begin
  865. if not assigned(st) then
  866. exit;
  867. nestedstructs:=tfpobjectlist.create(false);
  868. for i:=0 to st.DefList.Count-1 do
  869. begin
  870. def:=tdef(st.DefList[i]);
  871. case def.typ of
  872. objectdef:
  873. if not(oo_is_external in tobjectdef(def).objectoptions) then
  874. nestedstructs.add(def);
  875. recorddef:
  876. nestedstructs.add(def);
  877. end;
  878. end;
  879. for i:=0 to nestedstructs.count-1 do
  880. begin
  881. obj:=tabstractrecorddef(nestedstructs[i]);
  882. NewAsmFileForStructDef(obj);
  883. WriteExtraHeader(obj);
  884. WriteSymtableVarSyms(obj.symtable);
  885. AsmLn;
  886. WriteSymtableProcDefs(obj.symtable);
  887. WriteSymtableStructDefs(obj.symtable);
  888. end;
  889. nestedstructs.free;
  890. end;
  891. constructor TJasminAssembler.Create(smart: boolean);
  892. begin
  893. inherited create(smart);
  894. InstrWriter:=TJasminInstrWriter.Create(self);
  895. asmfiles:=TCmdStrList.Create;
  896. end;
  897. procedure TJasminAssembler.WriteAsmList;
  898. begin
  899. {$ifdef EXTDEBUG}
  900. if assigned(current_module.mainsource) then
  901. Comment(V_Debug,'Start writing Jasmin-styled assembler output for '+current_module.mainsource^);
  902. {$endif}
  903. AsmStartSize:=AsmSize;
  904. WriteExtraHeader(nil);
  905. (*
  906. for hal:=low(TasmlistType) to high(TasmlistType) do
  907. begin
  908. AsmWriteLn(target_asm.comment+'Begin asmlist '+AsmlistTypeStr[hal]);
  909. writetree(current_asmdata.asmlists[hal]);
  910. AsmWriteLn(target_asm.comment+'End asmlist '+AsmlistTypeStr[hal]);
  911. end;
  912. *)
  913. { print all global variables }
  914. WriteSymtableVarSyms(current_module.globalsymtable);
  915. WriteSymtableVarSyms(current_module.localsymtable);
  916. AsmLn;
  917. { print all global procedures/functions }
  918. WriteSymtableProcdefs(current_module.globalsymtable);
  919. WriteSymtableProcdefs(current_module.localsymtable);
  920. WriteSymtableStructDefs(current_module.globalsymtable);
  921. WriteSymtableStructDefs(current_module.localsymtable);
  922. AsmLn;
  923. {$ifdef EXTDEBUG}
  924. if assigned(current_module.mainsource) then
  925. Comment(V_Debug,'Done writing gas-styled assembler output for '+current_module.mainsource^);
  926. {$endif EXTDEBUG}
  927. end;
  928. {****************************************************************************}
  929. { Jasmin Instruction Writer }
  930. {****************************************************************************}
  931. constructor TJasminInstrWriter.create(_owner: TJasminAssembler);
  932. begin
  933. inherited create;
  934. owner := _owner;
  935. end;
  936. function getreferencestring(var ref : treference) : string;
  937. begin
  938. if (ref.arrayreftype<>art_none) or
  939. (ref.index<>NR_NO) then
  940. internalerror(2010122809);
  941. if assigned(ref.symbol) then
  942. begin
  943. // global symbol or field -> full type and name
  944. // ref.base can be <> NR_NO in case an instance field is loaded.
  945. // This register is not part of this instruction, it will have
  946. // been placed on the stack by the previous one.
  947. if (ref.offset<>0) then
  948. internalerror(2010122811);
  949. result:=ref.symbol.name;
  950. end
  951. else
  952. begin
  953. // local symbol -> stack slot, stored in offset
  954. if ref.base<>NR_STACK_POINTER_REG then
  955. internalerror(2010122810);
  956. result:=tostr(ref.offset);
  957. end;
  958. end;
  959. function getopstr(const o:toper) : ansistring;
  960. var
  961. d: double;
  962. s: single;
  963. begin
  964. case o.typ of
  965. top_reg:
  966. // should have been translated into a memory location by the
  967. // register allocator)
  968. if (cs_no_regalloc in current_settings.globalswitches) then
  969. getopstr:=std_regname(o.reg)
  970. else
  971. internalerror(2010122803);
  972. top_const:
  973. str(o.val,result);
  974. top_ref:
  975. getopstr:=getreferencestring(o.ref^);
  976. top_single:
  977. begin
  978. result:=constsingle(o.sval);
  979. end;
  980. top_double:
  981. begin
  982. result:=constdouble(o.dval);
  983. end;
  984. top_string:
  985. begin
  986. result:=constastr(o.pcval,o.pcvallen);
  987. end;
  988. top_wstring:
  989. begin
  990. result:=constwstr(o.pwstrval^.data,getlengthwidestring(o.pwstrval));
  991. end
  992. else
  993. internalerror(2010122802);
  994. end;
  995. end;
  996. procedure TJasminInstrWriter.WriteInstruction(hp: tai);
  997. var
  998. s: ansistring;
  999. i: byte;
  1000. sep: string[3];
  1001. begin
  1002. s:=#9+jas_op2str[taicpu(hp).opcode];
  1003. if taicpu(hp).ops<>0 then
  1004. begin
  1005. sep:=#9;
  1006. for i:=0 to taicpu(hp).ops-1 do
  1007. begin
  1008. s:=s+sep+getopstr(taicpu(hp).oper[i]^);
  1009. sep:=' ';
  1010. end;
  1011. end;
  1012. owner.AsmWriteLn(s);
  1013. end;
  1014. {****************************************************************************}
  1015. { Jasmin Instruction Writer }
  1016. {****************************************************************************}
  1017. const
  1018. as_jvm_jasmin_info : tasminfo =
  1019. (
  1020. id : as_jvm_jasmin;
  1021. idtxt : 'Jasmin';
  1022. asmbin : 'java';
  1023. asmcmd : '-jar $JASMINJAR $ASM -d $OBJDIR';
  1024. supported_targets : [system_jvm_java32];
  1025. flags : [];
  1026. labelprefix : 'L';
  1027. comment : ' ; ';
  1028. );
  1029. begin
  1030. RegisterAssembler(as_jvm_jasmin_info,TJasminAssembler);
  1031. end.