psub.pas 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl, Daniel Mantione
  3. Does the parsing and codegeneration at subroutine level
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit psub;
  18. {$i fpcdefs.inc}
  19. { $define debug_eh}
  20. interface
  21. uses
  22. globals,cclasses,
  23. node,nbas,nutils,aasmdata,
  24. symdef,procinfo,optdfa;
  25. type
  26. tcgprocinfo = class(tprocinfo)
  27. private type
  28. ttempinfo_flags_entry = record
  29. tempinfo : ptempinfo;
  30. flags : ttempinfoflags;
  31. end;
  32. ptempinfo_flags_entry = ^ttempinfo_flags_entry;
  33. private
  34. tempinfo_flags_map : TFPList;
  35. tempflags_swapped : boolean;
  36. procedure swap_tempflags;
  37. function store_node_tempflags(var n: tnode; arg: pointer): foreachnoderesult;
  38. procedure CreateInlineInfo;
  39. { returns the node which is the start of the user code, this is needed by the dfa }
  40. function GetUserCode: tnode;
  41. procedure maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  42. procedure add_entry_exit_code;
  43. procedure setup_tempgen;
  44. procedure OptimizeNodeTree;
  45. procedure convert_captured_syms;
  46. protected
  47. procedure generate_code_exceptfilters;
  48. public
  49. { code for the subroutine as tree }
  50. code : tnode;
  51. { positions in the tree for init/final }
  52. entry_asmnode,
  53. loadpara_asmnode,
  54. exitlabel_asmnode,
  55. stackcheck_asmnode,
  56. init_asmnode : tasmnode;
  57. temps_finalized : boolean;
  58. dfabuilder : TDFABuilder;
  59. destructor destroy;override;
  60. function calc_stackframe_size : longint;override;
  61. procedure printproc(pass:string);
  62. procedure generate_code;
  63. procedure generate_code_tree;
  64. procedure generate_exceptfilter(nestedpi: tcgprocinfo);
  65. procedure generate_exit_label(list: tasmlist); virtual;
  66. procedure resetprocdef;
  67. procedure add_to_symtablestack;
  68. procedure remove_from_symtablestack;
  69. procedure parse_body;
  70. procedure store_tempflags;
  71. procedure apply_tempflags;
  72. procedure reset_tempflags;
  73. function has_assembler_child : boolean;
  74. procedure set_eh_info; override;
  75. {$ifdef DEBUG_NODE_XML}
  76. procedure XMLPrintProc(FirstHalf: Boolean);
  77. {$endif DEBUG_NODE_XML}
  78. end;
  79. tread_proc_flag = (
  80. rpf_classmethod,
  81. rpf_generic,
  82. rpf_anonymous
  83. );
  84. tread_proc_flags = set of tread_proc_flag;
  85. procedure printnode_reset;
  86. {$ifdef DEBUG_NODE_XML}
  87. procedure XMLInitializeNodeFile(RootName, ModuleName: shortstring);
  88. procedure XMLFinalizeNodeFile(RootName: shortstring);
  89. {$endif DEBUG_NODE_XML}
  90. { reads the declaration blocks }
  91. procedure read_declarations(islibrary : boolean);
  92. { reads declarations in the interface part of a unit }
  93. procedure read_interface_declarations;
  94. { reads any routine in the implementation, or a non-method routine
  95. declaration in the interface (depending on whether or not parse_only is
  96. true) }
  97. function read_proc(flags:tread_proc_flags; usefwpd: tprocdef):tprocdef;
  98. { parses only the body of a non nested routine; needs a correctly setup pd }
  99. procedure read_proc_body(pd:tprocdef);
  100. procedure import_external_proc(pd:tprocdef);
  101. implementation
  102. uses
  103. sysutils,
  104. { common }
  105. cutils, cmsgs,
  106. { global }
  107. globtype,tokens,verbose,comphook,constexp,
  108. systems,cpubase,aasmbase,aasmtai,
  109. { symtable }
  110. symconst,symbase,symsym,symtype,symtable,defutil,defcmp,procdefutil,symcreat,
  111. paramgr,
  112. fmodule,
  113. { pass 1 }
  114. ngenutil,nld,ncal,ncon,nflw,nadd,ncnv,nmem,
  115. pass_1,
  116. {$ifdef state_tracking}
  117. nstate,
  118. {$endif state_tracking}
  119. { pass 2 }
  120. {$ifndef NOPASS2}
  121. pass_2,
  122. {$endif}
  123. { parser }
  124. scanner,gendef,
  125. pbase,pstatmnt,pdecl,pdecsub,pexports,pgenutil,pparautl,
  126. { codegen }
  127. tgobj,cgbase,cgobj,hlcgobj,hlcgcpu,dbgbase,
  128. ncgflw,
  129. ncgutil,
  130. optbase,
  131. opttail,
  132. optcse,
  133. optloop,
  134. optconstprop,
  135. optdeadstore,
  136. optloadmodifystore,
  137. optutils
  138. {$if defined(arm) or defined(m68k)}
  139. ,cpuinfo
  140. {$endif defined(arm) or defined(m68k)}
  141. {$ifndef NOOPT}
  142. ,aopt
  143. {$endif}
  144. ;
  145. function checknodeinlining(procdef: tprocdef): boolean;
  146. procedure _no_inline(const reason: TMsgStr);
  147. begin
  148. include(procdef.implprocoptions,pio_inline_not_possible);
  149. Message1(parser_n_not_supported_for_inline,reason);
  150. Message(parser_h_inlining_disabled);
  151. end;
  152. var
  153. i : integer;
  154. currpara : tparavarsym;
  155. begin
  156. result := false;
  157. { this code will never be used (only specialisations can be inlined),
  158. and moreover contains references to defs that are not stored in the
  159. ppu file }
  160. if df_generic in current_procinfo.procdef.defoptions then
  161. exit;
  162. if pi_has_assembler_block in current_procinfo.flags then
  163. begin
  164. _no_inline('assembler');
  165. exit;
  166. end;
  167. if (pi_has_global_goto in current_procinfo.flags) or
  168. (pi_has_interproclabel in current_procinfo.flags) then
  169. begin
  170. _no_inline('global goto');
  171. exit;
  172. end;
  173. if pi_has_nested_exit in current_procinfo.flags then
  174. begin
  175. _no_inline('nested exit');
  176. exit;
  177. end;
  178. if pi_calls_c_varargs in current_procinfo.flags then
  179. begin
  180. _no_inline('called C-style varargs functions');
  181. exit;
  182. end;
  183. { the compiler cannot handle inherited in inlined subroutines because
  184. it tries to search for self in the symtable, however, the symtable
  185. is not available }
  186. if pi_has_inherited in current_procinfo.flags then
  187. begin
  188. _no_inline('inherited');
  189. exit;
  190. end;
  191. if pio_nested_access in procdef.implprocoptions then
  192. begin
  193. _no_inline('access to local from nested scope');
  194. exit;
  195. end;
  196. { We can't support inlining for procedures that have nested
  197. procedures because the nested procedures use a fixed offset
  198. for accessing locals in the parent procedure (PFV) }
  199. if current_procinfo.has_nestedprocs then
  200. begin
  201. _no_inline('nested procedures');
  202. exit;
  203. end;
  204. if pi_uses_get_frame in current_procinfo.flags then
  205. begin
  206. _no_inline('get_frame');
  207. { for LLVM: it can inline things that FPC can't, but it mustn't
  208. inline this one }
  209. include(current_procinfo.procdef.implprocoptions,pio_inline_forbidden);
  210. exit;
  211. end;
  212. for i:=0 to procdef.paras.count-1 do
  213. begin
  214. currpara:=tparavarsym(procdef.paras[i]);
  215. case currpara.vardef.typ of
  216. arraydef :
  217. begin
  218. if is_array_of_const(currpara.vardef) or
  219. is_variant_array(currpara.vardef) then
  220. begin
  221. _no_inline('array of const');
  222. exit;
  223. end;
  224. { open arrays might need re-basing of the index, i.e. if you pass
  225. an array[1..10] as open array, you have to add 1 to all index operations
  226. if you directly inline it }
  227. if is_open_array(currpara.vardef) then
  228. begin
  229. _no_inline('open array');
  230. exit;
  231. end;
  232. end;
  233. else
  234. ;
  235. end;
  236. end;
  237. result:=true;
  238. end;
  239. {****************************************************************************
  240. PROCEDURE/FUNCTION BODY PARSING
  241. ****************************************************************************}
  242. procedure initializevars(p:TObject;arg:pointer);
  243. var
  244. b : tblocknode;
  245. begin
  246. if not (tsym(p).typ in [localvarsym,staticvarsym]) then
  247. exit;
  248. with tabstractnormalvarsym(p) do
  249. begin
  250. if assigned(defaultconstsym) then
  251. begin
  252. b:=tblocknode(arg);
  253. b.left:=cstatementnode.create(
  254. cassignmentnode.create(
  255. cloadnode.create(tsym(p),tsym(p).owner),
  256. cloadnode.create(defaultconstsym,defaultconstsym.owner)),
  257. b.left);
  258. end
  259. end;
  260. end;
  261. procedure check_finalize_paras(p:TObject;arg:pointer);
  262. begin
  263. if (tsym(p).typ=paravarsym) then
  264. begin
  265. if tparavarsym(p).needs_finalization then
  266. begin
  267. include(current_procinfo.flags,pi_needs_implicit_finally);
  268. include(current_procinfo.flags,pi_do_call);
  269. end;
  270. end;
  271. end;
  272. procedure check_finalize_locals(p:TObject;arg:pointer);
  273. begin
  274. { include the result: it needs to be finalized in case an exception }
  275. { occurs }
  276. if (tsym(p).typ=localvarsym) and
  277. (tlocalvarsym(p).refs>0) and
  278. is_managed_type(tlocalvarsym(p).vardef) then
  279. begin
  280. include(current_procinfo.flags,pi_needs_implicit_finally);
  281. include(current_procinfo.flags,pi_do_call);
  282. end;
  283. end;
  284. procedure init_main_block_syms(block: tnode);
  285. var
  286. oldfilepos: tfileposinfo;
  287. begin
  288. { initialized variables }
  289. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  290. begin
  291. { initialization of local variables with their initial
  292. values: part of function entry }
  293. oldfilepos:=current_filepos;
  294. current_filepos:=current_procinfo.entrypos;
  295. current_procinfo.procdef.localst.SymList.ForEachCall(@initializevars,block);
  296. current_filepos:=oldfilepos;
  297. end;
  298. if assigned(current_procinfo.procdef.parentfpstruct) then
  299. begin
  300. { finish the parentfpstruct (add padding, ...) }
  301. finish_parentfpstruct(current_procinfo.procdef);
  302. end;
  303. end;
  304. function block(islibrary : boolean) : tnode;
  305. begin
  306. { parse const,types and vars }
  307. read_declarations(islibrary);
  308. { do we have an assembler block without the po_assembler?
  309. we should allow this for Delphi compatibility (PFV) }
  310. if (token=_ASM) and (m_delphi in current_settings.modeswitches) then
  311. include(current_procinfo.procdef.procoptions,po_assembler);
  312. { Handle assembler block different }
  313. if (po_assembler in current_procinfo.procdef.procoptions) then
  314. begin
  315. block:=assembler_block;
  316. exit;
  317. end;
  318. {Unit initialization?.}
  319. if (
  320. assigned(current_procinfo.procdef.localst) and
  321. (current_procinfo.procdef.localst.symtablelevel=main_program_level) and
  322. (current_module.is_unit or islibrary)
  323. ) then
  324. begin
  325. if (token=_END) then
  326. begin
  327. consume(_END);
  328. { We need at least a node, else the entry/exit code is not
  329. generated and thus no PASCALMAIN symbol which we need (PFV) }
  330. if islibrary then
  331. block:=cnothingnode.create
  332. else
  333. block:=nil;
  334. end
  335. else
  336. begin
  337. if token=_INITIALIZATION then
  338. begin
  339. { The library init code is already called and does not
  340. need to be in the initfinal table (PFV) }
  341. block:=statement_block(_INITIALIZATION);
  342. init_main_block_syms(block);
  343. end
  344. else if token=_FINALIZATION then
  345. begin
  346. { when a unit has only a finalization section, we can come to this
  347. point when we try to read the nonh existing initalization section
  348. so we've to check if we are really try to parse the finalization }
  349. if current_procinfo.procdef.proctypeoption=potype_unitfinalize then
  350. block:=statement_block(_FINALIZATION)
  351. else
  352. block:=nil;
  353. end
  354. else
  355. block:=statement_block(_BEGIN);
  356. end;
  357. end
  358. else
  359. begin
  360. { parse routine body }
  361. block:=statement_block(_BEGIN);
  362. init_main_block_syms(block);
  363. end;
  364. end;
  365. {****************************************************************************
  366. PROCEDURE/FUNCTION COMPILING
  367. ****************************************************************************}
  368. procedure printnode_reset;
  369. begin
  370. assign(printnodefile,treelogfilename);
  371. {$push}{$I-}
  372. rewrite(printnodefile);
  373. {$pop}
  374. if ioresult<>0 then
  375. begin
  376. Comment(V_Error,'Error creating '+treelogfilename);
  377. exit;
  378. end;
  379. close(printnodefile);
  380. end;
  381. procedure add_label_init(p:TObject;arg:pointer);
  382. begin
  383. if tstoredsym(p).typ=labelsym then
  384. begin
  385. addstatement(tstatementnode(arg^),
  386. cifnode.create(caddnode.create(equaln,
  387. ccallnode.createintern('fpc_setjmp',
  388. ccallparanode.create(cloadnode.create(tlabelsym(p).jumpbuf,tlabelsym(p).jumpbuf.owner),nil)),
  389. cordconstnode.create(1,search_system_proc('fpc_setjmp').returndef,true))
  390. ,cgotonode.create(tlabelsym(p)),nil)
  391. );
  392. end;
  393. end;
  394. function generate_bodyentry_block:tnode;
  395. var
  396. srsym : tsym;
  397. para : tcallparanode;
  398. call : tcallnode;
  399. newstatement : tstatementnode;
  400. def : tabstractrecorddef;
  401. begin
  402. result:=internalstatements(newstatement);
  403. if assigned(current_structdef) then
  404. begin
  405. { a constructor needs a help procedure }
  406. if (current_procinfo.procdef.proctypeoption=potype_constructor) then
  407. begin
  408. if is_class(current_structdef) or
  409. (
  410. is_objectpascal_helper(current_structdef) and
  411. is_class(tobjectdef(current_structdef).extendeddef)
  412. ) then
  413. begin
  414. if is_objectpascal_helper(current_structdef) then
  415. def:=tabstractrecorddef(tobjectdef(current_structdef).extendeddef)
  416. else
  417. def:=current_structdef;
  418. srsym:=search_struct_member(def,'NEWINSTANCE');
  419. if assigned(srsym) and
  420. (srsym.typ=procsym) then
  421. begin
  422. { if vmt=1 then newinstance }
  423. call:=
  424. ccallnode.create(nil,tprocsym(srsym),srsym.owner,
  425. ctypeconvnode.create_internal(load_self_pointer_node,cclassrefdef.create(current_structdef)),
  426. [],nil);
  427. include(call.callnodeflags,cnf_ignore_devirt_wpo);
  428. addstatement(newstatement,cifnode.create(
  429. caddnode.create_internal(equaln,
  430. ctypeconvnode.create_internal(
  431. load_vmt_pointer_node,
  432. voidpointertype),
  433. cpointerconstnode.create(1,voidpointertype)),
  434. cassignmentnode.create(
  435. ctypeconvnode.create_internal(
  436. load_self_pointer_node,
  437. voidpointertype),
  438. call),
  439. nil));
  440. end
  441. else
  442. internalerror(200305108);
  443. end
  444. else
  445. if is_object(current_structdef) then
  446. begin
  447. { parameter 3 : vmt_offset }
  448. { parameter 2 : address of pointer to vmt,
  449. this is required to allow setting the vmt to -1 to indicate
  450. that memory was allocated }
  451. { parameter 1 : self pointer }
  452. para:=ccallparanode.create(
  453. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  454. ccallparanode.create(
  455. ctypeconvnode.create_internal(
  456. load_vmt_pointer_node,
  457. voidpointertype),
  458. ccallparanode.create(
  459. ctypeconvnode.create_internal(
  460. load_self_pointer_node,
  461. voidpointertype),
  462. nil)));
  463. addstatement(newstatement,cassignmentnode.create(
  464. ctypeconvnode.create_internal(
  465. load_self_pointer_node,
  466. voidpointertype),
  467. ccallnode.createintern('fpc_help_constructor',para)));
  468. end
  469. else
  470. if is_javaclass(current_structdef) or
  471. ((target_info.system in systems_jvm) and
  472. is_record(current_structdef)) then
  473. begin
  474. if (current_procinfo.procdef.proctypeoption=potype_constructor) and
  475. not current_procinfo.ConstructorCallingConstructor then
  476. begin
  477. { call inherited constructor }
  478. if is_javaclass(current_structdef) then
  479. srsym:=search_struct_member_no_helper(tobjectdef(current_structdef).childof,'CREATE')
  480. else
  481. srsym:=search_struct_member_no_helper(java_fpcbaserecordtype,'CREATE');
  482. if assigned(srsym) and
  483. (srsym.typ=procsym) then
  484. begin
  485. call:=ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[cnf_inherited],nil);
  486. exclude(tcallnode(call).callnodeflags,cnf_return_value_used);
  487. addstatement(newstatement,call);
  488. end
  489. else
  490. internalerror(2011010312);
  491. end;
  492. end
  493. else
  494. if not is_record(current_structdef) and
  495. not (
  496. is_objectpascal_helper(current_structdef) and
  497. (tobjectdef(current_structdef).extendeddef.typ<>objectdef)
  498. ) then
  499. internalerror(200305103);
  500. { if self=nil then exit
  501. calling fail instead of exit is useless because
  502. there is nothing to dispose (PFV) }
  503. if is_class_or_object(current_structdef) then
  504. addstatement(newstatement,cifnode.create(
  505. caddnode.create(equaln,
  506. load_self_pointer_node,
  507. cnilnode.create),
  508. cexitnode.create(nil),
  509. nil));
  510. end;
  511. { maybe call BeforeDestruction for classes }
  512. if (current_procinfo.procdef.proctypeoption=potype_destructor) and
  513. is_class(current_structdef) then
  514. begin
  515. srsym:=search_struct_member(current_structdef,'BEFOREDESTRUCTION');
  516. if assigned(srsym) and
  517. (srsym.typ=procsym) then
  518. begin
  519. { if vmt>0 then beforedestruction }
  520. addstatement(newstatement,cifnode.create(
  521. caddnode.create(gtn,
  522. ctypeconvnode.create_internal(
  523. load_vmt_pointer_node,ptrsinttype),
  524. ctypeconvnode.create_internal(
  525. cnilnode.create,ptrsinttype)),
  526. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  527. nil));
  528. end
  529. else
  530. internalerror(200305104);
  531. end;
  532. end;
  533. if m_non_local_goto in current_settings.modeswitches then
  534. tsymtable(current_procinfo.procdef.localst).SymList.ForEachCall(@add_label_init,@newstatement);
  535. initialize_capturer(current_procinfo,newstatement);
  536. end;
  537. function generate_bodyexit_block:tnode;
  538. var
  539. srsym : tsym;
  540. para : tcallparanode;
  541. newstatement : tstatementnode;
  542. oldlocalswitches: tlocalswitches;
  543. begin
  544. result:=internalstatements(newstatement);
  545. if assigned(current_structdef) then
  546. begin
  547. { Don't test self and the vmt here. The reason is that }
  548. { a constructor already checks whether these are valid }
  549. { before. Further, in case of TThread the thread may }
  550. { free the class instance right after AfterConstruction }
  551. { has been called, so it may no longer be valid (JM) }
  552. oldlocalswitches:=current_settings.localswitches;
  553. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  554. { a destructor needs a help procedure }
  555. if (current_procinfo.procdef.proctypeoption=potype_destructor) then
  556. begin
  557. if is_class(current_structdef) then
  558. begin
  559. srsym:=search_struct_member(current_structdef,'FREEINSTANCE');
  560. if assigned(srsym) and
  561. (srsym.typ=procsym) then
  562. begin
  563. { if self<>0 and vmt<>0 then freeinstance }
  564. addstatement(newstatement,cifnode.create(
  565. caddnode.create(andn,
  566. caddnode.create(unequaln,
  567. load_self_pointer_node,
  568. cnilnode.create),
  569. caddnode.create(unequaln,
  570. ctypeconvnode.create(
  571. load_vmt_pointer_node,
  572. voidpointertype),
  573. cpointerconstnode.create(0,voidpointertype))),
  574. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  575. nil));
  576. end
  577. else
  578. internalerror(2003051001);
  579. end
  580. else
  581. if is_object(current_structdef) then
  582. begin
  583. { finalize object data, but only if not in inherited call }
  584. if is_managed_type(current_structdef) then
  585. begin
  586. addstatement(newstatement,cifnode.create(
  587. caddnode.create(unequaln,
  588. ctypeconvnode.create_internal(load_vmt_pointer_node,voidpointertype),
  589. cnilnode.create),
  590. cnodeutils.finalize_data_node(load_self_node),
  591. nil));
  592. end;
  593. { parameter 3 : vmt_offset }
  594. { parameter 2 : pointer to vmt }
  595. { parameter 1 : self pointer }
  596. para:=ccallparanode.create(
  597. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  598. ccallparanode.create(
  599. ctypeconvnode.create_internal(
  600. load_vmt_pointer_node,
  601. voidpointertype),
  602. ccallparanode.create(
  603. ctypeconvnode.create_internal(
  604. load_self_pointer_node,
  605. voidpointertype),
  606. nil)));
  607. addstatement(newstatement,
  608. ccallnode.createintern('fpc_help_destructor',para));
  609. end
  610. else if is_javaclass(current_structdef) then
  611. begin
  612. { nothing to do }
  613. end
  614. else
  615. internalerror(200305105);
  616. end;
  617. current_settings.localswitches:=oldlocalswitches;
  618. end;
  619. end;
  620. {****************************************************************************
  621. TCGProcInfo
  622. ****************************************************************************}
  623. destructor tcgprocinfo.destroy;
  624. begin
  625. TFPList.FreeAndNilDisposing(tempinfo_flags_map,TypeInfo(ttempinfo_flags_entry));
  626. code.free;
  627. inherited destroy;
  628. end;
  629. function tcgprocinfo.calc_stackframe_size:longint;
  630. begin
  631. result:=Align(tg.direction*tg.lasttemp,current_settings.alignment.localalignmin);
  632. end;
  633. procedure tcgprocinfo.printproc(pass:string);
  634. begin
  635. assign(printnodefile,treelogfilename);
  636. {$push}{$I-}
  637. append(printnodefile);
  638. if ioresult<>0 then
  639. rewrite(printnodefile);
  640. {$pop}
  641. if ioresult<>0 then
  642. begin
  643. Comment(V_Error,'Error creating '+treelogfilename);
  644. exit;
  645. end;
  646. writeln(printnodefile);
  647. writeln(printnodefile,'*******************************************************************************');
  648. writeln(printnodefile, pass);
  649. writeln(printnodefile,procdef.fullprocname(false));
  650. writeln(printnodefile,'*******************************************************************************');
  651. printnode(printnodefile,code);
  652. close(printnodefile);
  653. end;
  654. procedure tcgprocinfo.maybe_add_constructor_wrapper(var tocode: tnode; withexceptblock: boolean);
  655. var
  656. oldlocalswitches: tlocalswitches;
  657. srsym: tsym;
  658. constructionblock,
  659. exceptblock,
  660. newblock: tblocknode;
  661. newstatement: tstatementnode;
  662. pd: tprocdef;
  663. constructionsuccessful: tlocalvarsym;
  664. begin
  665. if assigned(procdef.struct) and
  666. (procdef.proctypeoption=potype_constructor) then
  667. begin
  668. withexceptblock:=
  669. withexceptblock and
  670. not(target_info.system in systems_garbage_collected_managed_types);
  671. { Don't test self and the vmt here. See generate_bodyexit_block }
  672. { why (JM) }
  673. oldlocalswitches:=current_settings.localswitches;
  674. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  675. { call AfterConstruction for classes }
  676. constructionsuccessful:=nil;
  677. if is_class(procdef.struct) then
  678. begin
  679. constructionsuccessful:=clocalvarsym.create(internaltypeprefixName[itp_vmt_afterconstruction_local],vs_value,ptrsinttype,[]);
  680. procdef.localst.insertsym(constructionsuccessful,false);
  681. srsym:=search_struct_member(procdef.struct,'AFTERCONSTRUCTION');
  682. if not assigned(srsym) or
  683. (srsym.typ<>procsym) then
  684. internalerror(200305106);
  685. current_filepos:=entrypos;
  686. constructionblock:=internalstatements(newstatement);
  687. { initialise constructionsuccessful with -1, indicating that
  688. the construction was not successful and hence
  689. beforedestruction should not be called if a destructor is
  690. called from the constructor }
  691. addstatement(newstatement,cassignmentnode.create(
  692. cloadnode.create(constructionsuccessful,procdef.localst),
  693. genintconstnode(-1))
  694. );
  695. { first execute all constructor code. If no exception
  696. occurred then we will execute afterconstruction,
  697. otherwise we won't (the exception will jump over us) }
  698. addstatement(newstatement,tocode);
  699. current_filepos:=exitpos;
  700. { if implicit finally node wasn't created, then exit label and
  701. finalization code must be handled here and placed before
  702. afterconstruction }
  703. if not ((pi_needs_implicit_finally in flags) and
  704. (cs_implicit_exceptions in current_settings.moduleswitches)) then
  705. begin
  706. include(tocode.flags,nf_block_with_exit);
  707. if procdef.proctypeoption<>potype_exceptfilter then
  708. addstatement(newstatement,cfinalizetempsnode.create);
  709. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  710. temps_finalized:=true;
  711. end;
  712. { construction successful -> beforedestruction should be called
  713. if an exception happens now }
  714. addstatement(newstatement,cassignmentnode.create(
  715. cloadnode.create(constructionsuccessful,procdef.localst),
  716. genintconstnode(1))
  717. );
  718. { Self can be nil when fail is called }
  719. { if self<>nil and vmt<>nil then afterconstruction }
  720. addstatement(newstatement,cifnode.create(
  721. caddnode.create(andn,
  722. caddnode.create(unequaln,
  723. load_self_node,
  724. cnilnode.create),
  725. caddnode.create(unequaln,
  726. load_vmt_pointer_node,
  727. cnilnode.create)),
  728. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[],nil),
  729. nil));
  730. tocode:=constructionblock;
  731. end;
  732. if withexceptblock and (procdef.struct.typ=objectdef) then
  733. begin
  734. { Generate the implicit "fail" code for a constructor (destroy
  735. in case an exception happened) }
  736. pd:=tobjectdef(procdef.struct).find_destructor;
  737. { this will always be the case for classes, since tobject has
  738. a destructor }
  739. if assigned(pd) or is_object(procdef.struct) then
  740. begin
  741. current_filepos:=exitpos;
  742. exceptblock:=internalstatements(newstatement);
  743. { first free the instance if non-nil }
  744. if assigned(pd) then
  745. { if vmt<>0 then call destructor }
  746. addstatement(newstatement,
  747. cifnode.create(
  748. caddnode.create(unequaln,
  749. load_vmt_pointer_node,
  750. cnilnode.create),
  751. { cnf_create_failed -> don't call BeforeDestruction }
  752. ccallnode.create(nil,tprocsym(pd.procsym),pd.procsym.owner,load_self_node,[cnf_create_failed],nil),
  753. nil))
  754. else
  755. { object without destructor, call 'fail' helper }
  756. addstatement(newstatement,
  757. ccallnode.createintern('fpc_help_fail',
  758. ccallparanode.create(
  759. cordconstnode.create(tobjectdef(procdef.struct).vmt_offset,s32inttype,false),
  760. ccallparanode.create(
  761. ctypeconvnode.create_internal(
  762. load_vmt_pointer_node,
  763. voidpointertype),
  764. ccallparanode.create(
  765. ctypeconvnode.create_internal(
  766. load_self_pointer_node,
  767. voidpointertype),
  768. nil))))
  769. );
  770. { then re-raise the exception }
  771. addstatement(newstatement,craisenode.create(nil,nil,nil));
  772. current_filepos:=entrypos;
  773. newblock:=internalstatements(newstatement);
  774. { try
  775. tocode
  776. except
  777. exceptblock
  778. end
  779. }
  780. addstatement(newstatement,ctryexceptnode.create(
  781. tocode,
  782. nil,
  783. exceptblock));
  784. tocode:=newblock;
  785. end;
  786. end;
  787. current_settings.localswitches:=oldlocalswitches;
  788. end;
  789. end;
  790. procedure tcgprocinfo.add_entry_exit_code;
  791. var
  792. finalcode,
  793. bodyentrycode,
  794. bodyexitcode,
  795. wrappedbody,
  796. newblock : tnode;
  797. codestatement,
  798. newstatement : tstatementnode;
  799. oldfilepos : tfileposinfo;
  800. is_constructor: boolean;
  801. begin
  802. is_constructor:=assigned(procdef.struct) and
  803. (procdef.proctypeoption=potype_constructor);
  804. oldfilepos:=current_filepos;
  805. { Generate code/locations used at start of proc }
  806. current_filepos:=entrypos;
  807. entry_asmnode:=casmnode.create_get_position;
  808. loadpara_asmnode:=casmnode.create_get_position;
  809. stackcheck_asmnode:=casmnode.create_get_position;
  810. init_asmnode:=casmnode.create_get_position;
  811. bodyentrycode:=generate_bodyentry_block;
  812. { Generate code/locations used at end of proc }
  813. current_filepos:=exitpos;
  814. exitlabel_asmnode:=casmnode.create_get_position;
  815. temps_finalized:=false;
  816. bodyexitcode:=generate_bodyexit_block;
  817. { Check if bodyexitcode is not empty }
  818. with tstatementnode(tblocknode(bodyexitcode).statements) do
  819. if (statement.nodetype<>nothingn) or assigned(next) then
  820. { Indicate that the extra code is executed after the exit statement }
  821. include(flowcontrol,fc_no_direct_exit);
  822. { Generate procedure by combining init+body+final,
  823. depending on the implicit finally we need to add
  824. an try...finally...end wrapper }
  825. current_filepos:=entrypos;
  826. newblock:=internalstatements(newstatement);
  827. { Note - this is not strippable since it wraps the entire procedure }
  828. Exclude(TBlockNode(newblock).blocknodeflags, bnf_strippable);
  829. { initialization is common for all cases }
  830. addstatement(newstatement,loadpara_asmnode);
  831. addstatement(newstatement,stackcheck_asmnode);
  832. addstatement(newstatement,entry_asmnode);
  833. cnodeutils.procdef_block_add_implicit_initialize_nodes(procdef,newstatement);
  834. addstatement(newstatement,init_asmnode);
  835. if assigned(procdef.parentfpinitblock) then
  836. begin
  837. if assigned(tblocknode(procdef.parentfpinitblock).left) then
  838. begin
  839. if cnodeutils.check_insert_trashing(procdef) then
  840. cnodeutils.maybe_trash_variable(newstatement,tabstractnormalvarsym(procdef.parentfpstruct),cloadnode.create(procdef.parentfpstruct,procdef.parentfpstruct.owner));
  841. { could be an asmn in case of a pure assembler procedure,
  842. but those shouldn't access nested variables }
  843. addstatement(newstatement,procdef.parentfpinitblock);
  844. end
  845. else
  846. procdef.parentfpinitblock.free;
  847. procdef.parentfpinitblock:=nil;
  848. end;
  849. addstatement(newstatement,bodyentrycode);
  850. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  851. (pi_needs_implicit_finally in flags) and
  852. { but it's useless in init/final code of units }
  853. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  854. not(target_info.system in systems_garbage_collected_managed_types) and
  855. (f_exceptions in features) then
  856. begin
  857. { Any result of managed type must be returned in parameter }
  858. if is_managed_type(procdef.returndef) and
  859. (not paramanager.ret_in_param(procdef.returndef,procdef)) and
  860. (not is_class(procdef.returndef)) then
  861. InternalError(2013121301);
  862. { Generate special exception block only needed when
  863. implicit finally is used }
  864. current_filepos:=exitpos;
  865. { Generate code that will be in the try...finally }
  866. finalcode:=internalstatements(codestatement);
  867. if procdef.proctypeoption<>potype_exceptfilter then
  868. addstatement(codestatement,cfinalizetempsnode.create);
  869. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,codestatement);
  870. temps_finalized:=true;
  871. current_filepos:=entrypos;
  872. wrappedbody:=ctryfinallynode.create_implicit(code,finalcode);
  873. { afterconstruction must be called after finalizetemps, because it
  874. has to execute after the temps have been finalised in case of a
  875. refcounted class (afterconstruction decreases the refcount
  876. without freeing the instance if the count becomes nil, while
  877. the finalising of the temps can free the instance) }
  878. maybe_add_constructor_wrapper(wrappedbody,true);
  879. addstatement(newstatement,wrappedbody);
  880. addstatement(newstatement,exitlabel_asmnode);
  881. addstatement(newstatement,bodyexitcode);
  882. { set flag the implicit finally has been generated }
  883. include(flags,pi_has_implicit_finally);
  884. end
  885. else
  886. begin
  887. { constructors need destroy-on-exception code even if they don't
  888. have managed variables/temps }
  889. maybe_add_constructor_wrapper(code,
  890. (cs_implicit_exceptions in current_settings.moduleswitches) and (f_exceptions in features));
  891. current_filepos:=entrypos;
  892. addstatement(newstatement,code);
  893. current_filepos:=exitpos;
  894. if assigned(nestedexitlabel) then
  895. addstatement(newstatement,clabelnode.create(cnothingnode.create,nestedexitlabel));
  896. addstatement(newstatement,exitlabel_asmnode);
  897. addstatement(newstatement,bodyexitcode);
  898. if not is_constructor then
  899. begin
  900. if procdef.proctypeoption<>potype_exceptfilter then
  901. addstatement(newstatement,cfinalizetempsnode.create);
  902. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  903. temps_finalized:=true;
  904. end;
  905. end;
  906. if not temps_finalized then
  907. begin
  908. current_filepos:=exitpos;
  909. cnodeutils.procdef_block_add_implicit_finalize_nodes(procdef,newstatement);
  910. end;
  911. do_firstpass(newblock);
  912. code:=newblock;
  913. current_filepos:=oldfilepos;
  914. end;
  915. procedure clearrefs(p:TObject;arg:pointer);
  916. begin
  917. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) then
  918. if tabstractvarsym(p).refs>1 then
  919. tabstractvarsym(p).refs:=1;
  920. end;
  921. procedure translate_registers(p:TObject;list:pointer);
  922. begin
  923. if (tsym(p).typ in [localvarsym,paravarsym,staticvarsym]) and
  924. (tabstractnormalvarsym(p).localloc.loc in [LOC_REGISTER,LOC_CREGISTER,LOC_MMREGISTER,
  925. LOC_CMMREGISTER,LOC_FPUREGISTER,LOC_CFPUREGISTER]) then
  926. begin
  927. if not(cs_no_regalloc in current_settings.globalswitches) then
  928. begin
  929. cg.translate_register(tabstractnormalvarsym(p).localloc.register);
  930. if (tabstractnormalvarsym(p).localloc.registerhi<>NR_NO) then
  931. cg.translate_register(tabstractnormalvarsym(p).localloc.registerhi);
  932. end;
  933. end;
  934. end;
  935. {$if defined(i386) or defined(x86_64) or defined(arm) or defined(aarch64) or defined(riscv32) or defined(riscv64) or defined(m68k)}
  936. const
  937. exception_flags: array[boolean] of tprocinfoflags = (
  938. [],
  939. [pi_uses_exceptions,pi_needs_implicit_finally,pi_has_implicit_finally]
  940. );
  941. {$endif}
  942. procedure tcgprocinfo.setup_tempgen;
  943. begin
  944. tg:=tgobjclass.create;
  945. {$if defined(i386) or defined(x86_64) or defined(arm) or defined(aarch64) or defined(m68k)}
  946. {$if defined(arm)}
  947. { frame and stack pointer must be always the same on arm thumb so it makes no
  948. sense to fiddle with a frame pointer }
  949. if GenerateThumbCode then
  950. begin
  951. framepointer:=NR_STACK_POINTER_REG;
  952. tg.direction:=1;
  953. end
  954. else
  955. {$endif defined(arm)}
  956. begin
  957. { try to strip the stack frame }
  958. { set the framepointer to esp if:
  959. - no assembler directive, those are handled in assembler_block
  960. in pstatment.pas (for cases not caught by the Delphi
  961. exception below)
  962. - no exceptions are used
  963. - no pushes are used/esp modifications, could be:
  964. * outgoing parameters on the stack on non-fixed stack target
  965. * incoming parameters on the stack
  966. * open arrays
  967. - no inline assembler
  968. or
  969. - Delphi mode
  970. - assembler directive
  971. - no pushes are used/esp modifications, could be:
  972. * outgoing parameters on the stack
  973. * incoming parameters on the stack
  974. * open arrays
  975. - no local variables
  976. - stack frame cannot be optimized if using Win64 SEH
  977. (at least with the current state of our codegenerator).
  978. }
  979. if ((po_assembler in procdef.procoptions) and
  980. (m_delphi in current_settings.modeswitches) and
  981. { localst at main_program_level is a staticsymtable }
  982. (procdef.localst.symtablelevel<>main_program_level) and
  983. (tabstractlocalsymtable(procdef.localst).count_locals = 0)) or
  984. ((cs_opt_stackframe in current_settings.optimizerswitches) and
  985. not(cs_generate_stackframes in current_settings.localswitches) and
  986. not(cs_profile in current_settings.moduleswitches) and
  987. not(po_assembler in procdef.procoptions) and
  988. {$if defined(m68k)}
  989. { do not optimize away the frame pointer, if the CPU has no long
  990. displacement support, this fixes optimizations on the plain 68000
  991. until some shortcomings of the CG itself can be addressed. (KB) }
  992. (CPUM68K_HAS_BASEDISP in cpu_capabilities[current_settings.cputype]) and
  993. {$endif defined(m68k)}
  994. {$if defined(aarch64)}
  995. { on aarch64, it must be a leaf subroutine }
  996. not(pi_do_call in flags) and
  997. {$endif defined(aarch64)}
  998. not ((pi_has_stackparameter in flags)
  999. {$if defined(i386) or defined(x86_64)}
  1000. { Outgoing parameter(s) on stack do not need stackframe on x86 targets
  1001. with fixed stack. On ARM it fails, see bug #25050 }
  1002. and (not paramanager.use_fixed_stack)
  1003. {$endif defined(i386) or defined(x86_64)}
  1004. ) and
  1005. ((flags*([pi_has_assembler_block,pi_is_assembler,
  1006. pi_needs_stackframe]+
  1007. exception_flags[((target_info.cpu=cpu_i386) and (not paramanager.use_fixed_stack))
  1008. {$ifndef DISABLE_WIN64_SEH}
  1009. or (target_info.system=system_x86_64_win64)
  1010. {$endif DISABLE_WIN64_SEH}
  1011. ]))=[])
  1012. )
  1013. then
  1014. begin
  1015. { we need the parameter info here to determine if the procedure gets
  1016. parameters on the stack
  1017. calling generate_parameter_info doesn't hurt but it costs time
  1018. (necessary to init para_stack_size)
  1019. }
  1020. generate_parameter_info;
  1021. if not(procdef.stack_tainting_parameter(calleeside)) and
  1022. not(has_assembler_child)
  1023. { parasize must be really zero, this means also that no result may be returned
  1024. in a parameter }
  1025. and not((current_procinfo.procdef.proccalloption in clearstack_pocalls) and
  1026. not(current_procinfo.procdef.generate_safecall_wrapper) and
  1027. paramanager.ret_in_param(current_procinfo.procdef.returndef,current_procinfo.procdef)) then
  1028. begin
  1029. { Only need to set the framepointer }
  1030. framepointer:=NR_STACK_POINTER_REG;
  1031. tg.direction:=1;
  1032. Include(flags,pi_no_framepointer_needed)
  1033. end
  1034. {$if defined(arm)}
  1035. { On arm, the stack frame size can be estimated to avoid using an extra frame pointer,
  1036. in case parameters are passed on the stack.
  1037. However, the draw back is, if the estimation fails, compilation will break later on
  1038. with an internal error, so this switch is not enabled by default yet. To overcome this,
  1039. multipass compilation of subroutines must be supported
  1040. }
  1041. else if (cs_opt_forcenostackframe in current_settings.optimizerswitches) and
  1042. not(has_assembler_child) then
  1043. begin
  1044. { Only need to set the framepointer }
  1045. framepointer:=NR_STACK_POINTER_REG;
  1046. tg.direction:=1;
  1047. include(flags,pi_estimatestacksize);
  1048. set_first_temp_offset;
  1049. procdef.has_paraloc_info:=callnoside;
  1050. generate_parameter_info;
  1051. exit;
  1052. end;
  1053. {$endif defined(arm)}
  1054. end;
  1055. end;
  1056. {$endif defined(x86) or defined(arm) or defined(m68k)}
  1057. {$if defined(xtensa)}
  1058. { On xtensa, the stack frame size can be estimated to avoid using an extra frame pointer,
  1059. in case parameters are passed on the stack.
  1060. However, the draw back is, if the estimation fails, compilation will break later on
  1061. with an internal error, so this switch is not enabled by default yet. To overcome this,
  1062. multipass compilation of subroutines must be supported
  1063. }
  1064. if procdef.stack_tainting_parameter(calleeside) then
  1065. begin
  1066. include(flags,pi_estimatestacksize);
  1067. set_first_temp_offset;
  1068. procdef.has_paraloc_info:=callnoside;
  1069. generate_parameter_info;
  1070. exit;
  1071. end;
  1072. {$endif defined(xtensa)}
  1073. { set the start offset to the start of the temp area in the stack }
  1074. set_first_temp_offset;
  1075. end;
  1076. procedure tcgprocinfo.OptimizeNodeTree;
  1077. var
  1078. i : integer;
  1079. UserCode : TNode;
  1080. RedoDFA : boolean;
  1081. begin
  1082. { do this before adding the entry code else the tail recursion recognition won't work,
  1083. if this causes troubles, it must be if'ed
  1084. }
  1085. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  1086. (pi_is_recursive in flags) then
  1087. do_opttail(code,procdef);
  1088. if cs_opt_constant_propagate in current_settings.optimizerswitches then
  1089. begin
  1090. do_optconstpropagate(code,RedoDFA);
  1091. { RedoDFA value not used here }
  1092. RedoDFA:=false;
  1093. end;
  1094. if (cs_opt_nodedfa in current_settings.optimizerswitches) and
  1095. { creating dfa is not always possible }
  1096. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler])=[]) then
  1097. begin
  1098. dfabuilder:=TDFABuilder.Create;
  1099. dfabuilder.createdfainfo(code);
  1100. include(flags,pi_dfaavailable);
  1101. RedoDFA:=false;
  1102. if cs_opt_constant_propagate in current_settings.optimizerswitches then
  1103. begin
  1104. do_optconstpropagate(code,RedoDFA);
  1105. if RedoDFA then
  1106. begin
  1107. dfabuilder.redodfainfo(code);
  1108. RedoDFA:=false; { Don't redo it again unless necessary }
  1109. end;
  1110. { Don't re-run constant propagation as redoing DFA info didn't
  1111. actually change any nodes }
  1112. end;
  1113. if (cs_opt_loopstrength in current_settings.optimizerswitches)
  1114. { our induction variable strength reduction doesn't like
  1115. for loops with more than one entry }
  1116. and not(pi_has_label in flags) then
  1117. begin
  1118. RedoDFA:=OptimizeInductionVariables(code);
  1119. end;
  1120. if RedoDFA then
  1121. begin
  1122. dfabuilder.redodfainfo(code);
  1123. RedoDFA:=false; { Don't redo it again unless necessary }
  1124. end;
  1125. if cs_opt_forloop in current_settings.optimizerswitches then
  1126. RedoDFA:=OptimizeForLoop(code);
  1127. RedoDFA:=ConvertForLoops(code) or RedoDFA;
  1128. if RedoDFA then
  1129. dfabuilder.redodfainfo(code);
  1130. { when life info is available, we can give more sophisticated warning about uninitialized
  1131. variables ...
  1132. ... but not for the finalization section of a unit, we would need global dfa to handle
  1133. it properly }
  1134. if potype_unitfinalize<>procdef.proctypeoption then
  1135. { iterate through life info of the first node }
  1136. for i:=0 to dfabuilder.nodemap.count-1 do
  1137. begin
  1138. UserCode:=GetUserCode();
  1139. if DFASetIn(UserCode.optinfo^.life,i) then
  1140. begin
  1141. { do not warn for certain parameters: }
  1142. if not((tnode(dfabuilder.nodemap[i]).nodetype=loadn) and (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ=paravarsym) and
  1143. { do not warn about parameters passed by var }
  1144. (((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varspez=vs_var) and
  1145. { function result is passed by var but it must be initialized }
  1146. not(vo_is_funcret in tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions)) or
  1147. { do not warn about initialized hidden parameters }
  1148. ((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions*[vo_is_high_para,vo_is_parentfp,vo_is_result,vo_is_self])<>[]))) then
  1149. CheckAndWarn(UserCode,tnode(dfabuilder.nodemap[i]));
  1150. end
  1151. else
  1152. begin
  1153. if (tnode(dfabuilder.nodemap[i]).nodetype=loadn) and
  1154. (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ in [staticvarsym,localvarsym]) then
  1155. tabstractnormalvarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).noregvarinitneeded:=true
  1156. end;
  1157. end;
  1158. if cs_opt_dead_store_eliminate in current_settings.optimizerswitches then
  1159. begin
  1160. do_optdeadstoreelim(code,RedoDFA);
  1161. if RedoDFA then
  1162. dfabuilder.redodfainfo(code);
  1163. end;
  1164. end
  1165. else
  1166. begin
  1167. ConvertForLoops(code);
  1168. end;
  1169. if (cs_opt_remove_empty_proc in current_settings.optimizerswitches) and
  1170. (procdef.proctypeoption in [potype_operator,potype_procedure,potype_function]) and
  1171. (code.nodetype=blockn) and (tblocknode(code).statements=nil) then
  1172. procdef.isempty:=true;
  1173. if cs_opt_nodecse in current_settings.optimizerswitches then
  1174. do_optcse(code);
  1175. if cs_opt_use_load_modify_store in current_settings.optimizerswitches then
  1176. do_optloadmodifystore(code);
  1177. if (cs_opt_consts in current_settings.optimizerswitches) and
  1178. { non-local gotos can cause an fpc_setjmp call to be generated before
  1179. this block, which means the loaded value won't be loaded when the
  1180. longjmp is performed }
  1181. not(m_non_local_goto in current_settings.modeswitches) then
  1182. do_consttovar(code);
  1183. end;
  1184. function tcgprocinfo.has_assembler_child : boolean;
  1185. var
  1186. hp : tprocinfo;
  1187. begin
  1188. result:=false;
  1189. hp:=get_first_nestedproc;
  1190. while assigned(hp) do
  1191. begin
  1192. if (hp.flags*[pi_has_assembler_block,pi_is_assembler])<>[] then
  1193. begin
  1194. result:=true;
  1195. exit;
  1196. end;
  1197. hp:=tprocinfo(hp.next);
  1198. end;
  1199. end;
  1200. procedure tcgprocinfo.set_eh_info;
  1201. begin
  1202. inherited;
  1203. if (tf_use_psabieh in target_info.flags) and
  1204. ((pi_uses_exceptions in flags) or
  1205. ((cs_implicit_exceptions in current_settings.moduleswitches) and
  1206. (pi_needs_implicit_finally in flags))) or
  1207. (pi_has_except_table_data in flags) then
  1208. procdef.personality:=search_system_proc('_FPC_PSABIEH_PERSONALITY_V0');
  1209. end;
  1210. function tcgprocinfo.store_node_tempflags(var n: tnode; arg: pointer): foreachnoderesult;
  1211. var
  1212. nodeset : THashSet absolute arg;
  1213. entry : ptempinfo_flags_entry;
  1214. i : longint;
  1215. {hashsetitem: PHashSetItem;}
  1216. begin
  1217. result:=fen_true;
  1218. case n.nodetype of
  1219. tempcreaten:
  1220. begin
  1221. {$ifdef EXTDEBUG}
  1222. comment(V_Debug,'keeping track of new temp node: '+hexstr(ttempbasenode(n).tempinfo));
  1223. {$endif EXTDEBUG}
  1224. nodeset.FindOrAdd(ttempbasenode(n).tempinfo,sizeof(pointer));
  1225. end;
  1226. tempdeleten:
  1227. begin
  1228. {$ifdef EXTDEBUG}
  1229. comment(V_Debug,'got temp delete node: '+hexstr(ttempbasenode(n).tempinfo));
  1230. {$endif EXTDEBUG}
  1231. { don't remove temp nodes so that outside code can know if some temp
  1232. was only created in here }
  1233. (*hashsetitem:=nodeset.find(ttempbasenode(n).tempinfo,sizeof(pointer));
  1234. if assigned(hashsetitem) then
  1235. begin
  1236. {$ifdef EXTDEBUG}
  1237. comment(V_Debug,'no longer keeping track of temp node');
  1238. {$endif EXTDEBUG}
  1239. writeln('no longer keeping track of temp node');
  1240. nodeset.Remove(hashsetitem);
  1241. end;*)
  1242. end;
  1243. temprefn:
  1244. begin
  1245. {$ifdef EXTDEBUG}
  1246. comment(V_Debug,'found temp ref node: '+hexstr(ttempbasenode(n).tempinfo));
  1247. {$endif EXTDEBUG}
  1248. if not assigned(nodeset.find(ttempbasenode(n).tempinfo,sizeof(pointer))) then
  1249. begin
  1250. for i:=0 to tempinfo_flags_map.count-1 do
  1251. begin
  1252. entry:=ptempinfo_flags_entry(tempinfo_flags_map[i]);
  1253. {$ifdef EXTDEBUG}
  1254. comment(V_Debug,'comparing with tempinfo: '+hexstr(entry^.tempinfo));
  1255. {$endif EXTDEBUG}
  1256. if entry^.tempinfo=ttempbasenode(n).tempinfo then
  1257. begin
  1258. {$ifdef EXTDEBUG}
  1259. comment(V_Debug,'temp node exists');
  1260. {$endif EXTDEBUG}
  1261. exit;
  1262. end;
  1263. end;
  1264. {$ifdef EXTDEBUG}
  1265. comment(V_Debug,'storing node');
  1266. {$endif EXTDEBUG}
  1267. new(entry);
  1268. entry^.tempinfo:=ttempbasenode(n).tempinfo;
  1269. entry^.flags:=ttempinfoaccessor.gettempinfoflags(entry^.tempinfo);
  1270. tempinfo_flags_map.add(entry);
  1271. end
  1272. else
  1273. begin
  1274. {$ifdef EXTDEBUG}
  1275. comment(V_Debug,'ignoring node');
  1276. {$endif EXTDEBUG}
  1277. end;
  1278. end;
  1279. else
  1280. ;
  1281. end;
  1282. end;
  1283. procedure tcgprocinfo.store_tempflags;
  1284. var
  1285. nodeset : THashSet;
  1286. begin
  1287. if assigned(tempinfo_flags_map) then
  1288. internalerror(2020040601);
  1289. {$ifdef EXTDEBUG}
  1290. comment(V_Debug,'storing temp nodes of '+procdef.mangledname);
  1291. {$endif EXTDEBUG}
  1292. tempinfo_flags_map:=tfplist.create;
  1293. nodeset:=THashSet.Create(32,false,false);
  1294. foreachnode(code,@store_node_tempflags,nodeset);
  1295. nodeset.free;
  1296. end;
  1297. procedure tcgprocinfo.swap_tempflags;
  1298. var
  1299. entry : ptempinfo_flags_entry;
  1300. i : longint;
  1301. tempflags : ttempinfoflags;
  1302. begin
  1303. if not assigned(tempinfo_flags_map) then
  1304. exit;
  1305. for i:=0 to tempinfo_flags_map.count-1 do
  1306. begin
  1307. entry:=ptempinfo_flags_entry(tempinfo_flags_map[i]);
  1308. tempflags:=ttempinfoaccessor.gettempinfoflags(entry^.tempinfo);
  1309. ttempinfoaccessor.settempinfoflags(entry^.tempinfo,entry^.flags);
  1310. entry^.flags:=tempflags;
  1311. end;
  1312. end;
  1313. procedure tcgprocinfo.apply_tempflags;
  1314. begin
  1315. if tempflags_swapped then
  1316. internalerror(2020040602);
  1317. swap_tempflags;
  1318. tempflags_swapped:=true;
  1319. end;
  1320. procedure tcgprocinfo.reset_tempflags;
  1321. begin
  1322. if not tempflags_swapped then
  1323. internalerror(2020040603);
  1324. swap_tempflags;
  1325. tempflags_swapped:=false;
  1326. end;
  1327. {$ifdef DEBUG_NODE_XML}
  1328. procedure tcgprocinfo.XMLPrintProc(FirstHalf: Boolean);
  1329. var
  1330. T: Text;
  1331. W: Word;
  1332. syssym: tsyssym;
  1333. separate : boolean;
  1334. procedure PrintType(Flag: string);
  1335. begin
  1336. if df_generic in procdef.defoptions then
  1337. Write(T, ' type="generic ', Flag, '"')
  1338. else
  1339. Write(T, ' type="', Flag, '"');
  1340. end;
  1341. procedure PrintOption(Flag: string);
  1342. begin
  1343. WriteLn(T, PrintNodeIndention, '<option>', Flag, '</option>');
  1344. end;
  1345. begin
  1346. if current_module.ppxfilefail then
  1347. Exit;
  1348. Assign(T, current_module.ppxfilename);
  1349. {$push} {$I-}
  1350. Append(T);
  1351. if IOResult <> 0 then
  1352. begin
  1353. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  1354. current_module.ppxfilefail := True;
  1355. Exit;
  1356. end;
  1357. {$pop}
  1358. separate := (df_generic in procdef.defoptions);
  1359. { First half prints the header and the nodes as a "code" tag }
  1360. if FirstHalf or separate then
  1361. begin
  1362. Write(T, PrintNodeIndention, '<subroutine');
  1363. { Check to see if the procedure is a class or object method }
  1364. if Assigned(procdef.struct) then
  1365. begin
  1366. if Assigned(procdef.struct.objrealname) then
  1367. Write(T, ' struct="', SanitiseXMLString(procdef.struct.objrealname^), '"')
  1368. else
  1369. Write(T, ' struct="&lt;NULL&gt;"');
  1370. end;
  1371. case procdef.proctypeoption of
  1372. potype_none:
  1373. { Do nothing - should this be an internal error though? };
  1374. potype_procedure,
  1375. potype_function:
  1376. if po_classmethod in procdef.procoptions then
  1377. begin
  1378. if po_staticmethod in procdef.procoptions then
  1379. PrintType('static class method')
  1380. else
  1381. PrintType('class method');
  1382. end
  1383. else if df_generic in procdef.defoptions then
  1384. Write(T, ' type="generic"');
  1385. potype_proginit,
  1386. potype_unitinit:
  1387. PrintType('initialization');
  1388. potype_unitfinalize:
  1389. PrintType('finalization');
  1390. potype_constructor:
  1391. PrintType('constructor');
  1392. potype_destructor:
  1393. PrintType('destructor');
  1394. potype_operator:
  1395. PrintType('operator');
  1396. potype_class_constructor:
  1397. PrintType('class constructor');
  1398. potype_class_destructor:
  1399. PrintType('class destructor');
  1400. potype_propgetter:
  1401. PrintType('dispinterface getter');
  1402. potype_propsetter:
  1403. PrintType('dispinterface setter');
  1404. potype_exceptfilter:
  1405. PrintType('except filter');
  1406. potype_mainstub:
  1407. PrintType('main stub');
  1408. potype_libmainstub:
  1409. PrintType('library main stub');
  1410. potype_pkgstub:
  1411. PrintType('package stub');
  1412. end;
  1413. Write(T, ' name="', SanitiseXMLString(procdef.customprocname([pno_showhidden, pno_noclassmarker])), '"');
  1414. if (po_hascallingconvention in procdef.procoptions) or (procdef.proccalloption <> pocall_default) then
  1415. Write(T, ' convention="', proccalloptionStr[procdef.proccalloption], '"');
  1416. WriteLn(T, '>');
  1417. PrintNodeIndent;
  1418. if Assigned(procdef.returndef) and not is_void(procdef.returndef) then
  1419. WriteLn(T, PrintNodeIndention, '<returndef>', SanitiseXMLString(procdef.returndef.typesymbolprettyname), '</returndef>');
  1420. if po_reintroduce in procdef.procoptions then
  1421. PrintOption('reintroduce');
  1422. if po_virtualmethod in procdef.procoptions then
  1423. PrintOption('virtual');
  1424. if po_finalmethod in procdef.procoptions then
  1425. PrintOption('final');
  1426. if po_overridingmethod in procdef.procoptions then
  1427. PrintOption('override');
  1428. if po_overload in procdef.procoptions then
  1429. PrintOption('overload');
  1430. if po_compilerproc in procdef.procoptions then
  1431. PrintOption('compilerproc');
  1432. if po_assembler in procdef.procoptions then
  1433. PrintOption('assembler');
  1434. if po_nostackframe in procdef.procoptions then
  1435. PrintOption('nostackframe');
  1436. if po_inline in procdef.procoptions then
  1437. PrintOption('inline');
  1438. if po_noreturn in procdef.procoptions then
  1439. PrintOption('noreturn');
  1440. if po_noinline in procdef.procoptions then
  1441. PrintOption('noinline');
  1442. end;
  1443. if Assigned(Code) then
  1444. begin
  1445. if FirstHalf then
  1446. WriteLn(T, PrintNodeIndention, '<code>')
  1447. else
  1448. begin
  1449. WriteLn(T); { Line for spacing }
  1450. WriteLn(T, PrintNodeIndention, '<firstpass>');
  1451. end;
  1452. PrintNodeIndent;
  1453. XMLPrintNode(T, Code);
  1454. PrintNodeUnindent;
  1455. if FirstHalf then
  1456. WriteLn(T, PrintNodeIndention, '</code>')
  1457. else
  1458. WriteLn(T, PrintNodeIndention, '</firstpass>');
  1459. end
  1460. else { Code=Nil }
  1461. begin
  1462. { Don't print anything for second half - if there's no code, there's no firstpass }
  1463. if FirstHalf then
  1464. WriteLn(T, PrintNodeIndention, '<code />');
  1465. end;
  1466. { Print footer only for second half }
  1467. if (not FirstHalf) or separate then
  1468. begin
  1469. PrintNodeUnindent;
  1470. WriteLn(T, PrintNodeIndention, '</subroutine>');
  1471. WriteLn(T); { Line for spacing }
  1472. end;
  1473. Close(T);
  1474. end;
  1475. {$endif DEBUG_NODE_XML}
  1476. procedure tcgprocinfo.generate_code_tree;
  1477. var
  1478. hpi : tcgprocinfo;
  1479. begin
  1480. { generate code for this procedure }
  1481. generate_code;
  1482. { process nested procedures }
  1483. hpi:=tcgprocinfo(get_first_nestedproc);
  1484. while assigned(hpi) do
  1485. begin
  1486. hpi.generate_code_tree;
  1487. hpi:=tcgprocinfo(hpi.next);
  1488. end;
  1489. resetprocdef;
  1490. end;
  1491. procedure tcgprocinfo.generate_code_exceptfilters;
  1492. var
  1493. hpi : tcgprocinfo;
  1494. begin
  1495. hpi:=tcgprocinfo(get_first_nestedproc);
  1496. while assigned(hpi) do
  1497. begin
  1498. if hpi.procdef.proctypeoption=potype_exceptfilter then
  1499. begin
  1500. hpi.apply_tempflags;
  1501. generate_exceptfilter(hpi);
  1502. hpi.reset_tempflags;
  1503. end;
  1504. hpi:=tcgprocinfo(hpi.next);
  1505. end;
  1506. end;
  1507. { For SEH, the code from 'finally' blocks must be put into a separate procedures,
  1508. which can be called by OS during stack unwind. This resembles nested procedures,
  1509. but finalizer procedures do not have their own local variables and work directly
  1510. with the stack frame of parent. In particular, the tempgen must be shared, so
  1511. 1) finalizer procedure is able to finalize temps of the parent,
  1512. 2) if the finalizer procedure is complex enough to need its own temps, they are
  1513. allocated in stack frame of parent, so second-level finalizer procedures are
  1514. not needed.
  1515. Due to requirement of shared tempgen we cannot process finalizer as a regular nested
  1516. procedure (after the parent) and have to do it inline.
  1517. This is called by platform-specific tryfinallynodes during pass2.
  1518. Here we put away the codegen (which carries the register allocator state), process
  1519. the 'nested' procedure, then restore previous cg and continue processing the parent
  1520. procedure. generate_code() will create another cg, but not another tempgen because
  1521. setup_tempgen() is not called for potype_exceptfilter procedures. }
  1522. procedure tcgprocinfo.generate_exceptfilter(nestedpi: tcgprocinfo);
  1523. var
  1524. saved_cg: tcg;
  1525. saved_hlcg: thlcgobj;
  1526. {$ifdef cpu64bitalu}
  1527. saved_cg128 : tcg128;
  1528. {$else cpu64bitalu}
  1529. saved_cg64 : tcg64;
  1530. {$endif cpu64bitalu}
  1531. begin
  1532. if nestedpi.procdef.proctypeoption<>potype_exceptfilter then
  1533. InternalError(201201141);
  1534. { flush code generated this far }
  1535. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1536. { save the codegen }
  1537. saved_cg:=cg;
  1538. saved_hlcg:=hlcg;
  1539. cg:=nil;
  1540. hlcg:=nil;
  1541. {$ifdef cpu64bitalu}
  1542. saved_cg128:=cg128;
  1543. cg128:=nil;
  1544. {$else cpu64bitalu}
  1545. saved_cg64:=cg64;
  1546. cg64:=nil;
  1547. {$endif cpu64bitalu}
  1548. nestedpi.generate_code;
  1549. { prevents generating code the second time when processing nested procedures }
  1550. nestedpi.resetprocdef;
  1551. cg:=saved_cg;
  1552. hlcg:=saved_hlcg;
  1553. {$ifdef cpu64bitalu}
  1554. cg128:=saved_cg128;
  1555. {$else cpu64bitalu}
  1556. cg64:=saved_cg64;
  1557. {$endif cpu64bitalu}
  1558. add_reg_instruction_hook:[email protected]_reg_instruction;
  1559. end;
  1560. procedure tcgprocinfo.generate_exit_label(list: tasmlist);
  1561. begin
  1562. hlcg.a_label(list,CurrExitLabel);
  1563. end;
  1564. procedure tcgprocinfo.convert_captured_syms;
  1565. var
  1566. hpi : tcgprocinfo;
  1567. old_current_procinfo : tprocinfo;
  1568. begin
  1569. { do the conversion only if there haven't been any errors so far }
  1570. if ErrorCount<>0 then
  1571. exit;
  1572. old_current_procinfo:=current_procinfo;
  1573. current_procinfo:=self;
  1574. { process nested procedures }
  1575. hpi:=tcgprocinfo(get_first_nestedproc);
  1576. while assigned(hpi) do
  1577. begin
  1578. hpi.convert_captured_syms;
  1579. hpi:=tcgprocinfo(hpi.next);
  1580. end;
  1581. { convert the captured symbols for this routine }
  1582. if assigned(code) then
  1583. procdefutil.convert_captured_syms(procdef,code);
  1584. current_procinfo:=old_current_procinfo;
  1585. end;
  1586. procedure TCGProcinfo.CreateInlineInfo;
  1587. begin
  1588. new(procdef.inlininginfo);
  1589. procdef.inlininginfo^.code:=code.getcopy;
  1590. procdef.inlininginfo^.flags:=flags;
  1591. { The blocknode needs to set an exit label }
  1592. if procdef.inlininginfo^.code.nodetype=blockn then
  1593. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1594. procdef.has_inlininginfo:=true;
  1595. export_local_ref_syms;
  1596. export_local_ref_defs;
  1597. end;
  1598. procedure searchthreadvar(p: TObject; arg: pointer);
  1599. var
  1600. i : longint;
  1601. pd : tprocdef;
  1602. begin
  1603. case tsym(p).typ of
  1604. staticvarsym :
  1605. begin
  1606. { local (procedure or unit) variables only need finalization
  1607. if they are used
  1608. }
  1609. if (vo_is_thread_var in tstaticvarsym(p).varoptions) and
  1610. ((tstaticvarsym(p).refs>0) or
  1611. { global (unit) variables always need finalization, since
  1612. they may also be used in another unit
  1613. }
  1614. (tstaticvarsym(p).owner.symtabletype=globalsymtable)) and
  1615. (
  1616. (tstaticvarsym(p).varspez<>vs_const) or
  1617. (vo_force_finalize in tstaticvarsym(p).varoptions)
  1618. ) and
  1619. not(vo_is_funcret in tstaticvarsym(p).varoptions) and
  1620. not(vo_is_external in tstaticvarsym(p).varoptions) and
  1621. is_managed_type(tstaticvarsym(p).vardef) then
  1622. include(current_procinfo.flags,pi_uses_threadvar);
  1623. end;
  1624. procsym :
  1625. begin
  1626. for i:=0 to tprocsym(p).ProcdefList.Count-1 do
  1627. begin
  1628. pd:=tprocdef(tprocsym(p).ProcdefList[i]);
  1629. if assigned(pd.localst) and
  1630. (pd.procsym=tprocsym(p)) and
  1631. (pd.localst.symtabletype<>staticsymtable) then
  1632. pd.localst.SymList.ForEachCall(@searchthreadvar,arg);
  1633. end;
  1634. end;
  1635. else
  1636. ;
  1637. end;
  1638. end;
  1639. function searchusercode(var n: tnode; arg: pointer): foreachnoderesult;
  1640. begin
  1641. if nf_usercode_entry in n.flags then
  1642. begin
  1643. pnode(arg)^:=n;
  1644. result:=fen_norecurse_true
  1645. end
  1646. else
  1647. result:=fen_false;
  1648. end;
  1649. function TCGProcinfo.GetUserCode : tnode;
  1650. var
  1651. n : tnode;
  1652. begin
  1653. n:=nil;
  1654. foreachnodestatic(code,@searchusercode,@n);
  1655. if not(assigned(n)) then
  1656. internalerror(2013111004);
  1657. result:=n;
  1658. end;
  1659. procedure tcgprocinfo.generate_code;
  1660. procedure check_for_threadvars_in_initfinal;
  1661. begin
  1662. if current_procinfo.procdef.proctypeoption=potype_unitfinalize then
  1663. begin
  1664. { this is also used for initialization of variables in a
  1665. program which does not have a globalsymtable }
  1666. if assigned(current_module.globalsymtable) then
  1667. TSymtable(current_module.globalsymtable).SymList.ForEachCall(@searchthreadvar,nil);
  1668. TSymtable(current_module.localsymtable).SymList.ForEachCall(@searchthreadvar,nil);
  1669. end;
  1670. end;
  1671. function heuristics_favors_autoinlining(code: tnode): boolean;
  1672. var
  1673. complexityAvail : integer;
  1674. begin
  1675. { rough approximation if we should auto inline:
  1676. - if the tree is simple enough
  1677. - if the tree is not too big
  1678. A bigger tree which is simpler might be autoinlined otoh
  1679. a smaller and complexer tree as well: so we use the sum of
  1680. both measures here }
  1681. { This is a shortcutted version of
  1682. "result:=node_count(code)+node_complexity(code)<=25". }
  1683. complexityAvail:=25-node_complexity(code);
  1684. result:=(complexityAvail>0) and (node_count(code,complexityAvail+1)<=dword(complexityAvail));
  1685. end;
  1686. var
  1687. old_current_procinfo : tprocinfo;
  1688. oldmaxfpuregisters : longint;
  1689. oldfilepos : tfileposinfo;
  1690. old_current_structdef : tabstractrecorddef;
  1691. oldswitches : tlocalswitches;
  1692. templist : TAsmList;
  1693. headertai : tai;
  1694. procedure delete_marker(anode: tasmnode);
  1695. var
  1696. ai: tai;
  1697. begin
  1698. if assigned(anode) then
  1699. begin
  1700. ai:=anode.currenttai;
  1701. if assigned(ai) then
  1702. begin
  1703. aktproccode.remove(ai);
  1704. ai.free;
  1705. anode.currenttai:=nil;
  1706. end;
  1707. end;
  1708. end;
  1709. begin
  1710. { the initialization procedure can be empty, then we
  1711. don't need to generate anything. When it was an empty
  1712. procedure there would be at least a blocknode }
  1713. if not assigned(code) then
  1714. begin
  1715. {$ifdef DEBUG_NODE_XML}
  1716. { Print out nodes as they appear after the first pass }
  1717. XMLPrintProc(True);
  1718. XMLPrintProc(False);
  1719. {$endif DEBUG_NODE_XML}
  1720. exit;
  1721. end;
  1722. { We need valid code }
  1723. if Errorcount<>0 then
  1724. exit;
  1725. { No code can be generated for generic template }
  1726. if (df_generic in procdef.defoptions) then
  1727. internalerror(200511152);
  1728. { For regular procedures the RA and Tempgen shall not be available yet,
  1729. but exception filters reuse Tempgen of parent }
  1730. if assigned(tg)<>(procdef.proctypeoption=potype_exceptfilter) then
  1731. internalerror(200309201);
  1732. old_current_procinfo:=current_procinfo;
  1733. oldfilepos:=current_filepos;
  1734. old_current_structdef:=current_structdef;
  1735. oldmaxfpuregisters:=current_settings.maxfpuregisters;
  1736. current_procinfo:=self;
  1737. current_filepos:=entrypos;
  1738. current_structdef:=procdef.struct;
  1739. { store start of user code, it must be a block node, it will be used later one to
  1740. check variable lifeness }
  1741. include(code.flags,nf_usercode_entry);
  1742. { add wrapping code if necessary (initialization of typed constants on
  1743. some platforms, initing of local variables and out parameters with
  1744. trashing values, ...) }
  1745. { init/final code must be wrapped later (after code for main proc body
  1746. has been generated) }
  1747. if not(current_procinfo.procdef.proctypeoption in [potype_unitinit,potype_unitfinalize]) then
  1748. code:=cnodeutils.wrap_proc_body(procdef,code);
  1749. { automatic inlining? }
  1750. if (cs_opt_autoinline in current_settings.optimizerswitches) and
  1751. not(po_noinline in procdef.procoptions) and
  1752. { no inlining yet? }
  1753. not(procdef.has_inlininginfo) and not(has_nestedprocs) and
  1754. not(procdef.proctypeoption in [potype_proginit,potype_unitinit,potype_unitfinalize,potype_constructor,
  1755. potype_destructor,potype_class_constructor,potype_class_destructor]) and
  1756. ((procdef.procoptions*[po_exports,po_external,po_interrupt,po_virtualmethod,po_iocheck])=[]) and
  1757. (not(procdef.proccalloption in [pocall_safecall])) and
  1758. heuristics_favors_autoinlining(code) then
  1759. begin
  1760. { Can we inline this procedure? }
  1761. if checknodeinlining(procdef) then
  1762. begin
  1763. Message1(cg_d_autoinlining,procdef.GetTypeName);
  1764. include(procdef.procoptions,po_inline);
  1765. CreateInlineInfo;
  1766. end;
  1767. end;
  1768. templist:=TAsmList.create;
  1769. { add parast/localst to symtablestack }
  1770. add_to_symtablestack;
  1771. { clear register count }
  1772. procdef.localst.SymList.ForEachCall(@clearrefs,nil);
  1773. procdef.parast.SymList.ForEachCall(@clearrefs,nil);
  1774. { there's always a call to FPC_INITIALIZEUNITS/FPC_DO_EXIT in the main program }
  1775. if (procdef.localst.symtablelevel=main_program_level) and
  1776. (not current_module.is_unit) then
  1777. begin
  1778. include(flags,pi_do_call);
  1779. { the main program never returns due to the do_exit call }
  1780. if not(current_module.islibrary) and (procdef.proctypeoption=potype_proginit) then
  1781. include(procdef.procoptions,po_noreturn);
  1782. end;
  1783. { set implicit_finally flag when there are locals/paras to be finalized }
  1784. if not(po_assembler in current_procinfo.procdef.procoptions) then
  1785. begin
  1786. procdef.parast.SymList.ForEachCall(@check_finalize_paras,nil);
  1787. procdef.localst.SymList.ForEachCall(@check_finalize_locals,nil);
  1788. end;
  1789. {$ifdef SUPPORT_SAFECALL}
  1790. { set implicit_finally flag for if procedure is safecall }
  1791. if (tf_safecall_exceptions in target_info.flags) and
  1792. (procdef.proccalloption=pocall_safecall) then
  1793. include(flags, pi_needs_implicit_finally);
  1794. {$endif}
  1795. {$ifdef DEBUG_NODE_XML}
  1796. { Print out nodes as they appear after the first pass }
  1797. XMLPrintProc(True);
  1798. {$endif DEBUG_NODE_XML}
  1799. { firstpass everything }
  1800. flowcontrol:=[];
  1801. do_firstpass(code);
  1802. {$if defined(i386) or defined(i8086)}
  1803. if node_resources_fpu(code)>0 then
  1804. include(flags,pi_uses_fpu);
  1805. {$endif i386 or i8086}
  1806. { Print the node to tree.log }
  1807. if paraprintnodetree <> 0 then
  1808. printproc( 'after the firstpass');
  1809. OptimizeNodeTree;
  1810. { unit static/global symtables might contain threadvars which are not explicitly used but which might
  1811. require a tls register, so check for such variables }
  1812. check_for_threadvars_in_initfinal;
  1813. { add implicit entry and exit code }
  1814. add_entry_exit_code;
  1815. { only do secondpass if there are no errors }
  1816. if (ErrorCount<>0) then
  1817. begin
  1818. {$ifdef DEBUG_NODE_XML}
  1819. { Print out nodes as they appear after the first pass }
  1820. XMLPrintProc(False);
  1821. {$endif DEBUG_NODE_XML}
  1822. end
  1823. else
  1824. begin
  1825. create_hlcodegen;
  1826. setup_eh;
  1827. if (procdef.proctypeoption<>potype_exceptfilter) then
  1828. setup_tempgen;
  1829. { Create register allocator, must come after framepointer is known }
  1830. hlcg.init_register_allocators;
  1831. generate_parameter_info;
  1832. { allocate got register if needed }
  1833. allocate_got_register(aktproccode);
  1834. { allocate got register if needed }
  1835. allocate_tls_register(aktproccode);
  1836. { Allocate space in temp/registers for parast and localst }
  1837. current_filepos:=entrypos;
  1838. gen_alloc_symtable(aktproccode,procdef,procdef.parast);
  1839. gen_alloc_symtable(aktproccode,procdef,procdef.localst);
  1840. { Store temp offset for information about 'real' temps }
  1841. tempstart:=tg.lasttemp;
  1842. { Generate code to load register parameters in temps and insert local
  1843. copies for values parameters. This must be done before the code for the
  1844. body is generated because the localloc is updated.
  1845. Note: The generated code will be inserted after the code generation of
  1846. the body is finished, because only then the position is known }
  1847. current_filepos:=entrypos;
  1848. hlcg.gen_load_para_value(templist);
  1849. { caller paraloc info is also necessary in the stackframe_entry
  1850. code of the ppc (and possibly other processors) }
  1851. procdef.init_paraloc_info(callerside);
  1852. CalcExecutionWeights(code);
  1853. { Print the node to tree.log }
  1854. if paraprintnodetree <> 0 then
  1855. printproc( 'right before code generation');
  1856. {$ifdef DEBUG_NODE_XML}
  1857. { Print out nodes as they appear after the first pass }
  1858. XMLPrintProc(False);
  1859. {$endif DEBUG_NODE_XML}
  1860. { generate code for the node tree }
  1861. do_secondpass(code);
  1862. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1863. { The position of the loadpara_asmnode is now known }
  1864. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  1865. oldswitches:=current_settings.localswitches;
  1866. { first generate entry and initialize code with the correct
  1867. position and switches }
  1868. current_filepos:=entrypos;
  1869. current_settings.localswitches:=entryswitches;
  1870. cg.set_regalloc_live_range_direction(rad_backwards);
  1871. hlcg.gen_entry_code(templist);
  1872. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  1873. hlcg.gen_initialize_code(templist);
  1874. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  1875. { now generate finalize and exit code with the correct position
  1876. and switches }
  1877. current_filepos:=exitpos;
  1878. current_settings.localswitches:=exitswitches;
  1879. cg.set_regalloc_live_range_direction(rad_forward);
  1880. if assigned(finalize_procinfo) then
  1881. begin
  1882. if target_info.system in [system_aarch64_win64] then
  1883. tcgprocinfo(finalize_procinfo).store_tempflags
  1884. else
  1885. generate_exceptfilter(tcgprocinfo(finalize_procinfo));
  1886. end
  1887. else if not temps_finalized then
  1888. begin
  1889. hlcg.gen_finalize_code(templist);
  1890. { the finalcode must be concated if there was no position available,
  1891. using insertlistafter will result in an insert at the start
  1892. when currentai=nil }
  1893. aktproccode.concatlist(templist);
  1894. end;
  1895. { insert exit label at the correct position }
  1896. generate_exit_label(templist);
  1897. if assigned(exitlabel_asmnode.currenttai) then
  1898. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  1899. else
  1900. aktproccode.concatlist(templist);
  1901. { exit code }
  1902. hlcg.gen_exit_code(templist);
  1903. aktproccode.concatlist(templist);
  1904. { reset switches }
  1905. current_settings.localswitches:=oldswitches;
  1906. { generate symbol and save end of header position }
  1907. current_filepos:=entrypos;
  1908. hlcg.gen_proc_symbol(templist);
  1909. headertai:=tai(templist.last);
  1910. { insert symbol }
  1911. aktproccode.insertlist(templist);
  1912. { Free space in temp/registers for parast and localst, must be
  1913. done after gen_entry_code }
  1914. current_filepos:=exitpos;
  1915. { make sure the got/pic register doesn't get freed in the }
  1916. { middle of a loop }
  1917. if (tf_pic_uses_got in target_info.flags) and
  1918. (pi_needs_got in flags) and
  1919. (got<>NR_NO) then
  1920. cg.a_reg_sync(aktproccode,got);
  1921. if (pi_needs_tls in flags) and
  1922. (tlsoffset<>NR_NO) then
  1923. cg.a_reg_sync(aktproccode,tlsoffset);
  1924. gen_free_symtable(aktproccode,procdef.localst);
  1925. gen_free_symtable(aktproccode,procdef.parast);
  1926. { add code that will load the return value, this is not done
  1927. for assembler routines when they didn't reference the result
  1928. variable }
  1929. hlcg.gen_load_return_value(templist);
  1930. aktproccode.concatlist(templist);
  1931. { Already reserve all registers for stack checking code and
  1932. generate the call to the helper function }
  1933. if not(tf_no_generic_stackcheck in target_info.flags) and
  1934. (cs_check_stack in entryswitches) and
  1935. not(po_assembler in procdef.procoptions) and
  1936. (procdef.proctypeoption<>potype_proginit) then
  1937. begin
  1938. current_filepos:=entrypos;
  1939. hlcg.gen_stack_check_call(templist);
  1940. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist);
  1941. end;
  1942. { this code (got loading) comes before everything which has }
  1943. { already been generated, so reset the info about already }
  1944. { backwards extended registers (so their live range can be }
  1945. { extended backwards even further if needed) }
  1946. { This code must be }
  1947. { a) generated after do_secondpass has been called }
  1948. { (because pi_needs_got may be set there) }
  1949. { b) generated before register allocation, because the }
  1950. { got/pic register can be a virtual one }
  1951. { c) inserted before the entry code, because the entry }
  1952. { code may need global symbols such as init rtti }
  1953. { d) inserted after the stackframe allocation, because }
  1954. { this register may have to be spilled }
  1955. cg.set_regalloc_live_range_direction(rad_backwards_reinit);
  1956. current_filepos:=entrypos;
  1957. { load got if necessary }
  1958. cg.g_maybe_got_init(templist);
  1959. aktproccode.insertlistafter(headertai,templist);
  1960. { init tls if needed }
  1961. cg.g_maybe_tls_init(templist);
  1962. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist);
  1963. { re-enable if more code at the end is ever generated here
  1964. cg.set_regalloc_live_range_direction(rad_forward);
  1965. }
  1966. {$ifndef NoOpt}
  1967. {$ifndef i386}
  1968. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1969. { do not optimize pure assembler procedures }
  1970. not(pi_is_assembler in flags) then
  1971. preregallocschedule(aktproccode);
  1972. {$endif i386}
  1973. {$endif NoOpt}
  1974. { The procedure body is finished, we can now
  1975. allocate the registers }
  1976. cg.do_register_allocation(aktproccode,headertai);
  1977. { translate imag. register to their real counter parts
  1978. this is necessary for debuginfo and verbose assembler output
  1979. when SSA will be implemented, this will be more complicated because we've to
  1980. maintain location lists }
  1981. procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  1982. procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  1983. if (tf_pic_uses_got in target_info.flags) and (pi_needs_got in flags) and
  1984. not(cs_no_regalloc in current_settings.globalswitches) and
  1985. (got<>NR_NO) then
  1986. cg.translate_register(got);
  1987. { Add save and restore of used registers }
  1988. current_filepos:=entrypos;
  1989. gen_save_used_regs(templist);
  1990. { Remember the last instruction of register saving block
  1991. (may be =nil for e.g. assembler procedures) }
  1992. endprologue_ai:=templist.last;
  1993. aktproccode.insertlistafter(headertai,templist);
  1994. current_filepos:=exitpos;
  1995. gen_restore_used_regs(aktproccode);
  1996. { We know the size of the stack, now we can generate the
  1997. parameter that is passed to the stack checking code }
  1998. if not(tf_no_generic_stackcheck in target_info.flags) and
  1999. (cs_check_stack in entryswitches) and
  2000. not(po_assembler in procdef.procoptions) and
  2001. (procdef.proctypeoption<>potype_proginit) then
  2002. begin
  2003. current_filepos:=entrypos;
  2004. hlcg.gen_stack_check_size_para(templist);
  2005. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  2006. end;
  2007. current_procinfo.set_eh_info;
  2008. { Add entry code (stack allocation) after header }
  2009. current_filepos:=entrypos;
  2010. gen_proc_entry_code(templist);
  2011. aktproccode.insertlistafter(headertai,templist);
  2012. {$ifdef SUPPORT_SAFECALL}
  2013. { Set return value of safecall procedure if implicit try/finally blocks are disabled }
  2014. if not (cs_implicit_exceptions in current_settings.moduleswitches) and
  2015. (tf_safecall_exceptions in target_info.flags) and
  2016. (procdef.proccalloption=pocall_safecall) then
  2017. cg.a_load_const_reg(aktproccode,OS_ADDR,0,NR_FUNCTION_RETURN_REG);
  2018. {$endif}
  2019. { Add exit code at the end }
  2020. current_filepos:=exitpos;
  2021. gen_proc_exit_code(templist);
  2022. aktproccode.concatlist(templist);
  2023. { check if the implicit finally has been generated. The flag
  2024. should already be set in pass1 }
  2025. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  2026. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  2027. (pi_needs_implicit_finally in flags) and
  2028. not(pi_has_implicit_finally in flags) and
  2029. not(target_info.system in systems_garbage_collected_managed_types) then
  2030. internalerror(200405231);
  2031. { sanity check }
  2032. if not(assigned(current_procinfo.procdef.personality)) and
  2033. (tf_use_psabieh in target_info.flags) and
  2034. ((pi_uses_exceptions in flags) or
  2035. ((cs_implicit_exceptions in current_settings.moduleswitches) and
  2036. (pi_needs_implicit_finally in flags))) then
  2037. Internalerror(2019021005);
  2038. { Position markers are only used to insert additional code after the secondpass
  2039. and before this point. They are of no use in optimizer. Instead of checking and
  2040. ignoring all over the optimizer, just remove them here. }
  2041. delete_marker(entry_asmnode);
  2042. delete_marker(loadpara_asmnode);
  2043. delete_marker(exitlabel_asmnode);
  2044. delete_marker(stackcheck_asmnode);
  2045. delete_marker(init_asmnode);
  2046. {$ifndef NoOpt}
  2047. if not(cs_no_regalloc in current_settings.globalswitches) then
  2048. begin
  2049. if (cs_opt_level1 in current_settings.optimizerswitches) and
  2050. { do not optimize pure assembler procedures }
  2051. not(pi_is_assembler in flags) then
  2052. optimize(aktproccode);
  2053. {$ifndef i386}
  2054. { schedule after assembler optimization, it could have brought up
  2055. new schedule possibilities }
  2056. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  2057. { do not optimize pure assembler procedures }
  2058. not(pi_is_assembler in flags) then
  2059. preregallocschedule(aktproccode);
  2060. {$endif i386}
  2061. end;
  2062. {$endif NoOpt}
  2063. { Perform target-specific processing if necessary }
  2064. postprocess_code;
  2065. { Add end symbol and debug info }
  2066. { this must be done after the pcrelativedata is appended else the distance calculation of
  2067. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  2068. so it should be inserted before the end symbol (FK)
  2069. }
  2070. current_filepos:=exitpos;
  2071. hlcg.gen_proc_symbol_end(templist);
  2072. aktproccode.concatlist(templist);
  2073. { insert line debuginfo }
  2074. if (cs_debuginfo in current_settings.moduleswitches) or
  2075. (cs_use_lineinfo in current_settings.globalswitches) then
  2076. begin
  2077. { We only do this after the code generated because
  2078. otherwise for-loop counters moved to the struct cause
  2079. errors. And doing it before optimisation passes have run
  2080. causes problems when they manually look up symbols
  2081. like result and self (nutils.load_self_node etc). Still
  2082. do it nevertheless to to assist debug info generation
  2083. (hide original symbols, add absolutevarsyms that redirect
  2084. to their new locations in the parentfpstruct) }
  2085. if assigned(current_procinfo.procdef.parentfpstruct) then
  2086. redirect_parentfpstruct_local_syms(current_procinfo.procdef);
  2087. current_debuginfo.insertlineinfo(aktproccode);
  2088. end;
  2089. finish_eh;
  2090. hlcg.record_generated_code_for_procdef(current_procinfo.procdef,aktproccode,aktlocaldata);
  2091. { now generate code for any exception filters (they need the tempgen) }
  2092. generate_code_exceptfilters;
  2093. { only now we can remove the temps }
  2094. if (procdef.proctypeoption<>potype_exceptfilter) then
  2095. begin
  2096. tg.resettempgen;
  2097. tg.free;
  2098. tg:=nil;
  2099. end;
  2100. { stop tempgen and ra }
  2101. hlcg.done_register_allocators;
  2102. destroy_hlcodegen;
  2103. end;
  2104. dfabuilder.free;
  2105. { restore symtablestack }
  2106. remove_from_symtablestack;
  2107. { restore }
  2108. templist.free;
  2109. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  2110. current_filepos:=oldfilepos;
  2111. current_structdef:=old_current_structdef;
  2112. current_procinfo:=old_current_procinfo;
  2113. end;
  2114. procedure tcgprocinfo.add_to_symtablestack;
  2115. begin
  2116. { insert symtables for the class, but only if it is no nested function }
  2117. if assigned(procdef.struct) and
  2118. not(assigned(parent) and
  2119. assigned(parent.procdef) and
  2120. assigned(parent.procdef.struct)) then
  2121. push_nested_hierarchy(procdef.struct);
  2122. { insert parasymtable in symtablestack when parsing
  2123. a function }
  2124. if procdef.parast.symtablelevel>=normal_function_level then
  2125. symtablestack.push(procdef.parast);
  2126. { insert localsymtable, except for the main procedure
  2127. (in that case the localst is the unit's static symtable,
  2128. which is already on the stack) }
  2129. if procdef.localst.symtablelevel>=normal_function_level then
  2130. symtablestack.push(procdef.localst);
  2131. end;
  2132. procedure tcgprocinfo.remove_from_symtablestack;
  2133. begin
  2134. { remove localsymtable }
  2135. if procdef.localst.symtablelevel>=normal_function_level then
  2136. symtablestack.pop(procdef.localst);
  2137. { remove parasymtable }
  2138. if procdef.parast.symtablelevel>=normal_function_level then
  2139. symtablestack.pop(procdef.parast);
  2140. { remove symtables for the class, but only if it is no nested function }
  2141. if assigned(procdef.struct) and
  2142. not(assigned(parent) and
  2143. assigned(parent.procdef) and
  2144. assigned(parent.procdef.struct)) then
  2145. pop_nested_hierarchy(procdef.struct);
  2146. end;
  2147. procedure tcgprocinfo.resetprocdef;
  2148. begin
  2149. { remove code tree, if not inline procedure }
  2150. if assigned(code) then
  2151. begin
  2152. { the inline procedure has already got a copy of the tree
  2153. stored in procdef.inlininginfo }
  2154. code.free;
  2155. code:=nil;
  2156. end;
  2157. end;
  2158. procedure tcgprocinfo.parse_body;
  2159. var
  2160. old_current_procinfo : tprocinfo;
  2161. old_block_type : tblock_type;
  2162. st : TSymtable;
  2163. old_current_structdef: tabstractrecorddef;
  2164. old_current_genericdef,
  2165. old_current_specializedef: tstoreddef;
  2166. parentfpinitblock: tnode;
  2167. old_parse_generic: boolean;
  2168. recordtokens : boolean;
  2169. begin
  2170. old_current_procinfo:=current_procinfo;
  2171. old_block_type:=block_type;
  2172. old_current_structdef:=current_structdef;
  2173. old_current_genericdef:=current_genericdef;
  2174. old_current_specializedef:=current_specializedef;
  2175. old_parse_generic:=parse_generic;
  2176. current_procinfo:=self;
  2177. current_structdef:=procdef.struct;
  2178. { check if the definitions of certain types are available which might not be available in older rtls and
  2179. which are assigned "on the fly" in types_dec }
  2180. {$if not defined(jvm) and not defined(wasm)}
  2181. if not assigned(rec_exceptaddr) then
  2182. Message1(cg_f_internal_type_not_found,'TEXCEPTADDR');
  2183. if not assigned(rec_tguid) then
  2184. Message1(cg_f_internal_type_not_found,'TGUID');
  2185. if not assigned(rec_jmp_buf) then
  2186. Message1(cg_f_internal_type_not_found,'JMP_BUF');
  2187. {$endif}
  2188. { if the procdef is truly a generic (thus takes parameters itself) then
  2189. /that/ is our genericdef, not the - potentially - generic struct }
  2190. if procdef.is_generic then
  2191. begin
  2192. current_genericdef:=procdef;
  2193. parse_generic:=true;
  2194. end
  2195. else if assigned(current_structdef) and (df_generic in current_structdef.defoptions) then
  2196. begin
  2197. current_genericdef:=current_structdef;
  2198. parse_generic:=true;
  2199. end;
  2200. if assigned(current_structdef) and (df_specialization in current_structdef.defoptions) then
  2201. current_specializedef:=current_structdef;
  2202. { calculate the lexical level }
  2203. if procdef.parast.symtablelevel>maxnesting then
  2204. Message(parser_e_too_much_lexlevel);
  2205. block_type:=bt_body;
  2206. {$ifdef state_tracking}
  2207. { aktstate:=Tstate_storage.create;}
  2208. {$endif state_tracking}
  2209. { allocate the symbol for this procedure }
  2210. alloc_proc_symbol(procdef);
  2211. { add parast/localst to symtablestack }
  2212. add_to_symtablestack;
  2213. { save entry info }
  2214. entrypos:=current_filepos;
  2215. entryswitches:=current_settings.localswitches;
  2216. recordtokens:=procdef.is_generic or
  2217. (
  2218. assigned(procdef.struct) and
  2219. (df_generic in procdef.struct.defoptions) and
  2220. assigned(procdef.owner) and
  2221. (procdef.owner.defowner=procdef.struct)
  2222. );
  2223. if recordtokens then
  2224. begin
  2225. { start token recorder for generic template }
  2226. procdef.initgeneric;
  2227. current_scanner.startrecordtokens(procdef.generictokenbuf);
  2228. end;
  2229. { parse the code ... }
  2230. code:=block(current_module.islibrary);
  2231. postprocess_capturer(self);
  2232. if recordtokens then
  2233. begin
  2234. { stop token recorder for generic template }
  2235. current_scanner.stoprecordtokens;
  2236. { Give an error for accesses in the static symtable that aren't visible
  2237. outside the current unit }
  2238. st:=procdef.owner;
  2239. while (st.symtabletype in [ObjectSymtable,recordsymtable]) do
  2240. st:=st.defowner.owner;
  2241. if (pi_uses_static_symtable in flags) and
  2242. (st.symtabletype<>staticsymtable) then
  2243. Message(parser_e_global_generic_references_static);
  2244. end;
  2245. { save exit info }
  2246. exitswitches:=current_settings.localswitches;
  2247. exitpos:=last_endtoken_filepos;
  2248. { the procedure is now defined }
  2249. procdef.forwarddef:=false;
  2250. procdef.is_implemented:=true;
  2251. if assigned(code) then
  2252. begin
  2253. { get a better entry point }
  2254. entrypos:=code.fileinfo;
  2255. { Finish type checking pass }
  2256. do_typecheckpass(code);
  2257. if assigned(procdef.parentfpinitblock) then
  2258. begin
  2259. if assigned(tblocknode(procdef.parentfpinitblock).left) then
  2260. begin
  2261. parentfpinitblock:=procdef.parentfpinitblock;
  2262. do_typecheckpass(parentfpinitblock);
  2263. procdef.parentfpinitblock:=parentfpinitblock;
  2264. end
  2265. end;
  2266. end;
  2267. { Check for unused labels, forwards, symbols for procedures. Static
  2268. symtable is checked in pmodules.
  2269. The check must be done after the typecheckpass }
  2270. if (Errorcount=0) and
  2271. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  2272. begin
  2273. { check if forwards are resolved }
  2274. tstoredsymtable(procdef.localst).check_forwards;
  2275. { check if all labels are used }
  2276. tstoredsymtable(procdef.localst).checklabels;
  2277. { check for unused symbols, but only if there is no asm block }
  2278. if not(pi_has_assembler_block in flags) then
  2279. begin
  2280. tstoredsymtable(procdef.localst).allsymbolsused;
  2281. tstoredsymtable(procdef.parast).allsymbolsused;
  2282. end;
  2283. end;
  2284. if (po_inline in procdef.procoptions) and
  2285. { Can we inline this procedure? }
  2286. checknodeinlining(procdef) then
  2287. CreateInlineInfo;
  2288. { Print the node to tree.log }
  2289. if paraprintnodetree <> 0 then
  2290. printproc( 'after parsing');
  2291. {$ifdef DEBUG_NODE_XML}
  2292. { Methods of generic classes don't get any code generated, so output
  2293. the node tree here }
  2294. if (df_generic in procdef.defoptions) then
  2295. XMLPrintProc(True);
  2296. {$endif DEBUG_NODE_XML}
  2297. { ... remove symbol tables }
  2298. remove_from_symtablestack;
  2299. {$ifdef state_tracking}
  2300. { aktstate.destroy;}
  2301. {$endif state_tracking}
  2302. current_structdef:=old_current_structdef;
  2303. current_genericdef:=old_current_genericdef;
  2304. current_specializedef:=old_current_specializedef;
  2305. current_procinfo:=old_current_procinfo;
  2306. parse_generic:=old_parse_generic;
  2307. { Restore old state }
  2308. block_type:=old_block_type;
  2309. end;
  2310. {****************************************************************************
  2311. PROCEDURE/FUNCTION PARSING
  2312. ****************************************************************************}
  2313. procedure check_init_paras(p:TObject;arg:pointer);
  2314. begin
  2315. if tsym(p).typ<>paravarsym then
  2316. exit;
  2317. with tparavarsym(p) do
  2318. if (is_managed_type(vardef) and
  2319. (varspez in [vs_value,vs_out])) or
  2320. (is_shortstring(vardef) and
  2321. (varspez=vs_value)) then
  2322. include(current_procinfo.flags,pi_do_call);
  2323. end;
  2324. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  2325. {
  2326. Parses the procedure directives, then parses the procedure body, then
  2327. generates the code for it
  2328. }
  2329. var
  2330. oldfailtokenmode : tmodeswitches;
  2331. isnestedproc : boolean;
  2332. begin
  2333. Message1(parser_d_procedure_start,pd.fullprocname(false));
  2334. oldfailtokenmode:=[];
  2335. { create a new procedure }
  2336. current_procinfo:=cprocinfo.create(old_current_procinfo);
  2337. current_module.procinfo:=current_procinfo;
  2338. current_procinfo.procdef:=pd;
  2339. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  2340. { an anonymous function is always considered as nested }
  2341. if po_anonymous in pd.procoptions then
  2342. begin
  2343. current_procinfo.force_nested;
  2344. isnestedproc:=true;
  2345. end;
  2346. { Insert mangledname }
  2347. pd.aliasnames.insert(pd.mangledname);
  2348. { Handle Export of this procedure }
  2349. if (po_exports in pd.procoptions) and
  2350. (target_info.system in [system_i386_os2,system_i386_emx]) then
  2351. begin
  2352. pd.aliasnames.insert(pd.procsym.realname);
  2353. if cs_link_deffile in current_settings.globalswitches then
  2354. deffile.AddExport(pd.mangledname);
  2355. end;
  2356. { Insert result variables in the localst }
  2357. insert_funcret_local(pd);
  2358. { check if there are para's which require initing -> set }
  2359. { pi_do_call (if not yet set) }
  2360. if not(pi_do_call in current_procinfo.flags) then
  2361. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  2362. { set _FAIL as keyword if constructor }
  2363. if (pd.proctypeoption=potype_constructor) then
  2364. begin
  2365. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  2366. tokeninfo^[_FAIL].keyword:=alllanguagemodes;
  2367. end;
  2368. tcgprocinfo(current_procinfo).parse_body;
  2369. { reset _FAIL as _SELF normal }
  2370. if (pd.proctypeoption=potype_constructor) then
  2371. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  2372. { When it's a nested procedure then defer the code generation,
  2373. when back at normal function level then generate the code
  2374. for all defered nested procedures and the current procedure }
  2375. if not isnestedproc then
  2376. begin
  2377. if not(df_generic in current_procinfo.procdef.defoptions) then
  2378. begin
  2379. { also generate the bodies for all previously done
  2380. specializations so that we might inline them }
  2381. generate_specialization_procs;
  2382. { convert all load nodes that might have been captured by a
  2383. capture object }
  2384. tcgprocinfo(current_procinfo).convert_captured_syms;
  2385. tcgprocinfo(current_procinfo).generate_code_tree;
  2386. end;
  2387. end;
  2388. { release procinfo }
  2389. if tprocinfo(current_module.procinfo)<>current_procinfo then
  2390. internalerror(200304274);
  2391. current_module.procinfo:=current_procinfo.parent;
  2392. { For specialization we didn't record the last semicolon. Moving this parsing
  2393. into the parse_body routine is not done because of having better file position
  2394. information available }
  2395. if not current_procinfo.procdef.is_specialization and
  2396. not (po_anonymous in current_procinfo.procdef.procoptions) and
  2397. (
  2398. not assigned(current_procinfo.procdef.struct) or
  2399. not (df_specialization in current_procinfo.procdef.struct.defoptions)
  2400. or not (
  2401. assigned(current_procinfo.procdef.owner) and
  2402. (current_procinfo.procdef.owner.defowner=current_procinfo.procdef.struct)
  2403. )
  2404. ) then
  2405. consume(_SEMICOLON);
  2406. if not isnestedproc then
  2407. { current_procinfo is checked for nil later on }
  2408. freeandnil(current_procinfo);
  2409. end;
  2410. procedure read_proc_body(pd:tprocdef);
  2411. var
  2412. old_module_procinfo : tobject;
  2413. old_current_procinfo : tprocinfo;
  2414. begin
  2415. old_current_procinfo:=current_procinfo;
  2416. old_module_procinfo:=current_module.procinfo;
  2417. current_procinfo:=nil;
  2418. current_module.procinfo:=nil;
  2419. read_proc_body(nil,pd);
  2420. current_procinfo:=old_current_procinfo;
  2421. current_module.procinfo:=old_module_procinfo;
  2422. end;
  2423. function read_proc(flags:tread_proc_flags; usefwpd: tprocdef):tprocdef;
  2424. {
  2425. Parses the procedure directives, then parses the procedure body, then
  2426. generates the code for it
  2427. }
  2428. function convert_flags_to_ppf:tparse_proc_flags;inline;
  2429. begin
  2430. result:=[];
  2431. if rpf_classmethod in flags then
  2432. include(result,ppf_classmethod);
  2433. if rpf_generic in flags then
  2434. include(result,ppf_generic);
  2435. if rpf_anonymous in flags then
  2436. include(result,ppf_anonymous);
  2437. end;
  2438. var
  2439. old_current_procinfo : tprocinfo;
  2440. old_current_structdef: tabstractrecorddef;
  2441. old_current_genericdef,
  2442. old_current_specializedef: tstoreddef;
  2443. pdflags : tpdflags;
  2444. firstpd : tprocdef;
  2445. {$ifdef genericdef_for_nested}
  2446. def : tprocdef;
  2447. srsym : tsym;
  2448. i : longint;
  2449. {$endif genericdef_for_nested}
  2450. begin
  2451. { save old state }
  2452. old_current_procinfo:=current_procinfo;
  2453. old_current_structdef:=current_structdef;
  2454. old_current_genericdef:=current_genericdef;
  2455. old_current_specializedef:=current_specializedef;
  2456. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  2457. to another procdef }
  2458. current_procinfo:=nil;
  2459. current_structdef:=nil;
  2460. current_genericdef:=nil;
  2461. current_specializedef:=nil;
  2462. if not assigned(usefwpd) then
  2463. { parse procedure declaration }
  2464. result:=parse_proc_dec(convert_flags_to_ppf,old_current_structdef)
  2465. else
  2466. result:=usefwpd;
  2467. { set the default function options }
  2468. if parse_only then
  2469. begin
  2470. result.forwarddef:=true;
  2471. { set also the interface flag, for better error message when the
  2472. implementation doesn't match this header }
  2473. result.interfacedef:=true;
  2474. include(result.procoptions,po_global);
  2475. pdflags:=[pd_interface];
  2476. end
  2477. else
  2478. begin
  2479. pdflags:=[pd_body];
  2480. if (not current_module.in_interface) then
  2481. include(pdflags,pd_implemen);
  2482. if (not current_module.is_unit) or
  2483. create_smartlink_library then
  2484. include(result.procoptions,po_global);
  2485. result.forwarddef:=false;
  2486. end;
  2487. if not assigned(usefwpd) then
  2488. begin
  2489. { parse the directives that may follow }
  2490. parse_proc_directives(result,pdflags);
  2491. if not (rpf_anonymous in flags) then
  2492. { hint directives, these can be separated by semicolons here,
  2493. that needs to be handled here with a loop (PFV) }
  2494. while try_consume_hintdirective(result.symoptions,result.deprecatedmsg) do
  2495. Consume(_SEMICOLON);
  2496. { Set calling convention }
  2497. if parse_only then
  2498. handle_calling_convention(result,hcc_default_actions_intf)
  2499. else
  2500. handle_calling_convention(result,hcc_default_actions_impl)
  2501. end;
  2502. { search for forward declarations }
  2503. if not proc_add_definition(result) then
  2504. begin
  2505. { One may not implement a method of a type declared in a different unit }
  2506. if assigned(result.struct) and
  2507. (result.struct.symtable.moduleid<>current_module.moduleid) and
  2508. not result.is_specialization then
  2509. begin
  2510. MessagePos1(result.fileinfo,parser_e_method_for_type_in_other_unit,result.struct.typesymbolprettyname);
  2511. end
  2512. { A method must be forward defined (in the object declaration) }
  2513. else if assigned(result.struct) and
  2514. (not assigned(old_current_structdef)) then
  2515. begin
  2516. MessagePos1(result.fileinfo,parser_e_header_dont_match_any_member,result.fullprocname(false));
  2517. tprocsym(result.procsym).write_parameter_lists(result);
  2518. end
  2519. else
  2520. begin
  2521. { Give a better error if there is a forward def in the interface and only
  2522. a single implementation }
  2523. firstpd:=tprocdef(tprocsym(result.procsym).ProcdefList[0]);
  2524. if (not result.forwarddef) and
  2525. (not result.interfacedef) and
  2526. (tprocsym(result.procsym).ProcdefList.Count>1) and
  2527. firstpd.forwarddef and
  2528. firstpd.interfacedef and
  2529. not(tprocsym(result.procsym).ProcdefList.Count>2) and
  2530. { don't give an error if it may be an overload }
  2531. not(m_fpc in current_settings.modeswitches) and
  2532. (not(po_overload in result.procoptions) or
  2533. not(po_overload in firstpd.procoptions)) then
  2534. begin
  2535. MessagePos1(result.fileinfo,parser_e_header_dont_match_forward,result.fullprocname(false));
  2536. tprocsym(result.procsym).write_parameter_lists(result);
  2537. end
  2538. else
  2539. begin
  2540. if result.is_generic and not assigned(result.struct) then
  2541. tprocsym(result.procsym).owner.includeoption(sto_has_generic);
  2542. end;
  2543. end;
  2544. end;
  2545. { Set mangled name }
  2546. proc_set_mangledname(result);
  2547. { inherit generic flags from parent routine }
  2548. if assigned(old_current_procinfo) and
  2549. (old_current_procinfo.procdef.defoptions*[df_specialization,df_generic]<>[]) then
  2550. begin
  2551. if df_generic in old_current_procinfo.procdef.defoptions then
  2552. include(result.defoptions,df_generic);
  2553. if df_specialization in old_current_procinfo.procdef.defoptions then
  2554. begin
  2555. include(result.defoptions,df_specialization);
  2556. { the procdefs encountered here are nested procdefs of which
  2557. their complete definition also resides inside the current token
  2558. stream, thus access to their genericdef is not required }
  2559. {$ifdef genericdef_for_nested}
  2560. { find the corresponding routine in the generic routine }
  2561. if not assigned(old_current_procinfo.procdef.genericdef) then
  2562. internalerror(2016121701);
  2563. srsym:=tsym(tprocdef(old_current_procinfo.procdef.genericdef).getsymtable(gs_local).find(result.procsym.name));
  2564. if not assigned(srsym) or (srsym.typ<>procsym) then
  2565. internalerror(2016121702);
  2566. { in practice the generic procdef should be at the same index
  2567. as the index of the current procdef, but as there *might* be
  2568. differences between the amount of defs generated for the
  2569. specialization and the generic search for the def using
  2570. parameter comparison }
  2571. for i:=0 to tprocsym(srsym).procdeflist.count-1 do
  2572. begin
  2573. def:=tprocdef(tprocsym(srsym).procdeflist[i]);
  2574. if (compare_paras(def.paras,result.paras,cp_none,[cpo_ignorehidden,cpo_openequalisexact,cpo_ignoreuniv])=te_exact) and
  2575. (compare_defs(def.returndef,result.returndef,nothingn)=te_exact) then
  2576. begin
  2577. result.genericdef:=def;
  2578. break;
  2579. end;
  2580. end;
  2581. if not assigned(result.genericdef) then
  2582. internalerror(2016121703);
  2583. {$endif}
  2584. end;
  2585. end;
  2586. { compile procedure when a body is needed }
  2587. if (pd_body in pdflags) then
  2588. begin
  2589. read_proc_body(old_current_procinfo,result);
  2590. end
  2591. else
  2592. begin
  2593. { Handle imports }
  2594. if (po_external in result.procoptions) then
  2595. begin
  2596. import_external_proc(result);
  2597. {$ifdef cpuhighleveltarget}
  2598. { it's hard to factor this out in a virtual method, because the
  2599. generic version (the one inside this ifdef) doesn't fit in
  2600. hlcgobj but in symcreat or here, while the other version
  2601. doesn't fit in symcreat (since it uses the code generator).
  2602. Maybe we need another class for this kind of code that could
  2603. either be symcreat- or hlcgobj-based
  2604. }
  2605. if (not result.forwarddef) and
  2606. (result.hasforward) and
  2607. (proc_get_importname(result)<>'') then
  2608. begin
  2609. { we cannot handle the callee-side of variadic functions (and
  2610. even if we could, e.g. LLVM cannot call through to something
  2611. else in that case) }
  2612. if is_c_variadic(result) then
  2613. Message1(parser_e_callthrough_varargs,result.fullprocname(false));
  2614. call_through_new_name(result,proc_get_importname(result));
  2615. include(result.implprocoptions,pio_thunk);
  2616. end
  2617. else
  2618. {$endif cpuhighleveltarget}
  2619. begin
  2620. create_hlcodegen;
  2621. hlcg.handle_external_proc(
  2622. current_asmdata.asmlists[al_procedures],
  2623. result,
  2624. proc_get_importname(result));
  2625. destroy_hlcodegen;
  2626. end
  2627. end;
  2628. end;
  2629. { always register public functions that are only declared in the
  2630. implementation section as they might be called using an external
  2631. declaration from another unit }
  2632. if (po_global in result.procoptions) and
  2633. not result.interfacedef and
  2634. ([df_generic,df_specialization]*result.defoptions=[]) then
  2635. begin
  2636. result.register_def;
  2637. result.procsym.register_sym;
  2638. end;
  2639. { make sure that references to forward-declared functions are not }
  2640. { treated as references to external symbols, needed for darwin. }
  2641. { make sure we don't change the binding of real external symbols }
  2642. if (([po_external,po_weakexternal]*result.procoptions)=[]) and (pocall_internproc<>result.proccalloption) then
  2643. current_asmdata.DefineProcAsmSymbol(result,result.mangledname,result.needsglobalasmsym);
  2644. current_structdef:=old_current_structdef;
  2645. current_genericdef:=old_current_genericdef;
  2646. current_specializedef:=old_current_specializedef;
  2647. current_procinfo:=old_current_procinfo;
  2648. end;
  2649. procedure import_external_proc(pd:tprocdef);
  2650. var
  2651. name : string;
  2652. begin
  2653. if not (po_external in pd.procoptions) then
  2654. internalerror(2015121101);
  2655. { Import DLL specified? }
  2656. if assigned(pd.import_dll) then
  2657. begin
  2658. if assigned (pd.import_name) then
  2659. current_module.AddExternalImport(pd.import_dll^,
  2660. pd.import_name^,proc_get_importname(pd),
  2661. pd.import_nr,false,false)
  2662. else
  2663. current_module.AddExternalImport(pd.import_dll^,
  2664. proc_get_importname(pd),proc_get_importname(pd),
  2665. pd.import_nr,false,true);
  2666. end
  2667. else
  2668. begin
  2669. name:=proc_get_importname(pd);
  2670. { add import name to external list for DLL scanning }
  2671. if tf_has_dllscanner in target_info.flags then
  2672. current_module.dllscannerinputlist.Add(name,pd);
  2673. { needed for units that use functions in packages this way }
  2674. current_module.add_extern_asmsym(name,AB_EXTERNAL,AT_FUNCTION);
  2675. end;
  2676. end;
  2677. {****************************************************************************
  2678. DECLARATION PARSING
  2679. ****************************************************************************}
  2680. { search in symtablestack for not complete classes }
  2681. procedure check_forward_class(p:TObject;arg:pointer);
  2682. begin
  2683. if (tsym(p).typ=typesym) and
  2684. (ttypesym(p).typedef.typ=objectdef) and
  2685. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  2686. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  2687. end;
  2688. {$ifdef DEBUG_NODE_XML}
  2689. procedure XMLInitializeNodeFile(RootName, ModuleName: shortstring);
  2690. var
  2691. T: Text;
  2692. begin
  2693. Assign(T, current_module.ppxfilename);
  2694. {$push} {$I-}
  2695. Rewrite(T);
  2696. if IOResult<>0 then
  2697. begin
  2698. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  2699. current_module.ppxfilefail := True;
  2700. Exit;
  2701. end;
  2702. {$pop}
  2703. { Mark the node dump file as available for writing }
  2704. current_module.ppxfilefail := False;
  2705. WriteLn(T, '<?xml version="1.0" encoding="utf-8"?>');
  2706. WriteLn(T, '<', RootName, ' name="', ModuleName, '">');
  2707. Close(T);
  2708. printnodeindention := printnodespacing;
  2709. end;
  2710. procedure XMLFinalizeNodeFile(RootName: shortstring);
  2711. var
  2712. T: Text;
  2713. begin
  2714. if current_module.ppxfilefail then
  2715. Exit;
  2716. current_module.ppxfilefail := True; { File is now considered closed no matter what happens }
  2717. Assign(T, current_module.ppxfilename);
  2718. {$push} {$I-}
  2719. Append(T);
  2720. if IOResult<>0 then
  2721. begin
  2722. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  2723. Exit;
  2724. end;
  2725. {$pop}
  2726. WriteLn(T, '</', RootName, '>');
  2727. Close(T);
  2728. end;
  2729. {$endif DEBUG_NODE_XML}
  2730. procedure read_declarations(islibrary : boolean);
  2731. var
  2732. hadgeneric : boolean;
  2733. procedure handle_unexpected_had_generic;
  2734. begin
  2735. if hadgeneric then
  2736. begin
  2737. Message(parser_e_procedure_or_function_expected);
  2738. hadgeneric:=false;
  2739. end;
  2740. end;
  2741. var
  2742. is_classdef:boolean;
  2743. flags : tread_proc_flags;
  2744. begin
  2745. is_classdef:=false;
  2746. hadgeneric:=false;
  2747. repeat
  2748. if not assigned(current_procinfo) then
  2749. internalerror(200304251);
  2750. case token of
  2751. _LABEL:
  2752. begin
  2753. handle_unexpected_had_generic;
  2754. label_dec;
  2755. end;
  2756. _CONST:
  2757. begin
  2758. handle_unexpected_had_generic;
  2759. const_dec(hadgeneric);
  2760. end;
  2761. _TYPE:
  2762. begin
  2763. handle_unexpected_had_generic;
  2764. type_dec(hadgeneric);
  2765. end;
  2766. _VAR:
  2767. begin
  2768. handle_unexpected_had_generic;
  2769. var_dec(hadgeneric);
  2770. end;
  2771. _THREADVAR:
  2772. begin
  2773. handle_unexpected_had_generic;
  2774. threadvar_dec(hadgeneric);
  2775. end;
  2776. _CLASS:
  2777. begin
  2778. is_classdef:=false;
  2779. if try_to_consume(_CLASS) then
  2780. begin
  2781. { class modifier is only allowed for procedures, functions, }
  2782. { constructors, destructors }
  2783. if not((token in [_FUNCTION,_PROCEDURE,_DESTRUCTOR,_OPERATOR]) or (token=_CONSTRUCTOR)) and
  2784. not((token=_ID) and (idtoken=_OPERATOR)) then
  2785. Message(parser_e_procedure_or_function_expected);
  2786. if is_interface(current_structdef) then
  2787. Message(parser_e_no_static_method_in_interfaces)
  2788. else
  2789. { class methods are also allowed for Objective-C protocols }
  2790. is_classdef:=true;
  2791. end;
  2792. end;
  2793. _CONSTRUCTOR,
  2794. _DESTRUCTOR,
  2795. _FUNCTION,
  2796. _PROCEDURE,
  2797. _OPERATOR:
  2798. begin
  2799. if hadgeneric and not (token in [_PROCEDURE,_FUNCTION]) then
  2800. begin
  2801. Message(parser_e_procedure_or_function_expected);
  2802. hadgeneric:=false;
  2803. end;
  2804. flags:=[];
  2805. if is_classdef then
  2806. include(flags,rpf_classmethod);
  2807. if hadgeneric then
  2808. include(flags,rpf_generic);
  2809. read_proc(flags,nil);
  2810. is_classdef:=false;
  2811. hadgeneric:=false;
  2812. end;
  2813. _EXPORTS:
  2814. begin
  2815. handle_unexpected_had_generic;
  2816. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  2817. begin
  2818. Message(parser_e_syntax_error);
  2819. consume_all_until(_SEMICOLON);
  2820. end
  2821. else if islibrary or
  2822. (target_info.system in systems_unit_program_exports) then
  2823. read_exports
  2824. else
  2825. begin
  2826. Message(parser_w_unsupported_feature);
  2827. consume(_BEGIN);
  2828. end;
  2829. end;
  2830. _PROPERTY:
  2831. begin
  2832. handle_unexpected_had_generic;
  2833. if (m_fpc in current_settings.modeswitches) then
  2834. property_dec
  2835. else
  2836. break;
  2837. end;
  2838. else
  2839. begin
  2840. case idtoken of
  2841. _RESOURCESTRING:
  2842. begin
  2843. handle_unexpected_had_generic;
  2844. { m_class is needed, because the resourcestring
  2845. loading is in the ObjPas unit }
  2846. { if (m_class in current_settings.modeswitches) then}
  2847. resourcestring_dec(hadgeneric)
  2848. { else
  2849. break;}
  2850. end;
  2851. _OPERATOR:
  2852. begin
  2853. handle_unexpected_had_generic;
  2854. if is_classdef then
  2855. begin
  2856. read_proc([rpf_classmethod],nil);
  2857. is_classdef:=false;
  2858. end
  2859. else
  2860. break;
  2861. end;
  2862. _GENERIC:
  2863. begin
  2864. handle_unexpected_had_generic;
  2865. if not (m_delphi in current_settings.modeswitches) then
  2866. begin
  2867. consume(_ID);
  2868. hadgeneric:=true;
  2869. end
  2870. else
  2871. break;
  2872. end
  2873. else
  2874. break;
  2875. end;
  2876. end;
  2877. end;
  2878. until false;
  2879. { add implementations for synthetic method declarations added by
  2880. the compiler (not for unit/program init functions, their localst
  2881. is the staticst -> would duplicate the work done in pmodules) }
  2882. if (current_procinfo.procdef.localst.symtabletype=localsymtable) and
  2883. { we cannot call add_synthetic_method_implementations as it throws an internalerror if
  2884. the token is a string/char. As this is a syntax error and compilation will abort anyways,
  2885. skipping the call does not matter
  2886. }
  2887. (token<>_CSTRING) and
  2888. (token<>_CWCHAR) and
  2889. (token<>_CWSTRING) then
  2890. add_synthetic_method_implementations(current_procinfo.procdef.localst);
  2891. { check for incomplete class definitions, this is only required
  2892. for fpc modes }
  2893. if (m_fpc in current_settings.modeswitches) then
  2894. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  2895. end;
  2896. procedure read_interface_declarations;
  2897. var
  2898. hadgeneric : boolean;
  2899. procedure handle_unexpected_had_generic;
  2900. begin
  2901. if hadgeneric then
  2902. begin
  2903. Message(parser_e_procedure_or_function_expected);
  2904. hadgeneric:=false;
  2905. end;
  2906. end;
  2907. var
  2908. flags : tread_proc_flags;
  2909. begin
  2910. hadgeneric:=false;
  2911. repeat
  2912. case token of
  2913. _CONST :
  2914. begin
  2915. handle_unexpected_had_generic;
  2916. const_dec(hadgeneric);
  2917. end;
  2918. _TYPE :
  2919. begin
  2920. handle_unexpected_had_generic;
  2921. type_dec(hadgeneric);
  2922. end;
  2923. _VAR :
  2924. begin
  2925. handle_unexpected_had_generic;
  2926. var_dec(hadgeneric);
  2927. end;
  2928. _THREADVAR :
  2929. begin
  2930. handle_unexpected_had_generic;
  2931. threadvar_dec(hadgeneric);
  2932. end;
  2933. _FUNCTION,
  2934. _PROCEDURE,
  2935. _OPERATOR :
  2936. begin
  2937. if hadgeneric and not (token in [_FUNCTION, _PROCEDURE]) then
  2938. begin
  2939. message(parser_e_procedure_or_function_expected);
  2940. hadgeneric:=false;
  2941. end;
  2942. flags:=[];
  2943. if hadgeneric then
  2944. include(flags,rpf_generic);
  2945. read_proc(flags,nil);
  2946. hadgeneric:=false;
  2947. end;
  2948. else
  2949. begin
  2950. case idtoken of
  2951. _RESOURCESTRING :
  2952. begin
  2953. handle_unexpected_had_generic;
  2954. resourcestring_dec(hadgeneric);
  2955. end;
  2956. _PROPERTY:
  2957. begin
  2958. handle_unexpected_had_generic;
  2959. if (m_fpc in current_settings.modeswitches) then
  2960. property_dec
  2961. else
  2962. break;
  2963. end;
  2964. _GENERIC:
  2965. begin
  2966. handle_unexpected_had_generic;
  2967. if not (m_delphi in current_settings.modeswitches) then
  2968. begin
  2969. hadgeneric:=true;
  2970. consume(_ID);
  2971. end
  2972. else
  2973. break;
  2974. end
  2975. else
  2976. break;
  2977. end;
  2978. end;
  2979. end;
  2980. until false;
  2981. { check for incomplete class definitions, this is only required
  2982. for fpc modes }
  2983. if (m_fpc in current_settings.modeswitches) then
  2984. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  2985. end;
  2986. end.