psub.pas 115 KB

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