psub.pas 116 KB

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