psub.pas 81 KB

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