psub.pas 91 KB

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