psub.pas 103 KB

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