psub.pas 85 KB

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