agjasmin.pas 42 KB

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