psub.pas 86 KB

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