psub.pas 86 KB

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