psub.pas 105 KB

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