psub.pas 115 KB

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