psub.pas 97 KB

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