aasmcnst.pas 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269
  1. {
  2. Copyright (c) 2014 by Jonas Maebe, member of the Free Pascal development
  3. team
  4. This unit implements typed constant data elements at the assembler level
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2 of the License, or
  8. (at your option) any later version.
  9. This program 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
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software
  15. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  16. ****************************************************************************
  17. }
  18. unit aasmcnst;
  19. {$i fpcdefs.inc}
  20. interface
  21. uses
  22. cclasses,globtype,constexp,
  23. aasmbase,aasmdata,aasmtai,
  24. symconst,symbase,symtype,symdef,symsym;
  25. type
  26. { typed const: integer/floating point/string/pointer/... const along with
  27. tdef info }
  28. ttypedconstkind = (tck_simple, tck_array, tck_record);
  29. { the type of the element and its def }
  30. tai_abstracttypedconst = class abstract (tai)
  31. private
  32. procedure setdef(def: tdef);
  33. protected
  34. fadetyp: ttypedconstkind;
  35. { the def of this element }
  36. fdef: tdef;
  37. public
  38. constructor create(_adetyp: ttypedconstkind; _def: tdef);
  39. property adetyp: ttypedconstkind read fadetyp;
  40. property def: tdef read fdef write setdef;
  41. end;
  42. { a simple data element; the value is stored as a tai }
  43. tai_simpletypedconst = class(tai_abstracttypedconst)
  44. private
  45. procedure setval(AValue: tai);
  46. protected
  47. fval: tai;
  48. public
  49. constructor create(_adetyp: ttypedconstkind; _def: tdef; _val: tai);
  50. property val: tai read fval write setval;
  51. end;
  52. { an aggregate data element (record or array). Values are stored as an
  53. array of tsimpledataelement. }
  54. tai_aggregatetypedconst = class(tai_abstracttypedconst)
  55. public type
  56. { iterator to walk over all individual items in the aggregate }
  57. tadeenumerator = class(tobject)
  58. private
  59. fvalues: tfplist;
  60. fvaluespos: longint;
  61. function getcurrent: tai_abstracttypedconst;
  62. public
  63. constructor create(data: tai_aggregatetypedconst);
  64. function movenext: boolean;
  65. procedure reset;
  66. property current: tai_abstracttypedconst read getcurrent;
  67. end;
  68. protected
  69. fvalues: tfplist;
  70. fisstring: boolean;
  71. { converts the existing data to a single tai_string }
  72. procedure convert_to_string;
  73. procedure add_to_string(strtai: tai_string; othertai: tai);
  74. public
  75. constructor create(_adetyp: ttypedconstkind; _fdef: tdef);
  76. function getenumerator: tadeenumerator;
  77. procedure addvalue(val: tai_abstracttypedconst);
  78. function valuecount: longint;
  79. procedure insertvaluebeforepos(val: tai_abstracttypedconst; pos: longint);
  80. function replacevalueatpos(val: tai_abstracttypedconst; pos: longint): tai_abstracttypedconst;
  81. { change the type to a record, regardless of how the aggregate was created;
  82. the size of the original type and the record must match }
  83. procedure changetorecord(_def: trecorddef);
  84. procedure finish;
  85. destructor destroy; override;
  86. end;
  87. tasmlabofs = record
  88. lab: tasmlabel;
  89. ofs: asizeint;
  90. end;
  91. { flags for the finalisation of the typed const builder asmlist }
  92. ttcasmlistoption = (
  93. { the tasmsymbol is a tasmlabel }
  94. tcalo_is_lab,
  95. { start a new section (e.g., because we don't know the current section
  96. type) }
  97. tcalo_new_section,
  98. { this symbol is the start of a block of data that should be
  99. dead-stripable/smartlinkable; may imply starting a new section, but
  100. not necessarily (depends on what the platform requirements are) }
  101. tcalo_make_dead_strippable,
  102. { this symbol should never be removed by the linker }
  103. tcalo_no_dead_strip,
  104. { start of a vectorized but individually dead strippable list of elements,
  105. like the resource strings of a unit: they have to stay in this order,
  106. but individual elements can be removed }
  107. tcalo_vectorized_dead_strip_start,
  108. { item in the above list }
  109. tcalo_vectorized_dead_strip_item,
  110. { end of the above list }
  111. tcalo_vectorized_dead_strip_end,
  112. { symbol should be weakly defined }
  113. tcalo_weak,
  114. { symbol should be registered with the unit's public assembler symbols }
  115. tcalo_is_public_asm,
  116. { symbol should be declared with AT_DATA_FORCEINDIRECT }
  117. tcalo_data_force_indirect,
  118. { apply const_align() to the alignment, for user-defined data }
  119. tcalo_apply_constalign
  120. );
  121. ttcasmlistoptions = set of ttcasmlistoption;
  122. ttcdeadstripsectionsymboloption = (
  123. { define the symbol }
  124. tcdssso_define,
  125. { register the assembler symbol either with the public or extern assembler
  126. symbols of the unit }
  127. tcdssso_register_asmsym,
  128. { use the indirect symbol }
  129. tcdssso_use_indirect
  130. );
  131. ttcdeadstripsectionsymboloptions = set of ttcdeadstripsectionsymboloption;
  132. { information about aggregates we are parsing }
  133. taggregateinformation = class
  134. private
  135. fnextfieldname: TIDString;
  136. function getcuroffset: asizeint;
  137. procedure setnextfieldname(AValue: TIDString);
  138. protected
  139. { type of the aggregate }
  140. fdef: tdef;
  141. { type of the aggregate }
  142. ftyp: ttypedconstkind;
  143. { symtable entry of the previously emitted field in case of a
  144. record/object (nil if none emitted yet), used to insert alignment bytes
  145. if necessary for variant records and objects }
  146. fcurfield,
  147. { field corresponding to the data that will be emitted next in case of a
  148. record/object (nil if not set), used to handle variant records and
  149. objects }
  150. fnextfield: tfieldvarsym;
  151. { similar as the fcurfield/fnextfield above, but instead of fieldvarsyms
  152. these are indices in the symlist of a recorddef that correspond to
  153. fieldvarsyms. These are used only for non-variant records, simply
  154. traversing the fields in order. We could use the above method here as
  155. well, but to find the next field we'd always have to use
  156. symlist.indexof(fcurfield), which would be quite slow. These have -1 as
  157. value if they're not set }
  158. fcurindex,
  159. fnextindex: longint;
  160. { anonymous record that is being built as we add constant data }
  161. fanonrecord: boolean;
  162. property curindex: longint read fcurindex write fcurindex;
  163. property nextindex: longint read fnextindex write fnextindex;
  164. public
  165. constructor create(_def: tdef; _typ: ttypedconstkind); virtual;
  166. { calculated padding bytes for alignment if needed, and add the def of the
  167. next field in case we are constructing an anonymous record }
  168. function prepare_next_field(nextfielddef: tdef): asizeint; virtual;
  169. property def: tdef read fdef;
  170. property typ: ttypedconstkind read ftyp;
  171. property curfield: tfieldvarsym read fcurfield write fcurfield;
  172. property nextfield: tfieldvarsym read fnextfield write fnextfield;
  173. property nextfieldname: TIDString write setnextfieldname;
  174. property curoffset: asizeint read getcuroffset;
  175. property anonrecord: boolean read fanonrecord write fanonrecord;
  176. end;
  177. taggregateinformationclass = class of taggregateinformation;
  178. { information about a placeholder element that has been added, and which has
  179. to be replaced later with a real data element }
  180. ttypedconstplaceholder = class abstract
  181. def: tdef;
  182. constructor create(d: tdef);
  183. { same usage as ttai_typedconstbuilder.emit_tai }
  184. procedure replace(ai: tai; d: tdef); virtual; abstract;
  185. end;
  186. { Warning: never directly create a ttai_typedconstbuilder instance,
  187. instead create a cai_typedconstbuilder (this class can be overridden) }
  188. ttai_typedconstbuilder = class abstract
  189. { class type to use when creating new aggregate information instances }
  190. protected class var
  191. caggregateinformation: taggregateinformationclass;
  192. private
  193. function getcurragginfo: taggregateinformation;
  194. procedure set_next_field(AValue: tfieldvarsym);
  195. procedure set_next_field_name(AValue: TIDString);
  196. protected
  197. { temporary list in which all data is collected }
  198. fasmlist: tasmlist;
  199. { options for the final asmlist }
  200. foptions: ttcasmlistoptions;
  201. { while queueing elements of a compound expression, this is the current
  202. offset in the top-level array/record }
  203. fqueue_offset: asizeint;
  204. fqueued_def: tdef;
  205. { array of caggregateinformation instances }
  206. faggregateinformation: tfpobjectlist;
  207. { Support for generating data that is only referenced from the typed
  208. constant data that we are currently generated. Such data can all be put
  209. in the same dead-strippable unit, as it's either all included or none of
  210. it is included. This data can be spread over multiple kinds of sections
  211. though (e.g. rodata and rodata_no_rel), so per section keep track whether
  212. we already started a dead-strippable unit and if so, what the section
  213. name was (so that on platforms that perform the dead stripping based on
  214. sections, we put all data for one typed constant into a single section
  215. with the same name) }
  216. protected type
  217. tinternal_data_section_info = record
  218. secname: TSymStr;
  219. sectype: TAsmSectiontype;
  220. end;
  221. protected var
  222. { all internally generated data must be stored in the same list, as it must
  223. be consecutive (if it's spread over multiple lists, we don't know in
  224. which order they'll be concatenated) -> keep track of this list }
  225. finternal_data_asmlist: tasmlist;
  226. { kind of the last section we started in the finternal_data_asmlist, to
  227. avoid creating unnecessary section statements }
  228. finternal_data_current_section: TAsmSectiontype;
  229. { info about in which kinds of sections we have already emitted internal
  230. data, and what their names were }
  231. finternal_data_section_info: array of tinternal_data_section_info;
  232. { ensure that finalize_asmlist is called only once }
  233. fasmlist_finalized: boolean;
  234. { ensure that if it's vectorized dead strippable data, we called
  235. finalize_vectorized_dead_strip_asmlist instead of finalize_asmlist }
  236. fvectorized_finalize_called: boolean;
  237. { returns whether def must be handled as an aggregate on the current
  238. platform }
  239. function aggregate_kind(def: tdef): ttypedconstkind; virtual;
  240. { finalize the asmlist: add the necessary symbols etc }
  241. procedure finalize_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions); virtual;
  242. procedure finalize_asmlist_add_indirect_sym(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions); virtual;
  243. { functionality of the above for vectorized dead strippable sections }
  244. procedure finalize_vectorized_dead_strip_asmlist(def: tdef; const basename, itemname: TSymStr; st: tsymtable; alignment: shortint; options: ttcasmlistoptions); virtual;
  245. { called by the public emit_tai() routines to actually add the typed
  246. constant data; the public ones also take care of adding extra padding
  247. bytes etc (by calling this one) }
  248. procedure do_emit_tai(p: tai; def: tdef); virtual;
  249. { calls prepare_next_field() and adds the padding bytes in the current
  250. location }
  251. procedure pad_next_field(nextfielddef: tdef);
  252. { returns the index in finternal_data_section_info of the info for the
  253. section of type typ. Returns -1 if there is no such info yet }
  254. function get_internal_data_section_index(typ: TAsmSectiontype): longint;
  255. { get a start label for an internal data section (at the start of a
  256. potentially dead-strippable part) }
  257. function get_internal_data_section_start_label: tasmlabel; virtual;
  258. { get a label in the middle of an internal data section (no dead
  259. stripping) }
  260. function get_internal_data_section_internal_label: tasmlabel; virtual;
  261. { easy access to the top level aggregate information instance }
  262. property curagginfo: taggregateinformation read getcurragginfo;
  263. public
  264. constructor create(const options: ttcasmlistoptions); virtual;
  265. destructor destroy; override;
  266. public
  267. { returns a builder for generating data that is only referrenced by the
  268. typed constant date we are currently generating (e.g. string data for a
  269. pchar constant). Also returns the label that will be placed at the start
  270. of that data. list is the tasmlist to which the data will be added.
  271. secname can be empty to use a default }
  272. procedure start_internal_data_builder(list: tasmlist; sectype: TAsmSectiontype; const secname: TSymStr; out tcb: ttai_typedconstbuilder; out l: tasmlabel);
  273. { finish a previously started internal data builder, including
  274. concatenating all generated data to the provided list and freeing the
  275. builder }
  276. procedure finish_internal_data_builder(var tcb: ttai_typedconstbuilder; l: tasmlabel; def: tdef; alignment: longint);
  277. { add a simple constant data element (p) to the typed constant.
  278. def is the type of the added value }
  279. procedure emit_tai(p: tai; def: tdef); virtual;
  280. { same as above, for a special case: when the def is a procvardef and we
  281. want to use it explicitly as a procdef (i.e., not as a record with a
  282. code and data pointer in case of a complex procvardef) }
  283. procedure emit_tai_procvar2procdef(p: tai; pvdef: tprocvardef); virtual;
  284. protected
  285. procedure maybe_emit_tail_padding(def: tdef); virtual;
  286. function emit_string_const_common(stringtype: tstringtype; len: asizeint; encoding: tstringencoding; var startlab: tasmlabel):tasmlabofs;
  287. function get_dynstring_def_for_type(stringtype: tstringtype; winlikewidestring: boolean): tstringdef;
  288. procedure begin_aggregate_internal(def: tdef; anonymous: boolean); virtual;
  289. procedure end_aggregate_internal(def: tdef; anonymous: boolean); virtual;
  290. { when building an anonymous record, we cannot immediately insert the
  291. alignment before it in case it's nested, since we only know the required
  292. alignment once all fields have been inserted -> mark the location before
  293. the anonymous record, and insert the alignment once it's finished }
  294. procedure mark_anon_aggregate_alignment; virtual; abstract;
  295. procedure insert_marked_aggregate_alignment(def: tdef); virtual; abstract;
  296. class function get_vectorized_dead_strip_section_symbol(const basename: string; st: tsymtable; options: ttcdeadstripsectionsymboloptions; start: boolean): tasmsymbol; virtual;
  297. public
  298. class function get_vectorized_dead_strip_custom_section_name(const basename: TSymStr; st: tsymtable; out secname: TSymStr): boolean; virtual;
  299. { get the start/end symbol for a dead stripable vectorized section, such
  300. as the resourcestring data of a unit }
  301. class function get_vectorized_dead_strip_section_symbol_start(const basename: string; st: tsymtable; options: ttcdeadstripsectionsymboloptions): tasmsymbol; virtual;
  302. class function get_vectorized_dead_strip_section_symbol_end(const basename: string; st: tsymtable; options: ttcdeadstripsectionsymboloptions): tasmsymbol; virtual;
  303. class function get_dynstring_rec_name(typ: tstringtype; winlike: boolean; len: asizeint): TSymStr;
  304. class function get_dynstring_rec(typ: tstringtype; winlike: boolean; len: asizeint): trecorddef;
  305. { the datalist parameter specifies where the data for the string constant
  306. will be emitted (via an internal data builder) }
  307. function emit_ansistring_const(datalist: TAsmList; data: pchar; len: asizeint; encoding: tstringencoding): tasmlabofs;
  308. function emit_unicodestring_const(datalist: TAsmList; data: pointer; encoding: tstringencoding; winlike: boolean):tasmlabofs;
  309. { emits a tasmlabofs as returned by emit_*string_const }
  310. procedure emit_string_offset(const ll: tasmlabofs; const strlength: longint; const st: tstringtype; const winlikewidestring: boolean; const charptrdef: tdef);virtual;
  311. { emits a tasmlabofs as returned by begin_dynarray_const }
  312. procedure emit_dynarray_offset(const ll:tasmlabofs;const arrlength:asizeint;const arrdef:tdef);virtual;
  313. { starts a dynamic array constant so that its data can be emitted directly afterwards }
  314. function begin_dynarray_const(arrdef:tdef;var startlab:tasmlabel;out arrlengthloc:ttypedconstplaceholder):tasmlabofs;virtual;
  315. function end_dynarray_const(arrdef:tdef;arrlength:asizeint;arrlengthloc:ttypedconstplaceholder):tdef;virtual;
  316. { emit a shortstring constant, and return its def }
  317. function emit_shortstring_const(const str: shortstring): tdef;
  318. { emit a pchar string constant (the characters, not a pointer to them), and return its def }
  319. function emit_pchar_const(str: pchar; len: pint; copypchar: boolean): tdef;
  320. { emit a guid constant }
  321. procedure emit_guid_const(const guid: tguid);
  322. { emit a procdef constant }
  323. procedure emit_procdef_const(pd: tprocdef);
  324. { emit an ordinal constant }
  325. procedure emit_ord_const(value: int64; def: tdef);
  326. { emit a reference to a pooled shortstring constant }
  327. procedure emit_pooled_shortstring_const_ref(const str:shortstring);
  328. { begin a potential aggregate type. Must be called for any type
  329. that consists of multiple tai constant data entries, or that
  330. represents an aggregate at the Pascal level (a record, a non-dynamic
  331. array, ... }
  332. procedure maybe_begin_aggregate(def: tdef);
  333. { end a potential aggregate type. Must be paired with every
  334. maybe_begin_aggregate }
  335. procedure maybe_end_aggregate(def: tdef);
  336. { similar as above, but in case
  337. a) it's definitely a record
  338. b) the def of the record should be automatically constructed based on
  339. the types of the emitted fields
  340. packrecords: same as "pacrecords x"
  341. recordalign: specify the (minimum) alignment of the start of the record
  342. (no equivalent in source code), used as an alternative for explicit
  343. align statements. Use "1" if it should be calculated based on the
  344. fields
  345. recordalignmin: same as "codealign recordmin=x"
  346. maxcrecordalign: specify maximum C record alignment (no equivalent in
  347. source code)
  348. }
  349. function begin_anonymous_record(const optionalname: string; packrecords, recordalign, recordalignmin, maxcrecordalign: shortint): trecorddef; virtual;
  350. function end_anonymous_record: trecorddef; virtual;
  351. { add a placeholder element at the current position that later can be
  352. filled in with the actual data (via ttypedconstplaceholder.replace)
  353. useful in case you have table preceded by the number of elements, and
  354. you count the elements while building the table }
  355. function emit_placeholder(def: tdef): ttypedconstplaceholder; virtual; abstract;
  356. protected
  357. { common code to check whether a placeholder can be added at the current
  358. position }
  359. procedure check_add_placeholder(def: tdef);
  360. public
  361. { The next group of routines are for constructing complex expressions.
  362. While parsing a typed constant these operators are encountered from
  363. outer to inner, so that is also the order in which they should be
  364. added to the queue. Only one queue can be active at a time. }
  365. { Init the queue. Gives an internalerror if a queue was already active }
  366. procedure queue_init(todef: tdef); virtual;
  367. { queue an array/string indexing operation (performs all range checking,
  368. so it doesn't have to be duplicated in all descendents). }
  369. procedure queue_vecn(def: tdef; const index: tconstexprint); virtual;
  370. { queue a subscripting operation }
  371. procedure queue_subscriptn(def: tabstractrecorddef; vs: tfieldvarsym); virtual;
  372. { queue indexing a record recursively via several field names. The fields
  373. are specified in the inner to outer order (i.e., def.field1.field2) }
  374. function queue_subscriptn_multiple_by_name(def: tabstractrecorddef; const fields: array of TIDString): tdef;
  375. { queue a type conversion operation }
  376. procedure queue_typeconvn(fromdef, todef: tdef); virtual;
  377. { finalise the queue (so a new one can be created) and flush the
  378. previously queued operations, applying them in reverse order on a...}
  379. { ... procdef }
  380. procedure queue_emit_proc(pd: tprocdef); virtual;
  381. { ... staticvarsym }
  382. procedure queue_emit_staticvar(vs: tstaticvarsym); virtual;
  383. { ... labelsym }
  384. procedure queue_emit_label(l: tlabelsym); virtual;
  385. { ... constsym }
  386. procedure queue_emit_const(cs: tconstsym); virtual;
  387. { ... asmsym/asmlabel }
  388. procedure queue_emit_asmsym(sym: tasmsymbol; def: tdef); virtual;
  389. { ... an ordinal constant }
  390. procedure queue_emit_ordconst(value: int64; def: tdef); virtual;
  391. protected
  392. { returns whether queue_init has been called without a corresponding
  393. queue_emit_* to finish it }
  394. function queue_is_active: boolean;
  395. public
  396. { finalize the internal asmlist (if necessary) and return it.
  397. This asmlist will be freed when the builder is destroyed, so add its
  398. contents to another list first. This property should only be accessed
  399. once all data has been added. }
  400. function get_final_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: longint): tasmlist;
  401. function get_final_asmlist_vectorized_dead_strip(def: tdef; const basename, itemname: TSymStr; st: TSymtable; alignment: longint): tasmlist;
  402. { returns the offset of the string data relative to ansi/unicode/widestring
  403. constant labels. On most platforms, this is 0 (with the header at a
  404. negative offset), but on some platforms such negative offsets are not
  405. supported this is equal to the header size }
  406. class function get_string_symofs(typ: tstringtype; winlikewidestring: boolean): pint; virtual;
  407. { returns the offset of the array data relatve to dynamic array constant
  408. labels. On most platforms, this is 0 (with the header at a negative
  409. offset), but on some platforms such negative offsets are not supported
  410. and thus this is equal to the header size }
  411. class function get_dynarray_symofs:pint;virtual;
  412. { set the fieldvarsym whose data we will emit next; needed
  413. in case of variant records, so we know which part of the variant gets
  414. initialised. Also in case of objects, because the fieldvarsyms are spread
  415. over the symtables of the entire inheritance tree }
  416. property next_field: tfieldvarsym write set_next_field;
  417. { set the name of the next field that will be emitted for an anonymous
  418. record (also if that field is a nested anonymous record) }
  419. property next_field_name: TIDString write set_next_field_name;
  420. protected
  421. { these ones always return the actual offset, called by the above (and
  422. overridden versions) }
  423. class function get_string_header_size(typ: tstringtype; winlikewidestring: boolean): pint;
  424. class function get_dynarray_header_size:pint;
  425. end;
  426. ttai_typedconstbuilderclass = class of ttai_typedconstbuilder;
  427. tlowlevelaggregateinformation = class(taggregateinformation)
  428. protected
  429. fanonrecmarker: tai;
  430. public
  431. property anonrecmarker: tai read fanonrecmarker write fanonrecmarker;
  432. end;
  433. tlowleveltypedconstplaceholder = class(ttypedconstplaceholder)
  434. list: tasmlist;
  435. insertpos: tai;
  436. constructor create(l: tasmlist; pos: tai; d: tdef);
  437. procedure replace(ai: tai; d: tdef); override;
  438. end;
  439. ttai_lowleveltypedconstbuilder = class(ttai_typedconstbuilder)
  440. protected
  441. procedure mark_anon_aggregate_alignment; override;
  442. procedure insert_marked_aggregate_alignment(def: tdef); override;
  443. procedure finalize_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions); override;
  444. public
  445. { set the default value for caggregateinformation (= tlowlevelaggregateinformation) }
  446. class constructor classcreate;
  447. function emit_placeholder(def: tdef): ttypedconstplaceholder; override;
  448. end;
  449. var
  450. ctai_typedconstbuilder: ttai_typedconstbuilderclass;
  451. implementation
  452. uses
  453. cutils,
  454. verbose,globals,systems,widestr,
  455. fmodule,
  456. symtable,defutil;
  457. {****************************************************************************
  458. taggregateinformation
  459. ****************************************************************************}
  460. function taggregateinformation.getcuroffset: asizeint;
  461. var
  462. field: tfieldvarsym;
  463. begin
  464. if assigned(curfield) then
  465. result:=curfield.fieldoffset+curfield.vardef.size
  466. else if curindex<>-1 then
  467. begin
  468. field:=tfieldvarsym(tabstractrecorddef(def).symtable.symlist[curindex]);
  469. result:=field.fieldoffset+field.vardef.size
  470. end
  471. else
  472. result:=0
  473. end;
  474. procedure taggregateinformation.setnextfieldname(AValue: TIDString);
  475. begin
  476. if (fnextfieldname<>'') or
  477. not anonrecord then
  478. internalerror(2015071503);
  479. fnextfieldname:=AValue;
  480. end;
  481. constructor taggregateinformation.create(_def: tdef; _typ: ttypedconstkind);
  482. begin
  483. fdef:=_def;
  484. ftyp:=_typ;
  485. fcurindex:=-1;
  486. fnextindex:=-1;
  487. end;
  488. function taggregateinformation.prepare_next_field(nextfielddef: tdef): asizeint;
  489. var
  490. sym: tsym;
  491. currentoffset,nextoffset: asizeint;
  492. i: longint;
  493. begin
  494. { get the next field and its offset, and make that next field the current
  495. one }
  496. if assigned(nextfield) then
  497. begin
  498. nextoffset:=nextfield.fieldoffset;
  499. currentoffset:=curoffset;
  500. curfield:=nextfield;
  501. end
  502. else
  503. begin
  504. { must set nextfield for unions and objects, as we cannot
  505. automatically detect the "next" field in that case }
  506. if ((def.typ=recorddef) and
  507. trecorddef(def).isunion) or
  508. is_object(def) then
  509. internalerror(2014091202);
  510. { if we are constructing this record as data gets emitted, add a field
  511. for this data }
  512. if anonrecord then
  513. begin
  514. trecorddef(def).add_field_by_def(fnextfieldname,nextfielddef);
  515. fnextfieldname:='';
  516. end
  517. else if fnextfieldname<>'' then
  518. internalerror(2015071501);
  519. currentoffset:=curoffset;
  520. { find next field }
  521. i:=curindex;
  522. repeat
  523. inc(i);
  524. sym:=tsym(tabstractrecorddef(def).symtable.symlist[i]);
  525. until (sym.typ=fieldvarsym) and
  526. not(sp_static in sym.symoptions);
  527. curfield:=tfieldvarsym(sym);
  528. nextoffset:=curfield.fieldoffset;
  529. curindex:=i;
  530. end;
  531. { need padding? }
  532. result:=nextoffset-currentoffset;
  533. end;
  534. {****************************************************************************
  535. ttypedconstplaceholder
  536. ****************************************************************************}
  537. constructor ttypedconstplaceholder.create(d: tdef);
  538. begin
  539. def:=d;
  540. end;
  541. {****************************************************************************
  542. tai_abstracttypedconst
  543. ****************************************************************************}
  544. procedure tai_abstracttypedconst.setdef(def: tdef);
  545. begin
  546. { should not be changed, rewrite the calling code if this happens }
  547. if assigned(fdef) then
  548. Internalerror(2014080203);
  549. fdef:=def;
  550. end;
  551. constructor tai_abstracttypedconst.create(_adetyp: ttypedconstkind; _def: tdef);
  552. begin
  553. inherited create;
  554. typ:=ait_typedconst;
  555. fadetyp:=_adetyp;
  556. fdef:=_def;
  557. end;
  558. {****************************************************************************
  559. tai_simpletypedconst
  560. ****************************************************************************}
  561. procedure tai_simpletypedconst.setval(AValue: tai);
  562. begin
  563. fval:=AValue;
  564. end;
  565. constructor tai_simpletypedconst.create(_adetyp: ttypedconstkind; _def: tdef; _val: tai);
  566. begin
  567. inherited create(_adetyp,_def);
  568. fval:=_val;
  569. end;
  570. {****************************************************************************
  571. tai_aggregatetypedconst.tadeenumerator
  572. ****************************************************************************}
  573. constructor tai_aggregatetypedconst.tadeenumerator.create(data: tai_aggregatetypedconst);
  574. begin
  575. fvalues:=data.fvalues;
  576. fvaluespos:=-1;
  577. end;
  578. function tai_aggregatetypedconst.tadeenumerator.getcurrent: tai_abstracttypedconst;
  579. begin
  580. result:=tai_abstracttypedconst(fvalues[fvaluespos]);
  581. end;
  582. function tai_aggregatetypedconst.tadeenumerator.movenext: boolean;
  583. begin
  584. if fvaluespos<pred(fvalues.count) then
  585. begin
  586. inc(fvaluespos);
  587. result:=true
  588. end
  589. else
  590. result:=false;
  591. end;
  592. procedure tai_aggregatetypedconst.tadeenumerator.reset;
  593. begin
  594. fvaluespos:=0
  595. end;
  596. {****************************************************************************
  597. tai_aggregatetypedconst
  598. ****************************************************************************}
  599. procedure tai_aggregatetypedconst.convert_to_string;
  600. var
  601. ai: tai_abstracttypedconst;
  602. newstr: tai_string;
  603. begin
  604. newstr:=tai_string.Create('');
  605. for ai in self do
  606. begin
  607. if ai.adetyp<>tck_simple then
  608. internalerror(2014070103);
  609. add_to_string(newstr,tai_simpletypedconst(ai).val);
  610. ai.free;
  611. end;
  612. fvalues.count:=0;
  613. { the "nil" def will be replaced with an array def of the appropriate
  614. size once we're finished adding data, so we don't create intermediate
  615. arraydefs all the time }
  616. fvalues.add(tai_simpletypedconst.create(tck_simple,nil,newstr));
  617. end;
  618. procedure tai_aggregatetypedconst.add_to_string(strtai: tai_string; othertai: tai);
  619. begin
  620. case othertai.typ of
  621. ait_string:
  622. begin
  623. strtai.str:=reallocmem(strtai.str,strtai.len+tai_string(othertai).len+1);
  624. { also copy null terminator }
  625. move(tai_string(othertai).str[0],strtai.str[strtai.len],tai_string(othertai).len+1);
  626. { the null terminator is not part of the string data }
  627. strtai.len:=strtai.len+tai_string(othertai).len;
  628. end;
  629. ait_const:
  630. begin
  631. if tai_const(othertai).size<>1 then
  632. internalerror(2014070101);
  633. { it was already len+1 to hold the #0 -> realloc to len+2 }
  634. strtai.str:=reallocmem(strtai.str,strtai.len+2);
  635. strtai.str[strtai.len]:=ansichar(tai_const(othertai).value);
  636. strtai.str[strtai.len+1]:=#0;
  637. inc(strtai.len);
  638. end;
  639. else
  640. internalerror(2014070102);
  641. end;
  642. end;
  643. constructor tai_aggregatetypedconst.create(_adetyp: ttypedconstkind; _fdef: tdef);
  644. begin
  645. inherited;
  646. fisstring:=false;
  647. fvalues:=tfplist.create;
  648. end;
  649. function tai_aggregatetypedconst.getenumerator: tadeenumerator;
  650. begin
  651. result:=tadeenumerator.create(self);
  652. end;
  653. procedure tai_aggregatetypedconst.addvalue(val: tai_abstracttypedconst);
  654. begin
  655. { merge string constants and ordinal constants added in an array of
  656. char, to unify the length and the string data }
  657. if fisstring or
  658. ((val.adetyp=tck_simple) and
  659. (tai_simpletypedconst(val).val.typ=ait_string)) then
  660. begin
  661. if not fisstring and
  662. (fvalues.count>0) then
  663. convert_to_string;
  664. fisstring:=true;
  665. case fvalues.count of
  666. 0: fvalues.add(val);
  667. 1:
  668. begin
  669. add_to_string(tai_string(tai_simpletypedconst(fvalues[0]).val),tai_simpletypedconst(val).val);
  670. val.free
  671. end
  672. else
  673. internalerror(2014070104);
  674. end;
  675. end
  676. else
  677. fvalues.add(val);
  678. end;
  679. function tai_aggregatetypedconst.valuecount: longint;
  680. begin
  681. result:=fvalues.count;
  682. end;
  683. procedure tai_aggregatetypedconst.insertvaluebeforepos(val: tai_abstracttypedconst; pos: longint);
  684. begin
  685. fvalues.insert(pos,val);
  686. end;
  687. function tai_aggregatetypedconst.replacevalueatpos(val: tai_abstracttypedconst; pos: longint): tai_abstracttypedconst;
  688. begin
  689. result:=tai_abstracttypedconst(fvalues[pos]);
  690. fvalues[pos]:=val;
  691. end;
  692. procedure tai_aggregatetypedconst.changetorecord(_def: trecorddef);
  693. begin
  694. { must be a record of the same size as the current data }
  695. if assigned(fdef) and
  696. (fdef.size<>_def.size) then
  697. internalerror(2015122402);
  698. fdef:=_def;
  699. fadetyp:=tck_record;
  700. end;
  701. procedure tai_aggregatetypedconst.finish;
  702. begin
  703. if fisstring then
  704. begin
  705. { set the def: an array of char with the same length as the string
  706. data }
  707. if fvalues.count<>1 then
  708. internalerror(2014070105);
  709. tai_simpletypedconst(fvalues[0]).fdef:=
  710. carraydef.getreusable(cansichartype,
  711. tai_string(tai_simpletypedconst(fvalues[0]).val).len);
  712. end;
  713. end;
  714. destructor tai_aggregatetypedconst.destroy;
  715. begin
  716. fvalues.free;
  717. inherited destroy;
  718. end;
  719. {*****************************************************************************
  720. ttai_typedconstbuilder
  721. *****************************************************************************}
  722. function ttai_typedconstbuilder.getcurragginfo: taggregateinformation;
  723. begin
  724. if assigned(faggregateinformation) and
  725. (faggregateinformation.count>0) then
  726. result:=taggregateinformation(faggregateinformation[faggregateinformation.count-1])
  727. else
  728. result:=nil;
  729. end;
  730. procedure ttai_typedconstbuilder.set_next_field(AValue: tfieldvarsym);
  731. var
  732. info: taggregateinformation;
  733. begin
  734. info:=curagginfo;
  735. if not assigned(info) then
  736. internalerror(2014091206);
  737. info.nextfield:=AValue;
  738. end;
  739. procedure ttai_typedconstbuilder.set_next_field_name(AValue: TIDString);
  740. var
  741. info: taggregateinformation;
  742. begin
  743. info:=curagginfo;
  744. if not assigned(info) then
  745. internalerror(2015071502);
  746. info.nextfieldname:='$'+AValue;
  747. end;
  748. procedure ttai_typedconstbuilder.pad_next_field(nextfielddef: tdef);
  749. var
  750. fillbytes: asizeint;
  751. begin
  752. fillbytes:=curagginfo.prepare_next_field(nextfielddef);
  753. while fillbytes>0 do
  754. begin
  755. do_emit_tai(tai_const.create_8bit(0),u8inttype);
  756. dec(fillbytes);
  757. end;
  758. end;
  759. function ttai_typedconstbuilder.get_internal_data_section_index(typ: TAsmSectiontype): longint;
  760. begin
  761. { avoid wrong warning by -Oodfa }
  762. result:=-1;
  763. for result:=low(finternal_data_section_info) to high(finternal_data_section_info) do
  764. if finternal_data_section_info[result].sectype=typ then
  765. exit;
  766. result:=-1;
  767. end;
  768. function ttai_typedconstbuilder.get_internal_data_section_start_label: tasmlabel;
  769. begin
  770. { on Darwin, dead code/data stripping happens based on non-temporary
  771. labels (any label that doesn't start with "L" -- it doesn't have
  772. to be global) }
  773. if target_info.system in systems_darwin then
  774. current_asmdata.getstaticdatalabel(result)
  775. else if create_smartlink_library then
  776. current_asmdata.getglobaldatalabel(result)
  777. else
  778. current_asmdata.getlocaldatalabel(result);
  779. end;
  780. function ttai_typedconstbuilder.get_internal_data_section_internal_label: tasmlabel;
  781. begin
  782. if create_smartlink_library then
  783. { all labels need to be global in case they're in another object }
  784. current_asmdata.getglobaldatalabel(result)
  785. else
  786. { no special requirement for the label -> just get a local one }
  787. current_asmdata.getlocaldatalabel(result);
  788. end;
  789. function ttai_typedconstbuilder.aggregate_kind(def: tdef): ttypedconstkind;
  790. begin
  791. if (def.typ in [recorddef,filedef,variantdef]) or
  792. is_object(def) or
  793. ((def.typ=procvardef) and
  794. not tprocvardef(def).is_addressonly and
  795. not is_block(def)) then
  796. result:=tck_record
  797. else if ((def.typ=arraydef) and
  798. not is_dynamic_array(def)) or
  799. ((def.typ=setdef) and
  800. not is_smallset(def)) or
  801. is_shortstring(def) then
  802. result:=tck_array
  803. else
  804. result:=tck_simple;
  805. end;
  806. procedure ttai_typedconstbuilder.finalize_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions);
  807. var
  808. prelist: tasmlist;
  809. begin
  810. if tcalo_apply_constalign in options then
  811. alignment:=const_align(alignment);
  812. { have we finished all aggregates? }
  813. if (getcurragginfo<>nil) and
  814. { in case of syntax errors, the aggregate may not have been finished }
  815. (ErrorCount=0) then
  816. internalerror(2015072301);
  817. { must call finalize_vectorized_dead_strip_asmlist() instead }
  818. if (([tcalo_vectorized_dead_strip_start,
  819. tcalo_vectorized_dead_strip_item,
  820. tcalo_vectorized_dead_strip_end]*options)<>[]) and
  821. not fvectorized_finalize_called then
  822. internalerror(2015110602);
  823. prelist:=tasmlist.create;
  824. { only now add items based on the symbolname, because it may be
  825. modified by the "section" specifier in case of a typed constant }
  826. { both in case the data should be dead strippable and never dead
  827. stripped, it should be in a separate section (so this property doesn't
  828. affect other data) }
  829. if ([tcalo_no_dead_strip,tcalo_make_dead_strippable]*options)<>[] then
  830. begin
  831. maybe_new_object_file(prelist);
  832. { we always need a new section here, since if we started a new
  833. object file then we have to say what the section is, and otherwise
  834. we need a new section because that's how the dead stripping works }
  835. new_section(prelist,section,secname,alignment);
  836. end
  837. else if tcalo_new_section in options then
  838. begin
  839. { insert ait_cutobject for smart-linking on targets
  840. that do not support smarlinking based on sections,
  841. like msdos }
  842. if not (tf_smartlink_sections in target_info.flags) then
  843. maybe_new_object_file(prelist);
  844. new_section(prelist,section,secname,alignment);
  845. end
  846. else
  847. prelist.concat(cai_align.Create(alignment));
  848. { On Darwin, use .reference to ensure the data doesn't get dead stripped.
  849. On other platforms, the data must be in the .fpc section (which is
  850. kept via the linker script) }
  851. if tcalo_no_dead_strip in options then
  852. begin
  853. if (target_info.system in systems_darwin) then
  854. begin
  855. { Objective-C section declarations contain "no_dead_strip"
  856. attributes if none of their symbols need to be stripped -> don't
  857. add extra ".reference" statement for their symbols (gcc/clang
  858. don't either) }
  859. if not(section in [low(TObjCAsmSectionType)..high(TObjCAsmSectionType)]) then
  860. prelist.concat(tai_directive.Create(asd_reference,sym.name))
  861. end
  862. else if section<>sec_fpc then
  863. internalerror(2015101402);
  864. end;
  865. if not(tcalo_is_lab in options) then
  866. if sym.bind=AB_LOCAL then
  867. prelist.concat(tai_symbol.Create(sym,0))
  868. else
  869. prelist.concat(tai_symbol.Create_Global(sym,0))
  870. else
  871. prelist.concat(tai_label.Create(tasmlabel(sym)));
  872. if tcalo_weak in options then
  873. prelist.concat(tai_directive.Create(asd_weak_definition,sym.name));
  874. { insert the symbol information before the data }
  875. fasmlist.insertlist(prelist);
  876. { end of the symbol }
  877. fasmlist.concat(tai_symbol_end.Createname(sym.name));
  878. { free the temporary list }
  879. prelist.free;
  880. end;
  881. procedure ttai_typedconstbuilder.finalize_asmlist_add_indirect_sym(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions);
  882. var
  883. ptrdef : tdef;
  884. symind : tasmsymbol;
  885. indtcb : ttai_typedconstbuilder;
  886. indsecname : tsymstr;
  887. begin
  888. if (tcalo_data_force_indirect in options) and
  889. (sym.bind in [AB_GLOBAL,AB_COMMON]) and
  890. (sym.typ=AT_DATA) then
  891. begin
  892. ptrdef:=cpointerdef.getreusable(def);
  893. symind:=current_asmdata.DefineAsmSymbol(sym.name,AB_INDIRECT,AT_DATA,ptrdef);
  894. { reuse the section if possible }
  895. if section=sec_rodata then
  896. indsecname:=secname
  897. else
  898. indsecname:=lower(symind.name);
  899. indtcb:=ctai_typedconstbuilder.create([tcalo_new_section]);
  900. indtcb.emit_tai(tai_const.create_sym_offset(sym,0),ptrdef);
  901. current_asmdata.asmlists[al_indirectglobals].concatlist(indtcb.get_final_asmlist(
  902. symind,
  903. ptrdef,
  904. sec_rodata,
  905. indsecname,
  906. ptrdef.alignment));
  907. indtcb.free;
  908. if not (target_info.system in systems_indirect_var_imports) then
  909. current_module.add_public_asmsym(symind.name,AB_INDIRECT,AT_DATA);
  910. end;
  911. end;
  912. procedure ttai_typedconstbuilder.finalize_vectorized_dead_strip_asmlist(def: tdef; const basename, itemname: TSymStr; st: tsymtable; alignment: shortint; options: ttcasmlistoptions);
  913. var
  914. sym: tasmsymbol;
  915. secname: TSymStr;
  916. sectype: TAsmSectiontype;
  917. asmtype : TAsmsymtype;
  918. customsecname: boolean;
  919. dsopts : ttcdeadstripsectionsymboloptions;
  920. begin
  921. fvectorized_finalize_called:=true;
  922. sym:=nil;
  923. customsecname:=get_vectorized_dead_strip_custom_section_name(basename,st,secname);
  924. if customsecname then
  925. sectype:=sec_user
  926. else
  927. sectype:=sec_data;
  928. dsopts:=[tcdssso_define];
  929. if tcalo_is_public_asm in options then
  930. include(dsopts,tcdssso_register_asmsym);
  931. if tcalo_data_force_indirect in options then
  932. include(dsopts,tcdssso_use_indirect);
  933. if tcalo_vectorized_dead_strip_start in options then
  934. begin
  935. { the start and end names are predefined }
  936. if itemname<>'' then
  937. internalerror(2015110801);
  938. sym:=get_vectorized_dead_strip_section_symbol_start(basename,st,dsopts);
  939. if not customsecname then
  940. secname:=make_mangledname(basename,st,'1_START');
  941. end
  942. else if tcalo_vectorized_dead_strip_end in options then
  943. begin
  944. { the start and end names are predefined }
  945. if itemname<>'' then
  946. internalerror(2015110802);
  947. sym:=get_vectorized_dead_strip_section_symbol_end(basename,st,dsopts);
  948. if not customsecname then
  949. secname:=make_mangledname(basename,st,'3_END');
  950. end
  951. else if tcalo_vectorized_dead_strip_item in options then
  952. begin
  953. if tcalo_data_force_indirect in options then
  954. asmtype:=AT_DATA_FORCEINDIRECT
  955. else
  956. asmtype:=AT_DATA;
  957. sym:=current_asmdata.DefineAsmSymbol(make_mangledname(basename,st,itemname),AB_GLOBAL,asmtype,def);
  958. if tcalo_is_public_asm in options then
  959. current_module.add_public_asmsym(sym);
  960. if not customsecname then
  961. secname:=make_mangledname(basename,st,'2_'+itemname);
  962. exclude(options,tcalo_vectorized_dead_strip_item);
  963. end;
  964. finalize_asmlist(sym,def,sectype,secname,alignment,options);
  965. end;
  966. procedure ttai_typedconstbuilder.do_emit_tai(p: tai; def: tdef);
  967. begin
  968. { by default we don't care about the type }
  969. fasmlist.concat(p);
  970. end;
  971. function ttai_typedconstbuilder.get_final_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: longint): tasmlist;
  972. begin
  973. if not fasmlist_finalized then
  974. begin
  975. finalize_asmlist(sym,def,section,secname,alignment,foptions);
  976. finalize_asmlist_add_indirect_sym(sym,def,section,secname,alignment,foptions);
  977. fasmlist_finalized:=true;
  978. end;
  979. result:=fasmlist;
  980. end;
  981. function ttai_typedconstbuilder.get_final_asmlist_vectorized_dead_strip(def: tdef; const basename, itemname: TSymStr; st: TSymtable; alignment: longint): tasmlist;
  982. begin
  983. if not fasmlist_finalized then
  984. begin
  985. finalize_vectorized_dead_strip_asmlist(def,basename,itemname,st,alignment,foptions);
  986. fasmlist_finalized:=true;
  987. end;
  988. result:=fasmlist;
  989. end;
  990. class function ttai_typedconstbuilder.get_string_symofs(typ: tstringtype; winlikewidestring: boolean): pint;
  991. begin
  992. { darwin's linker does not support negative offsets }
  993. if not(target_info.system in systems_darwin) then
  994. result:=0
  995. else
  996. result:=get_string_header_size(typ,winlikewidestring);
  997. end;
  998. class function ttai_typedconstbuilder.get_dynarray_symofs:pint;
  999. begin
  1000. { darwin's linker does not support negative offsets }
  1001. if not (target_info.system in systems_darwin) then
  1002. result:=0
  1003. else
  1004. result:=get_dynarray_header_size;
  1005. end;
  1006. class function ttai_typedconstbuilder.get_string_header_size(typ: tstringtype; winlikewidestring: boolean): pint;
  1007. var
  1008. ansistring_header_size: pint;
  1009. unicodestring_header_size: pint;
  1010. begin
  1011. ansistring_header_size:=
  1012. { encoding }
  1013. 2 +
  1014. { elesize }
  1015. 2 +
  1016. {$ifdef cpu64bitaddr}
  1017. { alignment }
  1018. 4 +
  1019. {$endif cpu64bitaddr}
  1020. { reference count }
  1021. sizesinttype.size +
  1022. { length }
  1023. sizesinttype.size;
  1024. unicodestring_header_size:=ansistring_header_size;
  1025. case typ of
  1026. st_ansistring:
  1027. result:=ansistring_header_size;
  1028. st_unicodestring:
  1029. result:=unicodestring_header_size;
  1030. st_widestring:
  1031. if winlikewidestring then
  1032. result:=0
  1033. else
  1034. result:=unicodestring_header_size;
  1035. else
  1036. result:=0;
  1037. end;
  1038. end;
  1039. class function ttai_typedconstbuilder.get_dynarray_header_size:pint;
  1040. begin
  1041. result:=
  1042. { reference count }
  1043. ptrsinttype.size +
  1044. { high value }
  1045. sizesinttype.size;
  1046. end;
  1047. constructor ttai_typedconstbuilder.create(const options: ttcasmlistoptions);
  1048. begin
  1049. inherited create;
  1050. fasmlist:=tasmlist.create;
  1051. foptions:=options;
  1052. { queue is empty }
  1053. fqueue_offset:=low(fqueue_offset);
  1054. finternal_data_current_section:=sec_none;
  1055. end;
  1056. destructor ttai_typedconstbuilder.destroy;
  1057. begin
  1058. { the queue should have been flushed if it was used }
  1059. if fqueue_offset<>low(fqueue_offset) then
  1060. internalerror(2014062901);
  1061. faggregateinformation.free;
  1062. fasmlist.free;
  1063. inherited destroy;
  1064. end;
  1065. procedure ttai_typedconstbuilder.start_internal_data_builder(list: tasmlist; sectype: TAsmSectiontype; const secname: TSymStr; out tcb: ttai_typedconstbuilder; out l: tasmlabel);
  1066. var
  1067. options: ttcasmlistoptions;
  1068. foundsec: longint;
  1069. begin
  1070. { you can't start multiple concurrent internal data builders for the
  1071. same tcb, finish the first before starting another }
  1072. if finternal_data_current_section<>sec_none then
  1073. internalerror(2016082801);
  1074. { we don't know what was previously added to this list, so always add
  1075. a section header. We'll use the same section name in case multiple
  1076. items are added to the same kind of section (rodata, rodata_no_rel,
  1077. ...), so that everything will still end up in the same section even if
  1078. there are multiple section headers }
  1079. options:=[tcalo_is_lab,tcalo_new_section];
  1080. finternal_data_current_section:=sectype;
  1081. l:=nil;
  1082. { did we already create a section of this type for the internal data of
  1083. this builder? }
  1084. foundsec:=get_internal_data_section_index(sectype);
  1085. if foundsec=-1 then
  1086. begin
  1087. { we only need to start a dead-strippable section of data at the
  1088. start of the first subsection of this kind for this block.
  1089. exception: if dead stripping happens based on objects/libraries,
  1090. then we only have to create a new object file for the first
  1091. internal data section of any kind (all the rest will simply be put
  1092. in the same object file) }
  1093. if create_smartlink then
  1094. begin
  1095. if not create_smartlink_library or
  1096. (length(finternal_data_section_info)=0) then
  1097. include(options,tcalo_make_dead_strippable);
  1098. { on Darwin, dead code/data stripping happens based on non-
  1099. temporary labels (any label that doesn't start with "L" -- it
  1100. doesn't have to be global) -> add a non-temporary lobel at the
  1101. start of every kind of subsection created in this builder }
  1102. if target_info.system in systems_darwin then
  1103. l:=get_internal_data_section_start_label;
  1104. end;
  1105. foundsec:=length(finternal_data_section_info);
  1106. setlength(finternal_data_section_info,foundsec+1);
  1107. finternal_data_section_info[foundsec].sectype:=sectype;
  1108. end;
  1109. if not assigned(finternal_data_asmlist) and
  1110. (cs_create_smart in current_settings.moduleswitches) then
  1111. begin
  1112. l:=get_internal_data_section_start_label;
  1113. { the internal data list should only be assigned by this routine,
  1114. the first time that an internal data block is started }
  1115. if not assigned(list) or
  1116. assigned(finternal_data_asmlist) then
  1117. internalerror(2015032101);
  1118. finternal_data_asmlist:=list;
  1119. end
  1120. { all internal data for this tcb must go to the same list (otherwise all
  1121. data we want to add to the dead-strippable block is not guaranteed to
  1122. be sequential and e.g. in the same object file in case of library-based
  1123. dead stripping) }
  1124. else if (assigned(finternal_data_asmlist) and
  1125. (list<>finternal_data_asmlist)) or
  1126. not assigned(list) then
  1127. internalerror(2015032101);
  1128. finternal_data_asmlist:=list;
  1129. if not assigned(l) then
  1130. l:=get_internal_data_section_internal_label;
  1131. { first section of this kind -> set name }
  1132. if finternal_data_section_info[foundsec].secname='' then
  1133. if secname='' then
  1134. finternal_data_section_info[foundsec].secname:=l.Name
  1135. else
  1136. finternal_data_section_info[foundsec].secname:=secname
  1137. { if the name is specified multiple times, it must match }
  1138. else if (secname<>'') and
  1139. (finternal_data_section_info[foundsec].secname<>secname) then
  1140. internalerror(2015032401);
  1141. tcb:=ttai_typedconstbuilderclass(classtype).create(options);
  1142. end;
  1143. procedure ttai_typedconstbuilder.finish_internal_data_builder(var tcb: ttai_typedconstbuilder; l: tasmlabel; def: tdef; alignment: longint);
  1144. begin
  1145. finternal_data_asmlist.concatList(tcb.get_final_asmlist(l,def,
  1146. finternal_data_current_section,
  1147. finternal_data_section_info[get_internal_data_section_index(finternal_data_current_section)].secname,
  1148. alignment));
  1149. tcb.free;
  1150. tcb:=nil;
  1151. finternal_data_current_section:=sec_none;
  1152. end;
  1153. procedure ttai_typedconstbuilder.emit_tai(p: tai; def: tdef);
  1154. var
  1155. kind: ttypedconstkind;
  1156. info: taggregateinformation;
  1157. begin
  1158. { these elements can be aggregates themselves, e.g. a shortstring can
  1159. be emitted as a series of bytes and char arrays }
  1160. kind:=aggregate_kind(def);
  1161. info:=curagginfo;
  1162. if (kind<>tck_simple) and
  1163. (not assigned(info) or
  1164. (info.typ<>kind)) then
  1165. internalerror(2014091001);
  1166. { if we're emitting a record, handle the padding bytes, and in case of
  1167. an anonymous record also add the next field }
  1168. if assigned(info) then
  1169. begin
  1170. { queue_init already adds padding }
  1171. if not queue_is_active and
  1172. (is_record(info.def) or
  1173. is_object(info.def)) and
  1174. { may add support for these later }
  1175. not is_packed_record_or_object(info.def) then
  1176. pad_next_field(def);
  1177. end;
  1178. { emit the data }
  1179. do_emit_tai(p,def);
  1180. end;
  1181. procedure ttai_typedconstbuilder.emit_tai_procvar2procdef(p: tai; pvdef: tprocvardef);
  1182. begin
  1183. { nothing special by default, since we don't care about the type }
  1184. emit_tai(p,pvdef);
  1185. end;
  1186. procedure ttai_typedconstbuilder.maybe_emit_tail_padding(def: tdef);
  1187. var
  1188. info: taggregateinformation;
  1189. fillbytes: asizeint;
  1190. begin
  1191. info:=curagginfo;
  1192. if not assigned(info) then
  1193. internalerror(2014091002);
  1194. if def<>info.def then
  1195. internalerror(2014091205);
  1196. if (is_record(def) or
  1197. is_object(def)) and
  1198. not is_packed_record_or_object(def) then
  1199. begin
  1200. fillbytes:=def.size-info.curoffset;
  1201. while fillbytes>0 do
  1202. begin
  1203. do_emit_tai(Tai_const.Create_8bit(0),u8inttype);
  1204. dec(fillbytes)
  1205. end;
  1206. end;
  1207. end;
  1208. function ttai_typedconstbuilder.emit_string_const_common(stringtype: tstringtype; len: asizeint; encoding: tstringencoding; var startlab: tasmlabel): tasmlabofs;
  1209. var
  1210. string_symofs: asizeint;
  1211. charptrdef: tdef;
  1212. elesize: word;
  1213. begin
  1214. result.lab:=startlab;
  1215. result.ofs:=0;
  1216. { pack the data, so that we don't add unnecessary null bytes after the
  1217. constant string }
  1218. begin_anonymous_record('$'+get_dynstring_rec_name(stringtype,false,len),1,sizeof(TConstPtrUInt),1,1);
  1219. string_symofs:=get_string_symofs(stringtype,false);
  1220. { encoding }
  1221. emit_tai(tai_const.create_16bit(encoding),u16inttype);
  1222. inc(result.ofs,2);
  1223. { element size }
  1224. case stringtype of
  1225. st_ansistring:
  1226. begin
  1227. elesize:=1;
  1228. charptrdef:=charpointertype;
  1229. end;
  1230. st_unicodestring:
  1231. begin
  1232. elesize:=2;
  1233. charptrdef:=widecharpointertype;
  1234. end
  1235. else
  1236. internalerror(2014080401);
  1237. end;
  1238. emit_tai(tai_const.create_16bit(elesize),u16inttype);
  1239. inc(result.ofs,2);
  1240. {$ifdef cpu64bitaddr}
  1241. { dummy for alignment }
  1242. emit_tai(tai_const.create_32bit(0),u32inttype);
  1243. inc(result.ofs,4);
  1244. {$endif cpu64bitaddr}
  1245. emit_tai(tai_const.create_sizeint(-1),sizesinttype);
  1246. inc(result.ofs,sizesinttype.size);
  1247. emit_tai(tai_const.create_sizeint(len),sizesinttype);
  1248. inc(result.ofs,sizesinttype.size);
  1249. if string_symofs=0 then
  1250. begin
  1251. { results in slightly more efficient code }
  1252. emit_tai(tai_label.create(result.lab),charptrdef);
  1253. result.ofs:=0;
  1254. { create new label of the same kind (including whether or not the
  1255. name starts with target_asm.labelprefix in case it's AB_LOCAL,
  1256. so we keep the difference depending on whether the original was
  1257. allocated via getstatic/getlocal/getglobal datalabel) }
  1258. startlab:=tasmlabel.create(current_asmdata.AsmSymbolDict,startlab.name+'$strlab',startlab.bind,startlab.typ);
  1259. end;
  1260. { sanity check }
  1261. if result.ofs<>string_symofs then
  1262. internalerror(2012051701);
  1263. end;
  1264. function ttai_typedconstbuilder.get_dynstring_def_for_type(stringtype: tstringtype; winlikewidestring: boolean): tstringdef;
  1265. begin
  1266. if stringtype=st_ansistring then
  1267. result:=tstringdef(cansistringtype)
  1268. else if (stringtype=st_unicodestring) or
  1269. ((stringtype=st_widestring) and
  1270. not winlikewidestring) then
  1271. result:=tstringdef(cunicodestringtype)
  1272. else if stringtype=st_widestring then
  1273. result:=tstringdef(cwidestringtype)
  1274. else
  1275. internalerror(2015122101);
  1276. end;
  1277. procedure ttai_typedconstbuilder.begin_aggregate_internal(def: tdef; anonymous: boolean);
  1278. var
  1279. info: taggregateinformation;
  1280. tck: ttypedconstkind;
  1281. begin
  1282. tck:=aggregate_kind(def);
  1283. if tck=tck_simple then
  1284. exit;
  1285. if not assigned(faggregateinformation) then
  1286. faggregateinformation:=tfpobjectlist.create
  1287. { if we're starting an anonymous record, we can't align it yet because
  1288. the alignment depends on the fields that will be added -> we'll do
  1289. it at the end }
  1290. else if not anonymous or
  1291. ((def.typ<>recorddef) and
  1292. not is_object(def)) then
  1293. begin
  1294. { add padding if necessary, and update the current field/offset }
  1295. info:=curagginfo;
  1296. if (is_record(curagginfo.def) or
  1297. is_object(curagginfo.def)) and
  1298. not is_packed_record_or_object(curagginfo.def) then
  1299. begin
  1300. if queue_is_active then
  1301. internalerror(2015073001);
  1302. pad_next_field(def);
  1303. end;
  1304. end
  1305. { if this is the outer record, no padding is required; the alignment
  1306. has to be specified explicitly in that case via get_final_asmlist() }
  1307. else if assigned(curagginfo) and
  1308. (curagginfo.def.typ=recorddef) then
  1309. { mark where we'll have to insert the padding bytes at the end }
  1310. mark_anon_aggregate_alignment;
  1311. info:=caggregateinformation.create(def,aggregate_kind(def));
  1312. faggregateinformation.add(info);
  1313. end;
  1314. procedure ttai_typedconstbuilder.end_aggregate_internal(def: tdef; anonymous: boolean);
  1315. var
  1316. info: taggregateinformation;
  1317. tck: ttypedconstkind;
  1318. begin
  1319. tck:=aggregate_kind(def);
  1320. if tck=tck_simple then
  1321. exit;
  1322. { add tail padding if necessary }
  1323. maybe_emit_tail_padding(def);
  1324. { pop and free the information }
  1325. info:=curagginfo;
  1326. faggregateinformation.count:=faggregateinformation.count-1;
  1327. info.free;
  1328. end;
  1329. class function ttai_typedconstbuilder.get_vectorized_dead_strip_section_symbol(const basename: string; st: tsymtable; options: ttcdeadstripsectionsymboloptions; start: boolean): tasmsymbol;
  1330. var
  1331. name: TSymStr;
  1332. asmtype : TAsmsymtype;
  1333. begin
  1334. if start then
  1335. name:=make_mangledname(basename,st,'START')
  1336. else
  1337. name:=make_mangledname(basename,st,'END');
  1338. if tcdssso_define in options then
  1339. begin
  1340. if tcdssso_use_indirect in options then
  1341. asmtype:=AT_DATA_FORCEINDIRECT
  1342. else
  1343. asmtype:=AT_DATA;
  1344. result:=current_asmdata.DefineAsmSymbol(name,AB_GLOBAL,asmtype,voidpointertype);
  1345. if tcdssso_register_asmsym in options then
  1346. current_module.add_public_asmsym(result);
  1347. end
  1348. else
  1349. begin
  1350. result:=current_asmdata.RefAsmSymbol(name,AT_DATA,tcdssso_use_indirect in options);
  1351. if tcdssso_register_asmsym in options then
  1352. current_module.add_extern_asmsym(result);
  1353. end;
  1354. end;
  1355. class function ttai_typedconstbuilder.get_vectorized_dead_strip_custom_section_name(const basename: TSymStr; st: tsymtable; out secname: TSymStr): boolean;
  1356. begin
  1357. result:=false;
  1358. end;
  1359. class function ttai_typedconstbuilder.get_vectorized_dead_strip_section_symbol_start(const basename: string; st: tsymtable; options: ttcdeadstripsectionsymboloptions): tasmsymbol;
  1360. begin
  1361. result:=get_vectorized_dead_strip_section_symbol(basename,st,options,true);
  1362. end;
  1363. class function ttai_typedconstbuilder.get_vectorized_dead_strip_section_symbol_end(const basename: string; st: tsymtable; options: ttcdeadstripsectionsymboloptions): tasmsymbol;
  1364. begin
  1365. result:=get_vectorized_dead_strip_section_symbol(basename,st,options,false);
  1366. end;
  1367. class function ttai_typedconstbuilder.get_dynstring_rec_name(typ: tstringtype; winlike: boolean; len: asizeint): TSymStr;
  1368. begin
  1369. case typ of
  1370. st_ansistring:
  1371. result:='ansistrrec';
  1372. st_unicodestring,
  1373. st_widestring:
  1374. if (typ=st_unicodestring) or
  1375. not winlike then
  1376. result:='unicodestrrec'
  1377. else
  1378. result:='widestrrec';
  1379. else
  1380. internalerror(2014080402);
  1381. end;
  1382. result:=result+tostr(len);
  1383. end;
  1384. class function ttai_typedconstbuilder.get_dynstring_rec(typ: tstringtype; winlike: boolean; len: asizeint): trecorddef;
  1385. var
  1386. name: TSymStr;
  1387. streledef: tdef;
  1388. strtypesym: ttypesym;
  1389. srsym: tsym;
  1390. srsymtable: tsymtable;
  1391. begin
  1392. name:=get_dynstring_rec_name(typ,winlike,len);
  1393. { search in the interface of all units for the type to reuse it }
  1394. if searchsym_type(name,srsym,srsymtable) then
  1395. begin
  1396. result:=trecorddef(ttypesym(srsym).typedef);
  1397. exit;
  1398. end
  1399. else
  1400. begin
  1401. { also search the implementation of the current unit }
  1402. strtypesym:=try_search_current_module_type(name);
  1403. if assigned(strtypesym) then
  1404. begin
  1405. result:=trecorddef(strtypesym.typedef);
  1406. exit;
  1407. end;
  1408. end;
  1409. if (typ<>st_widestring) or
  1410. not winlike then
  1411. begin
  1412. result:=crecorddef.create_global_internal('$'+name,1,1,1);
  1413. { encoding }
  1414. result.add_field_by_def('',u16inttype);
  1415. { element size }
  1416. result.add_field_by_def('',u16inttype);
  1417. { elements }
  1418. case typ of
  1419. st_ansistring:
  1420. streledef:=cansichartype;
  1421. st_unicodestring:
  1422. streledef:=cwidechartype;
  1423. else
  1424. internalerror(2016082301);
  1425. end;
  1426. {$ifdef cpu64bitaddr}
  1427. { dummy for alignment }
  1428. result.add_field_by_def('',u32inttype);
  1429. {$endif cpu64bitaddr}
  1430. { reference count }
  1431. result.add_field_by_def('',sizesinttype);
  1432. { length in elements }
  1433. result.add_field_by_def('',sizesinttype);
  1434. end
  1435. else
  1436. begin
  1437. result:=crecorddef.create_global_internal('$'+name,4,
  1438. targetinfos[target_info.system]^.alignment.recordalignmin,
  1439. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1440. { length in bytes }
  1441. result.add_field_by_def('',s32inttype);
  1442. streledef:=cwidechartype;
  1443. end;
  1444. { data (include zero terminator) }
  1445. result.add_field_by_def('',carraydef.getreusable(streledef,len+1));
  1446. trecordsymtable(trecorddef(result).symtable).addalignmentpadding;
  1447. end;
  1448. function ttai_typedconstbuilder.emit_ansistring_const(datalist: TAsmList; data: pchar; len: asizeint; encoding: tstringencoding): tasmlabofs;
  1449. var
  1450. s: PChar;
  1451. startlab: tasmlabel;
  1452. ansistrrecdef: trecorddef;
  1453. datadef: tdef;
  1454. datatcb: ttai_typedconstbuilder;
  1455. begin
  1456. start_internal_data_builder(datalist,sec_rodata_norel,'',datatcb,startlab);
  1457. result:=datatcb.emit_string_const_common(st_ansistring,len,encoding,startlab);
  1458. getmem(s,len+1);
  1459. move(data^,s^,len);
  1460. s[len]:=#0;
  1461. { terminating zero included }
  1462. datadef:=carraydef.getreusable(cansichartype,len+1);
  1463. datatcb.maybe_begin_aggregate(datadef);
  1464. datatcb.emit_tai(tai_string.create_pchar(s,len+1),datadef);
  1465. datatcb.maybe_end_aggregate(datadef);
  1466. ansistrrecdef:=datatcb.end_anonymous_record;
  1467. finish_internal_data_builder(datatcb,startlab,ansistrrecdef,const_align(voidpointertype.alignment));
  1468. end;
  1469. function ttai_typedconstbuilder.emit_unicodestring_const(datalist: TAsmList; data: pointer; encoding: tstringencoding; winlike: boolean):tasmlabofs;
  1470. var
  1471. i, strlength: longint;
  1472. string_symofs: asizeint;
  1473. startlab: tasmlabel;
  1474. datadef: tdef;
  1475. datatcb: ttai_typedconstbuilder;
  1476. unicodestrrecdef: trecorddef;
  1477. begin
  1478. start_internal_data_builder(datalist,sec_rodata_norel,'',datatcb,startlab);
  1479. strlength:=getlengthwidestring(pcompilerwidestring(data));
  1480. if winlike then
  1481. begin
  1482. result.lab:=startlab;
  1483. datatcb.begin_anonymous_record('$'+get_dynstring_rec_name(st_widestring,true,strlength),
  1484. 4,4,
  1485. targetinfos[target_info.system]^.alignment.recordalignmin,
  1486. targetinfos[target_info.system]^.alignment.maxCrecordalign);
  1487. datatcb.emit_tai(Tai_const.Create_32bit(strlength*cwidechartype.size),s32inttype);
  1488. { can we optimise by placing the string constant label at the
  1489. required offset? }
  1490. string_symofs:=get_string_symofs(st_widestring,true);
  1491. if string_symofs=0 then
  1492. begin
  1493. { yes }
  1494. datatcb.emit_tai(Tai_label.Create(result.lab),widecharpointertype);
  1495. { allocate a separate label for the start of the data (see
  1496. emit_string_const_common() for explanation) }
  1497. startlab:=tasmlabel.create(current_asmdata.AsmSymbolDict,startlab.name+'$strlab',startlab.bind,startlab.typ);
  1498. end
  1499. else
  1500. internalerror(2015031502);
  1501. result.ofs:=string_symofs;
  1502. end
  1503. else
  1504. begin
  1505. result:=datatcb.emit_string_const_common(st_unicodestring,strlength,encoding,startlab);
  1506. end;
  1507. if cwidechartype.size = 2 then
  1508. begin
  1509. datadef:=carraydef.getreusable(cwidechartype,strlength+1);
  1510. datatcb.maybe_begin_aggregate(datadef);
  1511. for i:=0 to strlength-1 do
  1512. datatcb.emit_tai(Tai_const.Create_16bit(pcompilerwidestring(data)^.data[i]),cwidechartype);
  1513. { ending #0 }
  1514. datatcb.emit_tai(Tai_const.Create_16bit(0),cwidechartype);
  1515. datatcb.maybe_end_aggregate(datadef);
  1516. unicodestrrecdef:=datatcb.end_anonymous_record;
  1517. end
  1518. else
  1519. { code generation for other sizes must be written }
  1520. internalerror(200904271);
  1521. finish_internal_data_builder(datatcb,startlab,unicodestrrecdef,const_align(voidpointertype.alignment));
  1522. end;
  1523. procedure ttai_typedconstbuilder.emit_string_offset(const ll: tasmlabofs; const strlength: longint; const st: tstringtype; const winlikewidestring: boolean; const charptrdef: tdef);
  1524. begin
  1525. emit_tai(Tai_const.Create_sym_offset(ll.lab,ll.ofs),get_dynstring_def_for_type(st,winlikewidestring));
  1526. end;
  1527. procedure ttai_typedconstbuilder.emit_dynarray_offset(const ll:tasmlabofs;const arrlength:asizeint;const arrdef:tdef);
  1528. begin
  1529. emit_tai(tai_const.create_sym_offset(ll.lab,ll.ofs),arrdef);
  1530. end;
  1531. function ttai_typedconstbuilder.begin_dynarray_const(arrdef:tdef;var startlab:tasmlabel;out arrlengthloc:ttypedconstplaceholder):tasmlabofs;
  1532. var
  1533. dynarray_symofs: asizeint;
  1534. elesize: word;
  1535. begin
  1536. result.lab:=startlab;
  1537. result.ofs:=0;
  1538. { pack the data, so that we don't add unnecessary null bytes after the
  1539. constant string }
  1540. begin_anonymous_record('',1,sizeof(TConstPtrUInt),1,1);
  1541. dynarray_symofs:=get_dynarray_symofs;
  1542. { what to do if ptrsinttype <> sizesinttype??? }
  1543. emit_tai(tai_const.create_sizeint(-1),ptrsinttype);
  1544. inc(result.ofs,ptrsinttype.size);
  1545. arrlengthloc:=emit_placeholder(sizesinttype);
  1546. inc(result.ofs,sizesinttype.size);
  1547. if dynarray_symofs=0 then
  1548. begin
  1549. { results in slightly more efficient code }
  1550. emit_tai(tai_label.create(result.lab),arrdef);
  1551. result.ofs:=0;
  1552. { create new label of the same kind (including whether or not the
  1553. name starts with target_asm.labelprefix in case it's AB_LOCAL,
  1554. so we keep the difference depending on whether the original was
  1555. allocated via getstatic/getlocal/getglobal datalabel) }
  1556. startlab:=tasmlabel.create(current_asmdata.AsmSymbolDict,startlab.name+'$dynarrlab',startlab.bind,startlab.typ);
  1557. end;
  1558. { sanity check }
  1559. if result.ofs<>dynarray_symofs then
  1560. internalerror(2018020601);
  1561. end;
  1562. function ttai_typedconstbuilder.end_dynarray_const(arrdef:tdef;arrlength:asizeint;arrlengthloc:ttypedconstplaceholder):tdef;
  1563. begin
  1564. { we emit the high value, not the count }
  1565. arrlengthloc.replace(tai_const.Create_sizeint(arrlength-1),sizesinttype);
  1566. result:=end_anonymous_record;
  1567. end;
  1568. function ttai_typedconstbuilder.emit_shortstring_const(const str: shortstring): tdef;
  1569. begin
  1570. { we use an arraydef instead of a shortstringdef, because we don't have
  1571. functionality in place yet to reuse shortstringdefs of the same length
  1572. and neither the lowlevel nor the llvm typedconst builder cares about
  1573. this difference }
  1574. result:=carraydef.getreusable(cansichartype,length(str)+1);
  1575. maybe_begin_aggregate(result);
  1576. emit_tai(Tai_const.Create_8bit(length(str)),u8inttype);
  1577. if str<>'' then
  1578. emit_tai(Tai_string.Create(str),carraydef.getreusable(cansichartype,length(str)));
  1579. maybe_end_aggregate(result);
  1580. end;
  1581. function ttai_typedconstbuilder.emit_pchar_const(str: pchar; len: pint; copypchar: boolean): tdef;
  1582. var
  1583. newstr: pchar;
  1584. begin
  1585. result:=carraydef.getreusable(cansichartype,len+1);
  1586. maybe_begin_aggregate(result);
  1587. if (len=0) and
  1588. (not assigned(str) or
  1589. copypchar) then
  1590. emit_tai(Tai_const.Create_8bit(0),cansichartype)
  1591. else
  1592. begin
  1593. if copypchar then
  1594. begin
  1595. getmem(newstr,len+1);
  1596. move(str^,newstr^,len+1);
  1597. str:=newstr;
  1598. end;
  1599. emit_tai(Tai_string.Create_pchar(str,len+1),result);
  1600. end;
  1601. maybe_end_aggregate(result);
  1602. end;
  1603. procedure ttai_typedconstbuilder.emit_guid_const(const guid: tguid);
  1604. var
  1605. i: longint;
  1606. field: tfieldvarsym;
  1607. begin
  1608. maybe_begin_aggregate(rec_tguid);
  1609. { variant record -> must specify which fields get initialised }
  1610. next_field:=tfieldvarsym(rec_tguid.symtable.Find('DATA1'));
  1611. emit_tai(Tai_const.Create_32bit(longint(guid.D1)),u32inttype);
  1612. next_field:=tfieldvarsym(rec_tguid.symtable.Find('DATA2'));
  1613. emit_tai(Tai_const.Create_16bit(guid.D2),u16inttype);
  1614. next_field:=tfieldvarsym(rec_tguid.symtable.Find('DATA3'));
  1615. emit_tai(Tai_const.Create_16bit(guid.D3),u16inttype);
  1616. field:=tfieldvarsym(rec_tguid.symtable.Find('DATA4'));
  1617. next_field:=field;
  1618. { the array }
  1619. maybe_begin_aggregate(field.vardef);
  1620. for i:=Low(guid.D4) to High(guid.D4) do
  1621. emit_tai(Tai_const.Create_8bit(guid.D4[i]),u8inttype);
  1622. maybe_end_aggregate(field.vardef);
  1623. maybe_end_aggregate(rec_tguid);
  1624. end;
  1625. procedure ttai_typedconstbuilder.emit_procdef_const(pd: tprocdef);
  1626. begin
  1627. emit_tai(Tai_const.Createname(pd.mangledname,AT_FUNCTION,0),cprocvardef.getreusableprocaddr(pd));
  1628. end;
  1629. procedure ttai_typedconstbuilder.emit_ord_const(value: int64; def: tdef);
  1630. begin
  1631. case def.size of
  1632. 1:
  1633. emit_tai(Tai_const.Create_8bit(byte(value)),def);
  1634. 2:
  1635. emit_tai(Tai_const.Create_16bit(word(value)),def);
  1636. 4:
  1637. emit_tai(Tai_const.Create_32bit(longint(value)),def);
  1638. 8:
  1639. emit_tai(Tai_const.Create_64bit(value),def);
  1640. else
  1641. internalerror(2014100501);
  1642. end;
  1643. end;
  1644. procedure ttai_typedconstbuilder.emit_pooled_shortstring_const_ref(const str:shortstring);
  1645. var
  1646. pool : thashset;
  1647. entry : phashsetitem;
  1648. strlab : tasmlabel;
  1649. l : longint;
  1650. pc : pansichar;
  1651. datadef : tdef;
  1652. strtcb : ttai_typedconstbuilder;
  1653. begin
  1654. pool:=current_asmdata.ConstPools[sp_shortstr];
  1655. entry:=pool.FindOrAdd(@str[1],length(str));
  1656. { :-(, we must generate a new entry }
  1657. if not assigned(entry^.Data) then
  1658. begin
  1659. current_asmdata.getglobaldatalabel(strlab);
  1660. { include length and terminating zero for quick conversion to pchar }
  1661. l:=length(str);
  1662. getmem(pc,l+2);
  1663. move(str[1],pc[1],l);
  1664. pc[0]:=chr(l);
  1665. pc[l+1]:=#0;
  1666. datadef:=carraydef.getreusable(cansichartype,l+2);
  1667. { we start a new constbuilder as we don't know whether we're called
  1668. from inside an internal constbuilder }
  1669. strtcb:=ctai_typedconstbuilder.create([tcalo_is_lab,tcalo_make_dead_strippable,tcalo_apply_constalign]);
  1670. strtcb.maybe_begin_aggregate(datadef);
  1671. strtcb.emit_tai(Tai_string.Create_pchar(pc,l+2),datadef);
  1672. strtcb.maybe_end_aggregate(datadef);
  1673. current_asmdata.asmlists[al_typedconsts].concatList(
  1674. strtcb.get_final_asmlist(strlab,datadef,sec_rodata_norel,strlab.name,const_align(sizeof(pint)))
  1675. );
  1676. strtcb.free;
  1677. entry^.Data:=strlab;
  1678. end
  1679. else
  1680. strlab:=tasmlabel(entry^.Data);
  1681. emit_tai(tai_const.Create_sym(strlab),charpointertype);
  1682. end;
  1683. procedure ttai_typedconstbuilder.maybe_begin_aggregate(def: tdef);
  1684. begin
  1685. begin_aggregate_internal(def,false);
  1686. end;
  1687. procedure ttai_typedconstbuilder.maybe_end_aggregate(def: tdef);
  1688. begin
  1689. end_aggregate_internal(def,false);
  1690. end;
  1691. function ttai_typedconstbuilder.begin_anonymous_record(const optionalname: string; packrecords, recordalign, recordalignmin, maxcrecordalign: shortint): trecorddef;
  1692. var
  1693. anonrecorddef: trecorddef;
  1694. typesym: ttypesym;
  1695. begin
  1696. { if the name is specified, we create a typesym with that name in order
  1697. to ensure we can find it again later with that name -> reuse here as
  1698. well if possible (and that also avoids duplicate type name issues) }
  1699. if optionalname<>'' then
  1700. begin
  1701. typesym:=try_search_current_module_type(optionalname);
  1702. if assigned(typesym) then
  1703. begin
  1704. if typesym.typedef.typ<>recorddef then
  1705. internalerror(2015071401);
  1706. result:=trecorddef(typesym.typedef);
  1707. maybe_begin_aggregate(result);
  1708. exit;
  1709. end;
  1710. end;
  1711. { create skeleton def }
  1712. anonrecorddef:=crecorddef.create_global_internal(optionalname,packrecords,recordalignmin,maxcrecordalign);
  1713. trecordsymtable(anonrecorddef.symtable).recordalignment:=recordalign;
  1714. { generic aggregate housekeeping }
  1715. begin_aggregate_internal(anonrecorddef,true);
  1716. { mark as anonymous record }
  1717. curagginfo.anonrecord:=true;
  1718. { in case a descendent wants to do something with the anonrecorddef too }
  1719. result:=anonrecorddef;
  1720. end;
  1721. function ttai_typedconstbuilder.end_anonymous_record: trecorddef;
  1722. var
  1723. info: taggregateinformation;
  1724. anonrecord: boolean;
  1725. begin
  1726. info:=curagginfo;
  1727. if not assigned(info) or
  1728. (info.def.typ<>recorddef) then
  1729. internalerror(2014080201);
  1730. result:=trecorddef(info.def);
  1731. { make a copy, as we need it after info has been freed by
  1732. maybe_end_aggregate(result) }
  1733. anonrecord:=info.anonrecord;
  1734. { finalise the record skeleton (all fields have been added already by
  1735. emit_tai()) -- anonrecord may not be set in case we reused an earlier
  1736. constructed def }
  1737. if anonrecord then
  1738. trecordsymtable(result.symtable).addalignmentpadding;
  1739. end_aggregate_internal(result,true);
  1740. if anonrecord and
  1741. assigned(curagginfo) and
  1742. (curagginfo.def.typ=recorddef) then
  1743. insert_marked_aggregate_alignment(result);
  1744. end;
  1745. procedure ttai_typedconstbuilder.check_add_placeholder(def: tdef);
  1746. begin
  1747. { it only makes sense to add a placeholder inside an aggregate
  1748. (otherwise there can be but one element)
  1749. we cannot add a placeholder in the middle of a queued expression
  1750. either
  1751. the placeholder cannot be an aggregate }
  1752. if not assigned(curagginfo) or
  1753. queue_is_active or
  1754. (aggregate_kind(def)<>tck_simple) then
  1755. internalerror(2015091001);
  1756. end;
  1757. procedure ttai_typedconstbuilder.queue_init(todef: tdef);
  1758. var
  1759. info: taggregateinformation;
  1760. begin
  1761. { nested call to init? }
  1762. if fqueue_offset<>low(fqueue_offset) then
  1763. internalerror(2014062101);
  1764. { insert padding bytes before starting the queue, so that the first
  1765. padding byte won't be interpreted as the emitted value for this queue }
  1766. info:=curagginfo;
  1767. if assigned(info) then
  1768. begin
  1769. if ((info.def.typ=recorddef) or
  1770. is_object(info.def)) and
  1771. { may add support for these later }
  1772. not is_packed_record_or_object(info.def) then
  1773. pad_next_field(todef);
  1774. end;
  1775. fqueue_offset:=0;
  1776. fqueued_def:=todef;
  1777. end;
  1778. procedure ttai_typedconstbuilder.queue_vecn(def: tdef; const index: tconstexprint);
  1779. var
  1780. elelen,
  1781. vecbase: asizeint;
  1782. v: tconstexprint;
  1783. begin
  1784. elelen:=1;
  1785. vecbase:=0;
  1786. case def.typ of
  1787. stringdef :
  1788. ;
  1789. arraydef :
  1790. begin
  1791. if not is_packed_array(def) then
  1792. begin
  1793. elelen:=tarraydef(def).elesize;
  1794. vecbase:=tarraydef(def).lowrange;
  1795. end
  1796. else
  1797. Message(parser_e_packed_dynamic_open_array);
  1798. end;
  1799. else
  1800. Message(parser_e_illegal_expression);
  1801. end;
  1802. { Prevent overflow }
  1803. v:=index-vecbase;
  1804. if (v<int64(low(fqueue_offset))) or (v>int64(high(fqueue_offset))) then
  1805. message3(type_e_range_check_error_bounds,tostr(v),tostr(low(fqueue_offset)),tostr(high(fqueue_offset)));
  1806. if high(fqueue_offset)-fqueue_offset div elelen>v then
  1807. inc(fqueue_offset,elelen*v.svalue)
  1808. else
  1809. message3(type_e_range_check_error_bounds,tostr(index),tostr(vecbase),tostr(high(fqueue_offset)-fqueue_offset div elelen+vecbase))
  1810. end;
  1811. procedure ttai_typedconstbuilder.queue_subscriptn(def: tabstractrecorddef; vs: tfieldvarsym);
  1812. begin
  1813. inc(fqueue_offset,vs.fieldoffset);
  1814. end;
  1815. function ttai_typedconstbuilder.queue_subscriptn_multiple_by_name(def: tabstractrecorddef; const fields: array of TIDString): tdef;
  1816. var
  1817. syms,
  1818. parentdefs: tfplist;
  1819. sym: tsym;
  1820. curdef: tdef;
  1821. i: longint;
  1822. begin
  1823. result:=nil;
  1824. if length(fields)=0 then
  1825. internalerror(2015071601);
  1826. syms:=tfplist.Create;
  1827. syms.count:=length(fields);
  1828. parentdefs:=tfplist.create;
  1829. parentdefs.Count:=length(fields);
  1830. curdef:=def;
  1831. for i:=low(fields) to high(fields) do
  1832. begin
  1833. sym:=search_struct_member_no_helper(tabstractrecorddef(curdef),fields[i]);
  1834. if not assigned(sym) or
  1835. (sym.typ<>fieldvarsym) or
  1836. ((i<>high(fields)) and
  1837. not(tfieldvarsym(sym).vardef.typ in [objectdef,recorddef])) then
  1838. internalerror(2015071505);
  1839. syms[i]:=sym;
  1840. parentdefs[i]:=curdef;
  1841. curdef:=tfieldvarsym(sym).vardef;
  1842. result:=curdef;
  1843. end;
  1844. for i:=high(fields) downto low(fields) do
  1845. queue_subscriptn(tabstractrecorddef(parentdefs[i]),tfieldvarsym(syms[i]));
  1846. syms.free;
  1847. parentdefs.free;
  1848. end;
  1849. procedure ttai_typedconstbuilder.queue_typeconvn(fromdef, todef: tdef);
  1850. begin
  1851. { do nothing }
  1852. end;
  1853. procedure ttai_typedconstbuilder.queue_emit_proc(pd: tprocdef);
  1854. begin
  1855. if fqueue_offset<>0 then
  1856. internalerror(2014092101);
  1857. emit_procdef_const(pd);
  1858. fqueue_offset:=low(fqueue_offset);
  1859. end;
  1860. procedure ttai_typedconstbuilder.queue_emit_staticvar(vs: tstaticvarsym);
  1861. begin
  1862. { pointerdef because we are emitting a pointer to the staticvarsym
  1863. data, not the data itself }
  1864. emit_tai(Tai_const.Createname(vs.mangledname,AT_DATA,fqueue_offset),cpointerdef.getreusable(vs.vardef));
  1865. fqueue_offset:=low(fqueue_offset);
  1866. end;
  1867. procedure ttai_typedconstbuilder.queue_emit_label(l: tlabelsym);
  1868. begin
  1869. emit_tai(Tai_const.Createname(l.mangledname,fqueue_offset),voidcodepointertype);
  1870. fqueue_offset:=low(fqueue_offset);
  1871. end;
  1872. procedure ttai_typedconstbuilder.queue_emit_const(cs: tconstsym);
  1873. var
  1874. resourcestrrec: trecorddef;
  1875. begin
  1876. if cs.consttyp<>constresourcestring then
  1877. internalerror(2014062102);
  1878. if fqueue_offset<>0 then
  1879. internalerror(2014062103);
  1880. { warning: update if/when the type of resource strings changes }
  1881. case cs.consttyp of
  1882. constresourcestring:
  1883. begin
  1884. resourcestrrec:=trecorddef(search_system_type('TRESOURCESTRINGRECORD').typedef);
  1885. queue_subscriptn_multiple_by_name(resourcestrrec,['CURRENTVALUE']);
  1886. queue_emit_asmsym(current_asmdata.RefAsmSymbol(
  1887. make_mangledname('RESSTR',cs.owner,cs.name),AT_DATA),resourcestrrec
  1888. );
  1889. end;
  1890. { can these occur? }
  1891. constord,
  1892. conststring,constreal,
  1893. constset,constpointer,constnil,
  1894. constwstring,constguid:
  1895. internalerror(2015090903);
  1896. else
  1897. internalerror(2015090904);
  1898. end;
  1899. fqueue_offset:=low(fqueue_offset);
  1900. end;
  1901. procedure ttai_typedconstbuilder.queue_emit_asmsym(sym: tasmsymbol; def: tdef);
  1902. begin
  1903. { pointerdef, because "sym" represents the address of whatever the
  1904. data is }
  1905. def:=cpointerdef.getreusable(def);
  1906. emit_tai(Tai_const.Create_sym_offset(sym,fqueue_offset),def);
  1907. fqueue_offset:=low(fqueue_offset);
  1908. end;
  1909. procedure ttai_typedconstbuilder.queue_emit_ordconst(value: int64; def: tdef);
  1910. begin
  1911. emit_ord_const(value,def);
  1912. fqueue_offset:=low(fqueue_offset);
  1913. end;
  1914. function ttai_typedconstbuilder.queue_is_active: boolean;
  1915. begin
  1916. result:=fqueue_offset<>low(fqueue_offset)
  1917. end;
  1918. {****************************************************************************
  1919. tlowleveltypedconstplaceholder
  1920. ****************************************************************************}
  1921. constructor tlowleveltypedconstplaceholder.create(l: tasmlist; pos: tai; d: tdef);
  1922. begin
  1923. inherited create(d);
  1924. list:=l;
  1925. insertpos:=pos;
  1926. end;
  1927. procedure tlowleveltypedconstplaceholder.replace(ai: tai; d: tdef);
  1928. begin
  1929. if d<>def then
  1930. internalerror(2015091007);
  1931. list.insertafter(ai,insertpos);
  1932. list.remove(insertpos);
  1933. insertpos.free;
  1934. end;
  1935. {****************************************************************************
  1936. tai_abstracttypedconst
  1937. ****************************************************************************}
  1938. class constructor ttai_lowleveltypedconstbuilder.classcreate;
  1939. begin
  1940. caggregateinformation:=tlowlevelaggregateinformation;
  1941. end;
  1942. function ttai_lowleveltypedconstbuilder.emit_placeholder(def: tdef): ttypedconstplaceholder;
  1943. var
  1944. p: tai;
  1945. begin
  1946. check_add_placeholder(def);
  1947. p:=tai_marker.Create(mark_position);
  1948. emit_tai(p,def);
  1949. result:=tlowleveltypedconstplaceholder.create(fasmlist,p,def);
  1950. end;
  1951. procedure ttai_lowleveltypedconstbuilder.mark_anon_aggregate_alignment;
  1952. var
  1953. marker: tai_marker;
  1954. begin
  1955. marker:=tai_marker.Create(mark_position);
  1956. fasmlist.concat(marker);
  1957. tlowlevelaggregateinformation(curagginfo).anonrecmarker:=marker;
  1958. end;
  1959. procedure ttai_lowleveltypedconstbuilder.insert_marked_aggregate_alignment(def: tdef);
  1960. var
  1961. info: tlowlevelaggregateinformation;
  1962. fillbytes: asizeint;
  1963. begin
  1964. info:=tlowlevelaggregateinformation(curagginfo);
  1965. if not assigned(info.anonrecmarker) then
  1966. internalerror(2014091401);
  1967. fillbytes:=info.prepare_next_field(def);
  1968. while fillbytes>0 do
  1969. begin
  1970. fasmlist.insertafter(tai_const.create_8bit(0),info.anonrecmarker);
  1971. dec(fillbytes);
  1972. end;
  1973. fasmlist.remove(info.anonrecmarker);
  1974. info.anonrecmarker.free;
  1975. info.anonrecmarker:=nil;
  1976. end;
  1977. procedure ttai_lowleveltypedconstbuilder.finalize_asmlist(sym: tasmsymbol; def: tdef; section: TAsmSectiontype; const secname: TSymStr; alignment: shortint; const options: ttcasmlistoptions);
  1978. begin
  1979. inherited;
  1980. { The darwin/ppc64 assembler or linker seems to have trouble }
  1981. { if a section ends with a global label without any data after it. }
  1982. { So for safety, just put a dummy value here. }
  1983. { Further, the regular linker also kills this symbol when turning }
  1984. { on smart linking in case no value appears after it, so put the }
  1985. { dummy byte there always }
  1986. { Update: the Mac OS X 10.6 linker orders data that needs to be }
  1987. { relocated before all other data, so make this data relocatable, }
  1988. { otherwise the end label won't be moved with the rest }
  1989. if (tcalo_vectorized_dead_strip_end in options) and
  1990. (target_info.system in (systems_darwin+systems_aix)) then
  1991. fasmlist.concat(Tai_const.create_sym(sym));
  1992. end;
  1993. begin
  1994. ctai_typedconstbuilder:=ttai_lowleveltypedconstbuilder;
  1995. end.