psub.pas 115 KB

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