psub.pas 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077
  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. dfabuilder : TDFABuilder;
  40. destructor destroy;override;
  41. procedure printproc(pass:string);
  42. procedure generate_code;
  43. procedure resetprocdef;
  44. procedure add_to_symtablestack;
  45. procedure remove_from_symtablestack;
  46. procedure parse_body;
  47. function has_assembler_child : boolean;
  48. end;
  49. procedure printnode_reset;
  50. { reads the declaration blocks }
  51. procedure read_declarations(islibrary : boolean);
  52. { reads declarations in the interface part of a unit }
  53. procedure read_interface_declarations;
  54. procedure generate_specialization_procs;
  55. implementation
  56. uses
  57. sysutils,
  58. { common }
  59. cutils,
  60. { global }
  61. globtype,tokens,verbose,comphook,constexp,
  62. systems,
  63. { aasm }
  64. cpuinfo,cpubase,aasmbase,aasmtai,aasmdata,
  65. { symtable }
  66. symconst,symbase,symsym,symtype,symtable,defutil,
  67. paramgr,
  68. ppu,fmodule,
  69. { pass 1 }
  70. nutils,nld,ncal,ncon,nflw,nadd,ncnv,nmem,
  71. pass_1,
  72. {$ifdef state_tracking}
  73. nstate,
  74. {$endif state_tracking}
  75. { pass 2 }
  76. {$ifndef NOPASS2}
  77. pass_2,
  78. {$endif}
  79. { parser }
  80. scanner,import,gendef,
  81. pbase,pstatmnt,pdecl,pdecsub,pexports,
  82. { codegen }
  83. tgobj,cgbase,cgobj,cgcpu,dbgbase,
  84. ncgutil,regvars,
  85. optbase,
  86. opttail,
  87. optcse,optloop,
  88. optutils
  89. {$if defined(arm) or defined(avr32) or defined(powerpc) or defined(powerpc64)}
  90. ,aasmcpu
  91. {$endif arm}
  92. {$ifndef NOOPT}
  93. {$ifdef i386}
  94. ,aopt386
  95. {$else i386}
  96. ,aopt
  97. {$endif i386}
  98. {$endif}
  99. ;
  100. {****************************************************************************
  101. PROCEDURE/FUNCTION BODY PARSING
  102. ****************************************************************************}
  103. procedure initializevars(p:TObject;arg:pointer);
  104. var
  105. b : tblocknode;
  106. begin
  107. if not (tsym(p).typ in [localvarsym,staticvarsym]) then
  108. exit;
  109. with tabstractnormalvarsym(p) do
  110. begin
  111. if assigned(defaultconstsym) then
  112. begin
  113. b:=tblocknode(arg);
  114. b.left:=cstatementnode.create(
  115. cassignmentnode.create(
  116. cloadnode.create(tsym(p),tsym(p).owner),
  117. cloadnode.create(defaultconstsym,defaultconstsym.owner)),
  118. b.left);
  119. end;
  120. end;
  121. end;
  122. procedure check_finalize_paras(p:TObject;arg:pointer);
  123. begin
  124. if (tsym(p).typ=paravarsym) and
  125. (tparavarsym(p).varspez=vs_value) and
  126. is_managed_type(tparavarsym(p).vardef) then
  127. include(current_procinfo.flags,pi_needs_implicit_finally);
  128. end;
  129. procedure check_finalize_locals(p:TObject;arg:pointer);
  130. begin
  131. { include the result: it needs to be finalized in case an exception }
  132. { occurs }
  133. if (tsym(p).typ=localvarsym) and
  134. (tlocalvarsym(p).refs>0) and
  135. is_managed_type(tlocalvarsym(p).vardef) then
  136. include(current_procinfo.flags,pi_needs_implicit_finally);
  137. end;
  138. function block(islibrary : boolean) : tnode;
  139. var
  140. oldfilepos: tfileposinfo;
  141. begin
  142. { parse const,types and vars }
  143. read_declarations(islibrary);
  144. { do we have an assembler block without the po_assembler?
  145. we should allow this for Delphi compatibility (PFV) }
  146. if (token=_ASM) and (m_delphi in current_settings.modeswitches) then
  147. include(current_procinfo.procdef.procoptions,po_assembler);
  148. { Handle assembler block different }
  149. if (po_assembler in current_procinfo.procdef.procoptions) then
  150. begin
  151. block:=assembler_block;
  152. exit;
  153. end;
  154. {Unit initialization?.}
  155. if (
  156. assigned(current_procinfo.procdef.localst) and
  157. (current_procinfo.procdef.localst.symtablelevel=main_program_level) and
  158. (current_module.is_unit or islibrary)
  159. ) then
  160. begin
  161. if (token=_END) then
  162. begin
  163. consume(_END);
  164. { We need at least a node, else the entry/exit code is not
  165. generated and thus no PASCALMAIN symbol which we need (PFV) }
  166. if islibrary then
  167. block:=cnothingnode.create
  168. else
  169. block:=nil;
  170. end
  171. else
  172. begin
  173. if token=_INITIALIZATION then
  174. begin
  175. { The library init code is already called and does not
  176. need to be in the initfinal table (PFV) }
  177. block:=statement_block(_INITIALIZATION);
  178. { optimize empty initialization block away }
  179. if (block.nodetype=blockn) and (tblocknode(block).left=nil) then
  180. FreeAndNil(block)
  181. else
  182. if not islibrary then
  183. current_module.flags:=current_module.flags or uf_init;
  184. end
  185. else if token=_FINALIZATION then
  186. begin
  187. { when a unit has only a finalization section, we can come to this
  188. point when we try to read the nonh existing initalization section
  189. so we've to check if we are really try to parse the finalization }
  190. if current_procinfo.procdef.proctypeoption=potype_unitfinalize then
  191. begin
  192. block:=statement_block(_FINALIZATION);
  193. { optimize empty finalization block away }
  194. if (block.nodetype=blockn) and (tblocknode(block).left=nil) then
  195. FreeAndNil(block)
  196. else
  197. current_module.flags:=current_module.flags or uf_finalize;
  198. end
  199. else
  200. block:=nil;
  201. end
  202. else
  203. begin
  204. { The library init code is already called and does not
  205. need to be in the initfinal table (PFV) }
  206. if not islibrary then
  207. current_module.flags:=current_module.flags or uf_init;
  208. block:=statement_block(_BEGIN);
  209. end;
  210. end;
  211. end
  212. else
  213. begin
  214. block:=statement_block(_BEGIN);
  215. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  216. begin
  217. { initialization of local variables with their initial
  218. values: part of function entry }
  219. oldfilepos:=current_filepos;
  220. current_filepos:=current_procinfo.entrypos;
  221. current_procinfo.procdef.localst.SymList.ForEachCall(@initializevars,block);
  222. current_filepos:=oldfilepos;
  223. end;
  224. end;
  225. end;
  226. {****************************************************************************
  227. PROCEDURE/FUNCTION COMPILING
  228. ****************************************************************************}
  229. procedure printnode_reset;
  230. begin
  231. assign(printnodefile,treelogfilename);
  232. {$I-}
  233. rewrite(printnodefile);
  234. {$I+}
  235. if ioresult<>0 then
  236. begin
  237. Comment(V_Error,'Error creating '+treelogfilename);
  238. exit;
  239. end;
  240. close(printnodefile);
  241. end;
  242. procedure add_label_init(p:TObject;arg:pointer);
  243. begin
  244. if tstoredsym(p).typ=labelsym then
  245. begin
  246. addstatement(tstatementnode(arg^),
  247. cifnode.create(caddnode.create(equaln,
  248. ccallnode.createintern('fpc_setjmp',
  249. ccallparanode.create(cloadnode.create(tlabelsym(p).jumpbuf,tlabelsym(p).jumpbuf.owner),nil)),
  250. cordconstnode.create(1,sinttype,true))
  251. ,cgotonode.create(tlabelsym(p)),nil)
  252. );
  253. end;
  254. end;
  255. function generate_bodyentry_block:tnode;
  256. var
  257. srsym : tsym;
  258. para : tcallparanode;
  259. newstatement : tstatementnode;
  260. begin
  261. result:=internalstatements(newstatement);
  262. if assigned(current_structdef) then
  263. begin
  264. { a constructor needs a help procedure }
  265. if (current_procinfo.procdef.proctypeoption=potype_constructor) then
  266. begin
  267. if is_class(current_structdef) then
  268. begin
  269. include(current_procinfo.flags,pi_needs_implicit_finally);
  270. srsym:=search_struct_member(current_structdef,'NEWINSTANCE');
  271. if assigned(srsym) and
  272. (srsym.typ=procsym) then
  273. begin
  274. { if vmt>1 then newinstance }
  275. addstatement(newstatement,cifnode.create(
  276. caddnode.create(gtn,
  277. ctypeconvnode.create_internal(
  278. load_vmt_pointer_node,
  279. voidpointertype),
  280. cpointerconstnode.create(1,voidpointertype)),
  281. cassignmentnode.create(
  282. ctypeconvnode.create_internal(
  283. load_self_pointer_node,
  284. voidpointertype),
  285. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_vmt_pointer_node,[])),
  286. nil));
  287. end
  288. else
  289. internalerror(200305108);
  290. end
  291. else
  292. if is_object(current_structdef) then
  293. begin
  294. { parameter 3 : vmt_offset }
  295. { parameter 2 : address of pointer to vmt,
  296. this is required to allow setting the vmt to -1 to indicate
  297. that memory was allocated }
  298. { parameter 1 : self pointer }
  299. para:=ccallparanode.create(
  300. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  301. ccallparanode.create(
  302. ctypeconvnode.create_internal(
  303. load_vmt_pointer_node,
  304. voidpointertype),
  305. ccallparanode.create(
  306. ctypeconvnode.create_internal(
  307. load_self_pointer_node,
  308. voidpointertype),
  309. nil)));
  310. addstatement(newstatement,cassignmentnode.create(
  311. ctypeconvnode.create_internal(
  312. load_self_pointer_node,
  313. voidpointertype),
  314. ccallnode.createintern('fpc_help_constructor',para)));
  315. end
  316. else
  317. if not is_record(current_structdef) then
  318. internalerror(200305103);
  319. { if self=nil then exit
  320. calling fail instead of exit is useless because
  321. there is nothing to dispose (PFV) }
  322. if is_class_or_object(current_structdef) then
  323. addstatement(newstatement,cifnode.create(
  324. caddnode.create(equaln,
  325. load_self_pointer_node,
  326. cnilnode.create),
  327. cexitnode.create(nil),
  328. nil));
  329. end;
  330. { maybe call BeforeDestruction for classes }
  331. if (current_procinfo.procdef.proctypeoption=potype_destructor) and
  332. is_class(current_structdef) then
  333. begin
  334. srsym:=search_struct_member(current_structdef,'BEFOREDESTRUCTION');
  335. if assigned(srsym) and
  336. (srsym.typ=procsym) then
  337. begin
  338. { if vmt>0 then beforedestruction }
  339. addstatement(newstatement,cifnode.create(
  340. caddnode.create(gtn,
  341. ctypeconvnode.create_internal(
  342. load_vmt_pointer_node,ptrsinttype),
  343. ctypeconvnode.create_internal(
  344. cnilnode.create,ptrsinttype)),
  345. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  346. nil));
  347. end
  348. else
  349. internalerror(200305104);
  350. end;
  351. end;
  352. if m_non_local_goto in current_settings.modeswitches then
  353. tsymtable(current_procinfo.procdef.localst).SymList.ForEachCall(@add_label_init,@newstatement);
  354. end;
  355. function generate_bodyexit_block:tnode;
  356. var
  357. srsym : tsym;
  358. para : tcallparanode;
  359. newstatement : tstatementnode;
  360. oldlocalswitches: tlocalswitches;
  361. begin
  362. result:=internalstatements(newstatement);
  363. if assigned(current_structdef) then
  364. begin
  365. { Don't test self and the vmt here. The reason is that }
  366. { a constructor already checks whether these are valid }
  367. { before. Further, in case of TThread the thread may }
  368. { free the class instance right after AfterConstruction }
  369. { has been called, so it may no longer be valid (JM) }
  370. oldlocalswitches:=current_settings.localswitches;
  371. current_settings.localswitches:=oldlocalswitches-[cs_check_object,cs_check_range];
  372. { a destructor needs a help procedure }
  373. if (current_procinfo.procdef.proctypeoption=potype_destructor) then
  374. begin
  375. if is_class(current_structdef) then
  376. begin
  377. srsym:=search_struct_member(current_structdef,'FREEINSTANCE');
  378. if assigned(srsym) and
  379. (srsym.typ=procsym) then
  380. begin
  381. { if self<>0 and vmt<>0 then freeinstance }
  382. addstatement(newstatement,cifnode.create(
  383. caddnode.create(andn,
  384. caddnode.create(unequaln,
  385. load_self_pointer_node,
  386. cnilnode.create),
  387. caddnode.create(unequaln,
  388. ctypeconvnode.create(
  389. load_vmt_pointer_node,
  390. voidpointertype),
  391. cpointerconstnode.create(0,voidpointertype))),
  392. ccallnode.create(nil,tprocsym(srsym),srsym.owner,load_self_node,[]),
  393. nil));
  394. end
  395. else
  396. internalerror(200305108);
  397. end
  398. else
  399. if is_object(current_structdef) then
  400. begin
  401. { finalize object data, but only if not in inherited call }
  402. if is_managed_type(current_structdef) then
  403. begin
  404. addstatement(newstatement,cifnode.create(
  405. caddnode.create(unequaln,
  406. ctypeconvnode.create_internal(load_vmt_pointer_node,voidpointertype),
  407. cnilnode.create),
  408. finalize_data_node(load_self_node),
  409. nil));
  410. end;
  411. { parameter 3 : vmt_offset }
  412. { parameter 2 : pointer to vmt }
  413. { parameter 1 : self pointer }
  414. para:=ccallparanode.create(
  415. cordconstnode.create(tobjectdef(current_structdef).vmt_offset,s32inttype,false),
  416. ccallparanode.create(
  417. ctypeconvnode.create_internal(
  418. load_vmt_pointer_node,
  419. voidpointertype),
  420. ccallparanode.create(
  421. ctypeconvnode.create_internal(
  422. load_self_pointer_node,
  423. voidpointertype),
  424. nil)));
  425. addstatement(newstatement,
  426. ccallnode.createintern('fpc_help_destructor',para));
  427. end
  428. else
  429. internalerror(200305105);
  430. end;
  431. current_settings.localswitches:=oldlocalswitches;
  432. end;
  433. end;
  434. function generate_except_block:tnode;
  435. var
  436. newstatement : tstatementnode;
  437. { safecall handling }
  438. exceptobjnode,exceptaddrnode: ttempcreatenode;
  439. sym,exceptsym: tsym;
  440. begin
  441. generate_except_block:=internalstatements(newstatement);
  442. { a constructor needs call destructor (if available) when it
  443. is not inherited }
  444. if not assigned(current_structdef) or
  445. (current_procinfo.procdef.proctypeoption<>potype_constructor) then
  446. begin
  447. { no constructor }
  448. { must be the return value finalized before reraising the exception? }
  449. if (not is_void(current_procinfo.procdef.returndef)) and
  450. is_managed_type(current_procinfo.procdef.returndef) and
  451. (not paramanager.ret_in_param(current_procinfo.procdef.returndef, current_procinfo.procdef.proccalloption)) and
  452. (not is_class(current_procinfo.procdef.returndef)) then
  453. addstatement(newstatement,finalize_data_node(load_result_node));
  454. {$if defined(x86) or defined(arm)}
  455. { safecall handling }
  456. if (tf_safecall_exceptions in target_info.flags) and
  457. (current_procinfo.procdef.proccalloption=pocall_safecall) then
  458. begin
  459. { create a local hidden variable "safe_result" }
  460. { it will be used in ncgflw unit }
  461. { to set "real" result value for safecall routine }
  462. sym:=tlocalvarsym.create('$safe_result',vs_value,hresultdef,[]);
  463. include(sym.symoptions,sp_internal);
  464. current_procinfo.procdef.localst.insert(sym);
  465. { if safecall is used for a class method we need to call }
  466. { SafecallException virtual method }
  467. { In other case we return E_UNEXPECTED error value }
  468. if is_class(current_procinfo.procdef.struct) then
  469. begin
  470. { temp variable to store exception address }
  471. exceptaddrnode:=ctempcreatenode.create(voidpointertype,voidpointertype.size,
  472. tt_persistent,true);
  473. addstatement(newstatement,exceptaddrnode);
  474. addstatement(newstatement,
  475. cassignmentnode.create(
  476. ctemprefnode.create(exceptaddrnode),
  477. ccallnode.createintern('fpc_getexceptionaddr',nil)));
  478. { temp variable to store popped up exception }
  479. exceptobjnode:=ctempcreatenode.create(class_tobject,class_tobject.size,
  480. tt_persistent,true);
  481. addstatement(newstatement,exceptobjnode);
  482. addstatement(newstatement,
  483. cassignmentnode.create(
  484. ctemprefnode.create(exceptobjnode),
  485. ccallnode.createintern('fpc_popobjectstack', nil)));
  486. exceptsym:=search_struct_member(tobjectdef(current_procinfo.procdef.struct),'SAFECALLEXCEPTION');
  487. addstatement(newstatement,
  488. cassignmentnode.create(
  489. cloadnode.create(sym,sym.Owner),
  490. ccallnode.create(
  491. ccallparanode.create(ctemprefnode.create(exceptaddrnode),
  492. ccallparanode.create(ctemprefnode.create(exceptobjnode),nil)),
  493. tprocsym(exceptsym), tprocsym(exceptsym).owner,load_self_node,[])));
  494. addstatement(newstatement,ccallnode.createintern('fpc_destroyexception',
  495. ccallparanode.create(ctemprefnode.create(exceptobjnode),nil)));
  496. addstatement(newstatement,ctempdeletenode.create(exceptobjnode));
  497. addstatement(newstatement,ctempdeletenode.create(exceptaddrnode));
  498. end
  499. else
  500. begin
  501. { pop up and destroy an exception }
  502. addstatement(newstatement,ccallnode.createintern('fpc_destroyexception',
  503. ccallparanode.create(ccallnode.createintern('fpc_popobjectstack', nil),nil)));
  504. addstatement(newstatement,
  505. cassignmentnode.create(
  506. cloadnode.create(sym,sym.Owner),
  507. genintconstnode(HResult($8000FFFF))));
  508. end;
  509. end;
  510. {$endif}
  511. end;
  512. end;
  513. {****************************************************************************
  514. TCGProcInfo
  515. ****************************************************************************}
  516. destructor tcgprocinfo.destroy;
  517. begin
  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 : tprocinfo;
  733. begin
  734. result:=false;
  735. hp:=get_first_nestedproc;
  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:=tprocinfo(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) or defined(avr32)}
  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. {$ifdef AVR32}
  1110. { because of the limited constant size of the arm, all data access is done pc relative }
  1111. finalizeavr32code(aktproccode,aktlocaldata);
  1112. {$endif AVR32}
  1113. { Add end symbol and debug info }
  1114. { this must be done after the pcrelativedata is appended else the distance calculation of
  1115. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  1116. so it should be inserted before the end symbol (FK)
  1117. }
  1118. current_filepos:=exitpos;
  1119. gen_proc_symbol_end(templist);
  1120. aktproccode.concatlist(templist);
  1121. {$if defined(POWERPC) or defined(POWERPC64)}
  1122. fixup_jmps(aktproccode);
  1123. {$endif}
  1124. { insert line debuginfo }
  1125. if (cs_debuginfo in current_settings.moduleswitches) or
  1126. (cs_use_lineinfo in current_settings.globalswitches) then
  1127. current_debuginfo.insertlineinfo(aktproccode);
  1128. { add the procedure to the al_procedures }
  1129. maybe_new_object_file(current_asmdata.asmlists[al_procedures]);
  1130. new_section(current_asmdata.asmlists[al_procedures],sec_code,lower(procdef.mangledname),getprocalign);
  1131. current_asmdata.asmlists[al_procedures].concatlist(aktproccode);
  1132. { save local data (casetable) also in the same file }
  1133. if assigned(aktlocaldata) and
  1134. (not aktlocaldata.empty) then
  1135. current_asmdata.asmlists[al_procedures].concatlist(aktlocaldata);
  1136. { only now we can remove the temps }
  1137. tg.resettempgen;
  1138. { stop tempgen and ra }
  1139. tg.free;
  1140. cg.done_register_allocators;
  1141. destroy_codegen;
  1142. tg:=nil;
  1143. end;
  1144. dfabuilder.free;
  1145. { restore symtablestack }
  1146. remove_from_symtablestack;
  1147. { restore }
  1148. templist.free;
  1149. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  1150. current_filepos:=oldfilepos;
  1151. current_structdef:=old_current_structdef;
  1152. current_procinfo:=old_current_procinfo;
  1153. end;
  1154. procedure tcgprocinfo.add_to_symtablestack;
  1155. begin
  1156. { insert symtables for the class, but only if it is no nested function }
  1157. if assigned(procdef.struct) and
  1158. not(assigned(parent) and
  1159. assigned(parent.procdef) and
  1160. assigned(parent.procdef.struct)) then
  1161. push_nested_hierarchy(procdef.struct);
  1162. { insert parasymtable in symtablestack when parsing
  1163. a function }
  1164. if procdef.parast.symtablelevel>=normal_function_level then
  1165. symtablestack.push(procdef.parast);
  1166. { insert localsymtable, except for the main procedure
  1167. (in that case the localst is the unit's static symtable,
  1168. which is already on the stack) }
  1169. if procdef.localst.symtablelevel>=normal_function_level then
  1170. symtablestack.push(procdef.localst);
  1171. end;
  1172. procedure tcgprocinfo.remove_from_symtablestack;
  1173. begin
  1174. { remove localsymtable }
  1175. if procdef.localst.symtablelevel>=normal_function_level then
  1176. symtablestack.pop(procdef.localst);
  1177. { remove parasymtable }
  1178. if procdef.parast.symtablelevel>=normal_function_level then
  1179. symtablestack.pop(procdef.parast);
  1180. { remove symtables for the class, but only if it is no nested function }
  1181. if assigned(procdef.struct) and
  1182. not(assigned(parent) and
  1183. assigned(parent.procdef) and
  1184. assigned(parent.procdef.struct)) then
  1185. pop_nested_hierarchy(procdef.struct);
  1186. end;
  1187. procedure tcgprocinfo.resetprocdef;
  1188. begin
  1189. { remove code tree, if not inline procedure }
  1190. if assigned(code) then
  1191. begin
  1192. { the inline procedure has already got a copy of the tree
  1193. stored in procdef.inlininginfo }
  1194. code.free;
  1195. code:=nil;
  1196. end;
  1197. end;
  1198. function checknodeinlining(procdef: tprocdef): boolean;
  1199. var
  1200. i : integer;
  1201. currpara : tparavarsym;
  1202. begin
  1203. result := false;
  1204. if (pi_has_assembler_block in current_procinfo.flags) then
  1205. begin
  1206. Message1(parser_w_not_supported_for_inline,'assembler');
  1207. Message(parser_w_inlining_disabled);
  1208. exit;
  1209. end;
  1210. for i:=0 to procdef.paras.count-1 do
  1211. begin
  1212. currpara:=tparavarsym(procdef.paras[i]);
  1213. case currpara.vardef.typ of
  1214. formaldef :
  1215. begin
  1216. if (currpara.varspez in [vs_out,vs_var,vs_const,vs_constref]) then
  1217. begin
  1218. Message1(parser_w_not_supported_for_inline,'formal parameter');
  1219. Message(parser_w_inlining_disabled);
  1220. exit;
  1221. end;
  1222. end;
  1223. arraydef :
  1224. begin
  1225. if is_array_of_const(currpara.vardef) or
  1226. is_variant_array(currpara.vardef) then
  1227. begin
  1228. Message1(parser_w_not_supported_for_inline,'array of const');
  1229. Message(parser_w_inlining_disabled);
  1230. exit;
  1231. end;
  1232. { open arrays might need re-basing of the index, i.e. if you pass
  1233. an array[1..10] as open array, you have to add 1 to all index operations
  1234. if you directly inline it }
  1235. if is_open_array(currpara.vardef) then
  1236. begin
  1237. Message1(parser_w_not_supported_for_inline,'open array');
  1238. Message(parser_w_inlining_disabled);
  1239. exit;
  1240. end;
  1241. end;
  1242. end;
  1243. end;
  1244. result:=true;
  1245. end;
  1246. procedure tcgprocinfo.parse_body;
  1247. var
  1248. old_current_procinfo : tprocinfo;
  1249. old_block_type : tblock_type;
  1250. st : TSymtable;
  1251. old_current_structdef: tabstractrecorddef;
  1252. old_current_genericdef,
  1253. old_current_specializedef: tstoreddef;
  1254. begin
  1255. old_current_procinfo:=current_procinfo;
  1256. old_block_type:=block_type;
  1257. old_current_structdef:=current_structdef;
  1258. old_current_genericdef:=current_genericdef;
  1259. old_current_specializedef:=current_specializedef;
  1260. current_procinfo:=self;
  1261. current_structdef:=procdef.struct;
  1262. if assigned(current_structdef) and (df_generic in current_structdef.defoptions) then
  1263. current_genericdef:=current_structdef;
  1264. if assigned(current_structdef) and (df_specialization in current_structdef.defoptions) then
  1265. current_specializedef:=current_structdef;
  1266. { calculate the lexical level }
  1267. if procdef.parast.symtablelevel>maxnesting then
  1268. Message(parser_e_too_much_lexlevel);
  1269. block_type:=bt_body;
  1270. {$ifdef state_tracking}
  1271. { aktstate:=Tstate_storage.create;}
  1272. {$endif state_tracking}
  1273. { allocate the symbol for this procedure }
  1274. alloc_proc_symbol(procdef);
  1275. { add parast/localst to symtablestack }
  1276. add_to_symtablestack;
  1277. { save entry info }
  1278. entrypos:=current_filepos;
  1279. entryswitches:=current_settings.localswitches;
  1280. if (df_generic in procdef.defoptions) then
  1281. begin
  1282. { start token recorder for generic template }
  1283. procdef.initgeneric;
  1284. current_scanner.startrecordtokens(procdef.generictokenbuf);
  1285. end;
  1286. { parse the code ... }
  1287. code:=block(current_module.islibrary);
  1288. if (df_generic in procdef.defoptions) then
  1289. begin
  1290. { stop token recorder for generic template }
  1291. current_scanner.stoprecordtokens;
  1292. { Give an error for accesses in the static symtable that aren't visible
  1293. outside the current unit }
  1294. st:=procdef.owner;
  1295. while (st.symtabletype=ObjectSymtable) do
  1296. st:=st.defowner.owner;
  1297. if (pi_uses_static_symtable in flags) and
  1298. (st.symtabletype<>staticsymtable) then
  1299. Comment(V_Error,'Global Generic template references static symtable');
  1300. end;
  1301. { save exit info }
  1302. exitswitches:=current_settings.localswitches;
  1303. exitpos:=last_endtoken_filepos;
  1304. { the procedure is now defined }
  1305. procdef.forwarddef:=false;
  1306. if assigned(code) then
  1307. begin
  1308. { get a better entry point }
  1309. entrypos:=code.fileinfo;
  1310. { Finish type checking pass }
  1311. do_typecheckpass(code);
  1312. end;
  1313. { Check for unused labels, forwards, symbols for procedures. Static
  1314. symtable is checked in pmodules.
  1315. The check must be done after the typecheckpass }
  1316. if (Errorcount=0) and
  1317. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  1318. begin
  1319. { check if forwards are resolved }
  1320. tstoredsymtable(procdef.localst).check_forwards;
  1321. { check if all labels are used }
  1322. tstoredsymtable(procdef.localst).checklabels;
  1323. { check for unused symbols, but only if there is no asm block }
  1324. if not(pi_has_assembler_block in flags) then
  1325. begin
  1326. tstoredsymtable(procdef.localst).allsymbolsused;
  1327. tstoredsymtable(procdef.parast).allsymbolsused;
  1328. end;
  1329. end;
  1330. if (po_inline in procdef.procoptions) then
  1331. begin
  1332. { Can we inline this procedure? }
  1333. if checknodeinlining(procdef) then
  1334. begin
  1335. new(procdef.inlininginfo);
  1336. include(procdef.procoptions,po_has_inlininginfo);
  1337. procdef.inlininginfo^.code:=code.getcopy;
  1338. procdef.inlininginfo^.flags:=current_procinfo.flags;
  1339. { The blocknode needs to set an exit label }
  1340. if procdef.inlininginfo^.code.nodetype=blockn then
  1341. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1342. end;
  1343. end;
  1344. { Print the node to tree.log }
  1345. if paraprintnodetree=1 then
  1346. printproc( 'after parsing');
  1347. { ... remove symbol tables }
  1348. remove_from_symtablestack;
  1349. {$ifdef state_tracking}
  1350. { aktstate.destroy;}
  1351. {$endif state_tracking}
  1352. current_structdef:=old_current_structdef;
  1353. current_genericdef:=old_current_genericdef;
  1354. current_specializedef:=old_current_specializedef;
  1355. current_procinfo:=old_current_procinfo;
  1356. { Restore old state }
  1357. block_type:=old_block_type;
  1358. end;
  1359. {****************************************************************************
  1360. PROCEDURE/FUNCTION PARSING
  1361. ****************************************************************************}
  1362. procedure check_init_paras(p:TObject;arg:pointer);
  1363. begin
  1364. if tsym(p).typ<>paravarsym then
  1365. exit;
  1366. with tparavarsym(p) do
  1367. if is_managed_type(vardef) and
  1368. (varspez in [vs_value,vs_out]) then
  1369. include(current_procinfo.flags,pi_do_call);
  1370. end;
  1371. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  1372. {
  1373. Parses the procedure directives, then parses the procedure body, then
  1374. generates the code for it
  1375. }
  1376. procedure do_generate_code(pi:tcgprocinfo);
  1377. var
  1378. hpi : tcgprocinfo;
  1379. begin
  1380. { generate code for this procedure }
  1381. pi.generate_code;
  1382. { process nested procs }
  1383. hpi:=tcgprocinfo(pi.get_first_nestedproc);
  1384. while assigned(hpi) do
  1385. begin
  1386. do_generate_code(hpi);
  1387. hpi:=tcgprocinfo(hpi.next);
  1388. end;
  1389. pi.resetprocdef;
  1390. end;
  1391. var
  1392. oldfailtokenmode : tmodeswitch;
  1393. isnestedproc : boolean;
  1394. begin
  1395. Message1(parser_d_procedure_start,pd.fullprocname(false));
  1396. { create a new procedure }
  1397. current_procinfo:=cprocinfo.create(old_current_procinfo);
  1398. current_module.procinfo:=current_procinfo;
  1399. current_procinfo.procdef:=pd;
  1400. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  1401. { Insert mangledname }
  1402. pd.aliasnames.insert(pd.mangledname);
  1403. { Handle Export of this procedure }
  1404. if (po_exports in pd.procoptions) and
  1405. (target_info.system in [system_i386_os2,system_i386_emx]) then
  1406. begin
  1407. pd.aliasnames.insert(pd.procsym.realname);
  1408. if cs_link_deffile in current_settings.globalswitches then
  1409. deffile.AddExport(pd.mangledname);
  1410. end;
  1411. { Insert result variables in the localst }
  1412. insert_funcret_local(pd);
  1413. { check if there are para's which require initing -> set }
  1414. { pi_do_call (if not yet set) }
  1415. if not(pi_do_call in current_procinfo.flags) then
  1416. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  1417. { set _FAIL as keyword if constructor }
  1418. if (pd.proctypeoption=potype_constructor) then
  1419. begin
  1420. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  1421. tokeninfo^[_FAIL].keyword:=m_all;
  1422. end;
  1423. tcgprocinfo(current_procinfo).parse_body;
  1424. { We can't support inlining for procedures that have nested
  1425. procedures because the nested procedures use a fixed offset
  1426. for accessing locals in the parent procedure (PFV) }
  1427. if current_procinfo.has_nestedprocs then
  1428. begin
  1429. if (df_generic in current_procinfo.procdef.defoptions) then
  1430. Comment(V_Error,'Generic methods cannot have nested procedures')
  1431. else
  1432. if (po_inline in current_procinfo.procdef.procoptions) then
  1433. begin
  1434. Message1(parser_w_not_supported_for_inline,'nested procedures');
  1435. Message(parser_w_inlining_disabled);
  1436. exclude(current_procinfo.procdef.procoptions,po_inline);
  1437. end;
  1438. end;
  1439. { When it's a nested procedure then defer the code generation,
  1440. when back at normal function level then generate the code
  1441. for all defered nested procedures and the current procedure }
  1442. if not isnestedproc then
  1443. begin
  1444. if not(df_generic in current_procinfo.procdef.defoptions) then
  1445. do_generate_code(tcgprocinfo(current_procinfo));
  1446. end;
  1447. { reset _FAIL as _SELF normal }
  1448. if (pd.proctypeoption=potype_constructor) then
  1449. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  1450. { release procinfo }
  1451. if tprocinfo(current_module.procinfo)<>current_procinfo then
  1452. internalerror(200304274);
  1453. current_module.procinfo:=current_procinfo.parent;
  1454. { For specialization we didn't record the last semicolon. Moving this parsing
  1455. into the parse_body routine is not done because of having better file position
  1456. information available }
  1457. if not(df_specialization in current_procinfo.procdef.defoptions) then
  1458. consume(_SEMICOLON);
  1459. if not isnestedproc then
  1460. { current_procinfo is checked for nil later on }
  1461. freeandnil(current_procinfo);
  1462. end;
  1463. procedure read_proc(isclassmethod:boolean);
  1464. {
  1465. Parses the procedure directives, then parses the procedure body, then
  1466. generates the code for it
  1467. }
  1468. var
  1469. old_current_procinfo : tprocinfo;
  1470. old_current_structdef: tabstractrecorddef;
  1471. old_current_genericdef,
  1472. old_current_specializedef: tstoreddef;
  1473. pdflags : tpdflags;
  1474. pd,firstpd : tprocdef;
  1475. s : string;
  1476. begin
  1477. { save old state }
  1478. old_current_procinfo:=current_procinfo;
  1479. old_current_structdef:=current_structdef;
  1480. old_current_genericdef:=current_genericdef;
  1481. old_current_specializedef:=current_specializedef;
  1482. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  1483. to another procdef }
  1484. current_procinfo:=nil;
  1485. current_structdef:=nil;
  1486. current_genericdef:=nil;
  1487. current_specializedef:=nil;
  1488. { parse procedure declaration }
  1489. pd:=parse_proc_dec(isclassmethod,old_current_structdef);
  1490. { set the default function options }
  1491. if parse_only then
  1492. begin
  1493. pd.forwarddef:=true;
  1494. { set also the interface flag, for better error message when the
  1495. implementation doesn't much this header }
  1496. pd.interfacedef:=true;
  1497. include(pd.procoptions,po_global);
  1498. pdflags:=[pd_interface];
  1499. end
  1500. else
  1501. begin
  1502. pdflags:=[pd_body];
  1503. if (not current_module.in_interface) then
  1504. include(pdflags,pd_implemen);
  1505. if (not current_module.is_unit) or
  1506. create_smartlink or
  1507. {
  1508. taking addresses of static procedures goes wrong
  1509. if they aren't global when pic is used (FK)
  1510. }
  1511. (cs_create_pic in current_settings.moduleswitches) then
  1512. include(pd.procoptions,po_global);
  1513. pd.forwarddef:=false;
  1514. end;
  1515. { parse the directives that may follow }
  1516. parse_proc_directives(pd,pdflags);
  1517. { hint directives, these can be separated by semicolons here,
  1518. that needs to be handled here with a loop (PFV) }
  1519. while try_consume_hintdirective(pd.symoptions,pd.deprecatedmsg) do
  1520. Consume(_SEMICOLON);
  1521. { Set calling convention }
  1522. handle_calling_convention(pd);
  1523. { search for forward declarations }
  1524. if not proc_add_definition(pd) then
  1525. begin
  1526. { A method must be forward defined (in the object declaration) }
  1527. if assigned(pd.struct) and
  1528. (not assigned(old_current_structdef)) then
  1529. begin
  1530. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  1531. tprocsym(pd.procsym).write_parameter_lists(pd);
  1532. end
  1533. else
  1534. begin
  1535. { Give a better error if there is a forward def in the interface and only
  1536. a single implementation }
  1537. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  1538. if (not pd.forwarddef) and
  1539. (not pd.interfacedef) and
  1540. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  1541. firstpd.forwarddef and
  1542. firstpd.interfacedef and
  1543. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  1544. { don't give an error if it may be an overload }
  1545. not(m_fpc in current_settings.modeswitches) and
  1546. (not(po_overload in pd.procoptions) or
  1547. not(po_overload in firstpd.procoptions)) then
  1548. begin
  1549. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  1550. tprocsym(pd.procsym).write_parameter_lists(pd);
  1551. end;
  1552. end;
  1553. end;
  1554. { Set mangled name }
  1555. proc_set_mangledname(pd);
  1556. { compile procedure when a body is needed }
  1557. if (pd_body in pdflags) then
  1558. begin
  1559. read_proc_body(old_current_procinfo,pd);
  1560. end
  1561. else
  1562. begin
  1563. { Handle imports }
  1564. if (po_external in pd.procoptions) then
  1565. begin
  1566. { External declared in implementation, and there was already a
  1567. forward (or interface) declaration then we need to generate
  1568. a stub that calls the external routine }
  1569. if (not pd.forwarddef) and
  1570. (pd.hasforward)
  1571. { it is unclear to me what's the use of the following condition,
  1572. so commented out, see also issue #18371 (FK)
  1573. and
  1574. not(
  1575. assigned(pd.import_dll) and
  1576. (target_info.system in [system_i386_wdosx,
  1577. system_arm_wince,system_i386_wince])
  1578. ) } then
  1579. begin
  1580. s:=proc_get_importname(pd);
  1581. if s<>'' then
  1582. gen_external_stub(current_asmdata.asmlists[al_procedures],pd,s);
  1583. end;
  1584. { Import DLL specified? }
  1585. if assigned(pd.import_dll) then
  1586. begin
  1587. if assigned (pd.import_name) then
  1588. current_module.AddExternalImport(pd.import_dll^,
  1589. pd.import_name^,proc_get_importname(pd),
  1590. pd.import_nr,false,false)
  1591. else
  1592. current_module.AddExternalImport(pd.import_dll^,
  1593. proc_get_importname(pd),proc_get_importname(pd),
  1594. pd.import_nr,false,true);
  1595. end
  1596. else
  1597. begin
  1598. { add import name to external list for DLL scanning }
  1599. if tf_has_dllscanner in target_info.flags then
  1600. current_module.dllscannerinputlist.Add(proc_get_importname(pd),pd);
  1601. end;
  1602. end;
  1603. end;
  1604. { make sure that references to forward-declared functions are not }
  1605. { treated as references to external symbols, needed for darwin. }
  1606. { make sure we don't change the binding of real external symbols }
  1607. if not(po_external in pd.procoptions) then
  1608. begin
  1609. if (po_global in pd.procoptions) or
  1610. (cs_profile in current_settings.moduleswitches) then
  1611. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_GLOBAL,AT_FUNCTION)
  1612. else
  1613. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_LOCAL,AT_FUNCTION);
  1614. end;
  1615. current_structdef:=old_current_structdef;
  1616. current_genericdef:=old_current_genericdef;
  1617. current_specializedef:=old_current_specializedef;
  1618. current_procinfo:=old_current_procinfo;
  1619. end;
  1620. {****************************************************************************
  1621. DECLARATION PARSING
  1622. ****************************************************************************}
  1623. { search in symtablestack for not complete classes }
  1624. procedure check_forward_class(p:TObject;arg:pointer);
  1625. begin
  1626. if (tsym(p).typ=typesym) and
  1627. (ttypesym(p).typedef.typ=objectdef) and
  1628. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  1629. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  1630. end;
  1631. procedure read_declarations(islibrary : boolean);
  1632. var
  1633. is_classdef:boolean;
  1634. begin
  1635. is_classdef:=false;
  1636. repeat
  1637. if not assigned(current_procinfo) then
  1638. internalerror(200304251);
  1639. case token of
  1640. _LABEL:
  1641. label_dec;
  1642. _CONST:
  1643. const_dec;
  1644. _TYPE:
  1645. type_dec;
  1646. _VAR:
  1647. var_dec;
  1648. _THREADVAR:
  1649. threadvar_dec;
  1650. _CLASS:
  1651. begin
  1652. is_classdef:=false;
  1653. if try_to_consume(_CLASS) then
  1654. begin
  1655. { class modifier is only allowed for procedures, functions, }
  1656. { constructors, destructors, fields and properties }
  1657. if not(token in [_FUNCTION,_PROCEDURE,_PROPERTY,_VAR,_CONSTRUCTOR,_DESTRUCTOR,_OPERATOR]) and
  1658. not((token=_ID) and (idtoken=_OPERATOR)) then
  1659. Message(parser_e_procedure_or_function_expected);
  1660. if is_interface(current_structdef) then
  1661. Message(parser_e_no_static_method_in_interfaces)
  1662. else
  1663. { class methods are also allowed for Objective-C protocols }
  1664. is_classdef:=true;
  1665. end;
  1666. end;
  1667. _CONSTRUCTOR,
  1668. _DESTRUCTOR,
  1669. _FUNCTION,
  1670. _PROCEDURE,
  1671. _OPERATOR:
  1672. begin
  1673. read_proc(is_classdef);
  1674. is_classdef:=false;
  1675. end;
  1676. _EXPORTS:
  1677. begin
  1678. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  1679. begin
  1680. Message(parser_e_syntax_error);
  1681. consume_all_until(_SEMICOLON);
  1682. end
  1683. else if islibrary or
  1684. (target_info.system in systems_unit_program_exports) then
  1685. read_exports
  1686. else
  1687. begin
  1688. Message(parser_w_unsupported_feature);
  1689. consume(_BEGIN);
  1690. end;
  1691. end
  1692. else
  1693. begin
  1694. case idtoken of
  1695. _RESOURCESTRING:
  1696. begin
  1697. { m_class is needed, because the resourcestring
  1698. loading is in the ObjPas unit }
  1699. { if (m_class in current_settings.modeswitches) then}
  1700. resourcestring_dec
  1701. { else
  1702. break;}
  1703. end;
  1704. _OPERATOR:
  1705. begin
  1706. if is_classdef then
  1707. begin
  1708. read_proc(is_classdef);
  1709. is_classdef:=false;
  1710. end
  1711. else
  1712. break;
  1713. end;
  1714. _PROPERTY:
  1715. begin
  1716. if (m_fpc in current_settings.modeswitches) then
  1717. begin
  1718. property_dec(is_classdef);
  1719. is_classdef:=false;
  1720. end
  1721. else
  1722. break;
  1723. end;
  1724. else
  1725. break;
  1726. end;
  1727. end;
  1728. end;
  1729. until false;
  1730. { check for incomplete class definitions, this is only required
  1731. for fpc modes }
  1732. if (m_fpc in current_settings.modeswitches) then
  1733. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  1734. end;
  1735. procedure read_interface_declarations;
  1736. begin
  1737. repeat
  1738. case token of
  1739. _CONST :
  1740. const_dec;
  1741. _TYPE :
  1742. type_dec;
  1743. _VAR :
  1744. var_dec;
  1745. _THREADVAR :
  1746. threadvar_dec;
  1747. _FUNCTION,
  1748. _PROCEDURE,
  1749. _OPERATOR :
  1750. read_proc(false);
  1751. else
  1752. begin
  1753. case idtoken of
  1754. _RESOURCESTRING :
  1755. resourcestring_dec;
  1756. _PROPERTY:
  1757. begin
  1758. if (m_fpc in current_settings.modeswitches) then
  1759. property_dec(false)
  1760. else
  1761. break;
  1762. end;
  1763. else
  1764. break;
  1765. end;
  1766. end;
  1767. end;
  1768. until false;
  1769. { check for incomplete class definitions, this is only required
  1770. for fpc modes }
  1771. if (m_fpc in current_settings.modeswitches) then
  1772. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  1773. end;
  1774. {****************************************************************************
  1775. SPECIALIZATION BODY GENERATION
  1776. ****************************************************************************}
  1777. procedure specialize_objectdefs(p:TObject;arg:pointer);
  1778. var
  1779. i : longint;
  1780. hp : tdef;
  1781. oldcurrent_filepos : tfileposinfo;
  1782. oldsymtablestack : tsymtablestack;
  1783. oldextendeddefs : TFPHashObjectList;
  1784. pu : tused_unit;
  1785. hmodule : tmodule;
  1786. specobj : tabstractrecorddef;
  1787. begin
  1788. if not((tsym(p).typ=typesym) and
  1789. (ttypesym(p).typedef.typesym=tsym(p)) and
  1790. (ttypesym(p).typedef.typ in [objectdef,recorddef]) and
  1791. (df_specialization in ttypesym(p).typedef.defoptions)
  1792. ) then
  1793. exit;
  1794. { Setup symtablestack a definition time }
  1795. specobj:=tabstractrecorddef(ttypesym(p).typedef);
  1796. if not (is_class_or_object(specobj) or is_record(specobj)) then
  1797. exit;
  1798. oldsymtablestack:=symtablestack;
  1799. oldextendeddefs:=current_module.extendeddefs;
  1800. current_module.extendeddefs:=TFPHashObjectList.create(true);
  1801. symtablestack:=tdefawaresymtablestack.create;
  1802. if not assigned(specobj.genericdef) then
  1803. internalerror(200705151);
  1804. hmodule:=find_module_from_symtable(specobj.genericdef.owner);
  1805. if hmodule=nil then
  1806. internalerror(200705152);
  1807. pu:=tused_unit(hmodule.used_units.first);
  1808. while assigned(pu) do
  1809. begin
  1810. if not assigned(pu.u.globalsymtable) then
  1811. internalerror(200705153);
  1812. symtablestack.push(pu.u.globalsymtable);
  1813. pu:=tused_unit(pu.next);
  1814. end;
  1815. if assigned(hmodule.globalsymtable) then
  1816. symtablestack.push(hmodule.globalsymtable);
  1817. if assigned(hmodule.localsymtable) then
  1818. symtablestack.push(hmodule.localsymtable);
  1819. { procedure definitions for classes or objects }
  1820. for i:=0 to specobj.symtable.DefList.Count-1 do
  1821. begin
  1822. hp:=tdef(specobj.symtable.DefList[i]);
  1823. if hp.typ=procdef then
  1824. begin
  1825. if assigned(tprocdef(hp).genericdef) and
  1826. (tprocdef(hp).genericdef.typ=procdef) and
  1827. assigned(tprocdef(tprocdef(hp).genericdef).generictokenbuf) then
  1828. begin
  1829. oldcurrent_filepos:=current_filepos;
  1830. current_filepos:=tprocdef(tprocdef(hp).genericdef).fileinfo;
  1831. { use the index the module got from the current compilation process }
  1832. current_filepos.moduleindex:=hmodule.unit_index;
  1833. current_tokenpos:=current_filepos;
  1834. current_scanner.startreplaytokens(tprocdef(tprocdef(hp).genericdef).generictokenbuf);
  1835. read_proc_body(nil,tprocdef(hp));
  1836. current_filepos:=oldcurrent_filepos;
  1837. end
  1838. else
  1839. MessagePos1(tprocdef(hp).fileinfo,sym_e_forward_not_resolved,tprocdef(hp).fullprocname(false));
  1840. end;
  1841. end;
  1842. { Restore symtablestack }
  1843. current_module.extendeddefs.free;
  1844. current_module.extendeddefs:=oldextendeddefs;
  1845. symtablestack.free;
  1846. symtablestack:=oldsymtablestack;
  1847. end;
  1848. procedure generate_specialization_procs;
  1849. begin
  1850. if assigned(current_module.globalsymtable) then
  1851. current_module.globalsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1852. if assigned(current_module.localsymtable) then
  1853. current_module.localsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1854. end;
  1855. end.