psub.pas 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174
  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. saved_hlcg: thlcgobj;
  841. begin
  842. if nestedpi.procdef.proctypeoption<>potype_exceptfilter then
  843. InternalError(201201141);
  844. { flush code generated this far }
  845. aktproccode.concatlist(current_asmdata.CurrAsmList);
  846. { save the codegen }
  847. saved_cg:=cg;
  848. saved_hlcg:=hlcg;
  849. cg:=nil;
  850. hlcg:=nil;
  851. nestedpi.generate_code;
  852. { prevents generating code the second time when processing nested procedures }
  853. nestedpi.resetprocdef;
  854. cg:=saved_cg;
  855. hlcg:=saved_hlcg;
  856. add_reg_instruction_hook:[email protected]_reg_instruction;
  857. end;
  858. procedure tcgprocinfo.generate_code;
  859. var
  860. old_current_procinfo : tprocinfo;
  861. oldmaxfpuregisters : longint;
  862. oldfilepos : tfileposinfo;
  863. old_current_structdef : tabstractrecorddef;
  864. templist : TAsmList;
  865. headertai : tai;
  866. i : integer;
  867. varsym : tabstractnormalvarsym;
  868. {RedoDFA : boolean;}
  869. begin
  870. { the initialization procedure can be empty, then we
  871. don't need to generate anything. When it was an empty
  872. procedure there would be at least a blocknode }
  873. if not assigned(code) then
  874. exit;
  875. { We need valid code }
  876. if Errorcount<>0 then
  877. exit;
  878. { No code can be generated for generic template }
  879. if (df_generic in procdef.defoptions) then
  880. internalerror(200511152);
  881. { For regular procedures the RA and Tempgen shall not be available yet,
  882. but exception filters reuse Tempgen of parent }
  883. if assigned(tg)<>(procdef.proctypeoption=potype_exceptfilter) then
  884. internalerror(200309201);
  885. old_current_procinfo:=current_procinfo;
  886. oldfilepos:=current_filepos;
  887. old_current_structdef:=current_structdef;
  888. oldmaxfpuregisters:=current_settings.maxfpuregisters;
  889. current_procinfo:=self;
  890. current_filepos:=entrypos;
  891. current_structdef:=procdef.struct;
  892. templist:=TAsmList.create;
  893. { add parast/localst to symtablestack }
  894. add_to_symtablestack;
  895. { clear register count }
  896. procdef.localst.SymList.ForEachCall(@clearrefs,nil);
  897. procdef.parast.SymList.ForEachCall(@clearrefs,nil);
  898. { there's always a call to FPC_INITIALIZEUNITS/FPC_DO_EXIT in the main program }
  899. if (procdef.localst.symtablelevel=main_program_level) and
  900. (not current_module.is_unit) then
  901. include(flags,pi_do_call);
  902. { set implicit_finally flag when there are locals/paras to be finalized }
  903. procdef.parast.SymList.ForEachCall(@check_finalize_paras,nil);
  904. procdef.localst.SymList.ForEachCall(@check_finalize_locals,nil);
  905. {$if defined(x86) or defined(arm)}
  906. { set implicit_finally flag for if procedure is safecall }
  907. if (tf_safecall_exceptions in target_info.flags) and
  908. (procdef.proccalloption=pocall_safecall) then
  909. include(flags, pi_needs_implicit_finally);
  910. {$endif}
  911. { firstpass everything }
  912. flowcontrol:=[];
  913. do_firstpass(code);
  914. {$ifdef i386}
  915. procdef.fpu_used:=node_resources_fpu(code);
  916. if procdef.fpu_used>0 then
  917. include(flags,pi_uses_fpu);
  918. {$endif i386}
  919. { Print the node to tree.log }
  920. if paraprintnodetree=1 then
  921. printproc( 'after the firstpass');
  922. { do this before adding the entry code else the tail recursion recognition won't work,
  923. if this causes troubles, it must be if'ed
  924. }
  925. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  926. (pi_is_recursive in flags) then
  927. do_opttail(code,procdef);
  928. if (cs_opt_nodedfa in current_settings.optimizerswitches) and
  929. { creating dfa is not always possible }
  930. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler,
  931. pi_needs_implicit_finally,pi_has_implicit_finally])=[]) then
  932. begin
  933. dfabuilder:=TDFABuilder.Create;
  934. dfabuilder.createdfainfo(code);
  935. { when life info is available, we can give more sophisticated warning about unintialized
  936. variables }
  937. { iterate through life info of the first node }
  938. for i:=0 to dfabuilder.nodemap.count-1 do
  939. begin
  940. if DFASetIn(code.optinfo^.life,i) then
  941. case tnode(dfabuilder.nodemap[i]).nodetype of
  942. loadn:
  943. begin
  944. varsym:=tabstractnormalvarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry);
  945. { Give warning/note for living locals }
  946. if assigned(varsym.owner) and
  947. not(vo_is_external in varsym.varoptions) then
  948. begin
  949. if (vo_is_funcret in varsym.varoptions) then
  950. CGMessage(sym_w_function_result_uninitialized)
  951. else
  952. begin
  953. if (varsym.owner=procdef.localst) and not (vo_is_typed_const in varsym.varoptions) then
  954. CGMessage1(sym_w_uninitialized_local_variable,varsym.realname);
  955. end;
  956. end;
  957. end;
  958. end;
  959. end;
  960. include(flags,pi_dfaavailable);
  961. end;
  962. if (cs_opt_loopstrength in current_settings.optimizerswitches)
  963. { our induction variable strength reduction doesn't like
  964. for loops with more than one entry }
  965. and not(pi_has_label in flags) then
  966. begin
  967. {RedoDFA:=}OptimizeInductionVariables(code);
  968. end;
  969. if cs_opt_nodecse in current_settings.optimizerswitches then
  970. do_optcse(code);
  971. { add implicit entry and exit code }
  972. add_entry_exit_code;
  973. { only do secondpass if there are no errors }
  974. if (ErrorCount=0) then
  975. begin
  976. create_hlcodegen;
  977. if (procdef.proctypeoption<>potype_exceptfilter) then
  978. setup_tempgen;
  979. { Create register allocator, must come after framepointer is known }
  980. hlcg.init_register_allocators;
  981. generate_parameter_info;
  982. { allocate got register if needed }
  983. allocate_got_register(aktproccode);
  984. { Allocate space in temp/registers for parast and localst }
  985. current_filepos:=entrypos;
  986. gen_alloc_symtable(aktproccode,procdef.parast);
  987. gen_alloc_symtable(aktproccode,procdef.localst);
  988. { Store temp offset for information about 'real' temps }
  989. tempstart:=tg.lasttemp;
  990. { Generate code to load register parameters in temps and insert local
  991. copies for values parameters. This must be done before the code for the
  992. body is generated because the localloc is updated.
  993. Note: The generated code will be inserted after the code generation of
  994. the body is finished, because only then the position is known }
  995. {$ifdef oldregvars}
  996. assign_regvars(code);
  997. {$endif oldreg}
  998. current_filepos:=entrypos;
  999. hlcg.gen_load_para_value(templist);
  1000. { caller paraloc info is also necessary in the stackframe_entry
  1001. code of the ppc (and possibly other processors) }
  1002. procdef.init_paraloc_info(callerside);
  1003. { generate code for the node tree }
  1004. do_secondpass(code);
  1005. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1006. { The position of the loadpara_asmnode is now known }
  1007. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  1008. { first generate entry and initialize code with the correct
  1009. position and switches }
  1010. current_filepos:=entrypos;
  1011. current_settings.localswitches:=entryswitches;
  1012. cg.set_regalloc_live_range_direction(rad_backwards);
  1013. hlcg.gen_entry_code(templist);
  1014. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  1015. hlcg.gen_initialize_code(templist);
  1016. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  1017. { now generate finalize and exit code with the correct position
  1018. and switches }
  1019. current_filepos:=exitpos;
  1020. current_settings.localswitches:=exitswitches;
  1021. cg.set_regalloc_live_range_direction(rad_forward);
  1022. if assigned(finalize_procinfo) then
  1023. generate_exceptfilter(tcgprocinfo(finalize_procinfo))
  1024. else
  1025. begin
  1026. hlcg.gen_finalize_code(templist);
  1027. { the finalcode must be concated if there was no position available,
  1028. using insertlistafter will result in an insert at the start
  1029. when currentai=nil }
  1030. if assigned(final_asmnode) and assigned(final_asmnode.currenttai) then
  1031. aktproccode.insertlistafter(final_asmnode.currenttai,templist)
  1032. else
  1033. aktproccode.concatlist(templist);
  1034. end;
  1035. { insert exit label at the correct position }
  1036. hlcg.a_label(templist,CurrExitLabel);
  1037. if assigned(exitlabel_asmnode.currenttai) then
  1038. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  1039. else
  1040. aktproccode.concatlist(templist);
  1041. { exit code }
  1042. hlcg.gen_exit_code(templist);
  1043. aktproccode.concatlist(templist);
  1044. {$ifdef OLDREGVARS}
  1045. { note: this must be done only after as much code as possible has }
  1046. { been generated. The result is that when you ungetregister() a }
  1047. { regvar, it will actually free the regvar (and alse free the }
  1048. { the regvars at the same time). Doing this too early will }
  1049. { confuse the register allocator, as the regvars will still be }
  1050. { used. It should be done before loading the result regs (so }
  1051. { they don't conflict with the regvars) and before }
  1052. { gen_entry_code (that one has to be able to allocate the }
  1053. { regvars again) (JM) }
  1054. free_regvars(aktproccode);
  1055. {$endif OLDREGVARS}
  1056. { generate symbol and save end of header position }
  1057. current_filepos:=entrypos;
  1058. hlcg.gen_proc_symbol(templist);
  1059. headertai:=tai(templist.last);
  1060. { insert symbol }
  1061. aktproccode.insertlist(templist);
  1062. { Free space in temp/registers for parast and localst, must be
  1063. done after gen_entry_code }
  1064. current_filepos:=exitpos;
  1065. { make sure the got/pic register doesn't get freed in the }
  1066. { middle of a loop }
  1067. if (cs_create_pic in current_settings.moduleswitches) and
  1068. (pi_needs_got in flags) and
  1069. (got<>NR_NO) then
  1070. cg.a_reg_sync(aktproccode,got);
  1071. gen_free_symtable(aktproccode,procdef.localst);
  1072. gen_free_symtable(aktproccode,procdef.parast);
  1073. { add code that will load the return value, this is not done
  1074. for assembler routines when they didn't reference the result
  1075. variable }
  1076. hlcg.gen_load_return_value(templist);
  1077. aktproccode.concatlist(templist);
  1078. { Already reserve all registers for stack checking code and
  1079. generate the call to the helper function }
  1080. if not(tf_no_generic_stackcheck in target_info.flags) and
  1081. (cs_check_stack in entryswitches) and
  1082. not(po_assembler in procdef.procoptions) and
  1083. (procdef.proctypeoption<>potype_proginit) then
  1084. begin
  1085. current_filepos:=entrypos;
  1086. gen_stack_check_call(templist);
  1087. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  1088. end;
  1089. { this code (got loading) comes before everything which has }
  1090. { already been generated, so reset the info about already }
  1091. { backwards extended registers (so their live range can be }
  1092. { extended backwards even further if needed) }
  1093. { This code must be }
  1094. { a) generated after do_secondpass has been called }
  1095. { (because pi_needs_got may be set there) }
  1096. { b) generated before register allocation, because the }
  1097. { got/pic register can be a virtual one }
  1098. { c) inserted before the entry code, because the entry }
  1099. { code may need global symbols such as init rtti }
  1100. { d) inserted after the stackframe allocation, because }
  1101. { this register may have to be spilled }
  1102. cg.set_regalloc_live_range_direction(rad_backwards_reinit);
  1103. current_filepos:=entrypos;
  1104. { load got if necessary }
  1105. cg.g_maybe_got_init(templist);
  1106. aktproccode.insertlistafter(headertai,templist);
  1107. { re-enable if more code at the end is ever generated here
  1108. cg.set_regalloc_live_range_direction(rad_forward);
  1109. }
  1110. {$ifndef NoOpt}
  1111. {$ifndef i386}
  1112. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1113. { do not optimize pure assembler procedures }
  1114. not(pi_is_assembler in flags) then
  1115. preregallocschedule(aktproccode);
  1116. {$endif i386}
  1117. {$endif NoOpt}
  1118. { The procedure body is finished, we can now
  1119. allocate the registers }
  1120. cg.do_register_allocation(aktproccode,headertai);
  1121. { translate imag. register to their real counter parts
  1122. this is necessary for debuginfo and verbose assembler output
  1123. when SSA will be implented, this will be more complicated because we've to
  1124. maintain location lists }
  1125. procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  1126. procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  1127. if (cs_create_pic in current_settings.moduleswitches) and
  1128. (pi_needs_got in flags) and
  1129. not(cs_no_regalloc in current_settings.globalswitches) and
  1130. (got<>NR_NO) then
  1131. cg.translate_register(got);
  1132. { Add save and restore of used registers }
  1133. current_filepos:=entrypos;
  1134. gen_save_used_regs(templist);
  1135. { Remember the last instruction of register saving block
  1136. (may be =nil for e.g. assembler procedures) }
  1137. endprologue_ai:=templist.last;
  1138. aktproccode.insertlistafter(headertai,templist);
  1139. current_filepos:=exitpos;
  1140. gen_restore_used_regs(aktproccode);
  1141. { We know the size of the stack, now we can generate the
  1142. parameter that is passed to the stack checking code }
  1143. if not(tf_no_generic_stackcheck in target_info.flags) and
  1144. (cs_check_stack in entryswitches) and
  1145. not(po_assembler in procdef.procoptions) and
  1146. (procdef.proctypeoption<>potype_proginit) then
  1147. begin
  1148. current_filepos:=entrypos;
  1149. gen_stack_check_size_para(templist);
  1150. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  1151. end;
  1152. { Add entry code (stack allocation) after header }
  1153. current_filepos:=entrypos;
  1154. gen_proc_entry_code(templist);
  1155. aktproccode.insertlistafter(headertai,templist);
  1156. {$if defined(x86) or defined(arm)}
  1157. { Set return value of safecall procedure if implicit try/finally blocks are disabled }
  1158. if not (cs_implicit_exceptions in current_settings.moduleswitches) and
  1159. (tf_safecall_exceptions in target_info.flags) and
  1160. (procdef.proccalloption=pocall_safecall) then
  1161. cg.a_load_const_reg(aktproccode,OS_ADDR,0,NR_FUNCTION_RETURN_REG);
  1162. {$endif}
  1163. { Add exit code at the end }
  1164. current_filepos:=exitpos;
  1165. gen_proc_exit_code(templist);
  1166. aktproccode.concatlist(templist);
  1167. { check if the implicit finally has been generated. The flag
  1168. should already be set in pass1 }
  1169. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  1170. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  1171. (pi_needs_implicit_finally in flags) and
  1172. not(po_assembler in procdef.procoptions) and
  1173. not(pi_has_implicit_finally in flags) and
  1174. not(target_info.system in systems_garbage_collected_managed_types) then
  1175. internalerror(200405231);
  1176. {$ifndef NoOpt}
  1177. if not(cs_no_regalloc in current_settings.globalswitches) then
  1178. begin
  1179. if (cs_opt_level1 in current_settings.optimizerswitches) and
  1180. { do not optimize pure assembler procedures }
  1181. not(pi_is_assembler in flags) then
  1182. optimize(aktproccode);
  1183. {$ifndef i386}
  1184. { schedule after assembler optimization, it could have brought up
  1185. new schedule possibilities }
  1186. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1187. { do not optimize pure assembler procedures }
  1188. not(pi_is_assembler in flags) then
  1189. preregallocschedule(aktproccode);
  1190. {$endif i386}
  1191. end;
  1192. {$endif NoOpt}
  1193. {$ifdef ARM}
  1194. { because of the limited constant size of the arm, all data access is done pc relative }
  1195. finalizearmcode(aktproccode,aktlocaldata);
  1196. {$endif ARM}
  1197. {$ifdef AVR}
  1198. { because of the limited branch distance of cond. branches, they must be replaced
  1199. somtimes by normal jmps and an inverse branch }
  1200. finalizeavrcode(aktproccode);
  1201. {$endif AVR}
  1202. { Add end symbol and debug info }
  1203. { this must be done after the pcrelativedata is appended else the distance calculation of
  1204. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  1205. so it should be inserted before the end symbol (FK)
  1206. }
  1207. current_filepos:=exitpos;
  1208. hlcg.gen_proc_symbol_end(templist);
  1209. aktproccode.concatlist(templist);
  1210. {$if defined(POWERPC) or defined(POWERPC64)}
  1211. fixup_jmps(aktproccode);
  1212. {$endif}
  1213. { insert line debuginfo }
  1214. if (cs_debuginfo in current_settings.moduleswitches) or
  1215. (cs_use_lineinfo in current_settings.globalswitches) then
  1216. current_debuginfo.insertlineinfo(aktproccode);
  1217. hlcg.record_generated_code_for_procdef(current_procinfo.procdef,aktproccode,aktlocaldata);
  1218. { only now we can remove the temps }
  1219. if (procdef.proctypeoption<>potype_exceptfilter) then
  1220. begin
  1221. tg.resettempgen;
  1222. tg.free;
  1223. tg:=nil;
  1224. end;
  1225. { stop tempgen and ra }
  1226. hlcg.done_register_allocators;
  1227. destroy_hlcodegen;
  1228. end;
  1229. dfabuilder.free;
  1230. { restore symtablestack }
  1231. remove_from_symtablestack;
  1232. { restore }
  1233. templist.free;
  1234. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  1235. current_filepos:=oldfilepos;
  1236. current_structdef:=old_current_structdef;
  1237. current_procinfo:=old_current_procinfo;
  1238. end;
  1239. procedure tcgprocinfo.add_to_symtablestack;
  1240. begin
  1241. { insert symtables for the class, but only if it is no nested function }
  1242. if assigned(procdef.struct) and
  1243. not(assigned(parent) and
  1244. assigned(parent.procdef) and
  1245. assigned(parent.procdef.struct)) then
  1246. push_nested_hierarchy(procdef.struct);
  1247. { insert parasymtable in symtablestack when parsing
  1248. a function }
  1249. if procdef.parast.symtablelevel>=normal_function_level then
  1250. symtablestack.push(procdef.parast);
  1251. { insert localsymtable, except for the main procedure
  1252. (in that case the localst is the unit's static symtable,
  1253. which is already on the stack) }
  1254. if procdef.localst.symtablelevel>=normal_function_level then
  1255. symtablestack.push(procdef.localst);
  1256. end;
  1257. procedure tcgprocinfo.remove_from_symtablestack;
  1258. begin
  1259. { remove localsymtable }
  1260. if procdef.localst.symtablelevel>=normal_function_level then
  1261. symtablestack.pop(procdef.localst);
  1262. { remove parasymtable }
  1263. if procdef.parast.symtablelevel>=normal_function_level then
  1264. symtablestack.pop(procdef.parast);
  1265. { remove symtables for the class, but only if it is no nested function }
  1266. if assigned(procdef.struct) and
  1267. not(assigned(parent) and
  1268. assigned(parent.procdef) and
  1269. assigned(parent.procdef.struct)) then
  1270. pop_nested_hierarchy(procdef.struct);
  1271. end;
  1272. procedure tcgprocinfo.resetprocdef;
  1273. begin
  1274. { remove code tree, if not inline procedure }
  1275. if assigned(code) then
  1276. begin
  1277. { the inline procedure has already got a copy of the tree
  1278. stored in procdef.inlininginfo }
  1279. code.free;
  1280. code:=nil;
  1281. end;
  1282. end;
  1283. function checknodeinlining(procdef: tprocdef): boolean;
  1284. var
  1285. i : integer;
  1286. currpara : tparavarsym;
  1287. begin
  1288. result := false;
  1289. if (pi_has_assembler_block in current_procinfo.flags) then
  1290. begin
  1291. Message1(parser_h_not_supported_for_inline,'assembler');
  1292. Message(parser_h_inlining_disabled);
  1293. exit;
  1294. end;
  1295. for i:=0 to procdef.paras.count-1 do
  1296. begin
  1297. currpara:=tparavarsym(procdef.paras[i]);
  1298. case currpara.vardef.typ of
  1299. formaldef :
  1300. begin
  1301. if (currpara.varspez in [vs_out,vs_var,vs_const,vs_constref]) then
  1302. begin
  1303. Message1(parser_h_not_supported_for_inline,'formal parameter');
  1304. Message(parser_h_inlining_disabled);
  1305. exit;
  1306. end;
  1307. end;
  1308. arraydef :
  1309. begin
  1310. if is_array_of_const(currpara.vardef) or
  1311. is_variant_array(currpara.vardef) then
  1312. begin
  1313. Message1(parser_h_not_supported_for_inline,'array of const');
  1314. Message(parser_h_inlining_disabled);
  1315. exit;
  1316. end;
  1317. { open arrays might need re-basing of the index, i.e. if you pass
  1318. an array[1..10] as open array, you have to add 1 to all index operations
  1319. if you directly inline it }
  1320. if is_open_array(currpara.vardef) then
  1321. begin
  1322. Message1(parser_h_not_supported_for_inline,'open array');
  1323. Message(parser_h_inlining_disabled);
  1324. exit;
  1325. end;
  1326. end;
  1327. end;
  1328. end;
  1329. result:=true;
  1330. end;
  1331. procedure tcgprocinfo.parse_body;
  1332. var
  1333. old_current_procinfo : tprocinfo;
  1334. old_block_type : tblock_type;
  1335. st : TSymtable;
  1336. old_current_structdef: tabstractrecorddef;
  1337. old_current_genericdef,
  1338. old_current_specializedef: tstoreddef;
  1339. old_parse_generic: boolean;
  1340. begin
  1341. old_current_procinfo:=current_procinfo;
  1342. old_block_type:=block_type;
  1343. old_current_structdef:=current_structdef;
  1344. old_current_genericdef:=current_genericdef;
  1345. old_current_specializedef:=current_specializedef;
  1346. old_parse_generic:=parse_generic;
  1347. current_procinfo:=self;
  1348. current_structdef:=procdef.struct;
  1349. if assigned(current_structdef) and (df_generic in current_structdef.defoptions) then
  1350. begin
  1351. current_genericdef:=current_structdef;
  1352. parse_generic:=true;
  1353. end;
  1354. if assigned(current_structdef) and (df_specialization in current_structdef.defoptions) then
  1355. current_specializedef:=current_structdef;
  1356. { calculate the lexical level }
  1357. if procdef.parast.symtablelevel>maxnesting then
  1358. Message(parser_e_too_much_lexlevel);
  1359. block_type:=bt_body;
  1360. {$ifdef state_tracking}
  1361. { aktstate:=Tstate_storage.create;}
  1362. {$endif state_tracking}
  1363. { allocate the symbol for this procedure }
  1364. alloc_proc_symbol(procdef);
  1365. { add parast/localst to symtablestack }
  1366. add_to_symtablestack;
  1367. { save entry info }
  1368. entrypos:=current_filepos;
  1369. entryswitches:=current_settings.localswitches;
  1370. if (df_generic in procdef.defoptions) then
  1371. begin
  1372. { start token recorder for generic template }
  1373. procdef.initgeneric;
  1374. current_scanner.startrecordtokens(procdef.generictokenbuf);
  1375. end;
  1376. { parse the code ... }
  1377. code:=block(current_module.islibrary);
  1378. if (df_generic in procdef.defoptions) then
  1379. begin
  1380. { stop token recorder for generic template }
  1381. current_scanner.stoprecordtokens;
  1382. { Give an error for accesses in the static symtable that aren't visible
  1383. outside the current unit }
  1384. st:=procdef.owner;
  1385. while (st.symtabletype=ObjectSymtable) do
  1386. st:=st.defowner.owner;
  1387. if (pi_uses_static_symtable in flags) and
  1388. (st.symtabletype<>staticsymtable) then
  1389. Comment(V_Error,'Global Generic template references static symtable');
  1390. end;
  1391. { save exit info }
  1392. exitswitches:=current_settings.localswitches;
  1393. exitpos:=last_endtoken_filepos;
  1394. { the procedure is now defined }
  1395. procdef.forwarddef:=false;
  1396. if assigned(code) then
  1397. begin
  1398. { get a better entry point }
  1399. entrypos:=code.fileinfo;
  1400. { Finish type checking pass }
  1401. do_typecheckpass(code);
  1402. if assigned(procdef.parentfpinitblock) then
  1403. begin
  1404. tblocknode(code).left:=cstatementnode.create(procdef.parentfpinitblock,tblocknode(code).left);
  1405. do_typecheckpass(tblocknode(code).left);
  1406. procdef.parentfpinitblock:=nil;
  1407. end;
  1408. end;
  1409. { Check for unused labels, forwards, symbols for procedures. Static
  1410. symtable is checked in pmodules.
  1411. The check must be done after the typecheckpass }
  1412. if (Errorcount=0) and
  1413. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  1414. begin
  1415. { check if forwards are resolved }
  1416. tstoredsymtable(procdef.localst).check_forwards;
  1417. { check if all labels are used }
  1418. tstoredsymtable(procdef.localst).checklabels;
  1419. { check for unused symbols, but only if there is no asm block }
  1420. if not(pi_has_assembler_block in flags) then
  1421. begin
  1422. tstoredsymtable(procdef.localst).allsymbolsused;
  1423. tstoredsymtable(procdef.parast).allsymbolsused;
  1424. end;
  1425. end;
  1426. if (po_inline in procdef.procoptions) then
  1427. begin
  1428. { Can we inline this procedure? }
  1429. if checknodeinlining(procdef) then
  1430. begin
  1431. new(procdef.inlininginfo);
  1432. include(procdef.procoptions,po_has_inlininginfo);
  1433. procdef.inlininginfo^.code:=code.getcopy;
  1434. procdef.inlininginfo^.flags:=flags;
  1435. { The blocknode needs to set an exit label }
  1436. if procdef.inlininginfo^.code.nodetype=blockn then
  1437. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1438. end;
  1439. end;
  1440. { Print the node to tree.log }
  1441. if paraprintnodetree=1 then
  1442. printproc( 'after parsing');
  1443. { ... remove symbol tables }
  1444. remove_from_symtablestack;
  1445. {$ifdef state_tracking}
  1446. { aktstate.destroy;}
  1447. {$endif state_tracking}
  1448. current_structdef:=old_current_structdef;
  1449. current_genericdef:=old_current_genericdef;
  1450. current_specializedef:=old_current_specializedef;
  1451. current_procinfo:=old_current_procinfo;
  1452. parse_generic:=old_parse_generic;
  1453. { Restore old state }
  1454. block_type:=old_block_type;
  1455. end;
  1456. {****************************************************************************
  1457. PROCEDURE/FUNCTION PARSING
  1458. ****************************************************************************}
  1459. procedure check_init_paras(p:TObject;arg:pointer);
  1460. begin
  1461. if tsym(p).typ<>paravarsym then
  1462. exit;
  1463. with tparavarsym(p) do
  1464. if is_managed_type(vardef) and
  1465. (varspez in [vs_value,vs_out]) then
  1466. include(current_procinfo.flags,pi_do_call);
  1467. end;
  1468. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  1469. {
  1470. Parses the procedure directives, then parses the procedure body, then
  1471. generates the code for it
  1472. }
  1473. var
  1474. oldfailtokenmode : tmodeswitch;
  1475. isnestedproc : boolean;
  1476. begin
  1477. Message1(parser_d_procedure_start,pd.fullprocname(false));
  1478. { create a new procedure }
  1479. current_procinfo:=cprocinfo.create(old_current_procinfo);
  1480. current_module.procinfo:=current_procinfo;
  1481. current_procinfo.procdef:=pd;
  1482. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  1483. { Insert mangledname }
  1484. pd.aliasnames.insert(pd.mangledname);
  1485. { Handle Export of this procedure }
  1486. if (po_exports in pd.procoptions) and
  1487. (target_info.system in [system_i386_os2,system_i386_emx]) then
  1488. begin
  1489. pd.aliasnames.insert(pd.procsym.realname);
  1490. if cs_link_deffile in current_settings.globalswitches then
  1491. deffile.AddExport(pd.mangledname);
  1492. end;
  1493. { Insert result variables in the localst }
  1494. insert_funcret_local(pd);
  1495. { check if there are para's which require initing -> set }
  1496. { pi_do_call (if not yet set) }
  1497. if not(pi_do_call in current_procinfo.flags) then
  1498. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  1499. { set _FAIL as keyword if constructor }
  1500. if (pd.proctypeoption=potype_constructor) then
  1501. begin
  1502. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  1503. tokeninfo^[_FAIL].keyword:=m_all;
  1504. end;
  1505. tcgprocinfo(current_procinfo).parse_body;
  1506. { We can't support inlining for procedures that have nested
  1507. procedures because the nested procedures use a fixed offset
  1508. for accessing locals in the parent procedure (PFV) }
  1509. if current_procinfo.has_nestedprocs then
  1510. begin
  1511. if (df_generic in current_procinfo.procdef.defoptions) then
  1512. Comment(V_Error,'Generic methods cannot have nested procedures')
  1513. else
  1514. if (po_inline in current_procinfo.procdef.procoptions) then
  1515. begin
  1516. Message1(parser_h_not_supported_for_inline,'nested procedures');
  1517. Message(parser_h_inlining_disabled);
  1518. exclude(current_procinfo.procdef.procoptions,po_inline);
  1519. end;
  1520. end;
  1521. { When it's a nested procedure then defer the code generation,
  1522. when back at normal function level then generate the code
  1523. for all defered nested procedures and the current procedure }
  1524. if not isnestedproc then
  1525. begin
  1526. if not(df_generic in current_procinfo.procdef.defoptions) then
  1527. tcgprocinfo(current_procinfo).generate_code_tree;
  1528. end;
  1529. { reset _FAIL as _SELF normal }
  1530. if (pd.proctypeoption=potype_constructor) then
  1531. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  1532. { release procinfo }
  1533. if tprocinfo(current_module.procinfo)<>current_procinfo then
  1534. internalerror(200304274);
  1535. current_module.procinfo:=current_procinfo.parent;
  1536. { For specialization we didn't record the last semicolon. Moving this parsing
  1537. into the parse_body routine is not done because of having better file position
  1538. information available }
  1539. if not(df_specialization in current_procinfo.procdef.defoptions) then
  1540. consume(_SEMICOLON);
  1541. if not isnestedproc then
  1542. { current_procinfo is checked for nil later on }
  1543. freeandnil(current_procinfo);
  1544. end;
  1545. procedure read_proc(isclassmethod:boolean; usefwpd: tprocdef);
  1546. {
  1547. Parses the procedure directives, then parses the procedure body, then
  1548. generates the code for it
  1549. }
  1550. var
  1551. old_current_procinfo : tprocinfo;
  1552. old_current_structdef: tabstractrecorddef;
  1553. old_current_genericdef,
  1554. old_current_specializedef: tstoreddef;
  1555. pdflags : tpdflags;
  1556. pd,firstpd : tprocdef;
  1557. s : string;
  1558. begin
  1559. { save old state }
  1560. old_current_procinfo:=current_procinfo;
  1561. old_current_structdef:=current_structdef;
  1562. old_current_genericdef:=current_genericdef;
  1563. old_current_specializedef:=current_specializedef;
  1564. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  1565. to another procdef }
  1566. current_procinfo:=nil;
  1567. current_structdef:=nil;
  1568. current_genericdef:=nil;
  1569. current_specializedef:=nil;
  1570. if not assigned(usefwpd) then
  1571. { parse procedure declaration }
  1572. pd:=parse_proc_dec(isclassmethod,old_current_structdef)
  1573. else
  1574. pd:=usefwpd;
  1575. { set the default function options }
  1576. if parse_only then
  1577. begin
  1578. pd.forwarddef:=true;
  1579. { set also the interface flag, for better error message when the
  1580. implementation doesn't much this header }
  1581. pd.interfacedef:=true;
  1582. include(pd.procoptions,po_global);
  1583. pdflags:=[pd_interface];
  1584. end
  1585. else
  1586. begin
  1587. pdflags:=[pd_body];
  1588. if (not current_module.in_interface) then
  1589. include(pdflags,pd_implemen);
  1590. if (not current_module.is_unit) or
  1591. create_smartlink or
  1592. {
  1593. taking addresses of static procedures goes wrong
  1594. if they aren't global when pic is used (FK)
  1595. }
  1596. (cs_create_pic in current_settings.moduleswitches) then
  1597. include(pd.procoptions,po_global);
  1598. pd.forwarddef:=false;
  1599. end;
  1600. if not assigned(usefwpd) then
  1601. begin
  1602. { parse the directives that may follow }
  1603. parse_proc_directives(pd,pdflags);
  1604. { hint directives, these can be separated by semicolons here,
  1605. that needs to be handled here with a loop (PFV) }
  1606. while try_consume_hintdirective(pd.symoptions,pd.deprecatedmsg) do
  1607. Consume(_SEMICOLON);
  1608. { Set calling convention }
  1609. handle_calling_convention(pd);
  1610. end;
  1611. { search for forward declarations }
  1612. if not proc_add_definition(pd) then
  1613. begin
  1614. { A method must be forward defined (in the object declaration) }
  1615. if assigned(pd.struct) and
  1616. (not assigned(old_current_structdef)) then
  1617. begin
  1618. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  1619. tprocsym(pd.procsym).write_parameter_lists(pd);
  1620. end
  1621. else
  1622. begin
  1623. { Give a better error if there is a forward def in the interface and only
  1624. a single implementation }
  1625. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  1626. if (not pd.forwarddef) and
  1627. (not pd.interfacedef) and
  1628. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  1629. firstpd.forwarddef and
  1630. firstpd.interfacedef and
  1631. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  1632. { don't give an error if it may be an overload }
  1633. not(m_fpc in current_settings.modeswitches) and
  1634. (not(po_overload in pd.procoptions) or
  1635. not(po_overload in firstpd.procoptions)) then
  1636. begin
  1637. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  1638. tprocsym(pd.procsym).write_parameter_lists(pd);
  1639. end;
  1640. end;
  1641. end;
  1642. { Set mangled name }
  1643. proc_set_mangledname(pd);
  1644. { compile procedure when a body is needed }
  1645. if (pd_body in pdflags) then
  1646. begin
  1647. read_proc_body(old_current_procinfo,pd);
  1648. end
  1649. else
  1650. begin
  1651. { Handle imports }
  1652. if (po_external in pd.procoptions) then
  1653. begin
  1654. { External declared in implementation, and there was already a
  1655. forward (or interface) declaration then we need to generate
  1656. a stub that calls the external routine }
  1657. if (not pd.forwarddef) and
  1658. (pd.hasforward)
  1659. { it is unclear to me what's the use of the following condition,
  1660. so commented out, see also issue #18371 (FK)
  1661. and
  1662. not(
  1663. assigned(pd.import_dll) and
  1664. (target_info.system in [system_i386_wdosx,
  1665. system_arm_wince,system_i386_wince])
  1666. ) } then
  1667. begin
  1668. s:=proc_get_importname(pd);
  1669. if s<>'' then
  1670. gen_external_stub(current_asmdata.asmlists[al_procedures],pd,s);
  1671. end;
  1672. { Import DLL specified? }
  1673. if assigned(pd.import_dll) then
  1674. begin
  1675. if assigned (pd.import_name) then
  1676. current_module.AddExternalImport(pd.import_dll^,
  1677. pd.import_name^,proc_get_importname(pd),
  1678. pd.import_nr,false,false)
  1679. else
  1680. current_module.AddExternalImport(pd.import_dll^,
  1681. proc_get_importname(pd),proc_get_importname(pd),
  1682. pd.import_nr,false,true);
  1683. end
  1684. else
  1685. begin
  1686. { add import name to external list for DLL scanning }
  1687. if tf_has_dllscanner in target_info.flags then
  1688. current_module.dllscannerinputlist.Add(proc_get_importname(pd),pd);
  1689. end;
  1690. end;
  1691. end;
  1692. { make sure that references to forward-declared functions are not }
  1693. { treated as references to external symbols, needed for darwin. }
  1694. { make sure we don't change the binding of real external symbols }
  1695. if not(po_external in pd.procoptions) then
  1696. begin
  1697. if (po_global in pd.procoptions) or
  1698. (cs_profile in current_settings.moduleswitches) then
  1699. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_GLOBAL,AT_FUNCTION)
  1700. else
  1701. current_asmdata.DefineAsmSymbol(pd.mangledname,AB_LOCAL,AT_FUNCTION);
  1702. end;
  1703. current_structdef:=old_current_structdef;
  1704. current_genericdef:=old_current_genericdef;
  1705. current_specializedef:=old_current_specializedef;
  1706. current_procinfo:=old_current_procinfo;
  1707. end;
  1708. {****************************************************************************
  1709. DECLARATION PARSING
  1710. ****************************************************************************}
  1711. { search in symtablestack for not complete classes }
  1712. procedure check_forward_class(p:TObject;arg:pointer);
  1713. begin
  1714. if (tsym(p).typ=typesym) and
  1715. (ttypesym(p).typedef.typ=objectdef) and
  1716. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  1717. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  1718. end;
  1719. procedure read_declarations(islibrary : boolean);
  1720. var
  1721. is_classdef:boolean;
  1722. begin
  1723. is_classdef:=false;
  1724. repeat
  1725. if not assigned(current_procinfo) then
  1726. internalerror(200304251);
  1727. case token of
  1728. _LABEL:
  1729. label_dec;
  1730. _CONST:
  1731. const_dec;
  1732. _TYPE:
  1733. type_dec;
  1734. _VAR:
  1735. var_dec;
  1736. _THREADVAR:
  1737. threadvar_dec;
  1738. _CLASS:
  1739. begin
  1740. is_classdef:=false;
  1741. if try_to_consume(_CLASS) then
  1742. begin
  1743. { class modifier is only allowed for procedures, functions, }
  1744. { constructors, destructors }
  1745. if not(token in [_FUNCTION,_PROCEDURE,_CONSTRUCTOR,_DESTRUCTOR,_OPERATOR]) and
  1746. not((token=_ID) and (idtoken=_OPERATOR)) then
  1747. Message(parser_e_procedure_or_function_expected);
  1748. if is_interface(current_structdef) then
  1749. Message(parser_e_no_static_method_in_interfaces)
  1750. else
  1751. { class methods are also allowed for Objective-C protocols }
  1752. is_classdef:=true;
  1753. end;
  1754. end;
  1755. _CONSTRUCTOR,
  1756. _DESTRUCTOR,
  1757. _FUNCTION,
  1758. _PROCEDURE,
  1759. _OPERATOR:
  1760. begin
  1761. read_proc(is_classdef,nil);
  1762. is_classdef:=false;
  1763. end;
  1764. _EXPORTS:
  1765. begin
  1766. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  1767. begin
  1768. Message(parser_e_syntax_error);
  1769. consume_all_until(_SEMICOLON);
  1770. end
  1771. else if islibrary or
  1772. (target_info.system in systems_unit_program_exports) then
  1773. read_exports
  1774. else
  1775. begin
  1776. Message(parser_w_unsupported_feature);
  1777. consume(_BEGIN);
  1778. end;
  1779. end
  1780. else
  1781. begin
  1782. case idtoken of
  1783. _RESOURCESTRING:
  1784. begin
  1785. { m_class is needed, because the resourcestring
  1786. loading is in the ObjPas unit }
  1787. { if (m_class in current_settings.modeswitches) then}
  1788. resourcestring_dec
  1789. { else
  1790. break;}
  1791. end;
  1792. _OPERATOR:
  1793. begin
  1794. if is_classdef then
  1795. begin
  1796. read_proc(is_classdef,nil);
  1797. is_classdef:=false;
  1798. end
  1799. else
  1800. break;
  1801. end;
  1802. _PROPERTY:
  1803. begin
  1804. if (m_fpc in current_settings.modeswitches) then
  1805. property_dec
  1806. else
  1807. break;
  1808. end;
  1809. else
  1810. break;
  1811. end;
  1812. end;
  1813. end;
  1814. until false;
  1815. { add implementations for synthetic method declarations added by
  1816. the compiler (not for unit/program init functions, their localst
  1817. is the staticst -> would duplicate the work done in pmodules) }
  1818. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  1819. add_synthetic_method_implementations(current_procinfo.procdef.localst);
  1820. { check for incomplete class definitions, this is only required
  1821. for fpc modes }
  1822. if (m_fpc in current_settings.modeswitches) then
  1823. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  1824. end;
  1825. procedure read_interface_declarations;
  1826. begin
  1827. repeat
  1828. case token of
  1829. _CONST :
  1830. const_dec;
  1831. _TYPE :
  1832. type_dec;
  1833. _VAR :
  1834. var_dec;
  1835. _THREADVAR :
  1836. threadvar_dec;
  1837. _FUNCTION,
  1838. _PROCEDURE,
  1839. _OPERATOR :
  1840. read_proc(false,nil);
  1841. else
  1842. begin
  1843. case idtoken of
  1844. _RESOURCESTRING :
  1845. resourcestring_dec;
  1846. _PROPERTY:
  1847. begin
  1848. if (m_fpc in current_settings.modeswitches) then
  1849. property_dec
  1850. else
  1851. break;
  1852. end;
  1853. else
  1854. break;
  1855. end;
  1856. end;
  1857. end;
  1858. until false;
  1859. { check for incomplete class definitions, this is only required
  1860. for fpc modes }
  1861. if (m_fpc in current_settings.modeswitches) then
  1862. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  1863. end;
  1864. {****************************************************************************
  1865. SPECIALIZATION BODY GENERATION
  1866. ****************************************************************************}
  1867. procedure specialize_objectdefs(p:TObject;arg:pointer);
  1868. var
  1869. oldcurrent_filepos : tfileposinfo;
  1870. specobj : tabstractrecorddef;
  1871. state : tspecializationstate;
  1872. procedure process_abstractrecorddef(def:tabstractrecorddef);
  1873. var
  1874. i : longint;
  1875. hp : tdef;
  1876. hmodule : tmodule;
  1877. begin
  1878. hmodule:=find_module_from_symtable(def.genericdef.owner);
  1879. if hmodule=nil then
  1880. internalerror(201202041);
  1881. for i:=0 to def.symtable.DefList.Count-1 do
  1882. begin
  1883. hp:=tdef(def.symtable.DefList[i]);
  1884. if hp.typ=procdef then
  1885. begin
  1886. { only generate the code if we need a body }
  1887. if assigned(tprocdef(hp).struct) and not tprocdef(hp).forwarddef then
  1888. continue;
  1889. if assigned(tprocdef(hp).genericdef) and
  1890. (tprocdef(hp).genericdef.typ=procdef) and
  1891. assigned(tprocdef(tprocdef(hp).genericdef).generictokenbuf) then
  1892. begin
  1893. oldcurrent_filepos:=current_filepos;
  1894. current_filepos:=tprocdef(tprocdef(hp).genericdef).fileinfo;
  1895. { use the index the module got from the current compilation process }
  1896. current_filepos.moduleindex:=hmodule.unit_index;
  1897. current_tokenpos:=current_filepos;
  1898. current_scanner.startreplaytokens(tprocdef(tprocdef(hp).genericdef).generictokenbuf,
  1899. tprocdef(tprocdef(hp).genericdef).change_endian);
  1900. read_proc_body(nil,tprocdef(hp));
  1901. current_filepos:=oldcurrent_filepos;
  1902. end
  1903. { synthetic routines will be implemented afterwards }
  1904. else if tprocdef(hp).synthetickind=tsk_none then
  1905. MessagePos1(tprocdef(hp).fileinfo,sym_e_forward_not_resolved,tprocdef(hp).fullprocname(false));
  1906. end
  1907. else
  1908. if hp.typ in [objectdef,recorddef] then
  1909. { generate code for subtypes as well }
  1910. process_abstractrecorddef(tabstractrecorddef(hp));
  1911. end;
  1912. end;
  1913. begin
  1914. if not((tsym(p).typ=typesym) and
  1915. (ttypesym(p).typedef.typesym=tsym(p)) and
  1916. (ttypesym(p).typedef.typ in [objectdef,recorddef]) and
  1917. (df_specialization in ttypesym(p).typedef.defoptions)
  1918. ) then
  1919. exit;
  1920. { Setup symtablestack a definition time }
  1921. specobj:=tabstractrecorddef(ttypesym(p).typedef);
  1922. if not (is_class_or_object(specobj) or is_record(specobj) or is_javaclass(specobj)) then
  1923. exit;
  1924. specialization_init(specobj.genericdef,state);
  1925. { procedure definitions for classes or objects }
  1926. process_abstractrecorddef(specobj);
  1927. specialization_done(state);
  1928. end;
  1929. procedure generate_specialization_procs;
  1930. begin
  1931. if assigned(current_module.globalsymtable) then
  1932. current_module.globalsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1933. if assigned(current_module.localsymtable) then
  1934. current_module.localsymtable.SymList.ForEachCall(@specialize_objectdefs,nil);
  1935. end;
  1936. end.