psub.pas 94 KB

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