psub.pas 80 KB

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