2
0

psub.pas 129 KB

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