2
0

agllvm.pas 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. {
  2. Copyright (c) 1998-2013 by the Free Pascal team
  3. This unit implements the generic part of the LLVM IR 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 agllvm;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. globtype,globals,systems,
  22. aasmbase,aasmtai,aasmdata,
  23. assemble;
  24. type
  25. TLLVMInstrWriter = class;
  26. TLLVMModuleInlineAssemblyDecorator = class(TObject,IExternalAssemblerOutputFileDecorator)
  27. function LinePrefix: AnsiString;
  28. function LinePostfix: AnsiString;
  29. function LineFilter(const s: AnsiString): AnsiString;
  30. end;
  31. TLLVMAssember=class(texternalassembler)
  32. protected
  33. fdecllevel: longint;
  34. procedure WriteExtraHeader;virtual;
  35. procedure WriteExtraFooter;virtual;
  36. procedure WriteInstruction(hp: tai);
  37. procedure WriteLlvmInstruction(hp: tai);
  38. procedure WriteDirectiveName(dir: TAsmDirective); virtual;
  39. procedure WriteRealConst(hp: tai_realconst; do_line: boolean);
  40. procedure WriteOrdConst(hp: tai_const);
  41. procedure WriteTai(const replaceforbidden: boolean; const do_line: boolean; var InlineLevel: cardinal; var asmblock: boolean; var hp: tai);
  42. public
  43. constructor create(info: pasminfo; smart: boolean); override;
  44. function MakeCmdLine: TCmdStr; override;
  45. procedure WriteTree(p:TAsmList);override;
  46. procedure WriteAsmList;override;
  47. destructor destroy; override;
  48. protected
  49. InstrWriter: TLLVMInstrWriter;
  50. end;
  51. {# This is the base class for writing instructions.
  52. The WriteInstruction() method must be overridden
  53. to write a single instruction to the assembler
  54. file.
  55. }
  56. TLLVMInstrWriter = class
  57. constructor create(_owner: TLLVMAssember);
  58. procedure WriteInstruction(hp : tai);
  59. protected
  60. owner: TLLVMAssember;
  61. fstr: TSymStr;
  62. function getopstr(const o:toper; refwithalign: boolean) : TSymStr;
  63. end;
  64. implementation
  65. uses
  66. SysUtils,
  67. cutils,cfileutl,
  68. fmodule,verbose,
  69. aasmcnst,symconst,symdef,symtable,
  70. llvmbase,aasmllvm,itllvm,llvmdef,
  71. cgbase,cgutils,cpubase;
  72. const
  73. line_length = 70;
  74. type
  75. {$ifdef cpuextended}
  76. t80bitarray = array[0..9] of byte;
  77. {$endif cpuextended}
  78. t64bitarray = array[0..7] of byte;
  79. t32bitarray = array[0..3] of byte;
  80. {****************************************************************************}
  81. { Support routines }
  82. {****************************************************************************}
  83. function single2str(d : single) : string;
  84. var
  85. hs : string;
  86. begin
  87. str(d,hs);
  88. { replace space with + }
  89. if hs[1]=' ' then
  90. hs[1]:='+';
  91. single2str:=hs
  92. end;
  93. function double2str(d : double) : string;
  94. var
  95. hs : string;
  96. begin
  97. str(d,hs);
  98. { replace space with + }
  99. if hs[1]=' ' then
  100. hs[1]:='+';
  101. double2str:=hs
  102. end;
  103. function extended2str(e : extended) : string;
  104. var
  105. hs : string;
  106. begin
  107. str(e,hs);
  108. { replace space with + }
  109. if hs[1]=' ' then
  110. hs[1]:='+';
  111. extended2str:=hs
  112. end;
  113. {****************************************************************************}
  114. { Decorator for module-level inline assembly }
  115. {****************************************************************************}
  116. function TLLVMModuleInlineAssemblyDecorator.LinePrefix: AnsiString;
  117. begin
  118. result:='module asm "';
  119. end;
  120. function TLLVMModuleInlineAssemblyDecorator.LinePostfix: AnsiString;
  121. begin
  122. result:='"';
  123. end;
  124. function TLLVMModuleInlineAssemblyDecorator.LineFilter(const s: AnsiString): AnsiString;
  125. var
  126. i: longint;
  127. begin
  128. result:='';
  129. for i:=1 to length(s) do
  130. begin
  131. case s[i] of
  132. #0..#31,
  133. #127..#255,
  134. '"','\':
  135. result:=result+
  136. '\'+
  137. chr((ord(s[i]) shr 4)+ord('0'))+
  138. chr((ord(s[i]) and $f)+ord('0'));
  139. else
  140. result:=result+s[i];
  141. end;
  142. end;
  143. end;
  144. {****************************************************************************}
  145. { LLVM Instruction writer }
  146. {****************************************************************************}
  147. function getregisterstring(reg: tregister): ansistring;
  148. begin
  149. if getregtype(reg)=R_TEMPREGISTER then
  150. result:='%tmp.'
  151. else
  152. result:='%reg.'+tostr(byte(getregtype(reg)))+'_';
  153. result:=result+tostr(getsupreg(reg));
  154. end;
  155. function getreferencealignstring(var ref: treference) : ansistring;
  156. begin
  157. result:=', align '+tostr(ref.alignment);
  158. end;
  159. function getreferencestring(var ref : treference; withalign: boolean) : ansistring;
  160. begin
  161. result:='';
  162. if assigned(ref.relsymbol) or
  163. (assigned(ref.symbol) =
  164. (ref.base<>NR_NO)) or
  165. (ref.index<>NR_NO) or
  166. (ref.offset<>0) then
  167. begin
  168. result:=' **(error ref: ';
  169. if assigned(ref.symbol) then
  170. result:=result+'sym='+ref.symbol.name+', ';
  171. if assigned(ref.relsymbol) then
  172. result:=result+'sym='+ref.relsymbol.name+', ';
  173. if ref.base=NR_NO then
  174. result:=result+'base=NR_NO, ';
  175. if ref.index<>NR_NO then
  176. result:=result+'index<>NR_NO, ';
  177. if ref.offset<>0 then
  178. result:=result+'offset='+tostr(ref.offset);
  179. result:=result+')**'
  180. // internalerror(2013060225);
  181. end;
  182. if ref.base<>NR_NO then
  183. result:=result+getregisterstring(ref.base)
  184. else
  185. result:=result+LlvmAsmSymName(ref.symbol);
  186. if withalign then
  187. result:=result+getreferencealignstring(ref);
  188. end;
  189. function getparas(const o: toper): ansistring;
  190. var
  191. i: longint;
  192. para: pllvmcallpara;
  193. begin
  194. result:='(';
  195. for i:=0 to o.paras.count-1 do
  196. begin
  197. if i<>0 then
  198. result:=result+', ';
  199. para:=pllvmcallpara(o.paras[i]);
  200. result:=result+llvmencodetypename(para^.def);
  201. if para^.valueext<>lve_none then
  202. result:=result+llvmvalueextension2str[para^.valueext];
  203. case para^.loc of
  204. LOC_REGISTER,
  205. LOC_FPUREGISTER,
  206. LOC_MMREGISTER:
  207. result:=result+' '+getregisterstring(para^.reg);
  208. else
  209. internalerror(2014010801);
  210. end;
  211. end;
  212. result:=result+')';
  213. end;
  214. function llvmdoubletostr(const d: double): TSymStr;
  215. type
  216. tdoubleval = record
  217. case byte of
  218. 1: (d: double);
  219. 2: (i: int64);
  220. end;
  221. begin
  222. { "When using the hexadecimal form, constants of types half,
  223. float, and double are represented using the 16-digit form shown
  224. above (which matches the IEEE754 representation for double)"
  225. And always in big endian form (sign bit leftmost)
  226. }
  227. result:='0x'+hexstr(tdoubleval(d).i,16);
  228. end;
  229. {$if defined(cpuextended) and defined(FPC_HAS_TYPE_EXTENDED)}
  230. function llvmextendedtostr(const e: extended): TSymStr;
  231. var
  232. extendedval: record
  233. case byte of
  234. 1: (e: extended);
  235. 2: (r: packed record
  236. {$ifdef FPC_LITTLE_ENDIAN}
  237. l: int64;
  238. h: word;
  239. {$else FPC_LITTLE_ENDIAN}
  240. h: int64;
  241. l: word;
  242. {$endif FPC_LITTLE_ENDIAN}
  243. end;
  244. );
  245. end;
  246. begin
  247. extendedval.e:=e;
  248. { hex format is always big endian in llvm }
  249. result:='0xK'+hexstr(extendedval.r.h,sizeof(extendedval.r.h)*2)+
  250. hexstr(extendedval.r.l,sizeof(extendedval.r.l)*2);
  251. end;
  252. {$endif cpuextended}
  253. function TLLVMInstrWriter.getopstr(const o:toper; refwithalign: boolean) : TSymStr;
  254. var
  255. hs : ansistring;
  256. hp: tai;
  257. tmpinline: cardinal;
  258. tmpasmblock: boolean;
  259. begin
  260. case o.typ of
  261. top_reg:
  262. getopstr:=getregisterstring(o.reg);
  263. top_const:
  264. getopstr:=tostr(int64(o.val));
  265. top_ref:
  266. if o.ref^.refaddr=addr_full then
  267. begin
  268. getopstr:='';
  269. getopstr:=LlvmAsmSymName(o.ref^.symbol);
  270. if o.ref^.offset<>0 then
  271. internalerror(2013060223);
  272. end
  273. else
  274. getopstr:=getreferencestring(o.ref^,refwithalign);
  275. top_def:
  276. begin
  277. getopstr:=llvmencodetypename(o.def);
  278. end;
  279. top_cond:
  280. begin
  281. getopstr:=llvm_cond2str[o.cond];
  282. end;
  283. top_fpcond:
  284. begin
  285. getopstr:=llvm_fpcond2str[o.fpcond];
  286. end;
  287. top_single,
  288. top_double:
  289. begin
  290. { "When using the hexadecimal form, constants of types half,
  291. float, and double are represented using the 16-digit form shown
  292. above (which matches the IEEE754 representation for double)"
  293. And always in big endian form (sign bit leftmost)
  294. }
  295. if o.typ=top_double then
  296. result:=llvmdoubletostr(o.dval)
  297. else
  298. result:=llvmdoubletostr(o.sval)
  299. end;
  300. top_para:
  301. begin
  302. result:=getparas(o);
  303. end;
  304. top_tai:
  305. begin
  306. tmpinline:=1;
  307. tmpasmblock:=false;
  308. hp:=o.ai;
  309. owner.writer.AsmWrite(fstr);
  310. fstr:='';
  311. owner.WriteTai(false,false,tmpinline,tmpasmblock,hp);
  312. result:='';
  313. end;
  314. {$if defined(cpuextended) and defined(FPC_HAS_TYPE_EXTENDED)}
  315. top_extended80:
  316. begin
  317. result:=llvmextendedtostr(o.eval);
  318. end;
  319. {$endif cpuextended}
  320. top_undef:
  321. result:='undef'
  322. else
  323. internalerror(2013060227);
  324. end;
  325. end;
  326. procedure TLLVMInstrWriter.WriteInstruction(hp: tai);
  327. var
  328. op: tllvmop;
  329. sep: TSymStr;
  330. i, opstart: byte;
  331. nested: boolean;
  332. done: boolean;
  333. begin
  334. op:=taillvm(hp).llvmopcode;
  335. { we write everything immediately rather than adding it into a string,
  336. because operands may contain other tai that will also write things out
  337. (and their output must come after everything that was processed in this
  338. instruction, such as its opcode or previous operands) }
  339. if owner.fdecllevel=0 then
  340. owner.writer.AsmWrite(#9);
  341. sep:=' ';
  342. done:=false;
  343. opstart:=0;
  344. nested:=false;
  345. case op of
  346. la_type:
  347. begin
  348. owner.writer.AsmWrite(llvmtypeidentifier(taillvm(hp).oper[0]^.def));
  349. owner.writer.AsmWrite(' = type ');
  350. owner.writer.AsmWrite(llvmencodetypedecl(taillvm(hp).oper[0]^.def));
  351. done:=true;
  352. end;
  353. la_ret, la_br, la_switch, la_indirectbr,
  354. la_invoke, la_resume,
  355. la_unreachable,
  356. la_store,
  357. la_fence,
  358. la_cmpxchg,
  359. la_atomicrmw:
  360. begin
  361. { instructions that never have a result }
  362. end;
  363. la_call:
  364. begin
  365. if taillvm(hp).oper[1]^.reg<>NR_NO then
  366. owner.writer.AsmWrite(getregisterstring(taillvm(hp).oper[1]^.reg)+' = ');
  367. sep:=' ';
  368. opstart:=2;
  369. end;
  370. la_alloca:
  371. begin
  372. owner.writer.AsmWrite(getreferencestring(taillvm(hp).oper[0]^.ref^,false)+' = ');
  373. sep:=' ';
  374. opstart:=1;
  375. end;
  376. la_trunc, la_zext, la_sext, la_fptrunc, la_fpext,
  377. la_fptoui, la_fptosi, la_uitofp, la_sitofp,
  378. la_ptrtoint, la_inttoptr,
  379. la_bitcast:
  380. begin
  381. { destination can be empty in case of nested constructs, or
  382. data initialisers }
  383. if (taillvm(hp).oper[0]^.typ<>top_reg) or
  384. (taillvm(hp).oper[0]^.reg<>NR_NO) then
  385. owner.writer.AsmWrite(getopstr(taillvm(hp).oper[0]^,false)+' = ')
  386. else
  387. nested:=true;
  388. owner.writer.AsmWrite(llvm_op2str[op]);
  389. if not nested then
  390. owner.writer.AsmWrite(' ')
  391. else
  392. owner.writer.AsmWrite(' (');
  393. owner.writer.AsmWrite(getopstr(taillvm(hp).oper[1]^,false));
  394. { if there's a tai operand, its def is used instead of an
  395. explicit def operand }
  396. if taillvm(hp).ops=4 then
  397. begin
  398. owner.writer.AsmWrite(' ');
  399. owner.writer.AsmWrite(getopstr(taillvm(hp).oper[2]^,false));
  400. opstart:=3;
  401. end
  402. else
  403. opstart:=2;
  404. owner.writer.AsmWrite(' to ');
  405. owner.writer.AsmWrite(getopstr(taillvm(hp).oper[opstart]^,false));
  406. done:=true;
  407. end
  408. else
  409. begin
  410. if (taillvm(hp).oper[0]^.typ<>top_reg) or
  411. (taillvm(hp).oper[0]^.reg<>NR_NO) then
  412. begin
  413. owner.writer.AsmWrite(getopstr(taillvm(hp).oper[0]^,true)+' = ');
  414. end
  415. else
  416. nested:=true;
  417. sep:=' ';
  418. opstart:=1
  419. end;
  420. end;
  421. { process operands }
  422. if not done then
  423. begin
  424. owner.writer.AsmWrite(llvm_op2str[op]);
  425. if nested then
  426. owner.writer.AsmWrite(' (');
  427. if taillvm(hp).ops<>0 then
  428. begin
  429. for i:=opstart to taillvm(hp).ops-1 do
  430. begin
  431. owner.writer.AsmWrite(sep);
  432. owner.writer.AsmWrite(getopstr(taillvm(hp).oper[i]^,op in [la_load,la_store]));
  433. if (taillvm(hp).oper[i]^.typ in [top_def,top_cond,top_fpcond]) or
  434. (op=la_call) then
  435. sep :=' '
  436. else
  437. sep:=', ';
  438. end;
  439. end;
  440. end;
  441. if op=la_alloca then
  442. owner.writer.AsmWrite(getreferencealignstring(taillvm(hp).oper[0]^.ref^));
  443. if nested then
  444. owner.writer.AsmWrite(')')
  445. else if owner.fdecllevel=0 then
  446. owner.writer.AsmLn;
  447. end;
  448. {****************************************************************************}
  449. { LLVM Assembler writer }
  450. {****************************************************************************}
  451. destructor TLLVMAssember.Destroy;
  452. begin
  453. InstrWriter.free;
  454. inherited destroy;
  455. end;
  456. function TLLVMAssember.MakeCmdLine: TCmdStr;
  457. var
  458. optstr: TCmdStr;
  459. begin
  460. result := inherited MakeCmdLine;
  461. { standard optimization flags for llc -- todo: this needs to be split
  462. into a call to opt and one to llc }
  463. if cs_opt_level3 in current_settings.optimizerswitches then
  464. optstr:='-O3'
  465. else if cs_opt_level2 in current_settings.optimizerswitches then
  466. optstr:='-O2'
  467. else if cs_opt_level1 in current_settings.optimizerswitches then
  468. optstr:='-O1'
  469. else
  470. optstr:='-O0';
  471. { stack frame elimination }
  472. if not(cs_opt_stackframe in current_settings.optimizerswitches) then
  473. optstr:=optstr+' -disable-fp-elim';
  474. { fast math }
  475. if cs_opt_fastmath in current_settings.optimizerswitches then
  476. optstr:=optstr+' -enable-unsafe-fp-math -enable-fp-mad -fp-contract=fast';
  477. { smart linking }
  478. if cs_create_smart in current_settings.moduleswitches then
  479. optstr:=optstr+' -fdata-sections -fcode-sections';
  480. { pic }
  481. if cs_create_pic in current_settings.moduleswitches then
  482. optstr:=optstr+' -relocation-model=pic'
  483. else if not(target_info.system in systems_darwin) then
  484. optstr:=optstr+' -relocation-model=static'
  485. else
  486. optstr:=optstr+' -relocation-model=dynamic-no-pic';
  487. { our stack alignment is non-standard on some targets. The following
  488. parameter is however ignored on some targets by llvm, so it may not
  489. be enough }
  490. optstr:=optstr+' -stack-alignment='+tostr(target_info.stackalign*8);
  491. { force object output instead of textual assembler code }
  492. optstr:=optstr+' -filetype=obj';
  493. replace(result,'$OPT',optstr);
  494. end;
  495. procedure TLLVMAssember.WriteTree(p:TAsmList);
  496. var
  497. hp : tai;
  498. InlineLevel : cardinal;
  499. asmblock: boolean;
  500. do_line : boolean;
  501. replaceforbidden: boolean;
  502. begin
  503. if not assigned(p) then
  504. exit;
  505. replaceforbidden:=asminfo^.dollarsign<>'$';
  506. InlineLevel:=0;
  507. asmblock:=false;
  508. { lineinfo is only needed for al_procedures (PFV) }
  509. do_line:=(cs_asm_source in current_settings.globalswitches) or
  510. ((cs_lineinfo in current_settings.moduleswitches)
  511. and (p=current_asmdata.asmlists[al_procedures]));
  512. hp:=tai(p.first);
  513. while assigned(hp) do
  514. begin
  515. prefetch(pointer(hp.next)^);
  516. if not(hp.typ in SkipLineInfo) then
  517. begin
  518. current_filepos:=tailineinfo(hp).fileinfo;
  519. { no line info for inlined code }
  520. if do_line and (inlinelevel=0) then
  521. WriteSourceLine(hp as tailineinfo);
  522. end;
  523. WriteTai(replaceforbidden, do_line, InlineLevel, asmblock, hp);
  524. hp:=tai(hp.next);
  525. end;
  526. end;
  527. procedure TLLVMAssember.WriteExtraHeader;
  528. begin
  529. writer.AsmWrite('target datalayout = "');
  530. writer.AsmWrite(target_info.llvmdatalayout);
  531. writer.AsmWriteln('"');
  532. writer.AsmWrite('target triple = "');
  533. writer.AsmWrite(llvm_target_name);
  534. writer.AsmWriteln('"');
  535. end;
  536. procedure TLLVMAssember.WriteExtraFooter;
  537. begin
  538. end;
  539. procedure TLLVMAssember.WriteInstruction(hp: tai);
  540. begin
  541. end;
  542. procedure TLLVMAssember.WriteLlvmInstruction(hp: tai);
  543. begin
  544. InstrWriter.WriteInstruction(hp);
  545. end;
  546. procedure TLLVMAssember.WriteRealConst(hp: tai_realconst; do_line: boolean);
  547. begin
  548. if do_line and
  549. (fdecllevel=0) then
  550. begin
  551. case tai_realconst(hp).realtyp of
  552. aitrealconst_s32bit:
  553. writer.AsmWriteLn(asminfo^.comment+'value: '+single2str(tai_realconst(hp).value.s32val));
  554. aitrealconst_s64bit:
  555. writer.AsmWriteLn(asminfo^.comment+'value: '+double2str(tai_realconst(hp).value.s64val));
  556. {$if defined(cpuextended) and defined(FPC_HAS_TYPE_EXTENDED)}
  557. { can't write full 80 bit floating point constants yet on non-x86 }
  558. aitrealconst_s80bit:
  559. writer.AsmWriteLn(asminfo^.comment+'value: '+extended2str(tai_realconst(hp).value.s80val));
  560. {$endif cpuextended}
  561. aitrealconst_s64comp:
  562. writer.AsmWriteLn(asminfo^.comment+'value: '+extended2str(tai_realconst(hp).value.s64compval));
  563. else
  564. internalerror(2014050604);
  565. end;
  566. end;
  567. case hp.realtyp of
  568. aitrealconst_s32bit:
  569. writer.AsmWriteln(llvmdoubletostr(hp.value.s32val));
  570. aitrealconst_s64bit:
  571. writer.AsmWriteln(llvmdoubletostr(hp.value.s64val));
  572. {$if defined(cpuextended) and defined(FPC_HAS_TYPE_EXTENDED)}
  573. aitrealconst_s80bit:
  574. writer.AsmWriteln(llvmextendedtostr(hp.value.s80val));
  575. {$endif defined(cpuextended)}
  576. aitrealconst_s64comp:
  577. { handled as int64 most of the time in llvm }
  578. writer.AsmWriteln(tostr(round(hp.value.s64compval)));
  579. else
  580. internalerror(2014062401);
  581. end;
  582. end;
  583. procedure TLLVMAssember.WriteOrdConst(hp: tai_const);
  584. var
  585. consttyp: taiconst_type;
  586. begin
  587. if fdecllevel=0 then
  588. writer.AsmWrite(asminfo^.comment+' const ');
  589. consttyp:=hp.consttype;
  590. case consttyp of
  591. aitconst_got,
  592. aitconst_gotoff_symbol,
  593. aitconst_uleb128bit,
  594. aitconst_sleb128bit,
  595. aitconst_rva_symbol,
  596. aitconst_secrel32_symbol,
  597. aitconst_darwin_dwarf_delta32,
  598. aitconst_darwin_dwarf_delta64,
  599. aitconst_half16bit,
  600. aitconst_gs:
  601. internalerror(2014052901);
  602. aitconst_128bit,
  603. aitconst_64bit,
  604. aitconst_32bit,
  605. aitconst_16bit,
  606. aitconst_8bit,
  607. aitconst_16bit_unaligned,
  608. aitconst_32bit_unaligned,
  609. aitconst_64bit_unaligned:
  610. begin
  611. if fdecllevel=0 then
  612. writer.AsmWrite(asminfo^.comment);
  613. { can't have compile-time differences between symbols; these are
  614. normally for PIC, but llvm takes care of that for us }
  615. if assigned(hp.endsym) then
  616. internalerror(2014052902);
  617. if assigned(hp.sym) then
  618. begin
  619. writer.AsmWrite(LlvmAsmSymName(hp.sym));
  620. { can't have offsets }
  621. if hp.value<>0 then
  622. if fdecllevel<>0 then
  623. internalerror(2014052903)
  624. else
  625. writer.AsmWrite(' -- symbol offset: ' + tostr(hp.value));
  626. end
  627. else if hp.value=0 then
  628. writer.AsmWrite('zeroinitializer')
  629. else
  630. writer.AsmWrite(tostr(hp.value));
  631. if fdecllevel=0 then
  632. writer.AsmLn;
  633. end;
  634. else
  635. internalerror(200704251);
  636. end;
  637. end;
  638. procedure TLLVMAssember.WriteTai(const replaceforbidden: boolean; const do_line: boolean; var InlineLevel: cardinal; var asmblock: boolean; var hp: tai);
  639. procedure WriteFunctionFlags(pd: tprocdef);
  640. begin
  641. if (pos('FPC_SETJMP',upper(pd.mangledname))<>0) or
  642. (pd.mangledname=(target_info.cprefix+'setjmp')) then
  643. writer.AsmWrite(' returns_twice');
  644. if po_inline in pd.procoptions then
  645. writer.AsmWrite(' inlinehint');
  646. { ensure that functions that happen to have the same name as a
  647. standard C library function, but which are implemented in Pascal,
  648. are not considered to have the same semantics as the C function with
  649. the same name }
  650. if not(po_external in pd.procoptions) then
  651. writer.AsmWrite(' nobuiltin');
  652. if po_noreturn in pd.procoptions then
  653. writer.AsmWrite(' noreturn');
  654. end;
  655. procedure WriteTypedConstData(hp: tai_abstracttypedconst);
  656. var
  657. p: tai_abstracttypedconst;
  658. pval: tai;
  659. defstr: TSymStr;
  660. first, gotstring: boolean;
  661. begin
  662. defstr:=llvmencodetypename(hp.def);
  663. { write the struct, array or simple type }
  664. case hp.adetyp of
  665. tck_record:
  666. begin
  667. writer.AsmWrite(defstr);
  668. writer.AsmWrite(' ');
  669. if tabstractrecordsymtable(tabstractrecorddef(hp.def).symtable).usefieldalignment<>C_alignment then
  670. writer.AsmWrite('<{')
  671. else
  672. writer.AsmWrite('{');
  673. first:=true;
  674. for p in tai_aggregatetypedconst(hp) do
  675. begin
  676. if not first then
  677. writer.AsmWrite(', ')
  678. else
  679. first:=false;
  680. WriteTypedConstData(p);
  681. end;
  682. if tabstractrecordsymtable(tabstractrecorddef(hp.def).symtable).usefieldalignment<>C_alignment then
  683. writer.AsmWrite('}>')
  684. else
  685. writer.AsmWrite('}');
  686. end;
  687. tck_array:
  688. begin
  689. writer.AsmWrite(defstr);
  690. first:=true;
  691. gotstring:=false;
  692. for p in tai_aggregatetypedconst(hp) do
  693. begin
  694. if not first then
  695. writer.AsmWrite(',')
  696. else
  697. begin
  698. writer.AsmWrite(' ');
  699. if (tai_abstracttypedconst(p).adetyp=tck_simple) and
  700. (tai_simpletypedconst(p).val.typ=ait_string) then
  701. begin
  702. gotstring:=true;
  703. end
  704. else
  705. begin
  706. writer.AsmWrite('[');
  707. end;
  708. first:=false;
  709. end;
  710. { cannot concat strings and other things }
  711. if gotstring and
  712. ((tai_abstracttypedconst(p).adetyp<>tck_simple) or
  713. (tai_simpletypedconst(p).val.typ<>ait_string)) then
  714. internalerror(2014062701);
  715. WriteTypedConstData(p);
  716. end;
  717. if not gotstring then
  718. writer.AsmWrite(']');
  719. end;
  720. tck_simple:
  721. begin
  722. pval:=tai_simpletypedconst(hp).val;
  723. if pval.typ<>ait_string then
  724. begin
  725. writer.AsmWrite(defstr);
  726. writer.AsmWrite(' ');
  727. end;
  728. WriteTai(replaceforbidden,do_line,InlineLevel,asmblock,pval);
  729. end;
  730. end;
  731. end;
  732. var
  733. hp2: tai;
  734. s: string;
  735. i: longint;
  736. ch: ansichar;
  737. begin
  738. case hp.typ of
  739. ait_comment :
  740. begin
  741. writer.AsmWrite(asminfo^.comment);
  742. writer.AsmWritePChar(tai_comment(hp).str);
  743. if fdecllevel<>0 then
  744. internalerror(2015090601);
  745. writer.AsmLn;
  746. end;
  747. ait_regalloc :
  748. begin
  749. if (cs_asm_regalloc in current_settings.globalswitches) then
  750. begin
  751. writer.AsmWrite(#9+asminfo^.comment+'Register ');
  752. repeat
  753. writer.AsmWrite(std_regname(Tai_regalloc(hp).reg));
  754. if (hp.next=nil) or
  755. (tai(hp.next).typ<>ait_regalloc) or
  756. (tai_regalloc(hp.next).ratype<>tai_regalloc(hp).ratype) then
  757. break;
  758. hp:=tai(hp.next);
  759. writer.AsmWrite(',');
  760. until false;
  761. writer.AsmWrite(' ');
  762. writer.AsmWriteLn(regallocstr[tai_regalloc(hp).ratype]);
  763. end;
  764. end;
  765. ait_tempalloc :
  766. begin
  767. if (cs_asm_tempalloc in current_settings.globalswitches) then
  768. WriteTempalloc(tai_tempalloc(hp));
  769. end;
  770. ait_align,
  771. ait_section :
  772. begin
  773. { ignore, specified as part of declarations -- don't write
  774. comment, because could appear in the middle of an aggregate
  775. constant definition }
  776. end;
  777. ait_datablock :
  778. begin
  779. writer.AsmWrite(asminfo^.comment);
  780. writer.AsmWriteln('datablock');
  781. end;
  782. ait_const:
  783. begin
  784. WriteOrdConst(tai_const(hp));
  785. end;
  786. ait_realconst :
  787. begin
  788. WriteRealConst(tai_realconst(hp), do_line);
  789. end;
  790. ait_string :
  791. begin
  792. if fdecllevel=0 then
  793. writer.AsmWrite(asminfo^.comment);
  794. writer.AsmWrite('c"');
  795. for i:=1 to tai_string(hp).len do
  796. begin
  797. ch:=tai_string(hp).str[i-1];
  798. case ch of
  799. #0, {This can't be done by range, because a bug in FPC}
  800. #1..#31,
  801. #128..#255,
  802. '"',
  803. '\' : s:='\'+hexStr(ord(ch),2);
  804. else
  805. s:=ch;
  806. end;
  807. writer.AsmWrite(s);
  808. end;
  809. writer.AsmWriteLn('"');
  810. end;
  811. ait_label :
  812. begin
  813. if not asmblock and
  814. (tai_label(hp).labsym.is_used) then
  815. begin
  816. if (tai_label(hp).labsym.bind=AB_PRIVATE_EXTERN) then
  817. begin
  818. { should be emitted as part of the variable/function def }
  819. internalerror(2013010703);
  820. end;
  821. if tai_label(hp).labsym.bind in [AB_GLOBAL, AB_PRIVATE_EXTERN] then
  822. begin
  823. { should be emitted as part of the variable/function def }
  824. //internalerror(2013010704);
  825. writer.AsmWriteln(asminfo^.comment+'global/privateextern label: '+tai_label(hp).labsym.name);
  826. end;
  827. if replaceforbidden then
  828. writer.AsmWrite(ReplaceForbiddenAsmSymbolChars(tai_label(hp).labsym.name))
  829. else
  830. writer.AsmWrite(tai_label(hp).labsym.name);
  831. writer.AsmWriteLn(':');
  832. end;
  833. end;
  834. ait_symbol :
  835. begin
  836. if fdecllevel=0 then
  837. writer.AsmWrite(asminfo^.comment);
  838. writer.AsmWriteln(LlvmAsmSymName(tai_symbol(hp).sym));
  839. { todo }
  840. if tai_symbol(hp).has_value then
  841. internalerror(2014062402);
  842. end;
  843. ait_llvmdecl:
  844. begin
  845. if taillvmdecl(hp).def.typ=procdef then
  846. begin
  847. if not(ldf_definition in taillvmdecl(hp).flags) then
  848. begin
  849. writer.AsmWrite('declare');
  850. writer.AsmWrite(llvmencodeproctype(tprocdef(taillvmdecl(hp).def), taillvmdecl(hp).namesym.name, lpd_decl));
  851. WriteFunctionFlags(tprocdef(taillvmdecl(hp).def));
  852. writer.AsmLn;
  853. end
  854. else
  855. begin
  856. writer.AsmWrite('define');
  857. writer.AsmWrite(llvmencodeproctype(tprocdef(taillvmdecl(hp).def), '', lpd_decl));
  858. WriteFunctionFlags(tprocdef(taillvmdecl(hp).def));
  859. writer.AsmWriteln(' {');
  860. end;
  861. end
  862. else
  863. begin
  864. writer.AsmWrite(LlvmAsmSymName(taillvmdecl(hp).namesym));
  865. case taillvmdecl(hp).namesym.bind of
  866. AB_EXTERNAL:
  867. writer.AsmWrite(' = external ');
  868. AB_COMMON:
  869. writer.AsmWrite(' = common ');
  870. AB_LOCAL:
  871. writer.AsmWrite(' = internal ');
  872. AB_GLOBAL:
  873. writer.AsmWrite(' = ');
  874. AB_WEAK_EXTERNAL:
  875. writer.AsmWrite(' = extern_weak ');
  876. AB_PRIVATE_EXTERN:
  877. writer.AsmWrite('= linker_private ');
  878. else
  879. internalerror(2014020104);
  880. end;
  881. if (ldf_tls in taillvmdecl(hp).flags) then
  882. writer.AsmWrite('thread_local ');
  883. if ldf_unnamed_addr in taillvmdecl(hp).flags then
  884. writer.AsmWrite('unnamed_addr ');
  885. { todo: handle more different section types (mainly
  886. Objective-C }
  887. if taillvmdecl(hp).sec in [sec_rodata,sec_rodata_norel] then
  888. writer.AsmWrite('constant ')
  889. else
  890. writer.AsmWrite('global ');
  891. if not assigned(taillvmdecl(hp).initdata) then
  892. begin
  893. writer.AsmWrite(llvmencodetypename(taillvmdecl(hp).def));
  894. if not(taillvmdecl(hp).namesym.bind in [AB_EXTERNAL, AB_WEAK_EXTERNAL]) then
  895. writer.AsmWrite(' zeroinitializer');
  896. end
  897. else
  898. begin
  899. inc(fdecllevel);
  900. { can't have an external symbol with initialisation data }
  901. if taillvmdecl(hp).namesym.bind in [AB_EXTERNAL, AB_WEAK_EXTERNAL] then
  902. internalerror(2014052905);
  903. { bitcast initialisation data to the type of the constant }
  904. { write initialisation data }
  905. hp2:=tai(taillvmdecl(hp).initdata.first);
  906. while assigned(hp2) do
  907. begin
  908. WriteTai(replaceforbidden,do_line,InlineLevel,asmblock,hp2);
  909. hp2:=tai(hp2.next);
  910. end;
  911. dec(fdecllevel);
  912. end;
  913. { alignment }
  914. writer.AsmWrite(', align ');
  915. writer.AsmWriteln(tostr(taillvmdecl(hp).alignment));
  916. end;
  917. end;
  918. ait_llvmalias:
  919. begin
  920. writer.AsmWrite(LlvmAsmSymName(taillvmalias(hp).newsym));
  921. writer.AsmWrite(' = alias ');
  922. if taillvmalias(hp).linkage<>lll_default then
  923. begin
  924. str(taillvmalias(hp).linkage, s);
  925. writer.AsmWrite(copy(s, length('lll_')+1, 255));
  926. writer.AsmWrite(' ');
  927. end;
  928. if taillvmalias(hp).vis<>llv_default then
  929. begin
  930. str(taillvmalias(hp).vis, s);
  931. writer.AsmWrite(copy(s, length('llv_')+1, 255));
  932. writer.AsmWrite(' ');
  933. end;
  934. if taillvmalias(hp).def.typ=procdef then
  935. writer.AsmWrite(llvmencodeproctype(tabstractprocdef(taillvmalias(hp).def), '', lpd_alias))
  936. else
  937. writer.AsmWrite(llvmencodetypename(taillvmalias(hp).def));
  938. writer.AsmWrite('* ');
  939. writer.AsmWriteln(LlvmAsmSymName(taillvmalias(hp).oldsym));
  940. end;
  941. ait_symbolpair:
  942. begin
  943. { should be emitted as part of the symbol def }
  944. internalerror(2013010708);
  945. end;
  946. ait_weak:
  947. begin
  948. { should be emitted as part of the symbol def }
  949. internalerror(2013010709);
  950. end;
  951. ait_symbol_end :
  952. begin
  953. if tai_symbol_end(hp).sym.typ=AT_FUNCTION then
  954. writer.AsmWriteln('}')
  955. else
  956. writer.AsmWriteln('; ait_symbol_end error, should not be generated');
  957. // internalerror(2013010711);
  958. end;
  959. ait_instruction :
  960. begin
  961. WriteInstruction(hp);
  962. end;
  963. ait_llvmins:
  964. begin
  965. WriteLlvmInstruction(hp);
  966. end;
  967. ait_stab :
  968. begin
  969. internalerror(2013010712);
  970. end;
  971. ait_force_line,
  972. ait_function_name :
  973. ;
  974. ait_cutobject :
  975. begin
  976. end;
  977. ait_marker :
  978. case
  979. tai_marker(hp).kind of
  980. mark_NoLineInfoStart:
  981. inc(InlineLevel);
  982. mark_NoLineInfoEnd:
  983. dec(InlineLevel);
  984. { these cannot be nested }
  985. mark_AsmBlockStart:
  986. asmblock:=true;
  987. mark_AsmBlockEnd:
  988. asmblock:=false;
  989. end;
  990. ait_directive :
  991. begin
  992. WriteDirectiveName(tai_directive(hp).directive);
  993. if tai_directive(hp).name <>'' then
  994. writer.AsmWrite(tai_directive(hp).name);
  995. if fdecllevel<>0 then
  996. internalerror(2015090602);
  997. writer.AsmLn;
  998. end;
  999. ait_seh_directive :
  1000. begin
  1001. internalerror(2013010713);
  1002. end;
  1003. ait_varloc:
  1004. begin
  1005. if tai_varloc(hp).newlocationhi<>NR_NO then
  1006. writer.AsmWrite(strpnew('Var '+tai_varloc(hp).varsym.realname+' located in register '+
  1007. std_regname(tai_varloc(hp).newlocationhi)+':'+std_regname(tai_varloc(hp).newlocation)))
  1008. else
  1009. writer.AsmWrite(strpnew('Var '+tai_varloc(hp).varsym.realname+' located in register '+
  1010. std_regname(tai_varloc(hp).newlocation)));
  1011. if fdecllevel<>0 then
  1012. internalerror(2015090603);
  1013. writer.AsmLn;
  1014. end;
  1015. ait_typedconst:
  1016. begin
  1017. WriteTypedConstData(tai_abstracttypedconst(hp));
  1018. end
  1019. else
  1020. internalerror(2006012201);
  1021. end;
  1022. end;
  1023. constructor TLLVMAssember.create(info: pasminfo; smart: boolean);
  1024. begin
  1025. inherited;
  1026. InstrWriter:=TLLVMInstrWriter.create(self);
  1027. end;
  1028. procedure TLLVMAssember.WriteDirectiveName(dir: TAsmDirective);
  1029. begin
  1030. writer.AsmWrite('.'+directivestr[dir]+' ');
  1031. end;
  1032. procedure TLLVMAssember.WriteAsmList;
  1033. var
  1034. hal : tasmlisttype;
  1035. i: longint;
  1036. a: TExternalAssembler;
  1037. decorator: TLLVMModuleInlineAssemblyDecorator;
  1038. begin
  1039. WriteExtraHeader;
  1040. for hal:=low(TasmlistType) to high(TasmlistType) do
  1041. begin
  1042. if not assigned(current_asmdata.asmlists[hal]) or
  1043. current_asmdata.asmlists[hal].Empty then
  1044. continue;
  1045. writer.AsmWriteLn(asminfo^.comment+'Begin asmlist '+AsmlistTypeStr[hal]);
  1046. if hal<>al_pure_assembler then
  1047. writetree(current_asmdata.asmlists[hal])
  1048. else
  1049. begin
  1050. { write routines using the target-specific external assembler
  1051. writer, filtered using the LLVM module-level assembly
  1052. decorator }
  1053. decorator:=TLLVMModuleInlineAssemblyDecorator.Create;
  1054. writer.decorator:=decorator;
  1055. a:=GetExternalGnuAssemblerWithAsmInfoWriter(asminfo,writer);
  1056. a.WriteTree(current_asmdata.asmlists[hal]);
  1057. writer.decorator:=nil;
  1058. decorator.free;
  1059. end;
  1060. writer.AsmWriteLn(asminfo^.comment+'End asmlist '+AsmlistTypeStr[hal]);
  1061. end;
  1062. writer.AsmLn;
  1063. end;
  1064. {****************************************************************************}
  1065. { Abstract Instruction Writer }
  1066. {****************************************************************************}
  1067. constructor TLLVMInstrWriter.create(_owner: TLLVMAssember);
  1068. begin
  1069. inherited create;
  1070. owner := _owner;
  1071. end;
  1072. const
  1073. as_llvm_info : tasminfo =
  1074. (
  1075. id : as_llvm;
  1076. idtxt : 'LLVM-AS';
  1077. asmbin : 'llc';
  1078. asmcmd: '$OPT -o $OBJ $ASM';
  1079. supported_targets : [system_x86_64_linux,system_x86_64_darwin,system_powerpc64_darwin];
  1080. flags : [af_smartlink_sections];
  1081. labelprefix : 'L';
  1082. comment : '; ';
  1083. dollarsign: '$';
  1084. );
  1085. begin
  1086. RegisterAssembler(as_llvm_info,TLLVMAssember);
  1087. end.