psub.pas 105 KB

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