psub.pas 108 KB

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