psub.pas 130 KB

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