psub.pas 105 KB

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