psub.pas 93 KB

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