psub.pas 82 KB

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