psub.pas 122 KB

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