psub.pas 123 KB

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