assembler.scm 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850
  1. ;;; Guile bytecode assembler
  2. ;;; Copyright (C) 2001, 2009, 2010, 2012, 2013, 2014, 2015, 2017, 2018 Free Software Foundation, Inc.
  3. ;;;
  4. ;;; This library is free software; you can redistribute it and/or
  5. ;;; modify it under the terms of the GNU Lesser General Public
  6. ;;; License as published by the Free Software Foundation; either
  7. ;;; version 3 of the License, or (at your option) any later version.
  8. ;;;
  9. ;;; This library is distributed in the hope that it will be useful,
  10. ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. ;;; Lesser General Public License for more details.
  13. ;;;
  14. ;;; You should have received a copy of the GNU Lesser General Public
  15. ;;; License along with this library; if not, write to the Free Software
  16. ;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. ;;; Commentary:
  18. ;;;
  19. ;;; This module implements an assembler that creates an ELF image from
  20. ;;; bytecode assembly and macro-assembly. The input can be given in
  21. ;;; s-expression form, like ((OP ARG ...) ...). Internally there is a
  22. ;;; procedural interface, the emit-OP procedures, but that is not
  23. ;;; currently exported.
  24. ;;;
  25. ;;; "Primitive instructions" correspond to VM operations. Assemblers
  26. ;;; for primitive instructions are generated programmatically from
  27. ;;; (instruction-list), which itself is derived from the VM sources.
  28. ;;; There are also "macro-instructions" like "label" or "load-constant"
  29. ;;; that expand to 0 or more primitive instructions.
  30. ;;;
  31. ;;; The assembler also handles some higher-level tasks, like creating
  32. ;;; the symbol table, other metadata sections, creating a constant table
  33. ;;; for the whole compilation unit, and writing the dynamic section of
  34. ;;; the ELF file along with the appropriate initialization routines.
  35. ;;;
  36. ;;; Most compilers will want to use the trio of make-assembler,
  37. ;;; emit-text, and link-assembly. That will result in the creation of
  38. ;;; an ELF image as a bytevector, which can then be loaded using
  39. ;;; load-thunk-from-memory, or written to disk as a .go file.
  40. ;;;
  41. ;;; Code:
  42. (define-module (system vm assembler)
  43. #:use-module (system base target)
  44. #:use-module (system base types internal)
  45. #:use-module (system vm dwarf)
  46. #:use-module (system vm elf)
  47. #:use-module (system vm linker)
  48. #:use-module (system syntax internal)
  49. #:use-module (language bytecode)
  50. #:use-module (rnrs bytevectors)
  51. #:use-module (ice-9 binary-ports)
  52. #:use-module (ice-9 vlist)
  53. #:use-module (ice-9 match)
  54. #:use-module (srfi srfi-1)
  55. #:use-module (srfi srfi-4)
  56. #:use-module (srfi srfi-9)
  57. #:use-module (srfi srfi-11)
  58. #:export (make-assembler
  59. (emit-receive* . emit-receive)
  60. (emit-mov* . emit-mov)
  61. (emit-fmov* . emit-fmov)
  62. emit-u64=?
  63. emit-u64<?
  64. emit-u64-imm<?
  65. emit-imm-u64<?
  66. emit-s64-imm=?
  67. emit-s64<?
  68. emit-s64-imm<?
  69. emit-imm-s64<?
  70. emit-f64=?
  71. emit-f64<?
  72. emit-=?
  73. emit-<?
  74. emit-arguments<=?
  75. emit-positional-arguments<=?
  76. emit-immediate-tag=?
  77. emit-heap-tag=?
  78. emit-eq?
  79. emit-heap-numbers-equal?
  80. emit-j
  81. emit-jl
  82. emit-je
  83. emit-jnl
  84. emit-jne
  85. emit-jge
  86. emit-jnge
  87. emit-fixnum?
  88. emit-heap-object?
  89. emit-char?
  90. emit-eq-null?
  91. emit-eq-nil?
  92. emit-eq-false?
  93. emit-eq-true?
  94. emit-unspecified?
  95. emit-undefined?
  96. emit-eof-object?
  97. emit-untag-fixnum
  98. emit-tag-fixnum
  99. emit-untag-char
  100. emit-tag-char
  101. emit-throw
  102. (emit-throw/value* . emit-throw/value)
  103. (emit-throw/value+data* . emit-throw/value+data)
  104. emit-pair?
  105. emit-struct?
  106. emit-symbol?
  107. emit-variable?
  108. emit-vector?
  109. emit-mutable-vector?
  110. emit-immutable-vector?
  111. emit-weak-vector?
  112. emit-string?
  113. emit-heap-number?
  114. emit-hash-table?
  115. emit-pointer?
  116. emit-fluid?
  117. emit-stringbuf?
  118. emit-dynamic-state?
  119. emit-frame?
  120. emit-keyword?
  121. emit-syntax?
  122. emit-program?
  123. emit-vm-continuation?
  124. emit-bytevector?
  125. emit-weak-set?
  126. emit-weak-table?
  127. emit-array?
  128. emit-bitvector?
  129. emit-port?
  130. emit-smob?
  131. emit-bignum?
  132. emit-flonum?
  133. emit-compnum?
  134. emit-fracnum?
  135. emit-allocate-words
  136. emit-allocate-words/immediate
  137. emit-scm-ref
  138. emit-scm-set!
  139. emit-scm-ref/tag
  140. emit-scm-set!/tag
  141. emit-scm-ref/immediate
  142. emit-scm-set!/immediate
  143. emit-word-ref
  144. emit-word-set!
  145. emit-word-ref/immediate
  146. emit-word-set!/immediate
  147. emit-pointer-ref/immediate
  148. emit-pointer-set!/immediate
  149. emit-tail-pointer-ref/immediate
  150. emit-u8-ref
  151. emit-s8-ref
  152. emit-u16-ref
  153. emit-s16-ref
  154. emit-u32-ref
  155. emit-s32-ref
  156. emit-u64-ref
  157. emit-s64-ref
  158. emit-f32-ref
  159. emit-f64-ref
  160. emit-u8-set!
  161. emit-s8-set!
  162. emit-u16-set!
  163. emit-s16-set!
  164. emit-u32-set!
  165. emit-s32-set!
  166. emit-u64-set!
  167. emit-s64-set!
  168. emit-f32-set!
  169. emit-f64-set!
  170. emit-atomic-scm-ref/immediate
  171. emit-atomic-scm-set!/immediate
  172. emit-atomic-scm-swap!/immediate
  173. emit-atomic-scm-compare-and-swap!/immediate
  174. ;; Intrinsics.
  175. emit-add
  176. emit-add/immediate
  177. emit-sub
  178. emit-sub/immediate
  179. emit-mul
  180. emit-div
  181. emit-quo
  182. emit-rem
  183. emit-mod
  184. emit-logand
  185. emit-logior
  186. emit-logxor
  187. emit-logsub
  188. emit-string-set!
  189. emit-string->number
  190. emit-string->symbol
  191. emit-symbol->keyword
  192. emit-class-of
  193. emit-scm->f64
  194. emit-scm->u64
  195. emit-scm->u64/truncate
  196. emit-scm->s64
  197. emit-u64->scm
  198. emit-s64->scm
  199. emit-wind
  200. emit-unwind
  201. emit-push-fluid
  202. emit-pop-fluid
  203. emit-fluid-ref
  204. emit-fluid-set!
  205. emit-push-dynamic-state
  206. emit-pop-dynamic-state
  207. emit-lsh
  208. emit-rsh
  209. emit-lsh/immediate
  210. emit-rsh/immediate
  211. emit-resolve-module
  212. emit-lookup
  213. emit-define!
  214. emit-current-module
  215. emit-cache-ref
  216. emit-cache-set!
  217. emit-call
  218. emit-call-label
  219. emit-tail-call
  220. emit-tail-call-label
  221. (emit-instrument-entry* . emit-instrument-entry)
  222. (emit-instrument-loop* . emit-instrument-loop)
  223. emit-receive-values
  224. emit-return-values
  225. emit-call/cc
  226. emit-abort
  227. emit-builtin-ref
  228. emit-assert-nargs-ee
  229. emit-assert-nargs-ge
  230. emit-assert-nargs-le
  231. emit-alloc-frame
  232. emit-reset-frame
  233. emit-assert-nargs-ee/locals
  234. emit-bind-kwargs
  235. emit-bind-rest
  236. emit-load-label
  237. emit-resolve
  238. emit-prompt
  239. emit-current-thread
  240. emit-fadd
  241. emit-fsub
  242. emit-fmul
  243. emit-fdiv
  244. emit-uadd
  245. emit-usub
  246. emit-umul
  247. emit-uadd/immediate
  248. emit-usub/immediate
  249. emit-umul/immediate
  250. emit-ulogand
  251. emit-ulogior
  252. emit-ulogxor
  253. emit-ulogsub
  254. emit-ursh
  255. emit-srsh
  256. emit-ulsh
  257. emit-ursh/immediate
  258. emit-srsh/immediate
  259. emit-ulsh/immediate
  260. emit-make-array
  261. emit-load-f64
  262. emit-load-u64
  263. emit-load-s64
  264. emit-handle-interrupts
  265. emit-text
  266. link-assembly))
  267. ;; Like define-inlinable, but only for first-order uses of the defined
  268. ;; routine. Should residualize less code.
  269. (eval-when (expand)
  270. (define-syntax define-inline
  271. (lambda (x)
  272. (syntax-case x ()
  273. ((_ (name arg ...) body ...)
  274. (with-syntax (((temp ...) (generate-temporaries #'(arg ...))))
  275. #`(eval-when (expand)
  276. (define-syntax-rule (name temp ...)
  277. (let ((arg temp) ...)
  278. body ...)))))))))
  279. ;;; Bytecode consists of 32-bit units, often subdivided in some way.
  280. ;;; These helpers create one 32-bit unit from multiple components.
  281. (define-inline (check-urange x mask)
  282. (unless (and (exact-integer? x) (= x (logand x mask)))
  283. (error "out of range" x))
  284. x)
  285. (define-inline (check-srange x mask)
  286. (let ((x* (logand x mask)))
  287. (unless (if (negative? x)
  288. (= (+ x mask 1) x*)
  289. (= x x*))
  290. (error "out of range" x))
  291. x*))
  292. (define-inline (pack-u8-u24 x y)
  293. (let ((x (check-urange x #xff))
  294. (y (check-urange y #xffffff)))
  295. (logior x (ash y 8))))
  296. (define-inline (pack-u8-s24 x y)
  297. (let ((x (check-urange x #xff))
  298. (y (check-srange y #xffffff)))
  299. (logior x (ash y 8))))
  300. (define-inline (pack-u16-u16 x y)
  301. (let ((x (check-urange x #xffff))
  302. (y (check-urange y #xffff)))
  303. (logior x (ash y 16))))
  304. (define-inline (pack-u1-u7-u24 x y z)
  305. (let ((x (check-urange x #x1))
  306. (y (check-urange y #x7f))
  307. (z (check-urange z #xffffff)))
  308. (logior x (ash y 1) (ash z 8))))
  309. (define-inline (pack-u8-u12-u12 x y z)
  310. (let ((x (check-urange x #xff))
  311. (y (check-urange y #xfff))
  312. (z (check-urange z #xfff)))
  313. (logior x (ash y 8) (ash z 20))))
  314. (define-inline (pack-u8-u12-s12 x y z)
  315. (let ((x (check-urange x #xff))
  316. (y (check-urange y #xfff))
  317. (z (check-srange z #xfff)))
  318. (logior x (ash y 8) (ash z 20))))
  319. (define-inline (pack-u8-u8-u16 x y z)
  320. (let ((x (check-urange x #xff))
  321. (y (check-urange y #xff))
  322. (z (check-urange z #xffff)))
  323. (logior x (ash y 8) (ash z 16))))
  324. (define-inline (pack-u8-u8-u8-u8 x y z w)
  325. (let ((x (check-urange x #xff))
  326. (y (check-urange y #xff))
  327. (z (check-urange z #xff))
  328. (w (check-urange w #xff)))
  329. (logior x (ash y 8) (ash z 16) (ash w 24))))
  330. (eval-when (expand)
  331. (define-syntax pack-flags
  332. (syntax-rules ()
  333. ;; Add clauses as needed.
  334. ((pack-flags f1 f2) (logior (if f1 (ash 1 0) 0)
  335. (if f2 (ash 1 1) 0))))))
  336. (define-syntax-rule (define-byte-order-swapper name size ref set)
  337. (define* (name buf #:optional (start 0) (end (bytevector-length buf)))
  338. "Patch up the text buffer @var{buf}, swapping the endianness of each
  339. N-byte unit."
  340. (unless (zero? (modulo (- end start) size))
  341. (error "unexpected length"))
  342. (let lp ((pos start))
  343. (when (< pos end)
  344. (set buf pos (ref buf pos (endianness big)) (endianness little))
  345. (lp (+ pos size))))))
  346. (define-byte-order-swapper byte-swap/2!
  347. 2 bytevector-u16-ref bytevector-u16-set!)
  348. (define-byte-order-swapper byte-swap/4!
  349. 4 bytevector-u32-ref bytevector-u32-set!)
  350. (define-byte-order-swapper byte-swap/8!
  351. 8 bytevector-u64-ref bytevector-u64-set!)
  352. ;;; A <meta> entry collects metadata for one procedure. Procedures are
  353. ;;; written as contiguous ranges of bytecode.
  354. ;;;
  355. (eval-when (expand)
  356. (define-syntax-rule (assert-match arg pattern kind)
  357. (let ((x arg))
  358. (unless (match x (pattern #t) (_ #f))
  359. (error (string-append "expected " kind) x)))))
  360. (define-record-type <jit-data>
  361. (make-jit-data low-pc high-pc)
  362. jit-data?
  363. (low-pc jit-data-low-pc)
  364. (high-pc jit-data-high-pc))
  365. (define-record-type <meta>
  366. (%make-meta label properties low-pc high-pc arities jit-data-label)
  367. meta?
  368. (label meta-label)
  369. (properties meta-properties set-meta-properties!)
  370. (low-pc meta-low-pc)
  371. (high-pc meta-high-pc set-meta-high-pc!)
  372. (arities meta-arities set-meta-arities!)
  373. (jit-data-label meta-jit-data-label))
  374. (define (make-meta label properties low-pc)
  375. (assert-match label (or (? exact-integer?) (? symbol?)) "symbol")
  376. (assert-match properties (((? symbol?) . _) ...) "alist with symbolic keys")
  377. (%make-meta label properties low-pc #f '() (gensym "jit-data")))
  378. (define (meta-name meta)
  379. (assq-ref (meta-properties meta) 'name))
  380. ;; Metadata for one <lambda-case>.
  381. (define-record-type <arity>
  382. (make-arity req opt rest kw-indices allow-other-keys?
  383. low-pc high-pc definitions)
  384. arity?
  385. (req arity-req)
  386. (opt arity-opt)
  387. (rest arity-rest)
  388. (kw-indices arity-kw-indices)
  389. (allow-other-keys? arity-allow-other-keys?)
  390. (low-pc arity-low-pc)
  391. (high-pc arity-high-pc set-arity-high-pc!)
  392. (definitions arity-definitions set-arity-definitions!))
  393. ;;; An assembler collects all of the words emitted during assembly, and
  394. ;;; also maintains ancillary information such as the constant table, a
  395. ;;; relocation list, and so on.
  396. ;;;
  397. ;;; Bytecode consists of 32-bit units. We emit bytecode using native
  398. ;;; endianness. If we're targeting a foreign endianness, we byte-swap
  399. ;;; the bytevector as a whole instead of conditionalizing each access.
  400. ;;;
  401. (define-record-type <asm>
  402. (make-asm buf pos start
  403. labels relocs
  404. word-size endianness
  405. constants inits
  406. shstrtab next-section-number
  407. meta sources
  408. slot-maps)
  409. asm?
  410. ;; We write bytecode into a bytevector, growing the bytevector as
  411. ;; needed. asm-cur is that bytevector, and asm-pos is the byte offset
  412. ;; into the vector at which the next word should be written.
  413. ;;
  414. (buf asm-buf set-asm-buf!)
  415. (pos asm-pos set-asm-pos!)
  416. ;; asm-start is an absolute position, indicating the byte offset of
  417. ;; the beginning of an instruction. It is updated after writing all
  418. ;; the words for one primitive instruction. It models the position of
  419. ;; the instruction pointer during execution, given that the VM updates
  420. ;; the IP only at the end of executing the instruction, and is thus
  421. ;; useful for computing offsets between two points in a program.
  422. ;;
  423. (start asm-start set-asm-start!)
  424. ;; An alist of symbol -> position pairs, indicating the labels defined
  425. ;; in this compilation unit.
  426. ;;
  427. (labels asm-labels set-asm-labels!)
  428. ;; A list of relocations needed by the program text. We use an
  429. ;; internal representation for relocations, and handle textual
  430. ;; relative relocations in the assembler. Other kinds of relocations
  431. ;; are later reified as linker relocations and resolved by the linker.
  432. ;;
  433. (relocs asm-relocs set-asm-relocs!)
  434. ;; Target information.
  435. ;;
  436. (word-size asm-word-size)
  437. (endianness asm-endianness)
  438. ;; The constant table, as a vhash of object -> label. All constants
  439. ;; get de-duplicated and written into separate sections -- either the
  440. ;; .rodata section, for read-only data, or .data, for constants that
  441. ;; need initialization at load-time (like symbols). Constants can
  442. ;; depend on other constants (e.g. a symbol depending on a stringbuf),
  443. ;; so order in this table is important.
  444. ;;
  445. (constants asm-constants set-asm-constants!)
  446. ;; A list of instructions needed to initialize the constants. Will
  447. ;; run in a thunk with 2 local variables.
  448. ;;
  449. (inits asm-inits set-asm-inits!)
  450. ;; The shstrtab, for section names.
  451. ;;
  452. (shstrtab asm-shstrtab set-asm-shstrtab!)
  453. ;; The section number for the next section to be written.
  454. ;;
  455. (next-section-number asm-next-section-number set-asm-next-section-number!)
  456. ;; A list of <meta>, corresponding to procedure metadata.
  457. ;;
  458. (meta asm-meta set-asm-meta!)
  459. ;; A list of (pos . source) pairs, indicating source information. POS
  460. ;; is relative to the beginning of the text section, and SOURCE is in
  461. ;; the same format that source-properties returns.
  462. ;;
  463. (sources asm-sources set-asm-sources!)
  464. ;; A list of (pos . slot-map) pairs, indicating slot maps. POS is
  465. ;; relative to the beginning of the text section. SLOT-MAP is a
  466. ;; bitfield describing the stack at call sites, as an integer.
  467. ;;
  468. (slot-maps asm-slot-maps set-asm-slot-maps!))
  469. (define* (make-assembler #:key (word-size (target-word-size))
  470. (endianness (target-endianness)))
  471. "Create an assembler for a given target @var{word-size} and
  472. @var{endianness}, falling back to appropriate values for the configured
  473. target."
  474. (make-asm (make-u32vector 1000) 0 0
  475. (make-hash-table) '()
  476. word-size endianness
  477. vlist-null '()
  478. (make-string-table) 1
  479. '() '() '()))
  480. (define (intern-section-name! asm string)
  481. "Add a string to the section name table (shstrtab)."
  482. (string-table-intern! (asm-shstrtab asm) string))
  483. (define (grow-buffer! asm)
  484. "Grow the code buffer of the asm."
  485. (let* ((buf (asm-buf asm))
  486. (len (bytevector-length buf))
  487. (new (make-u32vector (ash len -1) 0)))
  488. (bytevector-copy! buf 0 new 0 len)
  489. (set-asm-buf! asm new)
  490. #f))
  491. (define-inline (emit asm u32)
  492. "Emit one 32-bit word into the instruction stream. Assumes that there
  493. is space for the word."
  494. (bytevector-u32-native-set! (asm-buf asm) (asm-pos asm) u32)
  495. (set-asm-pos! asm (+ (asm-pos asm) 4)))
  496. (define-inline (make-reloc type label base word)
  497. "Make an internal relocation of type @var{type} referencing symbol
  498. @var{label}, @var{word} words after position @var{start}. @var{type}
  499. may be x8-s24, indicating a 24-bit relative label reference that can be
  500. fixed up by the assembler, or s32, indicating a 32-bit relative
  501. reference that needs to be fixed up by the linker."
  502. (list type label base word))
  503. (define-inline (reset-asm-start! asm)
  504. "Reset the asm-start after writing the words for one instruction."
  505. (set-asm-start! asm (asm-pos asm)))
  506. (define (record-label-reference asm label)
  507. "Record an x8-s24 local label reference. This value will get patched
  508. up later by the assembler."
  509. (let* ((start (asm-start asm))
  510. (pos (asm-pos asm))
  511. (reloc (make-reloc 'x8-s24 label start (- pos start))))
  512. (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
  513. (define* (record-far-label-reference asm label #:optional (offset 0))
  514. "Record an s32 far label reference. This value will get patched up
  515. later by the linker."
  516. (let* ((start (- (asm-start asm) offset))
  517. (pos (asm-pos asm))
  518. (reloc (make-reloc 's32 label start (- pos start))))
  519. (set-asm-relocs! asm (cons reloc (asm-relocs asm)))))
  520. ;;;
  521. ;;; Primitive assemblers are defined by expanding `assembler' for each
  522. ;;; opcode in `(instruction-list)'.
  523. ;;;
  524. (eval-when (expand)
  525. (define (id-append ctx a b)
  526. (datum->syntax ctx (symbol-append (syntax->datum a) (syntax->datum b))))
  527. (define-syntax encoder
  528. (lambda (x)
  529. (define-syntax op-case
  530. (lambda (x)
  531. (syntax-case x ()
  532. ((_ asm name ((type arg ...) code ...) clause ...)
  533. #`(if (eq? name 'type)
  534. (with-syntax (((arg ...) (generate-temporaries #'(arg ...))))
  535. #'((arg ...)
  536. code ...))
  537. (op-case asm name clause ...)))
  538. ((_ asm name)
  539. #'(error "unmatched name" name)))))
  540. (define (pack-first-word asm opcode type)
  541. (with-syntax ((opcode opcode))
  542. (op-case
  543. asm type
  544. ((X32)
  545. (emit asm opcode))
  546. ((X8_S24 arg)
  547. (emit asm (pack-u8-u24 opcode arg)))
  548. ((X8_F24 arg)
  549. (emit asm (pack-u8-u24 opcode arg)))
  550. ((X8_C24 arg)
  551. (emit asm (pack-u8-u24 opcode arg)))
  552. ((X8_L24 label)
  553. (record-label-reference asm label)
  554. (emit asm opcode))
  555. ((X8_S8_I16 a imm)
  556. (emit asm (pack-u8-u8-u16 opcode a (immediate-bits asm imm))))
  557. ((X8_S12_S12 a b)
  558. (emit asm (pack-u8-u12-u12 opcode a b)))
  559. ((X8_S12_C12 a b)
  560. (emit asm (pack-u8-u12-u12 opcode a b)))
  561. ((X8_S12_Z12 a b)
  562. (emit asm (pack-u8-u12-s12 opcode a b)))
  563. ((X8_C12_C12 a b)
  564. (emit asm (pack-u8-u12-u12 opcode a b)))
  565. ((X8_F12_F12 a b)
  566. (emit asm (pack-u8-u12-u12 opcode a b)))
  567. ((X8_S8_S8_S8 a b c)
  568. (emit asm (pack-u8-u8-u8-u8 opcode a b c)))
  569. ((X8_S8_S8_C8 a b c)
  570. (emit asm (pack-u8-u8-u8-u8 opcode a b c)))
  571. ((X8_S8_C8_S8 a b c)
  572. (emit asm (pack-u8-u8-u8-u8 opcode a b c))))))
  573. (define (pack-tail-word asm type)
  574. (op-case
  575. asm type
  576. ((C32 a)
  577. (emit asm a))
  578. ((I32 imm)
  579. (let ((val (immediate-bits asm imm)))
  580. (emit asm val)))
  581. ((A32 imm)
  582. (unless (= (asm-word-size asm) 8)
  583. (error "make-long-immediate unavailable for this target"))
  584. (let ((bits (immediate-bits asm imm)))
  585. (emit asm (ash bits -32))
  586. (emit asm (logand bits (1- (ash 1 32))))))
  587. ((AF32 f64)
  588. (let ((u64 (u64vector-ref (f64vector f64) 0)))
  589. (emit asm (ash u64 -32))
  590. (emit asm (logand u64 (1- (ash 1 32))))))
  591. ((AU32 u64)
  592. (emit asm (ash u64 -32))
  593. (emit asm (logand u64 (1- (ash 1 32)))))
  594. ((AS32 s64)
  595. (let ((u64 (u64vector-ref (s64vector s64) 0)))
  596. (emit asm (ash u64 -32))
  597. (emit asm (logand u64 (1- (ash 1 32))))))
  598. ((B32))
  599. ((BU32))
  600. ((BS32))
  601. ((BF32))
  602. ((N32 label)
  603. (record-far-label-reference asm label)
  604. (emit asm 0))
  605. ((R32 label)
  606. (record-far-label-reference asm label)
  607. (emit asm 0))
  608. ((L32 label)
  609. (record-far-label-reference asm label)
  610. (emit asm 0))
  611. ((LO32 label offset)
  612. (record-far-label-reference asm label
  613. (* offset (asm-word-size asm)))
  614. (emit asm 0))
  615. ((C8_C24 a b)
  616. (emit asm (pack-u8-u24 a b)))
  617. ((C8_S24 a b)
  618. (emit asm (pack-u8-u24 a b)))
  619. ((C16_C16 a b)
  620. (emit asm (pack-u16-u16 a b)))
  621. ((B1_X7_L24 a label)
  622. (record-label-reference asm label)
  623. (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
  624. ((B1_C7_L24 a b label)
  625. (record-label-reference asm label)
  626. (emit asm (pack-u1-u7-u24 (if a 1 0) b 0)))
  627. ((B1_X31 a)
  628. (emit asm (pack-u1-u7-u24 (if a 1 0) 0 0)))
  629. ((B1_X7_S24 a b)
  630. (emit asm (pack-u1-u7-u24 (if a 1 0) 0 b)))
  631. ((B1_X7_F24 a b)
  632. (emit asm (pack-u1-u7-u24 (if a 1 0) 0 b)))
  633. ((B1_X7_C24 a b)
  634. (emit asm (pack-u1-u7-u24 (if a 1 0) 0 b)))
  635. ((X8_S24 a)
  636. (emit asm (pack-u8-u24 0 a)))
  637. ((X8_F24 a)
  638. (emit asm (pack-u8-u24 0 a)))
  639. ((X8_C24 a)
  640. (emit asm (pack-u8-u24 0 a)))
  641. ((X8_L24 label)
  642. (record-label-reference asm label)
  643. (emit asm 0))))
  644. (syntax-case x ()
  645. ((_ word0 word* ...)
  646. (with-syntax ((((formal0 ...)
  647. code0 ...)
  648. (pack-first-word #'asm #'opcode
  649. (syntax->datum #'word0)))
  650. ((((formal* ...)
  651. code* ...) ...)
  652. (map (lambda (word) (pack-tail-word #'asm word))
  653. (syntax->datum #'(word* ...)))))
  654. ;; The opcode is the last argument, so that assemblers don't
  655. ;; have to shuffle their arguments before tail-calling an
  656. ;; encoder.
  657. #'(lambda (asm formal0 ... formal* ... ... opcode)
  658. (let lp ()
  659. (let ((words (length '(word0 word* ...))))
  660. (unless (<= (+ (asm-pos asm) (* 4 words))
  661. (bytevector-length (asm-buf asm)))
  662. (grow-buffer! asm)
  663. (lp))))
  664. code0 ...
  665. code* ... ...
  666. (reset-asm-start! asm)))))))
  667. (define (encoder-name operands)
  668. (let lp ((operands operands) (out #'encode))
  669. (syntax-case operands ()
  670. (() out)
  671. ((operand . operands)
  672. (lp #'operands
  673. (id-append #'operand (id-append out out #'-) #'operand))))))
  674. (define-syntax define-encoder
  675. (lambda (x)
  676. (syntax-case x ()
  677. ((_ operand ...)
  678. (with-syntax ((encode (encoder-name #'(operand ...))))
  679. #'(define encode (encoder operand ...)))))))
  680. (define-syntax visit-instruction-kinds
  681. (lambda (x)
  682. (syntax-case x ()
  683. ((visit-instruction-kinds macro arg ...)
  684. (with-syntax (((operands ...)
  685. (delete-duplicates
  686. (map (match-lambda
  687. ((name opcode kind . operands)
  688. (datum->syntax #'macro operands)))
  689. (instruction-list)))))
  690. #'(begin
  691. (macro arg ... . operands)
  692. ...)))))))
  693. (visit-instruction-kinds define-encoder)
  694. ;; In Guile's VM, locals are usually addressed via the stack pointer
  695. ;; (SP). There can be up to 2^24 slots for local variables in a
  696. ;; frame. Some instructions encode their operands using a restricted
  697. ;; subset of the full 24-bit local address space, in order to make the
  698. ;; bytecode more dense in the usual case that a function needs few
  699. ;; local slots. To allow these instructions to be used when there are
  700. ;; many local slots, we can temporarily push the values on the stack,
  701. ;; operate on them there, and then store back any result as we pop the
  702. ;; SP to its original position.
  703. ;;
  704. ;; We implement this shuffling via wrapper encoders that have the same
  705. ;; arity as the encoder they wrap, e.g. encode-X8_S12_S12/shuffle that
  706. ;; wraps encode-X8_S12_S12. We make the emit-cons public interface
  707. ;; use the shuffling encoder. That way we solve the problem fully and
  708. ;; in just one place.
  709. (define (encode-X8_S12_S12!/shuffle asm a b opcode)
  710. (cond
  711. ((< (logior a b) (ash 1 12))
  712. (encode-X8_S12_S12 asm a b opcode))
  713. (else
  714. (emit-push asm a)
  715. (emit-push asm (1+ b))
  716. (encode-X8_S12_S12 asm 1 0 opcode)
  717. (emit-drop asm 2))))
  718. (define (encode-X8_S12_S12<-/shuffle asm dst a opcode)
  719. (cond
  720. ((< (logior dst a) (ash 1 12))
  721. (encode-X8_S12_S12 asm dst a opcode))
  722. (else
  723. (emit-push asm a)
  724. (encode-X8_S12_S12 asm 0 0 opcode)
  725. (emit-pop asm dst))))
  726. (define (encode-X8_S12_C12!/shuffle asm a const opcode)
  727. (cond
  728. ((< a (ash 1 12))
  729. (encode-X8_S12_C12 asm a const opcode))
  730. (else
  731. (emit-push asm a)
  732. (encode-X8_S12_C12 asm 0 const opcode)
  733. (emit-drop asm 1))))
  734. (define (encode-X8_S12_C12<-/shuffle asm dst const opcode)
  735. (cond
  736. ((< dst (ash 1 12))
  737. (encode-X8_S12_C12 asm dst const opcode))
  738. (else
  739. ;; Push garbage value to make space for dst.
  740. (emit-push asm dst)
  741. (encode-X8_S12_C12 asm 0 const opcode)
  742. (emit-pop asm dst))))
  743. (define (encode-X8_S12_Z12!/shuffle asm a const opcode)
  744. (cond
  745. ((< a (ash 1 12))
  746. (encode-X8_S12_Z12 asm a const opcode))
  747. (else
  748. (emit-push asm a)
  749. (encode-X8_S12_Z12 asm 0 const opcode)
  750. (emit-drop asm 1))))
  751. (define (encode-X8_S8_I16<-/shuffle asm dst imm opcode)
  752. (cond
  753. ((< dst (ash 1 8))
  754. (encode-X8_S8_I16 asm dst imm opcode))
  755. (else
  756. ;; Push garbage value to make space for dst.
  757. (emit-push asm dst)
  758. (encode-X8_S8_I16 asm 0 imm opcode)
  759. (emit-pop asm dst))))
  760. (define (encode-X8_S8_S8_S8!/shuffle asm a b c opcode)
  761. (cond
  762. ((< (logior a b c) (ash 1 8))
  763. (encode-X8_S8_S8_S8 asm a b c opcode))
  764. (else
  765. (emit-push asm a)
  766. (emit-push asm (+ b 1))
  767. (emit-push asm (+ c 2))
  768. (encode-X8_S8_S8_S8 asm 2 1 0 opcode)
  769. (emit-drop asm 3))))
  770. (define (encode-X8_S8_S8_S8<-/shuffle asm dst a b opcode)
  771. (cond
  772. ((< (logior dst a b) (ash 1 8))
  773. (encode-X8_S8_S8_S8 asm dst a b opcode))
  774. (else
  775. (emit-push asm a)
  776. (emit-push asm (1+ b))
  777. (encode-X8_S8_S8_S8 asm 1 1 0 opcode)
  778. (emit-drop asm 1)
  779. (emit-pop asm dst))))
  780. (define (encode-X8_S8_S8_C8<-/shuffle asm dst a const opcode)
  781. (cond
  782. ((< (logior dst a) (ash 1 8))
  783. (encode-X8_S8_S8_C8 asm dst a const opcode))
  784. (else
  785. (emit-push asm a)
  786. (encode-X8_S8_S8_C8 asm 0 0 const opcode)
  787. (emit-pop asm dst))))
  788. (define (encode-X8_S8_C8_S8!/shuffle asm a const b opcode)
  789. (cond
  790. ((< (logior a b) (ash 1 8))
  791. (encode-X8_S8_C8_S8 asm a const b opcode))
  792. (else
  793. (emit-push asm a)
  794. (emit-push asm (1+ b))
  795. (encode-X8_S8_C8_S8 asm 1 const 0 opcode)
  796. (emit-drop asm 2))))
  797. (define (encode-X8_S8_C8_S8<-/shuffle asm dst const a opcode)
  798. (cond
  799. ((< (logior dst a) (ash 1 8))
  800. (encode-X8_S8_C8_S8 asm dst const a opcode))
  801. (else
  802. (emit-push asm a)
  803. (encode-X8_S8_C8_S8 asm 0 const 0 opcode)
  804. (emit-pop asm dst))))
  805. (define (encode-X8_S8_S8_S8-C32<-/shuffle asm dst a b c32 opcode)
  806. (cond
  807. ((< (logior dst a b) (ash 1 8))
  808. (encode-X8_S8_S8_S8-C32 asm dst a b c32 opcode))
  809. (else
  810. (emit-push asm a)
  811. (emit-push asm (1+ b))
  812. (encode-X8_S8_S8_S8-C32 asm 1 1 0 c32 opcode)
  813. (emit-drop asm 1)
  814. (emit-pop asm dst))))
  815. (define (encode-X8_S8_S8_C8-C32<-/shuffle asm dst a const c32 opcode)
  816. (cond
  817. ((< (logior dst a) (ash 1 8))
  818. (encode-X8_S8_S8_C8-C32 asm dst a const c32 opcode))
  819. (else
  820. (emit-push asm a)
  821. (encode-X8_S8_S8_C8-C32 asm 0 0 const c32 opcode)
  822. (emit-pop asm dst))))
  823. (define (encode-X8_S8_S8_S8-C32!/shuffle asm a b c c32 opcode)
  824. (cond
  825. ((< (logior a b c) (ash 1 8))
  826. (encode-X8_S8_S8_S8-C32 asm a b c c32 opcode))
  827. (else
  828. (emit-push asm a)
  829. (emit-push asm (+ b 1))
  830. (emit-push asm (+ c 2))
  831. (encode-X8_S8_S8_S8-C32 asm 2 1 0 c32 opcode)
  832. (emit-drop asm 3))))
  833. (define (encode-X8_S12_S12-C32<-/shuffle asm dst src c32 opcode)
  834. (cond
  835. ((< (logior dst src) (ash 1 12))
  836. (encode-X8_S12_S12-C32 asm dst src c32 opcode))
  837. (else
  838. (emit-push asm src)
  839. (encode-X8_S12_S12-C32 asm 0 0 c32 opcode)
  840. (emit-pop asm dst))))
  841. (define (encode-X8_S12_S12-C32!/shuffle asm a b c32 opcode)
  842. (cond
  843. ((< (logior a b) (ash 1 12))
  844. (encode-X8_S12_S12-C32 asm a b c32 opcode))
  845. (else
  846. (emit-push asm a)
  847. (emit-push asm b)
  848. (encode-X8_S12_S12-C32 asm 1 0 c32 opcode)
  849. (emit-drop asm 2))))
  850. (eval-when (expand)
  851. (define (id-append ctx a b)
  852. (datum->syntax ctx (symbol-append (syntax->datum a) (syntax->datum b))))
  853. (define (shuffling-encoder-name kind operands)
  854. (match (cons (syntax->datum kind) (syntax->datum operands))
  855. (('! 'X8_S12_S12) #'encode-X8_S12_S12!/shuffle)
  856. (('<- 'X8_S12_S12) #'encode-X8_S12_S12<-/shuffle)
  857. (('! 'X8_S12_S12 'X8_C24) #'encode-X8_S12_S12-X8_C24!/shuffle)
  858. (('<- 'X8_S12_S12 'X8_C24) #'encode-X8_S12_S12-X8_C24<-/shuffle)
  859. (('! 'X8_S12_C12) #'encode-X8_S12_C12!/shuffle)
  860. (('<- 'X8_S12_C12) #'encode-X8_S12_C12<-/shuffle)
  861. (('! 'X8_S12_Z12) #'encode-X8_S12_Z12!/shuffle)
  862. (('<- 'X8_S8_I16) #'encode-X8_S8_I16<-/shuffle)
  863. (('! 'X8_S8_S8_S8) #'encode-X8_S8_S8_S8!/shuffle)
  864. (('<- 'X8_S8_S8_S8) #'encode-X8_S8_S8_S8<-/shuffle)
  865. (('<- 'X8_S8_S8_C8) #'encode-X8_S8_S8_C8<-/shuffle)
  866. (('<- 'X8_S8_S8_S8 'C32) #'encode-X8_S8_S8_S8-C32<-/shuffle)
  867. (('<- 'X8_S8_S8_C8 'C32) #'encode-X8_S8_S8_C8-C32<-/shuffle)
  868. (('! 'X8_S8_S8_C8 'C32) #'encode-X8_S8_S8_C8-C32!/shuffle)
  869. (('<- 'X8_S12_S12 'C32) #'encode-X8_S12_S12-C32<-/shuffle)
  870. (('! 'X8_S12_S12 'C32) #'encode-X8_S12_S12-C32!/shuffle)
  871. (('! 'X8_S8_C8_S8) #'encode-X8_S8_C8_S8!/shuffle)
  872. (('<- 'X8_S8_C8_S8) #'encode-X8_S8_C8_S8<-/shuffle)
  873. (else (encoder-name operands))))
  874. (define-syntax assembler
  875. (lambda (x)
  876. (define (word-args word)
  877. (match word
  878. ('C32 #'(a))
  879. ('I32 #'(imm))
  880. ('A32 #'(imm))
  881. ('AF32 #'(f64))
  882. ('AU32 #'(u64))
  883. ('AS32 #'(s64))
  884. ('B32 #'())
  885. ('BU32 #'())
  886. ('BS32 #'())
  887. ('BF32 #'())
  888. ('N32 #'(label))
  889. ('R32 #'(label))
  890. ('L32 #'(label))
  891. ('LO32 #'(label offset))
  892. ('C8_C24 #'(a b))
  893. ('C8_S24 #'(a b))
  894. ('C16_C16 #'(a b))
  895. ('B1_X7_L24 #'(a label))
  896. ('B1_C7_L24 #'(a b label))
  897. ('B1_X31 #'(a))
  898. ('B1_X7_S24 #'(a b))
  899. ('B1_X7_F24 #'(a b))
  900. ('B1_X7_C24 #'(a b))
  901. ('X8_S24 #'(arg))
  902. ('X8_F24 #'(arg))
  903. ('X8_C24 #'(arg))
  904. ('X8_L24 #'(label))
  905. ('X8_S8_I16 #'(a imm))
  906. ('X8_S12_S12 #'(a b))
  907. ('X8_S12_C12 #'(a b))
  908. ('X8_S12_Z12 #'(a b))
  909. ('X8_C12_C12 #'(a b))
  910. ('X8_F12_F12 #'(a b))
  911. ('X8_S8_S8_S8 #'(a b c))
  912. ('X8_S8_S8_C8 #'(a b c))
  913. ('X8_S8_C8_S8 #'(a b c))
  914. ('X32 #'())))
  915. (syntax-case x ()
  916. ((_ name opcode kind word ...)
  917. (with-syntax (((formal ...)
  918. (generate-temporaries
  919. (append-map word-args (syntax->datum #'(word ...)))))
  920. (encode (shuffling-encoder-name #'kind #'(word ...))))
  921. #'(lambda (asm formal ...)
  922. (encode asm formal ... opcode))))))))
  923. (define assemblers (make-hash-table))
  924. (eval-when (expand)
  925. (define-syntax define-assembler
  926. (lambda (x)
  927. (syntax-case x ()
  928. ((_ name opcode kind arg ...)
  929. (with-syntax ((emit (id-append #'name #'emit- #'name)))
  930. #'(define emit
  931. (let ((emit (assembler name opcode kind arg ...)))
  932. (hashq-set! assemblers 'name emit)
  933. emit)))))))
  934. (define-syntax visit-opcodes
  935. (lambda (x)
  936. (syntax-case x ()
  937. ((visit-opcodes macro arg ...)
  938. (with-syntax (((inst ...)
  939. (map (lambda (x) (datum->syntax #'macro x))
  940. (instruction-list))))
  941. #'(begin
  942. (macro arg ... . inst)
  943. ...)))))))
  944. (visit-opcodes define-assembler)
  945. ;; Shuffling is a general mechanism to get around address space
  946. ;; limitations for SP-relative variable references. FP-relative
  947. ;; variables need special support. Also, some instructions like `mov'
  948. ;; have multiple variations with different addressing limits.
  949. (define (emit-mov* asm dst src)
  950. (if (and (< dst (ash 1 12)) (< src (ash 1 12)))
  951. (emit-mov asm dst src)
  952. (emit-long-mov asm dst src)))
  953. (define (emit-fmov* asm dst src)
  954. (emit-long-fmov asm dst src))
  955. (define (emit-receive* asm dst proc nlocals)
  956. (if (and (< dst (ash 1 12)) (< proc (ash 1 12)))
  957. (emit-receive asm dst proc nlocals)
  958. (begin
  959. (emit-receive-values asm proc #t 1)
  960. (emit-fmov* asm dst (1+ proc))
  961. (emit-reset-frame asm nlocals))))
  962. (define (emit-throw/value* asm val param)
  963. (emit-throw/value asm val (intern-non-immediate asm param)))
  964. (define (emit-throw/value+data* asm val param)
  965. (emit-throw/value+data asm val (intern-non-immediate asm param)))
  966. (define (emit-instrument-entry* asm)
  967. (let ((meta (car (asm-meta asm))))
  968. (emit-instrument-entry asm (meta-jit-data-label meta))))
  969. (define (emit-instrument-loop* asm)
  970. (let ((meta (car (asm-meta asm))))
  971. (emit-instrument-loop asm (meta-jit-data-label meta))))
  972. (define (emit-text asm instructions)
  973. "Assemble @var{instructions} using the assembler @var{asm}.
  974. @var{instructions} is a sequence of instructions, expressed as a list of
  975. lists. This procedure can be called many times before calling
  976. @code{link-assembly}."
  977. (for-each (lambda (inst)
  978. (apply (or (hashq-ref assemblers (car inst))
  979. (error 'bad-instruction inst))
  980. asm
  981. (cdr inst)))
  982. instructions))
  983. ;;;
  984. ;;; The constant table records a topologically sorted set of literal
  985. ;;; constants used by a program. For example, a pair uses its car and
  986. ;;; cdr, a string uses its stringbuf, etc.
  987. ;;;
  988. ;;; Some things we want to add to the constant table are not actually
  989. ;;; Scheme objects: for example, stringbufs, cache cells for toplevel
  990. ;;; references, or cache cells for non-closure procedures. For these we
  991. ;;; define special record types and add instances of those record types
  992. ;;; to the table.
  993. ;;;
  994. (define (immediate-bits asm x)
  995. "Return the bit pattern to write into the buffer if @var{x} is
  996. immediate, and @code{#f} otherwise."
  997. (define tc2-int 2)
  998. (if (exact-integer? x)
  999. ;; Object is an immediate if it is a fixnum on the target.
  1000. (call-with-values (lambda ()
  1001. (case (asm-word-size asm)
  1002. ((4) (values (- #x20000000)
  1003. #x1fffffff))
  1004. ((8) (values (- #x2000000000000000)
  1005. #x1fffffffFFFFFFFF))
  1006. (else (error "unexpected word size"))))
  1007. (lambda (fixnum-min fixnum-max)
  1008. (and (<= fixnum-min x fixnum-max)
  1009. (let ((fixnum-bits (if (negative? x)
  1010. (+ fixnum-max 1 (logand x fixnum-max))
  1011. x)))
  1012. (logior (ash fixnum-bits 2) tc2-int)))))
  1013. ;; Otherwise, the object will be immediate on the target if and
  1014. ;; only if it is immediate on the host. Except for integers,
  1015. ;; which we handle specially above, any immediate value is an
  1016. ;; immediate on both 32-bit and 64-bit targets.
  1017. (let ((bits (object-address x)))
  1018. (and (not (zero? (logand bits 6)))
  1019. bits))))
  1020. (define-record-type <stringbuf>
  1021. (make-stringbuf string)
  1022. stringbuf?
  1023. (string stringbuf-string))
  1024. (define-record-type <static-procedure>
  1025. (make-static-procedure code)
  1026. static-procedure?
  1027. (code static-procedure-code))
  1028. (define-record-type <uniform-vector-backing-store>
  1029. (make-uniform-vector-backing-store bytes element-size)
  1030. uniform-vector-backing-store?
  1031. (bytes uniform-vector-backing-store-bytes)
  1032. (element-size uniform-vector-backing-store-element-size))
  1033. (define-record-type <cache-cell>
  1034. (make-cache-cell key)
  1035. cache-cell?
  1036. (key cache-cell-key))
  1037. (define (simple-vector? obj)
  1038. (and (vector? obj)
  1039. (equal? (array-shape obj) (list (list 0 (1- (vector-length obj)))))))
  1040. (define (simple-uniform-vector? obj)
  1041. (and (array? obj)
  1042. (symbol? (array-type obj))
  1043. (match (array-shape obj)
  1044. (((0 n)) #t)
  1045. (else #f))))
  1046. (define (statically-allocatable? x)
  1047. "Return @code{#t} if a non-immediate constant can be allocated
  1048. statically, and @code{#f} if it would need some kind of runtime
  1049. allocation."
  1050. (or (pair? x) (string? x) (stringbuf? x) (static-procedure? x)
  1051. (array? x) (syntax? x)))
  1052. (define (intern-constant asm obj)
  1053. "Add an object to the constant table, and return a label that can be
  1054. used to reference it. If the object is already present in the constant
  1055. table, its existing label is used directly."
  1056. (define (recur obj)
  1057. (intern-constant asm obj))
  1058. (define (field dst n obj)
  1059. (let ((src (recur obj)))
  1060. (if src
  1061. (if (statically-allocatable? obj)
  1062. `((static-patch! ,dst ,n ,src))
  1063. `((static-ref 1 ,src)
  1064. (static-set! 1 ,dst ,n)))
  1065. '())))
  1066. (define (intern obj label)
  1067. (cond
  1068. ((pair? obj)
  1069. (append (field label 0 (car obj))
  1070. (field label 1 (cdr obj))))
  1071. ((simple-vector? obj)
  1072. (let lp ((i 0) (inits '()))
  1073. (if (< i (vector-length obj))
  1074. (lp (1+ i)
  1075. (append-reverse (field label (1+ i) (vector-ref obj i))
  1076. inits))
  1077. (reverse inits))))
  1078. ((syntax? obj)
  1079. (append (field label 1 (syntax-expression obj))
  1080. (field label 2 (syntax-wrap obj))
  1081. (field label 3 (syntax-module obj))))
  1082. ((stringbuf? obj) '())
  1083. ((static-procedure? obj)
  1084. `((static-patch! ,label 1 ,(static-procedure-code obj))))
  1085. ((cache-cell? obj) '())
  1086. ((symbol? obj)
  1087. (unless (symbol-interned? obj)
  1088. (error "uninterned symbol cannot be saved to object file" obj))
  1089. `((make-non-immediate 1 ,(recur (symbol->string obj)))
  1090. (string->symbol 1 1)
  1091. (static-set! 1 ,label 0)))
  1092. ((string? obj)
  1093. `((static-patch! ,label 1 ,(recur (make-stringbuf obj)))))
  1094. ((keyword? obj)
  1095. `((static-ref 1 ,(recur (keyword->symbol obj)))
  1096. (symbol->keyword 1 1)
  1097. (static-set! 1 ,label 0)))
  1098. ((number? obj)
  1099. `((make-non-immediate 1 ,(recur (number->string obj)))
  1100. (string->number 1 1)
  1101. (static-set! 1 ,label 0)))
  1102. ((uniform-vector-backing-store? obj) '())
  1103. ((simple-uniform-vector? obj)
  1104. (let ((width (case (array-type obj)
  1105. ((vu8 u8 s8) 1)
  1106. ((u16 s16) 2)
  1107. ;; Bitvectors are addressed in 32-bit units.
  1108. ;; Although a complex number is 8 or 16 bytes wide,
  1109. ;; it should be byteswapped in 4 or 8 byte units.
  1110. ((u32 s32 f32 c32 b) 4)
  1111. ((u64 s64 f64 c64) 8)
  1112. (else
  1113. (error "unhandled array type" obj)))))
  1114. `((static-patch! ,label 2
  1115. ,(recur (make-uniform-vector-backing-store
  1116. (uniform-array->bytevector obj)
  1117. width))))))
  1118. ((array? obj)
  1119. `((static-patch! ,label 1 ,(recur (shared-array-root obj)))))
  1120. (else
  1121. (error "don't know how to intern" obj))))
  1122. (cond
  1123. ((immediate-bits asm obj) #f)
  1124. ((vhash-assoc obj (asm-constants asm)) => cdr)
  1125. (else
  1126. ;; Note that calling intern may mutate asm-constants and asm-inits.
  1127. (let* ((label (gensym "constant"))
  1128. (inits (intern obj label)))
  1129. (set-asm-constants! asm (vhash-cons obj label (asm-constants asm)))
  1130. (set-asm-inits! asm (append-reverse inits (asm-inits asm)))
  1131. label))))
  1132. (define (intern-non-immediate asm obj)
  1133. "Intern a non-immediate into the constant table, and return its
  1134. label."
  1135. (when (immediate-bits asm obj)
  1136. (error "expected a non-immediate" obj))
  1137. (intern-constant asm obj))
  1138. (define (intern-cache-cell asm key)
  1139. "Intern a cache cell into the constant table, and return its label.
  1140. If there is already a cache cell with the given scope and key, it is
  1141. returned instead."
  1142. (intern-constant asm (make-cache-cell key)))
  1143. ;;;
  1144. ;;; Macro assemblers bridge the gap between primitive instructions and
  1145. ;;; some higher-level operations.
  1146. ;;;
  1147. (eval-when (expand)
  1148. (define-syntax define-macro-assembler
  1149. (lambda (x)
  1150. (syntax-case x ()
  1151. ((_ (name arg ...) body body* ...)
  1152. (with-syntax ((emit (id-append #'name #'emit- #'name)))
  1153. #'(begin
  1154. (define emit
  1155. (let ((emit (lambda (arg ...) body body* ...)))
  1156. (hashq-set! assemblers 'name emit)
  1157. emit))
  1158. (export emit))))))))
  1159. (define-macro-assembler (load-constant asm dst obj)
  1160. (cond
  1161. ((immediate-bits asm obj)
  1162. => (lambda (bits)
  1163. (cond
  1164. ((and (< dst 256) (zero? (ash bits -16)))
  1165. (emit-make-short-immediate asm dst obj))
  1166. ((zero? (ash bits -32))
  1167. (emit-make-long-immediate asm dst obj))
  1168. (else
  1169. (emit-make-long-long-immediate asm dst obj)))))
  1170. ((statically-allocatable? obj)
  1171. (emit-make-non-immediate asm dst (intern-non-immediate asm obj)))
  1172. (else
  1173. (emit-static-ref asm dst (intern-non-immediate asm obj)))))
  1174. (define-macro-assembler (load-static-procedure asm dst label)
  1175. (let ((loc (intern-constant asm (make-static-procedure label))))
  1176. (emit-make-non-immediate asm dst loc)))
  1177. (define-syntax-rule (define-immediate-tag=?-macro-assembler name pred mask tag)
  1178. (define-macro-assembler (pred asm slot)
  1179. (emit-immediate-tag=? asm slot mask tag)))
  1180. (visit-immediate-tags define-immediate-tag=?-macro-assembler)
  1181. (define-syntax-rule (define-heap-tag=?-macro-assembler name pred mask tag)
  1182. (define-macro-assembler (pred asm slot)
  1183. (emit-heap-tag=? asm slot mask tag)))
  1184. (visit-heap-tags define-heap-tag=?-macro-assembler)
  1185. (define-syntax-rule (define-scm<-scm-scm-intrinsic name)
  1186. (define-macro-assembler (name asm dst a b)
  1187. (emit-call-scm<-scm-scm asm dst a b (intrinsic-name->index 'name))))
  1188. (define-syntax-rule (define-scm<-scm-uimm-intrinsic name)
  1189. (define-macro-assembler (name asm dst a b)
  1190. (emit-call-scm<-scm-uimm asm dst a b (intrinsic-name->index 'name))))
  1191. (define-syntax-rule (define-scm-sz-u32-intrinsic name)
  1192. (define-macro-assembler (name asm a b c)
  1193. (emit-call-scm-sz-u32 asm a b c (intrinsic-name->index 'name))))
  1194. (define-syntax-rule (define-scm<-scm-intrinsic name)
  1195. (define-macro-assembler (name asm dst src)
  1196. (emit-call-scm<-scm asm dst src (intrinsic-name->index 'name))))
  1197. (define-syntax-rule (define-f64<-scm-intrinsic name)
  1198. (define-macro-assembler (name asm dst src)
  1199. (emit-call-f64<-scm asm dst src (intrinsic-name->index 'name))))
  1200. (define-syntax-rule (define-u64<-scm-intrinsic name)
  1201. (define-macro-assembler (name asm dst src)
  1202. (emit-call-u64<-scm asm dst src (intrinsic-name->index 'name))))
  1203. (define-syntax-rule (define-s64<-scm-intrinsic name)
  1204. (define-macro-assembler (name asm dst src)
  1205. (emit-call-s64<-scm asm dst src (intrinsic-name->index 'name))))
  1206. (define-syntax-rule (define-scm<-u64-intrinsic name)
  1207. (define-macro-assembler (name asm dst src)
  1208. (emit-call-scm<-u64 asm dst src (intrinsic-name->index 'name))))
  1209. (define-syntax-rule (define-scm<-s64-intrinsic name)
  1210. (define-macro-assembler (name asm dst src)
  1211. (emit-call-scm<-s64 asm dst src (intrinsic-name->index 'name))))
  1212. (define-syntax-rule (define-thread-intrinsic name)
  1213. (define-macro-assembler (name asm)
  1214. (emit-call-thread asm (intrinsic-name->index 'name))))
  1215. (define-syntax-rule (define-thread-scm-intrinsic name)
  1216. (define-macro-assembler (name asm a)
  1217. (emit-call-thread-scm asm a (intrinsic-name->index 'name))))
  1218. (define-syntax-rule (define-thread-scm-scm-intrinsic name)
  1219. (define-macro-assembler (name asm a b)
  1220. (emit-call-thread-scm-scm asm a b (intrinsic-name->index 'name))))
  1221. (define-syntax-rule (define-scm<-thread-scm-intrinsic name)
  1222. (define-macro-assembler (name asm dst src)
  1223. (emit-call-scm<-thread-scm asm dst src (intrinsic-name->index 'name))))
  1224. (define-syntax-rule (define-scm<-scm-u64-intrinsic name)
  1225. (define-macro-assembler (name asm dst a b)
  1226. (emit-call-scm<-scm-u64 asm dst a b (intrinsic-name->index 'name))))
  1227. (define-syntax-rule (define-scm<-scm-bool-intrinsic name)
  1228. (define-macro-assembler (name asm dst a b)
  1229. (emit-call-scm<-scm-uimm asm dst a (if b 1 0) (intrinsic-name->index 'name))))
  1230. (define-syntax-rule (define-scm<-thread-intrinsic name)
  1231. (define-macro-assembler (name asm dst)
  1232. (emit-call-scm<-thread asm dst (intrinsic-name->index 'name))))
  1233. (define-scm<-scm-scm-intrinsic add)
  1234. (define-scm<-scm-uimm-intrinsic add/immediate)
  1235. (define-scm<-scm-scm-intrinsic sub)
  1236. (define-scm<-scm-uimm-intrinsic sub/immediate)
  1237. (define-scm<-scm-scm-intrinsic mul)
  1238. (define-scm<-scm-scm-intrinsic div)
  1239. (define-scm<-scm-scm-intrinsic quo)
  1240. (define-scm<-scm-scm-intrinsic rem)
  1241. (define-scm<-scm-scm-intrinsic mod)
  1242. (define-scm<-scm-scm-intrinsic logand)
  1243. (define-scm<-scm-scm-intrinsic logior)
  1244. (define-scm<-scm-scm-intrinsic logxor)
  1245. (define-scm<-scm-scm-intrinsic logsub)
  1246. (define-scm-sz-u32-intrinsic string-set!)
  1247. (define-scm<-scm-intrinsic string->number)
  1248. (define-scm<-scm-intrinsic string->symbol)
  1249. (define-scm<-scm-intrinsic symbol->keyword)
  1250. (define-scm<-scm-intrinsic class-of)
  1251. (define-f64<-scm-intrinsic scm->f64)
  1252. (define-u64<-scm-intrinsic scm->u64)
  1253. (define-u64<-scm-intrinsic scm->u64/truncate)
  1254. (define-s64<-scm-intrinsic scm->s64)
  1255. (define-scm<-u64-intrinsic u64->scm)
  1256. (define-scm<-s64-intrinsic s64->scm)
  1257. (define-thread-scm-scm-intrinsic wind)
  1258. (define-thread-intrinsic unwind)
  1259. (define-thread-scm-scm-intrinsic push-fluid)
  1260. (define-thread-intrinsic pop-fluid)
  1261. (define-scm<-thread-scm-intrinsic fluid-ref)
  1262. (define-thread-scm-scm-intrinsic fluid-set!)
  1263. (define-thread-scm-intrinsic push-dynamic-state)
  1264. (define-thread-intrinsic pop-dynamic-state)
  1265. (define-scm<-scm-u64-intrinsic lsh)
  1266. (define-scm<-scm-u64-intrinsic rsh)
  1267. (define-scm<-scm-uimm-intrinsic lsh/immediate)
  1268. (define-scm<-scm-uimm-intrinsic rsh/immediate)
  1269. (define-scm<-scm-bool-intrinsic resolve-module)
  1270. (define-scm<-scm-scm-intrinsic lookup)
  1271. (define-scm<-scm-scm-intrinsic define!)
  1272. (define-scm<-thread-intrinsic current-module)
  1273. (define-macro-assembler (begin-program asm label properties)
  1274. (emit-label asm label)
  1275. (let ((meta (make-meta label properties (asm-start asm))))
  1276. (set-asm-meta! asm (cons meta (asm-meta asm))))
  1277. (emit-instrument-entry* asm))
  1278. (define-macro-assembler (end-program asm)
  1279. (let ((meta (car (asm-meta asm))))
  1280. (set-meta-high-pc! meta (asm-start asm))
  1281. (set-meta-arities! meta (reverse (meta-arities meta)))
  1282. (set-asm-constants!
  1283. asm
  1284. (vhash-cons (make-jit-data (meta-low-pc meta) (meta-high-pc meta))
  1285. (meta-jit-data-label meta)
  1286. (asm-constants asm)))))
  1287. (define-macro-assembler (begin-standard-arity asm req nlocals alternate)
  1288. (emit-begin-opt-arity asm req '() #f nlocals alternate))
  1289. (define-macro-assembler (begin-opt-arity asm req opt rest nlocals alternate)
  1290. (emit-begin-kw-arity asm req opt rest '() #f nlocals alternate))
  1291. (define-macro-assembler (begin-kw-arity asm req opt rest kw-indices
  1292. allow-other-keys? nlocals alternate)
  1293. (assert-match req ((? symbol?) ...) "list of symbols")
  1294. (assert-match opt ((? symbol?) ...) "list of symbols")
  1295. (assert-match rest (or #f (? symbol?)) "#f or symbol")
  1296. (assert-match kw-indices (((? keyword?) . (? integer?)) ...)
  1297. "alist of keyword -> integer")
  1298. (assert-match allow-other-keys? (? boolean?) "boolean")
  1299. (assert-match nlocals (? integer?) "integer")
  1300. (assert-match alternate (or #f (? exact-integer?) (? symbol?)) "#f or symbol")
  1301. (let* ((meta (car (asm-meta asm)))
  1302. (arity (make-arity req opt rest kw-indices allow-other-keys?
  1303. ;; Include the initial instrument-entry in
  1304. ;; the first arity.
  1305. (if (null? (meta-arities meta))
  1306. (meta-low-pc meta)
  1307. (asm-start asm))
  1308. #f '()))
  1309. ;; The procedure itself is in slot 0, in the standard calling
  1310. ;; convention. For procedure prologues, nreq includes the
  1311. ;; procedure, so here we add 1.
  1312. (nreq (1+ (length req)))
  1313. (nopt (length opt))
  1314. (rest? (->bool rest)))
  1315. (set-meta-arities! meta (cons arity (meta-arities meta)))
  1316. (cond
  1317. ((or allow-other-keys? (pair? kw-indices))
  1318. (emit-kw-prelude asm nreq nopt rest? kw-indices allow-other-keys?
  1319. nlocals alternate))
  1320. ((or rest? (pair? opt))
  1321. (emit-opt-prelude asm nreq nopt rest? nlocals alternate))
  1322. (else
  1323. (emit-standard-prelude asm nreq nlocals alternate)))))
  1324. (define-macro-assembler (end-arity asm)
  1325. (let ((arity (car (meta-arities (car (asm-meta asm))))))
  1326. (set-arity-definitions! arity (reverse (arity-definitions arity)))
  1327. (set-arity-high-pc! arity (asm-start asm))))
  1328. (define-macro-assembler (standard-prelude asm nreq nlocals alternate)
  1329. (cond
  1330. (alternate
  1331. (emit-arguments<=? asm nreq)
  1332. (emit-jne asm alternate)
  1333. (emit-alloc-frame asm nlocals))
  1334. ((and (< nreq (ash 1 12)) (< (- nlocals nreq) (ash 1 12)))
  1335. (emit-assert-nargs-ee/locals asm nreq (- nlocals nreq)))
  1336. (else
  1337. (emit-assert-nargs-ee asm nreq)
  1338. (emit-alloc-frame asm nlocals))))
  1339. (define-macro-assembler (opt-prelude asm nreq nopt rest? nlocals alternate)
  1340. (if alternate
  1341. (begin
  1342. (emit-arguments<=? asm nreq)
  1343. (emit-jl asm alternate))
  1344. (emit-assert-nargs-ge asm nreq))
  1345. (cond
  1346. (rest?
  1347. (emit-bind-rest asm (+ nreq nopt)))
  1348. (alternate
  1349. (emit-arguments<=? asm (+ nreq nopt))
  1350. ;; The arguments<=? instruction sets NONE to indicate greater-than,
  1351. ;; whereas for <, NONE usually indicates greater-than-or-equal,
  1352. ;; hence the name jge. Perhaps we just need to rename jge to
  1353. ;; br-if-none.
  1354. (emit-jge asm alternate))
  1355. (else
  1356. (emit-assert-nargs-le asm (+ nreq nopt))))
  1357. (emit-alloc-frame asm nlocals))
  1358. (define-macro-assembler (kw-prelude asm nreq nopt rest? kw-indices
  1359. allow-other-keys? nlocals alternate)
  1360. (if alternate
  1361. (begin
  1362. (emit-arguments<=? asm nreq)
  1363. (emit-jl asm alternate)
  1364. (unless rest?
  1365. (emit-positional-arguments<=? asm nreq (+ nreq nopt))
  1366. (emit-jge asm alternate)))
  1367. (emit-assert-nargs-ge asm nreq))
  1368. (let ((ntotal (fold (lambda (kw ntotal)
  1369. (match kw
  1370. (((? keyword?) . idx)
  1371. (max (1+ idx) ntotal))))
  1372. (+ nreq nopt) kw-indices)))
  1373. ;; FIXME: port 581f410f
  1374. (emit-bind-kwargs asm nreq
  1375. (pack-flags allow-other-keys? rest?)
  1376. (+ nreq nopt)
  1377. ntotal
  1378. (intern-constant asm kw-indices))
  1379. (emit-alloc-frame asm nlocals)))
  1380. (define-macro-assembler (label asm sym)
  1381. (hashq-set! (asm-labels asm) sym (asm-start asm)))
  1382. (define-macro-assembler (source asm source)
  1383. (set-asm-sources! asm (acons (asm-start asm) source (asm-sources asm))))
  1384. (define-macro-assembler (definition asm name slot representation)
  1385. (let* ((arity (car (meta-arities (car (asm-meta asm)))))
  1386. (def (vector name slot representation
  1387. (- (asm-start asm) (arity-low-pc arity)))))
  1388. (set-arity-definitions! arity (cons def (arity-definitions arity)))))
  1389. (define-macro-assembler (cache-ref asm dst key)
  1390. (emit-static-ref asm dst (intern-cache-cell asm key)))
  1391. (define-macro-assembler (cache-set! asm key val)
  1392. (emit-static-set! asm val (intern-cache-cell asm key) 0))
  1393. (define-macro-assembler (slot-map asm proc-slot slot-map)
  1394. (unless (zero? slot-map)
  1395. (set-asm-slot-maps! asm (cons
  1396. (cons* (asm-start asm) proc-slot slot-map)
  1397. (asm-slot-maps asm)))))
  1398. ;;;
  1399. ;;; Helper for linking objects.
  1400. ;;;
  1401. (define (make-object asm name bv relocs labels . kwargs)
  1402. "Make a linker object. This helper handles interning the name in the
  1403. shstrtab, assigning the size, allocating a fresh index, and defining a
  1404. corresponding linker symbol for the start of the section."
  1405. (let ((name-idx (intern-section-name! asm (symbol->string name)))
  1406. (index (asm-next-section-number asm)))
  1407. (set-asm-next-section-number! asm (1+ index))
  1408. (make-linker-object (apply make-elf-section
  1409. #:index index
  1410. #:name name-idx
  1411. #:size (bytevector-length bv)
  1412. kwargs)
  1413. bv relocs
  1414. (cons (make-linker-symbol name 0) labels))))
  1415. ;;;
  1416. ;;; Linking the constant table. This code is somewhat intertwingled
  1417. ;;; with the intern-constant code above, as that procedure also
  1418. ;;; residualizes instructions to initialize constants at load time.
  1419. ;;;
  1420. (define (write-immediate asm buf pos bits)
  1421. (let ((endianness (asm-endianness asm)))
  1422. (case (asm-word-size asm)
  1423. ((4) (bytevector-u32-set! buf pos bits endianness))
  1424. ((8) (bytevector-u64-set! buf pos bits endianness))
  1425. (else (error "bad word size" asm)))))
  1426. (define (write-placeholder asm buf pos)
  1427. (write-immediate asm buf pos (immediate-bits asm #f)))
  1428. (define (emit-init-constants asm)
  1429. "If there is writable data that needs initialization at runtime, emit
  1430. a procedure to do that and return its label. Otherwise return
  1431. @code{#f}."
  1432. (let ((inits (asm-inits asm)))
  1433. (and (not (null? inits))
  1434. (let ((label (gensym "init-constants")))
  1435. (emit-text asm
  1436. `((begin-program ,label ())
  1437. (assert-nargs-ee/locals 1 1)
  1438. ,@(reverse inits)
  1439. (reset-frame 1)
  1440. (load-constant 0 ,*unspecified*)
  1441. (return-values)
  1442. (end-program)))
  1443. label))))
  1444. (define (link-data asm data name)
  1445. "Link the static data for a program into the @var{name} section (which
  1446. should be .data or .rodata), and return the resulting linker object.
  1447. @var{data} should be a vhash mapping objects to labels."
  1448. (define (align address alignment)
  1449. (+ address
  1450. (modulo (- alignment (modulo address alignment)) alignment)))
  1451. (define tc7-vector #x0d)
  1452. (define vector-immutable-flag #x80)
  1453. (define tc7-string #x15)
  1454. (define string-read-only-flag #x200)
  1455. (define tc7-stringbuf #x27)
  1456. (define stringbuf-wide-flag #x400)
  1457. (define tc7-syntax #x3d)
  1458. (define tc7-program #x45)
  1459. (define tc7-bytevector #x4d)
  1460. ;; This flag is intended to be left-shifted by 7 bits.
  1461. (define bytevector-immutable-flag #x200)
  1462. (define tc7-array #x5d)
  1463. (define tc7-bitvector #x5f)
  1464. (define bitvector-immutable-flag #x80)
  1465. (let ((word-size (asm-word-size asm))
  1466. (endianness (asm-endianness asm)))
  1467. (define (byte-length x)
  1468. (cond
  1469. ((stringbuf? x)
  1470. (let ((x (stringbuf-string x)))
  1471. (+ (* 2 word-size)
  1472. (case (string-bytes-per-char x)
  1473. ((1) (1+ (string-length x)))
  1474. ((4) (* (1+ (string-length x)) 4))
  1475. (else (error "bad string bytes per char" x))))))
  1476. ((static-procedure? x)
  1477. (* 2 word-size))
  1478. ((string? x)
  1479. (* 4 word-size))
  1480. ((pair? x)
  1481. (* 2 word-size))
  1482. ((simple-vector? x)
  1483. (* (1+ (vector-length x)) word-size))
  1484. ((syntax? x)
  1485. (* 4 word-size))
  1486. ((jit-data? x)
  1487. (case word-size
  1488. ((4) (+ word-size (* 4 3)))
  1489. ((8) (+ word-size (* 4 4))) ;; One additional uint32_t for padding.
  1490. (else (error word-size))))
  1491. ((simple-uniform-vector? x)
  1492. (* 4 word-size))
  1493. ((uniform-vector-backing-store? x)
  1494. (bytevector-length (uniform-vector-backing-store-bytes x)))
  1495. ((array? x)
  1496. (* word-size (+ 3 (* 3 (array-rank x)))))
  1497. (else
  1498. word-size)))
  1499. (define (write-constant-reference buf pos x)
  1500. (let ((bits (immediate-bits asm x)))
  1501. (if bits
  1502. (write-immediate asm buf pos bits)
  1503. ;; The asm-inits will fix up any reference to a
  1504. ;; non-immediate.
  1505. (write-placeholder asm buf pos))))
  1506. (define (write buf pos obj)
  1507. (cond
  1508. ((stringbuf? obj)
  1509. (let* ((x (stringbuf-string obj))
  1510. (len (string-length x))
  1511. (tag (logior tc7-stringbuf
  1512. (if (= (string-bytes-per-char x) 1)
  1513. 0
  1514. stringbuf-wide-flag))))
  1515. (case word-size
  1516. ((4)
  1517. (bytevector-u32-set! buf pos tag endianness)
  1518. (bytevector-u32-set! buf (+ pos 4) len endianness))
  1519. ((8)
  1520. (bytevector-u64-set! buf pos tag endianness)
  1521. (bytevector-u64-set! buf (+ pos 8) len endianness))
  1522. (else
  1523. (error "bad word size" asm)))
  1524. (let ((pos (+ pos (* word-size 2))))
  1525. (case (string-bytes-per-char x)
  1526. ((1)
  1527. (let lp ((i 0))
  1528. (if (< i len)
  1529. (let ((u8 (char->integer (string-ref x i))))
  1530. (bytevector-u8-set! buf (+ pos i) u8)
  1531. (lp (1+ i)))
  1532. (bytevector-u8-set! buf (+ pos i) 0))))
  1533. ((4)
  1534. (let lp ((i 0))
  1535. (if (< i len)
  1536. (let ((u32 (char->integer (string-ref x i))))
  1537. (bytevector-u32-set! buf (+ pos (* i 4)) u32 endianness)
  1538. (lp (1+ i)))
  1539. (bytevector-u32-set! buf (+ pos (* i 4)) 0 endianness))))
  1540. (else (error "bad string bytes per char" x))))))
  1541. ((static-procedure? obj)
  1542. (case word-size
  1543. ((4)
  1544. (bytevector-u32-set! buf pos tc7-program endianness)
  1545. (bytevector-u32-set! buf (+ pos 4) 0 endianness))
  1546. ((8)
  1547. (bytevector-u64-set! buf pos tc7-program endianness)
  1548. (bytevector-u64-set! buf (+ pos 8) 0 endianness))
  1549. (else (error "bad word size"))))
  1550. ((cache-cell? obj)
  1551. (write-placeholder asm buf pos))
  1552. ((jit-data? obj)
  1553. ;; Default initialization of 0.
  1554. (values))
  1555. ((string? obj)
  1556. (let ((tag (logior tc7-string string-read-only-flag)))
  1557. (case word-size
  1558. ((4)
  1559. (bytevector-u32-set! buf pos tag endianness)
  1560. (write-placeholder asm buf (+ pos 4)) ; stringbuf
  1561. (bytevector-u32-set! buf (+ pos 8) 0 endianness)
  1562. (bytevector-u32-set! buf (+ pos 12) (string-length obj) endianness))
  1563. ((8)
  1564. (bytevector-u64-set! buf pos tag endianness)
  1565. (write-placeholder asm buf (+ pos 8)) ; stringbuf
  1566. (bytevector-u64-set! buf (+ pos 16) 0 endianness)
  1567. (bytevector-u64-set! buf (+ pos 24) (string-length obj) endianness))
  1568. (else (error "bad word size")))))
  1569. ((pair? obj)
  1570. (write-constant-reference buf pos (car obj))
  1571. (write-constant-reference buf (+ pos word-size) (cdr obj)))
  1572. ((simple-vector? obj)
  1573. (let* ((len (vector-length obj))
  1574. (tag (logior tc7-vector vector-immutable-flag (ash len 8))))
  1575. (case word-size
  1576. ((4) (bytevector-u32-set! buf pos tag endianness))
  1577. ((8) (bytevector-u64-set! buf pos tag endianness))
  1578. (else (error "bad word size")))
  1579. (let lp ((i 0))
  1580. (when (< i (vector-length obj))
  1581. (let ((pos (+ pos word-size (* i word-size)))
  1582. (elt (vector-ref obj i)))
  1583. (write-constant-reference buf pos elt)
  1584. (lp (1+ i)))))))
  1585. ((symbol? obj)
  1586. (write-placeholder asm buf pos))
  1587. ((keyword? obj)
  1588. (write-placeholder asm buf pos))
  1589. ((syntax? obj)
  1590. (case word-size
  1591. ((4) (bytevector-u32-set! buf pos tc7-syntax endianness))
  1592. ((8) (bytevector-u64-set! buf pos tc7-syntax endianness))
  1593. (else (error "bad word size")))
  1594. (write-constant-reference buf (+ pos (* 1 word-size))
  1595. (syntax-expression obj))
  1596. (write-constant-reference buf (+ pos (* 2 word-size))
  1597. (syntax-wrap obj))
  1598. (write-constant-reference buf (+ pos (* 3 word-size))
  1599. (syntax-module obj)))
  1600. ((number? obj)
  1601. (write-placeholder asm buf pos))
  1602. ((simple-uniform-vector? obj)
  1603. (let ((tag (if (bitvector? obj)
  1604. (logior tc7-bitvector
  1605. bitvector-immutable-flag)
  1606. (logior tc7-bytevector
  1607. ;; Bytevector immutable flag also shifted
  1608. ;; left.
  1609. (ash (logior bytevector-immutable-flag
  1610. (array-type-code obj))
  1611. 7)))))
  1612. (case word-size
  1613. ((4)
  1614. (bytevector-u32-set! buf pos tag endianness)
  1615. (bytevector-u32-set! buf (+ pos 4)
  1616. (if (bitvector? obj)
  1617. (bitvector-length obj)
  1618. (bytevector-length obj))
  1619. endianness) ; length
  1620. (bytevector-u32-set! buf (+ pos 8) 0 endianness) ; pointer
  1621. (write-placeholder asm buf (+ pos 12))) ; owner
  1622. ((8)
  1623. (bytevector-u64-set! buf pos tag endianness)
  1624. (bytevector-u64-set! buf (+ pos 8)
  1625. (if (bitvector? obj)
  1626. (bitvector-length obj)
  1627. (bytevector-length obj))
  1628. endianness) ; length
  1629. (bytevector-u64-set! buf (+ pos 16) 0 endianness) ; pointer
  1630. (write-placeholder asm buf (+ pos 24))) ; owner
  1631. (else (error "bad word size")))))
  1632. ((uniform-vector-backing-store? obj)
  1633. (let ((bv (uniform-vector-backing-store-bytes obj)))
  1634. (bytevector-copy! bv 0 buf pos (bytevector-length bv))
  1635. (unless (eq? endianness (native-endianness))
  1636. (case (uniform-vector-backing-store-element-size obj)
  1637. ((1) #f) ;; Nothing to do.
  1638. ((2) (byte-swap/2! buf pos (+ pos (bytevector-length bv))))
  1639. ((4) (byte-swap/4! buf pos (+ pos (bytevector-length bv))))
  1640. ((8) (byte-swap/8! buf pos (+ pos (bytevector-length bv))))
  1641. (else (error "FIXME: Implement byte order swap"))))))
  1642. ((array? obj)
  1643. (let-values
  1644. ;; array tag + rank + contp flag: see libguile/arrays.h .
  1645. (((tag) (logior tc7-array (ash (array-rank obj) 17) (ash 1 16)))
  1646. ((bv-set! bvs-set!)
  1647. (case word-size
  1648. ((4) (values bytevector-u32-set! bytevector-s32-set!))
  1649. ((8) (values bytevector-u64-set! bytevector-s64-set!))
  1650. (else (error "bad word size")))))
  1651. (bv-set! buf pos tag endianness)
  1652. (write-placeholder asm buf (+ pos word-size)) ; root vector (fixed later)
  1653. (bv-set! buf (+ pos (* word-size 2)) 0 endianness) ; base
  1654. (let lp ((pos (+ pos (* word-size 3)))
  1655. (bounds (array-shape obj))
  1656. (incs (shared-array-increments obj)))
  1657. (when (pair? bounds)
  1658. (bvs-set! buf pos (first (first bounds)) endianness)
  1659. (bvs-set! buf (+ pos word-size) (second (first bounds)) endianness)
  1660. (bvs-set! buf (+ pos (* word-size 2)) (first incs) endianness)
  1661. (lp (+ pos (* 3 word-size)) (cdr bounds) (cdr incs))))))
  1662. (else
  1663. (error "unrecognized object" obj))))
  1664. (define (add-relocs obj pos relocs)
  1665. (match obj
  1666. (($ <jit-data> low-pc high-pc)
  1667. ;; Patch "start" and "end" fields of "struct jit_data".
  1668. (cons* (make-linker-reloc 'rel32/1 (+ pos word-size 4)
  1669. (+ low-pc word-size 4)
  1670. '.rtl-text)
  1671. (make-linker-reloc 'rel32/1 (+ pos word-size 8)
  1672. (+ high-pc word-size 8)
  1673. '.rtl-text)
  1674. relocs))
  1675. (_ relocs)))
  1676. (cond
  1677. ((vlist-null? data) #f)
  1678. (else
  1679. (let* ((byte-len (vhash-fold (lambda (k v len)
  1680. (+ (byte-length k) (align len 8)))
  1681. 0 data))
  1682. (buf (make-bytevector byte-len 0)))
  1683. (let lp ((i 0) (pos 0) (relocs '()) (symbols '()))
  1684. (if (< i (vlist-length data))
  1685. (match (vlist-ref data i)
  1686. ((obj . obj-label)
  1687. (write buf pos obj)
  1688. (lp (1+ i)
  1689. (align (+ (byte-length obj) pos) 8)
  1690. (add-relocs obj pos relocs)
  1691. (cons (make-linker-symbol obj-label pos) symbols))))
  1692. (make-object asm name buf relocs symbols
  1693. #:flags (match name
  1694. ('.data (logior SHF_ALLOC SHF_WRITE))
  1695. ('.rodata SHF_ALLOC))))))))))
  1696. (define (link-constants asm)
  1697. "Link sections to hold constants needed by the program text emitted
  1698. using @var{asm}.
  1699. Returns three values: an object for the .rodata section, an object for
  1700. the .data section, and a label for an initialization procedure. Any of
  1701. these may be @code{#f}."
  1702. (define (shareable? x)
  1703. (cond
  1704. ((stringbuf? x) #t)
  1705. ((pair? x)
  1706. (and (immediate-bits asm (car x)) (immediate-bits asm (cdr x))))
  1707. ((simple-vector? x)
  1708. (let lp ((i 0))
  1709. (or (= i (vector-length x))
  1710. (and (immediate-bits asm (vector-ref x i))
  1711. (lp (1+ i))))))
  1712. ((uniform-vector-backing-store? x) #t)
  1713. (else #f)))
  1714. (let* ((init-constants (emit-init-constants asm))
  1715. (constants (asm-constants asm))
  1716. (len (vlist-length constants)))
  1717. (let lp ((i 0)
  1718. (ro vlist-null)
  1719. (rw vlist-null))
  1720. (if (= i len)
  1721. (values (link-data asm ro '.rodata)
  1722. (link-data asm rw '.data)
  1723. init-constants)
  1724. (match (vlist-ref constants i)
  1725. ((obj . label)
  1726. (if (shareable? obj)
  1727. (lp (1+ i) (vhash-consq obj label ro) rw)
  1728. (lp (1+ i) ro (vhash-consq obj label rw)))))))))
  1729. ;;;
  1730. ;;; Linking program text.
  1731. ;;;
  1732. (define (process-relocs buf relocs labels)
  1733. "Patch up internal x8-s24 relocations, and any s32 relocations that
  1734. reference symbols in the text section. Return a list of linker
  1735. relocations for references to symbols defined outside the text section."
  1736. (fold
  1737. (lambda (reloc tail)
  1738. (match reloc
  1739. ((type label base offset)
  1740. (let ((abs (hashq-ref labels label))
  1741. (dst (+ base offset)))
  1742. (case type
  1743. ((s32)
  1744. (if abs
  1745. (let ((rel (- abs base)))
  1746. (unless (zero? (logand rel #x3))
  1747. (error "reloc not in 32-bit units!"))
  1748. (bytevector-s32-native-set! buf dst (ash rel -2))
  1749. tail)
  1750. (cons (make-linker-reloc 'rel32/4 dst offset label)
  1751. tail)))
  1752. ((x8-s24)
  1753. (unless abs
  1754. (error "unbound near relocation" reloc))
  1755. (let ((rel (- abs base))
  1756. (u32 (bytevector-u32-native-ref buf dst)))
  1757. (unless (zero? (logand rel #x3))
  1758. (error "reloc not in 32-bit units!"))
  1759. (bytevector-u32-native-set! buf dst
  1760. (pack-u8-s24 (logand u32 #xff)
  1761. (ash rel -2)))
  1762. tail))
  1763. (else (error "bad relocation kind" reloc)))))))
  1764. '()
  1765. relocs))
  1766. (define (process-labels labels)
  1767. "Define linker symbols for the label-offset map in @var{labels}.
  1768. The offsets are expected to be expressed in words."
  1769. (hash-map->list (lambda (label loc)
  1770. (make-linker-symbol label loc))
  1771. labels))
  1772. (define (link-text-object asm)
  1773. "Link the .rtl-text section, swapping the endianness of the bytes if
  1774. needed."
  1775. (let ((buf (make-bytevector (asm-pos asm))))
  1776. (bytevector-copy! (asm-buf asm) 0 buf 0 (bytevector-length buf))
  1777. (unless (eq? (asm-endianness asm) (native-endianness))
  1778. (byte-swap/4! buf))
  1779. (make-object asm '.rtl-text
  1780. buf
  1781. (process-relocs buf (asm-relocs asm)
  1782. (asm-labels asm))
  1783. (process-labels (asm-labels asm)))))
  1784. ;;;
  1785. ;;; Create the frame maps. These maps are used by GC to identify dead
  1786. ;;; slots in pending call frames, to avoid marking them. We only do
  1787. ;;; this when frame makes a non-tail call, as that is the common case.
  1788. ;;; Only the topmost frame will see a GC at any other point, but we mark
  1789. ;;; top frames conservatively as serializing live slot maps at every
  1790. ;;; instruction would take up too much space in the object file.
  1791. ;;;
  1792. ;; The .guile.frame-maps section starts with two packed u32 values: one
  1793. ;; indicating the offset of the first byte of the .rtl-text section, and
  1794. ;; another indicating the relative offset in bytes of the slots data.
  1795. (define frame-maps-prefix-len 8)
  1796. ;; Each header is 8 bytes: 4 for the offset from .rtl_text, and 4 for
  1797. ;; the offset of the slot map from the beginning of the
  1798. ;; .guile.frame-maps section. The length of a frame map depends on the
  1799. ;; frame size at the call site, and is not encoded into this section as
  1800. ;; it is available at run-time.
  1801. (define frame-map-header-len 8)
  1802. (define (link-frame-maps asm)
  1803. (define (map-byte-length proc-slot)
  1804. (ceiling-quotient (* 2 (- proc-slot 2)) 8))
  1805. (define (make-frame-maps maps count map-len)
  1806. (let* ((endianness (asm-endianness asm))
  1807. (header-pos frame-maps-prefix-len)
  1808. (map-pos (+ header-pos (* count frame-map-header-len)))
  1809. (bv (make-bytevector (+ map-pos map-len) 0)))
  1810. (bytevector-u32-set! bv 4 map-pos endianness)
  1811. (let lp ((maps maps) (header-pos header-pos) (map-pos map-pos))
  1812. (match maps
  1813. (()
  1814. (make-object asm '.guile.frame-maps bv
  1815. (list (make-linker-reloc 'abs32/1 0 0 '.rtl-text))
  1816. '() #:type SHT_PROGBITS #:flags SHF_ALLOC))
  1817. (((pos proc-slot . map) . maps)
  1818. (bytevector-u32-set! bv header-pos pos endianness)
  1819. (bytevector-u32-set! bv (+ header-pos 4) map-pos endianness)
  1820. (let write-bytes ((map-pos map-pos)
  1821. (map map)
  1822. (byte-length (map-byte-length proc-slot)))
  1823. (if (zero? byte-length)
  1824. (lp maps (+ header-pos frame-map-header-len) map-pos)
  1825. (begin
  1826. (bytevector-u8-set! bv map-pos (logand map #xff))
  1827. (write-bytes (1+ map-pos) (ash map -8)
  1828. (1- byte-length))))))))))
  1829. (match (asm-slot-maps asm)
  1830. (() #f)
  1831. (in
  1832. (let lp ((in in) (out '()) (count 0) (map-len 0))
  1833. (match in
  1834. (() (make-frame-maps out count map-len))
  1835. (((and head (pos proc-slot . map)) . in)
  1836. (lp in (cons head out)
  1837. (1+ count)
  1838. (+ (map-byte-length proc-slot) map-len))))))))
  1839. ;;;
  1840. ;;; Linking other sections of the ELF file, like the dynamic segment,
  1841. ;;; the symbol table, etc.
  1842. ;;;
  1843. ;; FIXME: Define these somewhere central, shared with C.
  1844. (define *bytecode-major-version* #x0300)
  1845. (define *bytecode-minor-version* 0)
  1846. (define (link-dynamic-section asm text rw rw-init frame-maps)
  1847. "Link the dynamic section for an ELF image with bytecode @var{text},
  1848. given the writable data section @var{rw} needing fixup from the
  1849. procedure with label @var{rw-init}. @var{rw-init} may be false. If
  1850. @var{rw} is true, it will be added to the GC roots at runtime."
  1851. (define-syntax-rule (emit-dynamic-section word-size %set-uword! reloc-type)
  1852. (let* ((endianness (asm-endianness asm))
  1853. (words 6)
  1854. (words (if rw (+ words 4) words))
  1855. (words (if rw-init (+ words 2) words))
  1856. (words (if frame-maps (+ words 2) words))
  1857. (bv (make-bytevector (* word-size words) 0))
  1858. (set-uword!
  1859. (lambda (i uword)
  1860. (%set-uword! bv (* i word-size) uword endianness)))
  1861. (relocs '())
  1862. (set-label!
  1863. (lambda (i label)
  1864. (set! relocs (cons (make-linker-reloc 'reloc-type
  1865. (* i word-size) 0 label)
  1866. relocs))
  1867. (%set-uword! bv (* i word-size) 0 endianness))))
  1868. (set-uword! 0 DT_GUILE_VM_VERSION)
  1869. (set-uword! 1 (logior (ash *bytecode-major-version* 16)
  1870. *bytecode-minor-version*))
  1871. (set-uword! 2 DT_GUILE_ENTRY)
  1872. (set-label! 3 '.rtl-text)
  1873. (when rw
  1874. ;; Add roots to GC.
  1875. (set-uword! 4 DT_GUILE_GC_ROOT)
  1876. (set-label! 5 '.data)
  1877. (set-uword! 6 DT_GUILE_GC_ROOT_SZ)
  1878. (set-uword! 7 (bytevector-length (linker-object-bv rw)))
  1879. (when rw-init
  1880. (set-uword! 8 DT_INIT) ; constants
  1881. (set-label! 9 rw-init)))
  1882. (when frame-maps
  1883. (set-uword! (- words 4) DT_GUILE_FRAME_MAPS)
  1884. (set-label! (- words 3) '.guile.frame-maps))
  1885. (set-uword! (- words 2) DT_NULL)
  1886. (set-uword! (- words 1) 0)
  1887. (make-object asm '.dynamic bv relocs '()
  1888. #:type SHT_DYNAMIC #:flags SHF_ALLOC)))
  1889. (case (asm-word-size asm)
  1890. ((4) (emit-dynamic-section 4 bytevector-u32-set! abs32/1))
  1891. ((8) (emit-dynamic-section 8 bytevector-u64-set! abs64/1))
  1892. (else (error "bad word size" asm))))
  1893. (define (link-shstrtab asm)
  1894. "Link the string table for the section headers."
  1895. (intern-section-name! asm ".shstrtab")
  1896. (make-object asm '.shstrtab
  1897. (link-string-table! (asm-shstrtab asm))
  1898. '() '()
  1899. #:type SHT_STRTAB #:flags 0))
  1900. (define (link-symtab text-section asm)
  1901. (let* ((endianness (asm-endianness asm))
  1902. (word-size (asm-word-size asm))
  1903. (size (elf-symbol-len word-size))
  1904. (meta (reverse (asm-meta asm)))
  1905. (n (length meta))
  1906. (strtab (make-string-table))
  1907. (bv (make-bytevector (* n size) 0)))
  1908. (define (intern-string! name)
  1909. (string-table-intern! strtab (if name (symbol->string name) "")))
  1910. (for-each
  1911. (lambda (meta n)
  1912. (let ((name (intern-string! (meta-name meta))))
  1913. (write-elf-symbol bv (* n size) endianness word-size
  1914. (make-elf-symbol
  1915. #:name name
  1916. ;; Symbol value and size are measured in
  1917. ;; bytes, not u32s.
  1918. #:value (meta-low-pc meta)
  1919. #:size (- (meta-high-pc meta)
  1920. (meta-low-pc meta))
  1921. #:type STT_FUNC
  1922. #:visibility STV_HIDDEN
  1923. #:shndx (elf-section-index text-section)))))
  1924. meta (iota n))
  1925. (let ((strtab (make-object asm '.strtab
  1926. (link-string-table! strtab)
  1927. '() '()
  1928. #:type SHT_STRTAB #:flags 0)))
  1929. (values (make-object asm '.symtab
  1930. bv
  1931. '() '()
  1932. #:type SHT_SYMTAB #:flags 0 #:entsize size
  1933. #:link (elf-section-index
  1934. (linker-object-section strtab)))
  1935. strtab))))
  1936. ;;; The .guile.arities section describes the arities that a function can
  1937. ;;; have. It is in two parts: a sorted array of headers describing
  1938. ;;; basic arities, and an array of links out to a string table (and in
  1939. ;;; the case of keyword arguments, to the data section) for argument
  1940. ;;; names. The whole thing is prefixed by a uint32 indicating the
  1941. ;;; offset of the end of the headers array.
  1942. ;;;
  1943. ;;; The arity headers array is a packed array of structures of the form:
  1944. ;;;
  1945. ;;; struct arity_header {
  1946. ;;; uint32_t low_pc;
  1947. ;;; uint32_t high_pc;
  1948. ;;; uint32_t offset;
  1949. ;;; uint32_t flags;
  1950. ;;; uint32_t nreq;
  1951. ;;; uint32_t nopt;
  1952. ;;; uint32_t nlocals;
  1953. ;;; }
  1954. ;;;
  1955. ;;; All of the offsets and addresses are 32 bits. We can expand in the
  1956. ;;; future to use 64-bit offsets if appropriate, but there are other
  1957. ;;; aspects of bytecode that constrain us to a total image that fits in
  1958. ;;; 32 bits, so for the moment we'll simplify the problem space.
  1959. ;;;
  1960. ;;; The following flags values are defined:
  1961. ;;;
  1962. ;;; #x1: has-rest?
  1963. ;;; #x2: allow-other-keys?
  1964. ;;; #x4: has-keyword-args?
  1965. ;;; #x8: is-case-lambda?
  1966. ;;; #x10: is-in-case-lambda?
  1967. ;;;
  1968. ;;; Functions with a single arity specify their number of required and
  1969. ;;; optional arguments in nreq and nopt, and do not have the
  1970. ;;; is-case-lambda? flag set. Their "offset" member links to an array
  1971. ;;; of pointers into the associated .guile.arities.strtab string table,
  1972. ;;; identifying the argument names. This offset is relative to the
  1973. ;;; start of the .guile.arities section.
  1974. ;;;
  1975. ;;; If the arity has keyword arguments -- if has-keyword-args? is set in
  1976. ;;; the flags -- the first uint32 pointed to by offset encodes a link to
  1977. ;;; the "keyword indices" literal, in the data section. Then follow the
  1978. ;;; names for all locals, in order, as uleb128 values. The required
  1979. ;;; arguments will be the first locals, followed by the optionals,
  1980. ;;; followed by the rest argument if if has-rest? is set. The names
  1981. ;;; point into the associated string table section.
  1982. ;;;
  1983. ;;; Functions with no arities have no arities information present in the
  1984. ;;; .guile.arities section.
  1985. ;;;
  1986. ;;; Functions with multiple arities are preceded by a header with
  1987. ;;; is-case-lambda? set. All other fields are 0, except low-pc and
  1988. ;;; high-pc which should be the bounds of the whole function. Headers
  1989. ;;; for the individual arities follow, with the is-in-case-lambda? flag
  1990. ;;; set. In this way the whole headers array is sorted in increasing
  1991. ;;; low-pc order, and case-lambda clauses are contained within the
  1992. ;;; [low-pc, high-pc] of the case-lambda header.
  1993. ;; Length of the prefix to the arities section, in bytes.
  1994. (define arities-prefix-len 4)
  1995. ;; Length of an arity header, in bytes.
  1996. (define arity-header-len (* 7 4))
  1997. ;; Some helpers.
  1998. (define (put-uleb128 port val)
  1999. (let lp ((val val))
  2000. (let ((next (ash val -7)))
  2001. (if (zero? next)
  2002. (put-u8 port val)
  2003. (begin
  2004. (put-u8 port (logior #x80 (logand val #x7f)))
  2005. (lp next))))))
  2006. (define (put-sleb128 port val)
  2007. (let lp ((val val))
  2008. (if (<= 0 (+ val 64) 127)
  2009. (put-u8 port (logand val #x7f))
  2010. (begin
  2011. (put-u8 port (logior #x80 (logand val #x7f)))
  2012. (lp (ash val -7))))))
  2013. (define (port-position port)
  2014. (seek port 0 SEEK_CUR))
  2015. (define-inline (pack-arity-flags has-rest? allow-other-keys?
  2016. has-keyword-args? is-case-lambda?
  2017. is-in-case-lambda?)
  2018. (logior (if has-rest? (ash 1 0) 0)
  2019. (if allow-other-keys? (ash 1 1) 0)
  2020. (if has-keyword-args? (ash 1 2) 0)
  2021. (if is-case-lambda? (ash 1 3) 0)
  2022. (if is-in-case-lambda? (ash 1 4) 0)))
  2023. (define (write-arities asm metas headers names-port strtab)
  2024. (define (write-header pos low-pc high-pc offset flags nreq nopt nlocals)
  2025. (unless (<= (+ nreq nopt) nlocals)
  2026. (error "forgot to emit definition instructions?"))
  2027. (bytevector-u32-set! headers pos low-pc (asm-endianness asm))
  2028. (bytevector-u32-set! headers (+ pos 4) high-pc (asm-endianness asm))
  2029. (bytevector-u32-set! headers (+ pos 8) offset (asm-endianness asm))
  2030. (bytevector-u32-set! headers (+ pos 12) flags (asm-endianness asm))
  2031. (bytevector-u32-set! headers (+ pos 16) nreq (asm-endianness asm))
  2032. (bytevector-u32-set! headers (+ pos 20) nopt (asm-endianness asm))
  2033. (bytevector-u32-set! headers (+ pos 24) nlocals (asm-endianness asm)))
  2034. (define (write-kw-indices kw-indices relocs)
  2035. ;; FIXME: Assert that kw-indices is already interned.
  2036. (if (pair? kw-indices)
  2037. (let ((pos (+ (bytevector-length headers)
  2038. (port-position names-port)))
  2039. (label (intern-constant asm kw-indices)))
  2040. (put-bytevector names-port #vu8(0 0 0 0))
  2041. (cons (make-linker-reloc 'abs32/1 pos 0 label) relocs))
  2042. relocs))
  2043. (define (write-arity pos arity in-case-lambda? relocs)
  2044. (write-header pos (arity-low-pc arity)
  2045. (arity-high-pc arity)
  2046. ;; FIXME: Seems silly to add on bytevector-length of
  2047. ;; headers, given the arities-prefix.
  2048. (+ (bytevector-length headers) (port-position names-port))
  2049. (pack-arity-flags (arity-rest arity)
  2050. (arity-allow-other-keys? arity)
  2051. (pair? (arity-kw-indices arity))
  2052. #f
  2053. in-case-lambda?)
  2054. (length (arity-req arity))
  2055. (length (arity-opt arity))
  2056. (length (arity-definitions arity)))
  2057. (let ((relocs (write-kw-indices (arity-kw-indices arity) relocs)))
  2058. ;; Write local names.
  2059. (let lp ((definitions (arity-definitions arity)))
  2060. (match definitions
  2061. (() relocs)
  2062. ((#(name slot representation def) . definitions)
  2063. (let ((sym (if (symbol? name)
  2064. (string-table-intern! strtab (symbol->string name))
  2065. 0)))
  2066. (put-uleb128 names-port sym)
  2067. (lp definitions)))))
  2068. ;; Now write their definitions.
  2069. (let lp ((definitions (arity-definitions arity)))
  2070. (match definitions
  2071. (() relocs)
  2072. ((#(name slot representation def) . definitions)
  2073. (put-uleb128 names-port def)
  2074. (let ((tag (case representation
  2075. ((scm) 0)
  2076. ((f64) 1)
  2077. ((u64) 2)
  2078. ((s64) 3)
  2079. ((ptr) 4)
  2080. (else (error "what!" representation)))))
  2081. (put-uleb128 names-port (logior (ash slot 3) tag)))
  2082. (lp definitions))))))
  2083. (let lp ((metas metas) (pos arities-prefix-len) (relocs '()))
  2084. (match metas
  2085. (()
  2086. (unless (= pos (bytevector-length headers))
  2087. (error "expected to fully fill the bytevector"
  2088. pos (bytevector-length headers)))
  2089. relocs)
  2090. ((meta . metas)
  2091. (match (meta-arities meta)
  2092. (() (lp metas pos relocs))
  2093. ((arity)
  2094. (lp metas
  2095. (+ pos arity-header-len)
  2096. (write-arity pos arity #f relocs)))
  2097. (arities
  2098. ;; Write a case-lambda header, then individual arities.
  2099. ;; The case-lambda header's offset link is 0.
  2100. (write-header pos (meta-low-pc meta) (meta-high-pc meta) 0
  2101. (pack-arity-flags #f #f #f #t #f) 0 0 0)
  2102. (let lp* ((arities arities) (pos (+ pos arity-header-len))
  2103. (relocs relocs))
  2104. (match arities
  2105. (() (lp metas pos relocs))
  2106. ((arity . arities)
  2107. (lp* arities
  2108. (+ pos arity-header-len)
  2109. (write-arity pos arity #t relocs)))))))))))
  2110. (define (link-arities asm)
  2111. (define (meta-arities-header-size meta)
  2112. (define (lambda-size arity)
  2113. arity-header-len)
  2114. (define (case-lambda-size arities)
  2115. (fold +
  2116. arity-header-len ;; case-lambda header
  2117. (map lambda-size arities))) ;; the cases
  2118. (match (meta-arities meta)
  2119. (() 0)
  2120. ((arity) (lambda-size arity))
  2121. (arities (case-lambda-size arities))))
  2122. (define (bytevector-append a b)
  2123. (let ((out (make-bytevector (+ (bytevector-length a)
  2124. (bytevector-length b)))))
  2125. (bytevector-copy! a 0 out 0 (bytevector-length a))
  2126. (bytevector-copy! b 0 out (bytevector-length a) (bytevector-length b))
  2127. out))
  2128. (let* ((endianness (asm-endianness asm))
  2129. (metas (reverse (asm-meta asm)))
  2130. (header-size (fold (lambda (meta size)
  2131. (+ size (meta-arities-header-size meta)))
  2132. arities-prefix-len
  2133. metas))
  2134. (strtab (make-string-table))
  2135. (headers (make-bytevector header-size 0)))
  2136. (bytevector-u32-set! headers 0 (bytevector-length headers) endianness)
  2137. (let-values (((names-port get-name-bv) (open-bytevector-output-port)))
  2138. (let* ((relocs (write-arities asm metas headers names-port strtab))
  2139. (strtab (make-object asm '.guile.arities.strtab
  2140. (link-string-table! strtab)
  2141. '() '()
  2142. #:type SHT_STRTAB #:flags 0)))
  2143. (values (make-object asm '.guile.arities
  2144. (bytevector-append headers (get-name-bv))
  2145. relocs '()
  2146. #:type SHT_PROGBITS #:flags 0
  2147. #:link (elf-section-index
  2148. (linker-object-section strtab)))
  2149. strtab)))))
  2150. ;;;
  2151. ;;; The .guile.docstrs section is a packed, sorted array of (pc, str)
  2152. ;;; values. Pc and str are both 32 bits wide. (Either could change to
  2153. ;;; 64 bits if appropriate in the future.) Pc is the address of the
  2154. ;;; entry to a program, relative to the start of the text section, in
  2155. ;;; bytes, and str is an index into the associated .guile.docstrs.strtab
  2156. ;;; string table section.
  2157. ;;;
  2158. ;; The size of a docstrs entry, in bytes.
  2159. (define docstr-size 8)
  2160. (define (link-docstrs asm)
  2161. (define (find-docstrings)
  2162. (filter-map (lambda (meta)
  2163. (define (is-documentation? pair)
  2164. (eq? (car pair) 'documentation))
  2165. (let* ((props (meta-properties meta))
  2166. (tail (find-tail is-documentation? props)))
  2167. (and tail
  2168. (not (find-tail is-documentation? (cdr tail)))
  2169. (string? (cdar tail))
  2170. (cons (meta-low-pc meta) (cdar tail)))))
  2171. (reverse (asm-meta asm))))
  2172. (let* ((endianness (asm-endianness asm))
  2173. (docstrings (find-docstrings))
  2174. (strtab (make-string-table))
  2175. (bv (make-bytevector (* (length docstrings) docstr-size) 0)))
  2176. (fold (lambda (pair pos)
  2177. (match pair
  2178. ((pc . string)
  2179. (bytevector-u32-set! bv pos pc endianness)
  2180. (bytevector-u32-set! bv (+ pos 4)
  2181. (string-table-intern! strtab string)
  2182. endianness)
  2183. (+ pos docstr-size))))
  2184. 0
  2185. docstrings)
  2186. (let ((strtab (make-object asm '.guile.docstrs.strtab
  2187. (link-string-table! strtab)
  2188. '() '()
  2189. #:type SHT_STRTAB #:flags 0)))
  2190. (values (make-object asm '.guile.docstrs
  2191. bv
  2192. '() '()
  2193. #:type SHT_PROGBITS #:flags 0
  2194. #:link (elf-section-index
  2195. (linker-object-section strtab)))
  2196. strtab))))
  2197. ;;;
  2198. ;;; The .guile.procprops section is a packed, sorted array of (pc, addr)
  2199. ;;; values. Pc and addr are both 32 bits wide. (Either could change to
  2200. ;;; 64 bits if appropriate in the future.) Pc is the address of the
  2201. ;;; entry to a program, relative to the start of the text section, and
  2202. ;;; addr is the address of the associated properties alist, relative to
  2203. ;;; the start of the ELF image.
  2204. ;;;
  2205. ;;; Since procedure properties are stored in the data sections, we need
  2206. ;;; to link the procedures property section first. (Note that this
  2207. ;;; constraint does not apply to the arities section, which may
  2208. ;;; reference the data sections via the kw-indices literal, because
  2209. ;;; assembling the text section already makes sure that the kw-indices
  2210. ;;; are interned.)
  2211. ;;;
  2212. ;; The size of a procprops entry, in bytes.
  2213. (define procprops-size 8)
  2214. (define (link-procprops asm)
  2215. (define (assoc-remove-one alist key value-pred)
  2216. (match alist
  2217. (() '())
  2218. ((((? (lambda (x) (eq? x key))) . value) . alist)
  2219. (if (value-pred value)
  2220. alist
  2221. (acons key value alist)))
  2222. (((k . v) . alist)
  2223. (acons k v (assoc-remove-one alist key value-pred)))))
  2224. (define (props-without-name-or-docstring meta)
  2225. (assoc-remove-one
  2226. (assoc-remove-one (meta-properties meta) 'name (lambda (x) #t))
  2227. 'documentation
  2228. string?))
  2229. (define (find-procprops)
  2230. (filter-map (lambda (meta)
  2231. (let ((props (props-without-name-or-docstring meta)))
  2232. (and (pair? props)
  2233. (cons (meta-low-pc meta) props))))
  2234. (reverse (asm-meta asm))))
  2235. (let* ((endianness (asm-endianness asm))
  2236. (procprops (find-procprops))
  2237. (bv (make-bytevector (* (length procprops) procprops-size) 0)))
  2238. (let lp ((procprops procprops) (pos 0) (relocs '()))
  2239. (match procprops
  2240. (()
  2241. (make-object asm '.guile.procprops
  2242. bv
  2243. relocs '()
  2244. #:type SHT_PROGBITS #:flags 0))
  2245. (((pc . props) . procprops)
  2246. (bytevector-u32-set! bv pos pc endianness)
  2247. (lp procprops
  2248. (+ pos procprops-size)
  2249. (cons (make-linker-reloc 'abs32/1 (+ pos 4) 0
  2250. (intern-constant asm props))
  2251. relocs)))))))
  2252. ;;;
  2253. ;;; The DWARF .debug_info, .debug_abbrev, .debug_str, and .debug_loc
  2254. ;;; sections provide line number and local variable liveness
  2255. ;;; information. Their format is defined by the DWARF
  2256. ;;; specifications.
  2257. ;;;
  2258. (define (asm-language asm)
  2259. ;; FIXME: Plumb language through to the assembler.
  2260. 'scheme)
  2261. ;; -> 5 values: .debug_info, .debug_abbrev, .debug_str, .debug_loc, .debug_lines
  2262. (define (link-debug asm)
  2263. (define (put-s8 port val)
  2264. (let ((bv (make-bytevector 1)))
  2265. (bytevector-s8-set! bv 0 val)
  2266. (put-bytevector port bv)))
  2267. (define (put-u16 port val)
  2268. (let ((bv (make-bytevector 2)))
  2269. (bytevector-u16-set! bv 0 val (asm-endianness asm))
  2270. (put-bytevector port bv)))
  2271. (define (put-u32 port val)
  2272. (let ((bv (make-bytevector 4)))
  2273. (bytevector-u32-set! bv 0 val (asm-endianness asm))
  2274. (put-bytevector port bv)))
  2275. (define (put-u64 port val)
  2276. (let ((bv (make-bytevector 8)))
  2277. (bytevector-u64-set! bv 0 val (asm-endianness asm))
  2278. (put-bytevector port bv)))
  2279. (define (meta->subprogram-die meta)
  2280. `(subprogram
  2281. (@ ,@(cond
  2282. ((meta-name meta)
  2283. => (lambda (name) `((name ,(symbol->string name)))))
  2284. (else
  2285. '()))
  2286. (low-pc ,(meta-label meta))
  2287. (high-pc ,(- (meta-high-pc meta) (meta-low-pc meta))))))
  2288. (define (make-compile-unit-die asm)
  2289. `(compile-unit
  2290. (@ (producer ,(string-append "Guile " (version)))
  2291. (language ,(asm-language asm))
  2292. (low-pc .rtl-text)
  2293. (high-pc ,(asm-pos asm))
  2294. (stmt-list 0))
  2295. ,@(map meta->subprogram-die (reverse (asm-meta asm)))))
  2296. (let-values (((die-port get-die-bv) (open-bytevector-output-port))
  2297. ((die-relocs) '())
  2298. ((abbrev-port get-abbrev-bv) (open-bytevector-output-port))
  2299. ;; (tag has-kids? attrs forms) -> code
  2300. ((abbrevs) vlist-null)
  2301. ((strtab) (make-string-table))
  2302. ((line-port get-line-bv) (open-bytevector-output-port))
  2303. ((line-relocs) '())
  2304. ;; file -> code
  2305. ((files) vlist-null))
  2306. (define (write-abbrev code tag has-children? attrs forms)
  2307. (put-uleb128 abbrev-port code)
  2308. (put-uleb128 abbrev-port (tag-name->code tag))
  2309. (put-u8 abbrev-port (children-name->code (if has-children? 'yes 'no)))
  2310. (for-each (lambda (attr form)
  2311. (put-uleb128 abbrev-port (attribute-name->code attr))
  2312. (put-uleb128 abbrev-port (form-name->code form)))
  2313. attrs forms)
  2314. (put-uleb128 abbrev-port 0)
  2315. (put-uleb128 abbrev-port 0))
  2316. (define (intern-abbrev tag has-children? attrs forms)
  2317. (let ((key (list tag has-children? attrs forms)))
  2318. (match (vhash-assoc key abbrevs)
  2319. ((_ . code) code)
  2320. (#f (let ((code (1+ (vlist-length abbrevs))))
  2321. (set! abbrevs (vhash-cons key code abbrevs))
  2322. (write-abbrev code tag has-children? attrs forms)
  2323. code)))))
  2324. (define (intern-file file)
  2325. (match (vhash-assoc file files)
  2326. ((_ . code) code)
  2327. (#f (let ((code (1+ (vlist-length files))))
  2328. (set! files (vhash-cons file code files))
  2329. code))))
  2330. (define (write-sources)
  2331. ;; Choose line base and line range values that will allow for an
  2332. ;; address advance range of 16 words. The special opcode range is
  2333. ;; from 10 to 255, so 246 values.
  2334. (define base -4)
  2335. (define range 15)
  2336. (define min-inc 4) ; Minimum PC increment.
  2337. (let lp ((sources (asm-sources asm)) (out '()))
  2338. (match sources
  2339. (((pc . s) . sources)
  2340. (let ((file (assq-ref s 'filename))
  2341. (line (assq-ref s 'line))
  2342. (col (assq-ref s 'column)))
  2343. (lp sources
  2344. ;; Guile line and column numbers are 0-indexed, but
  2345. ;; they are 1-indexed for DWARF.
  2346. (if (and line col)
  2347. (cons (list pc
  2348. (if (string? file) (intern-file file) 0)
  2349. (1+ line)
  2350. (1+ col))
  2351. out)
  2352. out))))
  2353. (()
  2354. ;; Compilation unit header for .debug_line. We write in
  2355. ;; DWARF 2 format because more tools understand it than DWARF
  2356. ;; 4, which incompatibly adds another field to this header.
  2357. (put-u32 line-port 0) ; Length; will patch later.
  2358. (put-u16 line-port 2) ; DWARF 2 format.
  2359. (put-u32 line-port 0) ; Prologue length; will patch later.
  2360. (put-u8 line-port min-inc) ; Minimum instruction length: 4 bytes.
  2361. (put-u8 line-port 1) ; Default is-stmt: true.
  2362. (put-s8 line-port base) ; Line base. See the DWARF standard.
  2363. (put-u8 line-port range) ; Line range. See the DWARF standard.
  2364. (put-u8 line-port 10) ; Opcode base: the first "special" opcode.
  2365. ;; A table of the number of uleb128 arguments taken by each
  2366. ;; of the standard opcodes.
  2367. (put-u8 line-port 0) ; 1: copy
  2368. (put-u8 line-port 1) ; 2: advance-pc
  2369. (put-u8 line-port 1) ; 3: advance-line
  2370. (put-u8 line-port 1) ; 4: set-file
  2371. (put-u8 line-port 1) ; 5: set-column
  2372. (put-u8 line-port 0) ; 6: negate-stmt
  2373. (put-u8 line-port 0) ; 7: set-basic-block
  2374. (put-u8 line-port 0) ; 8: const-add-pc
  2375. (put-u8 line-port 1) ; 9: fixed-advance-pc
  2376. ;; Include directories, as a zero-terminated sequence of
  2377. ;; nul-terminated strings. Nothing, for the moment.
  2378. (put-u8 line-port 0)
  2379. ;; File table. For each file that contributes to this
  2380. ;; compilation unit, a nul-terminated file name string, and a
  2381. ;; uleb128 for each of directory the file was found in, the
  2382. ;; modification time, and the file's size in bytes. We pass
  2383. ;; zero for the latter three fields.
  2384. (vlist-fold-right
  2385. (lambda (pair seed)
  2386. (match pair
  2387. ((file . code)
  2388. (put-bytevector line-port (string->utf8 file))
  2389. (put-u8 line-port 0)
  2390. (put-uleb128 line-port 0) ; directory
  2391. (put-uleb128 line-port 0) ; mtime
  2392. (put-uleb128 line-port 0))) ; size
  2393. seed)
  2394. #f
  2395. files)
  2396. (put-u8 line-port 0) ; 0 byte terminating file list.
  2397. ;; Patch prologue length.
  2398. (let ((offset (port-position line-port)))
  2399. (seek line-port 6 SEEK_SET)
  2400. (put-u32 line-port (- offset 10))
  2401. (seek line-port offset SEEK_SET))
  2402. ;; Now write the statement program.
  2403. (let ()
  2404. (define (extended-op opcode payload-len)
  2405. (put-u8 line-port 0) ; extended op
  2406. (put-uleb128 line-port (1+ payload-len)) ; payload-len + opcode
  2407. (put-uleb128 line-port opcode))
  2408. (define (set-address sym)
  2409. (define (add-reloc! kind)
  2410. (set! line-relocs
  2411. (cons (make-linker-reloc kind
  2412. (port-position line-port)
  2413. 0
  2414. sym)
  2415. line-relocs)))
  2416. (match (asm-word-size asm)
  2417. (4
  2418. (extended-op 2 4)
  2419. (add-reloc! 'abs32/1)
  2420. (put-u32 line-port 0))
  2421. (8
  2422. (extended-op 2 8)
  2423. (add-reloc! 'abs64/1)
  2424. (put-u64 line-port 0))))
  2425. (define (end-sequence pc)
  2426. (let ((pc-inc (/ (- (asm-pos asm) pc) min-inc)))
  2427. (put-u8 line-port 2) ; advance-pc
  2428. (put-uleb128 line-port pc-inc))
  2429. (extended-op 1 0))
  2430. (define (advance-pc pc-inc line-inc)
  2431. (let ((spec (+ (- line-inc base)
  2432. (* (/ pc-inc min-inc) range)
  2433. 10)))
  2434. (cond
  2435. ((or (< line-inc base) (>= line-inc (+ base range)))
  2436. (advance-line line-inc)
  2437. (advance-pc pc-inc 0))
  2438. ((<= spec 255)
  2439. (put-u8 line-port spec))
  2440. ((< spec 500)
  2441. (put-u8 line-port 8) ; const-advance-pc
  2442. (advance-pc (- pc-inc (* (floor/ (- 255 10) range) min-inc))
  2443. line-inc))
  2444. (else
  2445. (put-u8 line-port 2) ; advance-pc
  2446. (put-uleb128 line-port (/ pc-inc min-inc))
  2447. (advance-pc 0 line-inc)))))
  2448. (define (advance-line inc)
  2449. (put-u8 line-port 3)
  2450. (put-sleb128 line-port inc))
  2451. (define (set-file file)
  2452. (put-u8 line-port 4)
  2453. (put-uleb128 line-port file))
  2454. (define (set-column col)
  2455. (put-u8 line-port 5)
  2456. (put-uleb128 line-port col))
  2457. (set-address '.rtl-text)
  2458. (let lp ((in out) (pc 0) (file 1) (line 1) (col 0))
  2459. (match in
  2460. (()
  2461. (when (null? out)
  2462. ;; There was no source info in the first place. Set
  2463. ;; file register to 0 before adding final row.
  2464. (set-file 0))
  2465. (end-sequence pc))
  2466. (((pc* file* line* col*) . in*)
  2467. (cond
  2468. ((and (eqv? file file*) (eqv? line line*) (eqv? col col*))
  2469. (lp in* pc file line col))
  2470. (else
  2471. (unless (eqv? col col*)
  2472. (set-column col*))
  2473. (unless (eqv? file file*)
  2474. (set-file file*))
  2475. (advance-pc (- pc* pc) (- line* line))
  2476. (lp in* pc* file* line* col*)))))))))))
  2477. (define (compute-code attr val)
  2478. (match attr
  2479. ('name (string-table-intern! strtab val))
  2480. ('low-pc val)
  2481. ('high-pc val)
  2482. ('producer (string-table-intern! strtab val))
  2483. ('language (language-name->code val))
  2484. ('stmt-list val)))
  2485. (define (choose-form attr val code)
  2486. (cond
  2487. ((string? val) 'strp)
  2488. ((eq? attr 'stmt-list) 'sec-offset)
  2489. ((eq? attr 'low-pc) 'addr)
  2490. ((exact-integer? code)
  2491. (cond
  2492. ((< code 0) 'sleb128)
  2493. ((<= code #xff) 'data1)
  2494. ((<= code #xffff) 'data2)
  2495. ((<= code #xffffffff) 'data4)
  2496. ((<= code #xffffffffffffffff) 'data8)
  2497. (else 'uleb128)))
  2498. (else (error "unhandled case" attr val code))))
  2499. (define (add-die-relocation! kind sym)
  2500. (set! die-relocs
  2501. (cons (make-linker-reloc kind (port-position die-port) 0 sym)
  2502. die-relocs)))
  2503. (define (write-value code form)
  2504. (match form
  2505. ('data1 (put-u8 die-port code))
  2506. ('data2 (put-u16 die-port code))
  2507. ('data4 (put-u32 die-port code))
  2508. ('data8 (put-u64 die-port code))
  2509. ('uleb128 (put-uleb128 die-port code))
  2510. ('sleb128 (put-sleb128 die-port code))
  2511. ('addr
  2512. (match (asm-word-size asm)
  2513. (4
  2514. (add-die-relocation! 'abs32/1 code)
  2515. (put-u32 die-port 0))
  2516. (8
  2517. (add-die-relocation! 'abs64/1 code)
  2518. (put-u64 die-port 0))))
  2519. ('sec-offset (put-u32 die-port code))
  2520. ('strp (put-u32 die-port code))))
  2521. (define (write-die die)
  2522. (match die
  2523. ((tag ('@ (attrs vals) ...) children ...)
  2524. (let* ((codes (map compute-code attrs vals))
  2525. (forms (map choose-form attrs vals codes))
  2526. (has-children? (not (null? children)))
  2527. (abbrev-code (intern-abbrev tag has-children? attrs forms)))
  2528. (put-uleb128 die-port abbrev-code)
  2529. (for-each write-value codes forms)
  2530. (when has-children?
  2531. (for-each write-die children)
  2532. (put-uleb128 die-port 0))))))
  2533. ;; Compilation unit header.
  2534. (put-u32 die-port 0) ; Length; will patch later.
  2535. (put-u16 die-port 4) ; DWARF 4.
  2536. (put-u32 die-port 0) ; Abbrevs offset.
  2537. (put-u8 die-port (asm-word-size asm)) ; Address size.
  2538. (write-die (make-compile-unit-die asm))
  2539. ;; Terminate the abbrevs list.
  2540. (put-uleb128 abbrev-port 0)
  2541. (write-sources)
  2542. (values (let ((bv (get-die-bv)))
  2543. ;; Patch DWARF32 length.
  2544. (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
  2545. (asm-endianness asm))
  2546. (make-object asm '.debug_info bv die-relocs '()
  2547. #:type SHT_PROGBITS #:flags 0))
  2548. (make-object asm '.debug_abbrev (get-abbrev-bv) '() '()
  2549. #:type SHT_PROGBITS #:flags 0)
  2550. (make-object asm '.debug_str (link-string-table! strtab) '() '()
  2551. #:type SHT_PROGBITS #:flags 0)
  2552. (make-object asm '.debug_loc #vu8() '() '()
  2553. #:type SHT_PROGBITS #:flags 0)
  2554. (let ((bv (get-line-bv)))
  2555. ;; Patch DWARF32 length.
  2556. (bytevector-u32-set! bv 0 (- (bytevector-length bv) 4)
  2557. (asm-endianness asm))
  2558. (make-object asm '.debug_line bv line-relocs '()
  2559. #:type SHT_PROGBITS #:flags 0)))))
  2560. (define (link-objects asm)
  2561. (let*-values (;; Link procprops before constants, because it probably
  2562. ;; interns more constants.
  2563. ((procprops) (link-procprops asm))
  2564. ((ro rw rw-init) (link-constants asm))
  2565. ;; Link text object after constants, so that the
  2566. ;; constants initializer gets included.
  2567. ((text) (link-text-object asm))
  2568. ((frame-maps) (link-frame-maps asm))
  2569. ((dt) (link-dynamic-section asm text rw rw-init frame-maps))
  2570. ((symtab strtab) (link-symtab (linker-object-section text) asm))
  2571. ((arities arities-strtab) (link-arities asm))
  2572. ((docstrs docstrs-strtab) (link-docstrs asm))
  2573. ((dinfo dabbrev dstrtab dloc dline) (link-debug asm))
  2574. ;; This needs to be linked last, because linking other
  2575. ;; sections adds entries to the string table.
  2576. ((shstrtab) (link-shstrtab asm)))
  2577. (filter identity
  2578. (list text ro frame-maps rw dt symtab strtab
  2579. arities arities-strtab
  2580. docstrs docstrs-strtab procprops
  2581. dinfo dabbrev dstrtab dloc dline
  2582. shstrtab))))
  2583. ;;;
  2584. ;;; High-level public interfaces.
  2585. ;;;
  2586. (define* (link-assembly asm #:key (page-aligned? #t))
  2587. "Produce an ELF image from the code and data emitted into @var{asm}.
  2588. The result is a bytevector, by default linked so that read-only and
  2589. writable data are on separate pages. Pass @code{#:page-aligned? #f} to
  2590. disable this behavior."
  2591. (link-elf (link-objects asm) #:page-aligned? page-aligned?))