psub.pas 126 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242
  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(FirstHalf: Boolean);
  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) or defined(m68k)}
  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) or defined(m68k)}
  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)
  1040. { parasize must be really zero, this means also that no result may be returned
  1041. in a parameter }
  1042. and not((current_procinfo.procdef.proccalloption in clearstack_pocalls) and
  1043. not(current_procinfo.procdef.generate_safecall_wrapper) and
  1044. paramanager.ret_in_param(current_procinfo.procdef.returndef,current_procinfo.procdef))
  1045. {and (para_stack_size=0)} then
  1046. begin
  1047. { Only need to set the framepointer }
  1048. framepointer:=NR_STACK_POINTER_REG;
  1049. tg.direction:=1;
  1050. end
  1051. {$if defined(arm)}
  1052. { On arm, the stack frame size can be estimated to avoid using an extra frame pointer,
  1053. in case parameters are passed on the stack.
  1054. However, the draw back is, if the estimation fails, compilation will break later on
  1055. with an internal error, so this switch is not enabled by default yet. To overcome this,
  1056. multipass compilation of subroutines must be supported
  1057. }
  1058. else if (cs_opt_forcenostackframe in current_settings.optimizerswitches) and
  1059. not(has_assembler_child) then
  1060. begin
  1061. { Only need to set the framepointer }
  1062. framepointer:=NR_STACK_POINTER_REG;
  1063. tg.direction:=1;
  1064. include(flags,pi_estimatestacksize);
  1065. set_first_temp_offset;
  1066. procdef.has_paraloc_info:=callnoside;
  1067. generate_parameter_info;
  1068. exit;
  1069. end;
  1070. {$endif defined(arm)}
  1071. end;
  1072. end;
  1073. {$endif defined(x86) or defined(arm) or defined(m68k)}
  1074. {$if defined(xtensa)}
  1075. { On xtensa, the stack frame size can be estimated to avoid using an extra frame pointer,
  1076. in case parameters are passed on the stack.
  1077. However, the draw back is, if the estimation fails, compilation will break later on
  1078. with an internal error, so this switch is not enabled by default yet. To overcome this,
  1079. multipass compilation of subroutines must be supported
  1080. }
  1081. if procdef.stack_tainting_parameter(calleeside) then
  1082. begin
  1083. include(flags,pi_estimatestacksize);
  1084. set_first_temp_offset;
  1085. procdef.has_paraloc_info:=callnoside;
  1086. generate_parameter_info;
  1087. exit;
  1088. end;
  1089. {$endif defined(xtensa)}
  1090. { set the start offset to the start of the temp area in the stack }
  1091. set_first_temp_offset;
  1092. end;
  1093. procedure tcgprocinfo.OptimizeNodeTree;
  1094. var
  1095. i : integer;
  1096. RedoDFA: Boolean;
  1097. {RedoDFA : boolean;}
  1098. begin
  1099. { do this before adding the entry code else the tail recursion recognition won't work,
  1100. if this causes troubles, it must be if'ed
  1101. }
  1102. if (cs_opt_tailrecursion in current_settings.optimizerswitches) and
  1103. (pi_is_recursive in flags) then
  1104. do_opttail(code,procdef);
  1105. if cs_opt_constant_propagate in current_settings.optimizerswitches then
  1106. do_optconstpropagate(code);
  1107. if (cs_opt_nodedfa in current_settings.optimizerswitches) and
  1108. { creating dfa is not always possible }
  1109. ((flags*[pi_has_assembler_block,pi_uses_exceptions,pi_is_assembler])=[]) then
  1110. begin
  1111. dfabuilder:=TDFABuilder.Create;
  1112. dfabuilder.createdfainfo(code);
  1113. include(flags,pi_dfaavailable);
  1114. RedoDFA:=false;
  1115. if (cs_opt_loopstrength in current_settings.optimizerswitches)
  1116. { our induction variable strength reduction doesn't like
  1117. for loops with more than one entry }
  1118. and not(pi_has_label in flags) then
  1119. begin
  1120. RedoDFA:=OptimizeInductionVariables(code);
  1121. end;
  1122. if RedoDFA then
  1123. begin
  1124. dfabuilder.resetdfainfo(code);
  1125. dfabuilder.createdfainfo(code);
  1126. include(flags,pi_dfaavailable);
  1127. end;
  1128. RedoDFA:=OptimizeForLoop(code);
  1129. RedoDFA:=ConvertForLoops(code) or RedoDFA;
  1130. if RedoDFA then
  1131. begin
  1132. dfabuilder.resetdfainfo(code);
  1133. dfabuilder.createdfainfo(code);
  1134. include(flags,pi_dfaavailable);
  1135. end;
  1136. { when life info is available, we can give more sophisticated warning about uninitialized
  1137. variables ...
  1138. ... but not for the finalization section of a unit, we would need global dfa to handle
  1139. it properly }
  1140. if potype_unitfinalize<>procdef.proctypeoption then
  1141. { iterate through life info of the first node }
  1142. for i:=0 to dfabuilder.nodemap.count-1 do
  1143. begin
  1144. if DFASetIn(GetUserCode.optinfo^.life,i) then
  1145. begin
  1146. { do not warn for certain parameters: }
  1147. if not((tnode(dfabuilder.nodemap[i]).nodetype=loadn) and (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ=paravarsym) and
  1148. { do not warn about parameters passed by var }
  1149. (((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varspez=vs_var) and
  1150. { function result is passed by var but it must be initialized }
  1151. not(vo_is_funcret in tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions)) or
  1152. { do not warn about initialized hidden parameters }
  1153. ((tparavarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).varoptions*[vo_is_high_para,vo_is_parentfp,vo_is_result,vo_is_self])<>[]))) then
  1154. CheckAndWarn(GetUserCode,tnode(dfabuilder.nodemap[i]));
  1155. end
  1156. else
  1157. begin
  1158. if (tnode(dfabuilder.nodemap[i]).nodetype=loadn) and
  1159. (tloadnode(dfabuilder.nodemap[i]).symtableentry.typ in [staticvarsym,localvarsym]) then
  1160. tabstractnormalvarsym(tloadnode(dfabuilder.nodemap[i]).symtableentry).noregvarinitneeded:=true
  1161. end;
  1162. end;
  1163. end
  1164. else
  1165. begin
  1166. ConvertForLoops(code);
  1167. end;
  1168. if (pi_dfaavailable in flags) and (cs_opt_dead_store_eliminate in current_settings.optimizerswitches) then
  1169. do_optdeadstoreelim(code);
  1170. if (cs_opt_remove_empty_proc in current_settings.optimizerswitches) and
  1171. (procdef.proctypeoption in [potype_operator,potype_procedure,potype_function]) and
  1172. (code.nodetype=blockn) and (tblocknode(code).statements=nil) then
  1173. procdef.isempty:=true;
  1174. end;
  1175. function tcgprocinfo.has_assembler_child : boolean;
  1176. var
  1177. hp : tprocinfo;
  1178. begin
  1179. result:=false;
  1180. hp:=get_first_nestedproc;
  1181. while assigned(hp) do
  1182. begin
  1183. if (hp.flags*[pi_has_assembler_block,pi_is_assembler])<>[] then
  1184. begin
  1185. result:=true;
  1186. exit;
  1187. end;
  1188. hp:=tprocinfo(hp.next);
  1189. end;
  1190. end;
  1191. procedure tcgprocinfo.set_eh_info;
  1192. begin
  1193. inherited;
  1194. if (tf_use_psabieh in target_info.flags) and
  1195. ((pi_uses_exceptions in flags) or
  1196. ((cs_implicit_exceptions in current_settings.moduleswitches) and
  1197. (pi_needs_implicit_finally in flags))) or
  1198. (pi_has_except_table_data in flags) then
  1199. procdef.personality:=search_system_proc('_FPC_PSABIEH_PERSONALITY_V0');
  1200. end;
  1201. function tcgprocinfo.store_node_tempflags(var n: tnode; arg: pointer): foreachnoderesult;
  1202. var
  1203. nodeset : THashSet absolute arg;
  1204. entry : ptempinfo_flags_entry;
  1205. i : longint;
  1206. hashsetitem: PHashSetItem;
  1207. begin
  1208. result:=fen_true;
  1209. case n.nodetype of
  1210. tempcreaten:
  1211. begin
  1212. {$ifdef EXTDEBUG}
  1213. comment(V_Debug,'keeping track of new temp node: '+hexstr(ttempbasenode(n).tempinfo));
  1214. {$endif EXTDEBUG}
  1215. nodeset.FindOrAdd(ttempbasenode(n).tempinfo,sizeof(pointer));
  1216. end;
  1217. tempdeleten:
  1218. begin
  1219. {$ifdef EXTDEBUG}
  1220. comment(V_Debug,'got temp delete node: '+hexstr(ttempbasenode(n).tempinfo));
  1221. {$endif EXTDEBUG}
  1222. { don't remove temp nodes so that outside code can know if some temp
  1223. was only created in here }
  1224. (*hashsetitem:=nodeset.find(ttempbasenode(n).tempinfo,sizeof(pointer));
  1225. if assigned(hashsetitem) then
  1226. begin
  1227. {$ifdef EXTDEBUG}
  1228. comment(V_Debug,'no longer keeping track of temp node');
  1229. {$endif EXTDEBUG}
  1230. writeln('no longer keeping track of temp node');
  1231. nodeset.Remove(hashsetitem);
  1232. end;*)
  1233. end;
  1234. temprefn:
  1235. begin
  1236. {$ifdef EXTDEBUG}
  1237. comment(V_Debug,'found temp ref node: '+hexstr(ttempbasenode(n).tempinfo));
  1238. {$endif EXTDEBUG}
  1239. if not assigned(nodeset.find(ttempbasenode(n).tempinfo,sizeof(pointer))) then
  1240. begin
  1241. for i:=0 to tempinfo_flags_map.count-1 do
  1242. begin
  1243. entry:=ptempinfo_flags_entry(tempinfo_flags_map[i]);
  1244. {$ifdef EXTDEBUG}
  1245. comment(V_Debug,'comparing with tempinfo: '+hexstr(entry^.tempinfo));
  1246. {$endif EXTDEBUG}
  1247. if entry^.tempinfo=ttempbasenode(n).tempinfo then
  1248. begin
  1249. {$ifdef EXTDEBUG}
  1250. comment(V_Debug,'temp node exists');
  1251. {$endif EXTDEBUG}
  1252. exit;
  1253. end;
  1254. end;
  1255. {$ifdef EXTDEBUG}
  1256. comment(V_Debug,'storing node');
  1257. {$endif EXTDEBUG}
  1258. new(entry);
  1259. entry^.tempinfo:=ttempbasenode(n).tempinfo;
  1260. entry^.flags:=ttempinfoaccessor.gettempinfoflags(entry^.tempinfo);
  1261. tempinfo_flags_map.add(entry);
  1262. end
  1263. else
  1264. begin
  1265. {$ifdef EXTDEBUG}
  1266. comment(V_Debug,'ignoring node');
  1267. {$endif EXTDEBUG}
  1268. end;
  1269. end;
  1270. else
  1271. ;
  1272. end;
  1273. end;
  1274. procedure tcgprocinfo.store_tempflags;
  1275. var
  1276. nodeset : THashSet;
  1277. begin
  1278. if assigned(tempinfo_flags_map) then
  1279. internalerror(2020040601);
  1280. {$ifdef EXTDEBUG}
  1281. comment(V_Debug,'storing temp nodes of '+procdef.mangledname);
  1282. {$endif EXTDEBUG}
  1283. tempinfo_flags_map:=tfplist.create;
  1284. nodeset:=THashSet.Create(32,false,false);
  1285. foreachnode(code,@store_node_tempflags,nodeset);
  1286. nodeset.free;
  1287. end;
  1288. procedure tcgprocinfo.swap_tempflags;
  1289. var
  1290. entry : ptempinfo_flags_entry;
  1291. i : longint;
  1292. tempflags : ttempinfoflags;
  1293. begin
  1294. if not assigned(tempinfo_flags_map) then
  1295. exit;
  1296. for i:=0 to tempinfo_flags_map.count-1 do
  1297. begin
  1298. entry:=ptempinfo_flags_entry(tempinfo_flags_map[i]);
  1299. tempflags:=ttempinfoaccessor.gettempinfoflags(entry^.tempinfo);
  1300. ttempinfoaccessor.settempinfoflags(entry^.tempinfo,entry^.flags);
  1301. entry^.flags:=tempflags;
  1302. end;
  1303. end;
  1304. procedure tcgprocinfo.apply_tempflags;
  1305. begin
  1306. if tempflags_swapped then
  1307. internalerror(2020040602);
  1308. swap_tempflags;
  1309. tempflags_swapped:=true;
  1310. end;
  1311. procedure tcgprocinfo.reset_tempflags;
  1312. begin
  1313. if not tempflags_swapped then
  1314. internalerror(2020040603);
  1315. swap_tempflags;
  1316. tempflags_swapped:=false;
  1317. end;
  1318. {$ifdef DEBUG_NODE_XML}
  1319. procedure tcgprocinfo.XMLPrintProc(FirstHalf: Boolean);
  1320. var
  1321. T: Text;
  1322. W: Word;
  1323. syssym: tsyssym;
  1324. separate : boolean;
  1325. procedure PrintType(Flag: string);
  1326. begin
  1327. if df_generic in procdef.defoptions then
  1328. Write(T, ' type="generic ', Flag, '"')
  1329. else
  1330. Write(T, ' type="', Flag, '"');
  1331. end;
  1332. procedure PrintOption(Flag: string);
  1333. begin
  1334. WriteLn(T, PrintNodeIndention, '<option>', Flag, '</option>');
  1335. end;
  1336. begin
  1337. if current_module.ppxfilefail then
  1338. Exit;
  1339. Assign(T, current_module.ppxfilename);
  1340. {$push} {$I-}
  1341. Append(T);
  1342. if IOResult <> 0 then
  1343. begin
  1344. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  1345. current_module.ppxfilefail := True;
  1346. Exit;
  1347. end;
  1348. {$pop}
  1349. separate := (df_generic in procdef.defoptions);
  1350. { First half prints the header and the nodes as a "code" tag }
  1351. if FirstHalf or separate then
  1352. begin
  1353. Write(T, PrintNodeIndention, '<subroutine');
  1354. { Check to see if the procedure is a class or object method }
  1355. if Assigned(procdef.struct) then
  1356. begin
  1357. if Assigned(procdef.struct.objrealname) then
  1358. Write(T, ' struct="', SanitiseXMLString(procdef.struct.objrealname^), '"')
  1359. else
  1360. Write(T, ' struct="&lt;NULL&gt;"');
  1361. end;
  1362. case procdef.proctypeoption of
  1363. potype_none:
  1364. { Do nothing - should this be an internal error though? };
  1365. potype_procedure,
  1366. potype_function:
  1367. if po_classmethod in procdef.procoptions then
  1368. begin
  1369. if po_staticmethod in procdef.procoptions then
  1370. PrintType('static class method')
  1371. else
  1372. PrintType('class method');
  1373. end
  1374. else if df_generic in procdef.defoptions then
  1375. Write(T, ' type="generic"');
  1376. potype_proginit,
  1377. potype_unitinit:
  1378. PrintType('initialization');
  1379. potype_unitfinalize:
  1380. PrintType('finalization');
  1381. potype_constructor:
  1382. PrintType('constructor');
  1383. potype_destructor:
  1384. PrintType('destructor');
  1385. potype_operator:
  1386. PrintType('operator');
  1387. potype_class_constructor:
  1388. PrintType('class constructor');
  1389. potype_class_destructor:
  1390. PrintType('class destructor');
  1391. potype_propgetter:
  1392. PrintType('dispinterface getter');
  1393. potype_propsetter:
  1394. PrintType('dispinterface setter');
  1395. potype_exceptfilter:
  1396. PrintType('except filter');
  1397. potype_mainstub:
  1398. PrintType('main stub');
  1399. potype_libmainstub:
  1400. PrintType('library main stub');
  1401. potype_pkgstub:
  1402. PrintType('package stub');
  1403. end;
  1404. Write(T, ' name="', SanitiseXMLString(procdef.customprocname([pno_showhidden, pno_noclassmarker])), '"');
  1405. if po_hascallingconvention in procdef.procoptions then
  1406. Write(T, ' convention="', proccalloptionStr[procdef.proccalloption], '"');
  1407. WriteLn(T, '>');
  1408. PrintNodeIndent;
  1409. if Assigned(procdef.returndef) and not is_void(procdef.returndef) then
  1410. WriteLn(T, PrintNodeIndention, '<returndef>', SanitiseXMLString(procdef.returndef.typesymbolprettyname), '</returndef>');
  1411. if po_reintroduce in procdef.procoptions then
  1412. PrintOption('reintroduce');
  1413. if po_virtualmethod in procdef.procoptions then
  1414. PrintOption('virtual');
  1415. if po_finalmethod in procdef.procoptions then
  1416. PrintOption('final');
  1417. if po_overridingmethod in procdef.procoptions then
  1418. PrintOption('override');
  1419. if po_overload in procdef.procoptions then
  1420. PrintOption('overload');
  1421. if po_compilerproc in procdef.procoptions then
  1422. PrintOption('compilerproc');
  1423. if po_assembler in procdef.procoptions then
  1424. PrintOption('assembler');
  1425. if po_nostackframe in procdef.procoptions then
  1426. PrintOption('nostackframe');
  1427. if po_inline in procdef.procoptions then
  1428. PrintOption('inline');
  1429. if po_noreturn in procdef.procoptions then
  1430. PrintOption('noreturn');
  1431. if po_noinline in procdef.procoptions then
  1432. PrintOption('noinline');
  1433. end;
  1434. if Assigned(Code) then
  1435. begin
  1436. if FirstHalf then
  1437. WriteLn(T, PrintNodeIndention, '<code>')
  1438. else
  1439. begin
  1440. WriteLn(T); { Line for spacing }
  1441. WriteLn(T, PrintNodeIndention, '<firstpass>');
  1442. end;
  1443. PrintNodeIndent;
  1444. XMLPrintNode(T, Code);
  1445. PrintNodeUnindent;
  1446. if FirstHalf then
  1447. WriteLn(T, PrintNodeIndention, '</code>')
  1448. else
  1449. WriteLn(T, PrintNodeIndention, '</firstpass>');
  1450. end
  1451. else { Code=Nil }
  1452. begin
  1453. { Don't print anything for second half - if there's no code, there's no firstpass }
  1454. if FirstHalf then
  1455. WriteLn(T, PrintNodeIndention, '<code />');
  1456. end;
  1457. { Print footer only for second half }
  1458. if (not FirstHalf) or separate then
  1459. begin
  1460. PrintNodeUnindent;
  1461. WriteLn(T, PrintNodeIndention, '</subroutine>');
  1462. WriteLn(T); { Line for spacing }
  1463. end;
  1464. Close(T);
  1465. end;
  1466. {$endif DEBUG_NODE_XML}
  1467. procedure tcgprocinfo.generate_code_tree;
  1468. var
  1469. hpi : tcgprocinfo;
  1470. begin
  1471. { generate code for this procedure }
  1472. generate_code;
  1473. { process nested procedures }
  1474. hpi:=tcgprocinfo(get_first_nestedproc);
  1475. while assigned(hpi) do
  1476. begin
  1477. hpi.generate_code_tree;
  1478. hpi:=tcgprocinfo(hpi.next);
  1479. end;
  1480. resetprocdef;
  1481. end;
  1482. procedure tcgprocinfo.generate_code_exceptfilters;
  1483. var
  1484. hpi : tcgprocinfo;
  1485. begin
  1486. hpi:=tcgprocinfo(get_first_nestedproc);
  1487. while assigned(hpi) do
  1488. begin
  1489. if hpi.procdef.proctypeoption=potype_exceptfilter then
  1490. begin
  1491. hpi.apply_tempflags;
  1492. generate_exceptfilter(hpi);
  1493. hpi.reset_tempflags;
  1494. end;
  1495. hpi:=tcgprocinfo(hpi.next);
  1496. end;
  1497. end;
  1498. { For SEH, the code from 'finally' blocks must be put into a separate procedures,
  1499. which can be called by OS during stack unwind. This resembles nested procedures,
  1500. but finalizer procedures do not have their own local variables and work directly
  1501. with the stack frame of parent. In particular, the tempgen must be shared, so
  1502. 1) finalizer procedure is able to finalize temps of the parent,
  1503. 2) if the finalizer procedure is complex enough to need its own temps, they are
  1504. allocated in stack frame of parent, so second-level finalizer procedures are
  1505. not needed.
  1506. Due to requirement of shared tempgen we cannot process finalizer as a regular nested
  1507. procedure (after the parent) and have to do it inline.
  1508. This is called by platform-specific tryfinallynodes during pass2.
  1509. Here we put away the codegen (which carries the register allocator state), process
  1510. the 'nested' procedure, then restore previous cg and continue processing the parent
  1511. procedure. generate_code() will create another cg, but not another tempgen because
  1512. setup_tempgen() is not called for potype_exceptfilter procedures. }
  1513. procedure tcgprocinfo.generate_exceptfilter(nestedpi: tcgprocinfo);
  1514. var
  1515. saved_cg: tcg;
  1516. saved_hlcg: thlcgobj;
  1517. {$ifdef cpu64bitalu}
  1518. saved_cg128 : tcg128;
  1519. {$else cpu64bitalu}
  1520. saved_cg64 : tcg64;
  1521. {$endif cpu64bitalu}
  1522. begin
  1523. if nestedpi.procdef.proctypeoption<>potype_exceptfilter then
  1524. InternalError(201201141);
  1525. { flush code generated this far }
  1526. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1527. { save the codegen }
  1528. saved_cg:=cg;
  1529. saved_hlcg:=hlcg;
  1530. cg:=nil;
  1531. hlcg:=nil;
  1532. {$ifdef cpu64bitalu}
  1533. saved_cg128:=cg128;
  1534. cg128:=nil;
  1535. {$else cpu64bitalu}
  1536. saved_cg64:=cg64;
  1537. cg64:=nil;
  1538. {$endif cpu64bitalu}
  1539. nestedpi.generate_code;
  1540. { prevents generating code the second time when processing nested procedures }
  1541. nestedpi.resetprocdef;
  1542. cg:=saved_cg;
  1543. hlcg:=saved_hlcg;
  1544. {$ifdef cpu64bitalu}
  1545. cg128:=saved_cg128;
  1546. {$else cpu64bitalu}
  1547. cg64:=saved_cg64;
  1548. {$endif cpu64bitalu}
  1549. add_reg_instruction_hook:[email protected]_reg_instruction;
  1550. end;
  1551. procedure TCGProcinfo.CreateInlineInfo;
  1552. begin
  1553. new(procdef.inlininginfo);
  1554. procdef.inlininginfo^.code:=code.getcopy;
  1555. procdef.inlininginfo^.flags:=flags;
  1556. { The blocknode needs to set an exit label }
  1557. if procdef.inlininginfo^.code.nodetype=blockn then
  1558. include(procdef.inlininginfo^.code.flags,nf_block_with_exit);
  1559. procdef.has_inlininginfo:=true;
  1560. export_local_ref_syms;
  1561. export_local_ref_defs;
  1562. end;
  1563. procedure searchthreadvar(p: TObject; arg: pointer);
  1564. var
  1565. i : longint;
  1566. pd : tprocdef;
  1567. begin
  1568. case tsym(p).typ of
  1569. staticvarsym :
  1570. begin
  1571. { local (procedure or unit) variables only need finalization
  1572. if they are used
  1573. }
  1574. if (vo_is_thread_var in tstaticvarsym(p).varoptions) and
  1575. ((tstaticvarsym(p).refs>0) or
  1576. { global (unit) variables always need finalization, since
  1577. they may also be used in another unit
  1578. }
  1579. (tstaticvarsym(p).owner.symtabletype=globalsymtable)) and
  1580. (
  1581. (tstaticvarsym(p).varspez<>vs_const) or
  1582. (vo_force_finalize in tstaticvarsym(p).varoptions)
  1583. ) and
  1584. not(vo_is_funcret in tstaticvarsym(p).varoptions) and
  1585. not(vo_is_external in tstaticvarsym(p).varoptions) and
  1586. is_managed_type(tstaticvarsym(p).vardef) then
  1587. include(current_procinfo.flags,pi_uses_threadvar);
  1588. end;
  1589. procsym :
  1590. begin
  1591. for i:=0 to tprocsym(p).ProcdefList.Count-1 do
  1592. begin
  1593. pd:=tprocdef(tprocsym(p).ProcdefList[i]);
  1594. if assigned(pd.localst) and
  1595. (pd.procsym=tprocsym(p)) and
  1596. (pd.localst.symtabletype<>staticsymtable) then
  1597. pd.localst.SymList.ForEachCall(@searchthreadvar,arg);
  1598. end;
  1599. end;
  1600. else
  1601. ;
  1602. end;
  1603. end;
  1604. function searchusercode(var n: tnode; arg: pointer): foreachnoderesult;
  1605. begin
  1606. if nf_usercode_entry in n.flags then
  1607. begin
  1608. pnode(arg)^:=n;
  1609. result:=fen_norecurse_true
  1610. end
  1611. else
  1612. result:=fen_false;
  1613. end;
  1614. function TCGProcinfo.GetUserCode : tnode;
  1615. var
  1616. n : tnode;
  1617. begin
  1618. n:=nil;
  1619. foreachnodestatic(code,@searchusercode,@n);
  1620. if not(assigned(n)) then
  1621. internalerror(2013111004);
  1622. result:=n;
  1623. end;
  1624. procedure tcgprocinfo.generate_code;
  1625. procedure check_for_threadvars_in_initfinal;
  1626. begin
  1627. if current_procinfo.procdef.proctypeoption=potype_unitfinalize then
  1628. begin
  1629. { this is also used for initialization of variables in a
  1630. program which does not have a globalsymtable }
  1631. if assigned(current_module.globalsymtable) then
  1632. TSymtable(current_module.globalsymtable).SymList.ForEachCall(@searchthreadvar,nil);
  1633. TSymtable(current_module.localsymtable).SymList.ForEachCall(@searchthreadvar,nil);
  1634. end;
  1635. end;
  1636. var
  1637. old_current_procinfo : tprocinfo;
  1638. oldmaxfpuregisters : longint;
  1639. oldfilepos : tfileposinfo;
  1640. old_current_structdef : tabstractrecorddef;
  1641. oldswitches : tlocalswitches;
  1642. templist : TAsmList;
  1643. headertai : tai;
  1644. procedure delete_marker(anode: tasmnode);
  1645. var
  1646. ai: tai;
  1647. begin
  1648. if assigned(anode) then
  1649. begin
  1650. ai:=anode.currenttai;
  1651. if assigned(ai) then
  1652. begin
  1653. aktproccode.remove(ai);
  1654. ai.free;
  1655. anode.currenttai:=nil;
  1656. end;
  1657. end;
  1658. end;
  1659. begin
  1660. { the initialization procedure can be empty, then we
  1661. don't need to generate anything. When it was an empty
  1662. procedure there would be at least a blocknode }
  1663. if not assigned(code) then
  1664. begin
  1665. {$ifdef DEBUG_NODE_XML}
  1666. { Print out nodes as they appear after the first pass }
  1667. XMLPrintProc(True);
  1668. XMLPrintProc(False);
  1669. {$endif DEBUG_NODE_XML}
  1670. exit;
  1671. end;
  1672. { We need valid code }
  1673. if Errorcount<>0 then
  1674. exit;
  1675. { No code can be generated for generic template }
  1676. if (df_generic in procdef.defoptions) then
  1677. internalerror(200511152);
  1678. { For regular procedures the RA and Tempgen shall not be available yet,
  1679. but exception filters reuse Tempgen of parent }
  1680. if assigned(tg)<>(procdef.proctypeoption=potype_exceptfilter) then
  1681. internalerror(200309201);
  1682. old_current_procinfo:=current_procinfo;
  1683. oldfilepos:=current_filepos;
  1684. old_current_structdef:=current_structdef;
  1685. oldmaxfpuregisters:=current_settings.maxfpuregisters;
  1686. current_procinfo:=self;
  1687. current_filepos:=entrypos;
  1688. current_structdef:=procdef.struct;
  1689. { store start of user code, it must be a block node, it will be used later one to
  1690. check variable lifeness }
  1691. include(code.flags,nf_usercode_entry);
  1692. { add wrapping code if necessary (initialization of typed constants on
  1693. some platforms, initing of local variables and out parameters with
  1694. trashing values, ...) }
  1695. { init/final code must be wrapped later (after code for main proc body
  1696. has been generated) }
  1697. if not(current_procinfo.procdef.proctypeoption in [potype_unitinit,potype_unitfinalize]) then
  1698. code:=cnodeutils.wrap_proc_body(procdef,code);
  1699. { automatic inlining? }
  1700. if (cs_opt_autoinline in current_settings.optimizerswitches) and
  1701. not(po_noinline in procdef.procoptions) and
  1702. { no inlining yet? }
  1703. not(procdef.has_inlininginfo) and not(has_nestedprocs) and
  1704. not(procdef.proctypeoption in [potype_proginit,potype_unitinit,potype_unitfinalize,potype_constructor,
  1705. potype_destructor,potype_class_constructor,potype_class_destructor]) and
  1706. ((procdef.procoptions*[po_exports,po_external,po_interrupt,po_virtualmethod,po_iocheck])=[]) and
  1707. (not(procdef.proccalloption in [pocall_safecall])) and
  1708. { rough approximation if we should auto inline:
  1709. - if the tree is simple enough
  1710. - if the tree is not too big
  1711. A bigger tree which is simpler might be autoinlined otoh
  1712. a smaller and complexer tree as well: so we use the sum of
  1713. both measures here }
  1714. (node_count(code)+node_complexity(code)<=25) then
  1715. begin
  1716. { Can we inline this procedure? }
  1717. if checknodeinlining(procdef) then
  1718. begin
  1719. Message1(cg_d_autoinlining,procdef.GetTypeName);
  1720. include(procdef.procoptions,po_inline);
  1721. CreateInlineInfo;
  1722. end;
  1723. end;
  1724. templist:=TAsmList.create;
  1725. { add parast/localst to symtablestack }
  1726. add_to_symtablestack;
  1727. { clear register count }
  1728. procdef.localst.SymList.ForEachCall(@clearrefs,nil);
  1729. procdef.parast.SymList.ForEachCall(@clearrefs,nil);
  1730. { there's always a call to FPC_INITIALIZEUNITS/FPC_DO_EXIT in the main program }
  1731. if (procdef.localst.symtablelevel=main_program_level) and
  1732. (not current_module.is_unit) then
  1733. begin
  1734. include(flags,pi_do_call);
  1735. { the main program never returns due to the do_exit call }
  1736. if not(current_module.islibrary) and (procdef.proctypeoption=potype_proginit) then
  1737. include(procdef.procoptions,po_noreturn);
  1738. end;
  1739. { set implicit_finally flag when there are locals/paras to be finalized }
  1740. if not(po_assembler in current_procinfo.procdef.procoptions) then
  1741. begin
  1742. procdef.parast.SymList.ForEachCall(@check_finalize_paras,nil);
  1743. procdef.localst.SymList.ForEachCall(@check_finalize_locals,nil);
  1744. end;
  1745. {$ifdef SUPPORT_SAFECALL}
  1746. { set implicit_finally flag for if procedure is safecall }
  1747. if (tf_safecall_exceptions in target_info.flags) and
  1748. (procdef.proccalloption=pocall_safecall) then
  1749. include(flags, pi_needs_implicit_finally);
  1750. {$endif}
  1751. {$ifdef DEBUG_NODE_XML}
  1752. { Print out nodes as they appear after the first pass }
  1753. XMLPrintProc(True);
  1754. {$endif DEBUG_NODE_XML}
  1755. { firstpass everything }
  1756. flowcontrol:=[];
  1757. do_firstpass(code);
  1758. {$if defined(i386) or defined(i8086)}
  1759. if node_resources_fpu(code)>0 then
  1760. include(flags,pi_uses_fpu);
  1761. {$endif i386 or i8086}
  1762. { Print the node to tree.log }
  1763. if paraprintnodetree <> 0 then
  1764. printproc( 'after the firstpass');
  1765. OptimizeNodeTree;
  1766. { unit static/global symtables might contain threadvars which are not explicitly used but which might
  1767. require a tls register, so check for such variables }
  1768. check_for_threadvars_in_initfinal;
  1769. { add implicit entry and exit code }
  1770. add_entry_exit_code;
  1771. if cs_opt_nodecse in current_settings.optimizerswitches then
  1772. do_optcse(code);
  1773. if cs_opt_use_load_modify_store in current_settings.optimizerswitches then
  1774. do_optloadmodifystore(code);
  1775. { only do secondpass if there are no errors }
  1776. if (ErrorCount<>0) then
  1777. begin
  1778. {$ifdef DEBUG_NODE_XML}
  1779. { Print out nodes as they appear after the first pass }
  1780. XMLPrintProc(False);
  1781. {$endif DEBUG_NODE_XML}
  1782. end
  1783. else
  1784. begin
  1785. create_hlcodegen;
  1786. setup_eh;
  1787. if (procdef.proctypeoption<>potype_exceptfilter) then
  1788. setup_tempgen;
  1789. { Create register allocator, must come after framepointer is known }
  1790. hlcg.init_register_allocators;
  1791. generate_parameter_info;
  1792. { allocate got register if needed }
  1793. allocate_got_register(aktproccode);
  1794. { allocate got register if needed }
  1795. allocate_tls_register(aktproccode);
  1796. { Allocate space in temp/registers for parast and localst }
  1797. current_filepos:=entrypos;
  1798. gen_alloc_symtable(aktproccode,procdef,procdef.parast);
  1799. gen_alloc_symtable(aktproccode,procdef,procdef.localst);
  1800. { Store temp offset for information about 'real' temps }
  1801. tempstart:=tg.lasttemp;
  1802. { Generate code to load register parameters in temps and insert local
  1803. copies for values parameters. This must be done before the code for the
  1804. body is generated because the localloc is updated.
  1805. Note: The generated code will be inserted after the code generation of
  1806. the body is finished, because only then the position is known }
  1807. {$ifdef oldregvars}
  1808. assign_regvars(code);
  1809. {$endif oldreg}
  1810. current_filepos:=entrypos;
  1811. hlcg.gen_load_para_value(templist);
  1812. { caller paraloc info is also necessary in the stackframe_entry
  1813. code of the ppc (and possibly other processors) }
  1814. procdef.init_paraloc_info(callerside);
  1815. CalcExecutionWeights(code);
  1816. { Print the node to tree.log }
  1817. if paraprintnodetree <> 0 then
  1818. printproc( 'right before code generation');
  1819. {$ifdef DEBUG_NODE_XML}
  1820. { Print out nodes as they appear after the first pass }
  1821. XMLPrintProc(False);
  1822. {$endif DEBUG_NODE_XML}
  1823. { generate code for the node tree }
  1824. do_secondpass(code);
  1825. aktproccode.concatlist(current_asmdata.CurrAsmList);
  1826. { The position of the loadpara_asmnode is now known }
  1827. aktproccode.insertlistafter(loadpara_asmnode.currenttai,templist);
  1828. oldswitches:=current_settings.localswitches;
  1829. { first generate entry and initialize code with the correct
  1830. position and switches }
  1831. current_filepos:=entrypos;
  1832. current_settings.localswitches:=entryswitches;
  1833. cg.set_regalloc_live_range_direction(rad_backwards);
  1834. hlcg.gen_entry_code(templist);
  1835. aktproccode.insertlistafter(entry_asmnode.currenttai,templist);
  1836. hlcg.gen_initialize_code(templist);
  1837. aktproccode.insertlistafter(init_asmnode.currenttai,templist);
  1838. { now generate finalize and exit code with the correct position
  1839. and switches }
  1840. current_filepos:=exitpos;
  1841. current_settings.localswitches:=exitswitches;
  1842. cg.set_regalloc_live_range_direction(rad_forward);
  1843. if assigned(finalize_procinfo) then
  1844. begin
  1845. if target_info.system in [system_aarch64_win64] then
  1846. tcgprocinfo(finalize_procinfo).store_tempflags
  1847. else
  1848. generate_exceptfilter(tcgprocinfo(finalize_procinfo));
  1849. end
  1850. else if not temps_finalized then
  1851. begin
  1852. hlcg.gen_finalize_code(templist);
  1853. { the finalcode must be concated if there was no position available,
  1854. using insertlistafter will result in an insert at the start
  1855. when currentai=nil }
  1856. aktproccode.concatlist(templist);
  1857. end;
  1858. { insert exit label at the correct position }
  1859. hlcg.a_label(templist,CurrExitLabel);
  1860. if assigned(exitlabel_asmnode.currenttai) then
  1861. aktproccode.insertlistafter(exitlabel_asmnode.currenttai,templist)
  1862. else
  1863. aktproccode.concatlist(templist);
  1864. { exit code }
  1865. hlcg.gen_exit_code(templist);
  1866. aktproccode.concatlist(templist);
  1867. { reset switches }
  1868. current_settings.localswitches:=oldswitches;
  1869. {$ifdef OLDREGVARS}
  1870. { note: this must be done only after as much code as possible has }
  1871. { been generated. The result is that when you ungetregister() a }
  1872. { regvar, it will actually free the regvar (and alse free the }
  1873. { the regvars at the same time). Doing this too early will }
  1874. { confuse the register allocator, as the regvars will still be }
  1875. { used. It should be done before loading the result regs (so }
  1876. { they don't conflict with the regvars) and before }
  1877. { gen_entry_code (that one has to be able to allocate the }
  1878. { regvars again) (JM) }
  1879. free_regvars(aktproccode);
  1880. {$endif OLDREGVARS}
  1881. { generate symbol and save end of header position }
  1882. current_filepos:=entrypos;
  1883. hlcg.gen_proc_symbol(templist);
  1884. headertai:=tai(templist.last);
  1885. { insert symbol }
  1886. aktproccode.insertlist(templist);
  1887. { Free space in temp/registers for parast and localst, must be
  1888. done after gen_entry_code }
  1889. current_filepos:=exitpos;
  1890. { make sure the got/pic register doesn't get freed in the }
  1891. { middle of a loop }
  1892. if (tf_pic_uses_got in target_info.flags) and
  1893. (pi_needs_got in flags) and
  1894. (got<>NR_NO) then
  1895. cg.a_reg_sync(aktproccode,got);
  1896. if (pi_needs_tls in flags) and
  1897. (tlsoffset<>NR_NO) then
  1898. cg.a_reg_sync(aktproccode,tlsoffset);
  1899. gen_free_symtable(aktproccode,procdef.localst);
  1900. gen_free_symtable(aktproccode,procdef.parast);
  1901. { add code that will load the return value, this is not done
  1902. for assembler routines when they didn't reference the result
  1903. variable }
  1904. hlcg.gen_load_return_value(templist);
  1905. aktproccode.concatlist(templist);
  1906. { Already reserve all registers for stack checking code and
  1907. generate the call to the helper function }
  1908. if not(tf_no_generic_stackcheck in target_info.flags) and
  1909. (cs_check_stack in entryswitches) and
  1910. not(po_assembler in procdef.procoptions) and
  1911. (procdef.proctypeoption<>potype_proginit) then
  1912. begin
  1913. current_filepos:=entrypos;
  1914. hlcg.gen_stack_check_call(templist);
  1915. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist);
  1916. end;
  1917. { this code (got loading) comes before everything which has }
  1918. { already been generated, so reset the info about already }
  1919. { backwards extended registers (so their live range can be }
  1920. { extended backwards even further if needed) }
  1921. { This code must be }
  1922. { a) generated after do_secondpass has been called }
  1923. { (because pi_needs_got may be set there) }
  1924. { b) generated before register allocation, because the }
  1925. { got/pic register can be a virtual one }
  1926. { c) inserted before the entry code, because the entry }
  1927. { code may need global symbols such as init rtti }
  1928. { d) inserted after the stackframe allocation, because }
  1929. { this register may have to be spilled }
  1930. cg.set_regalloc_live_range_direction(rad_backwards_reinit);
  1931. current_filepos:=entrypos;
  1932. { load got if necessary }
  1933. cg.g_maybe_got_init(templist);
  1934. aktproccode.insertlistafter(headertai,templist);
  1935. { init tls if needed }
  1936. cg.g_maybe_tls_init(templist);
  1937. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist);
  1938. { re-enable if more code at the end is ever generated here
  1939. cg.set_regalloc_live_range_direction(rad_forward);
  1940. }
  1941. {$ifndef NoOpt}
  1942. {$ifndef i386}
  1943. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  1944. { do not optimize pure assembler procedures }
  1945. not(pi_is_assembler in flags) then
  1946. preregallocschedule(aktproccode);
  1947. {$endif i386}
  1948. {$endif NoOpt}
  1949. { The procedure body is finished, we can now
  1950. allocate the registers }
  1951. cg.do_register_allocation(aktproccode,headertai);
  1952. { translate imag. register to their real counter parts
  1953. this is necessary for debuginfo and verbose assembler output
  1954. when SSA will be implented, this will be more complicated because we've to
  1955. maintain location lists }
  1956. procdef.parast.SymList.ForEachCall(@translate_registers,templist);
  1957. procdef.localst.SymList.ForEachCall(@translate_registers,templist);
  1958. if (tf_pic_uses_got in target_info.flags) and (pi_needs_got in flags) and
  1959. not(cs_no_regalloc in current_settings.globalswitches) and
  1960. (got<>NR_NO) then
  1961. cg.translate_register(got);
  1962. { Add save and restore of used registers }
  1963. current_filepos:=entrypos;
  1964. gen_save_used_regs(templist);
  1965. { Remember the last instruction of register saving block
  1966. (may be =nil for e.g. assembler procedures) }
  1967. endprologue_ai:=templist.last;
  1968. aktproccode.insertlistafter(headertai,templist);
  1969. current_filepos:=exitpos;
  1970. gen_restore_used_regs(aktproccode);
  1971. { We know the size of the stack, now we can generate the
  1972. parameter that is passed to the stack checking code }
  1973. if not(tf_no_generic_stackcheck in target_info.flags) and
  1974. (cs_check_stack in entryswitches) and
  1975. not(po_assembler in procdef.procoptions) and
  1976. (procdef.proctypeoption<>potype_proginit) then
  1977. begin
  1978. current_filepos:=entrypos;
  1979. hlcg.gen_stack_check_size_para(templist);
  1980. aktproccode.insertlistafter(stackcheck_asmnode.currenttai,templist)
  1981. end;
  1982. current_procinfo.set_eh_info;
  1983. { Add entry code (stack allocation) after header }
  1984. current_filepos:=entrypos;
  1985. gen_proc_entry_code(templist);
  1986. aktproccode.insertlistafter(headertai,templist);
  1987. {$ifdef SUPPORT_SAFECALL}
  1988. { Set return value of safecall procedure if implicit try/finally blocks are disabled }
  1989. if not (cs_implicit_exceptions in current_settings.moduleswitches) and
  1990. (tf_safecall_exceptions in target_info.flags) and
  1991. (procdef.proccalloption=pocall_safecall) then
  1992. cg.a_load_const_reg(aktproccode,OS_ADDR,0,NR_FUNCTION_RETURN_REG);
  1993. {$endif}
  1994. { Add exit code at the end }
  1995. current_filepos:=exitpos;
  1996. gen_proc_exit_code(templist);
  1997. aktproccode.concatlist(templist);
  1998. { check if the implicit finally has been generated. The flag
  1999. should already be set in pass1 }
  2000. if (cs_implicit_exceptions in current_settings.moduleswitches) and
  2001. not(procdef.proctypeoption in [potype_unitfinalize,potype_unitinit]) and
  2002. (pi_needs_implicit_finally in flags) and
  2003. not(pi_has_implicit_finally in flags) and
  2004. not(target_info.system in systems_garbage_collected_managed_types) then
  2005. internalerror(200405231);
  2006. { sanity check }
  2007. if not(assigned(current_procinfo.procdef.personality)) and
  2008. (tf_use_psabieh in target_info.flags) and
  2009. ((pi_uses_exceptions in flags) or
  2010. ((cs_implicit_exceptions in current_settings.moduleswitches) and
  2011. (pi_needs_implicit_finally in flags))) then
  2012. Internalerror(2019021005);
  2013. { Position markers are only used to insert additional code after the secondpass
  2014. and before this point. They are of no use in optimizer. Instead of checking and
  2015. ignoring all over the optimizer, just remove them here. }
  2016. delete_marker(entry_asmnode);
  2017. delete_marker(loadpara_asmnode);
  2018. delete_marker(exitlabel_asmnode);
  2019. delete_marker(stackcheck_asmnode);
  2020. delete_marker(init_asmnode);
  2021. {$ifndef NoOpt}
  2022. if not(cs_no_regalloc in current_settings.globalswitches) then
  2023. begin
  2024. if (cs_opt_level1 in current_settings.optimizerswitches) and
  2025. { do not optimize pure assembler procedures }
  2026. not(pi_is_assembler in flags) then
  2027. optimize(aktproccode);
  2028. {$ifndef i386}
  2029. { schedule after assembler optimization, it could have brought up
  2030. new schedule possibilities }
  2031. if (cs_opt_scheduler in current_settings.optimizerswitches) and
  2032. { do not optimize pure assembler procedures }
  2033. not(pi_is_assembler in flags) then
  2034. preregallocschedule(aktproccode);
  2035. {$endif i386}
  2036. end;
  2037. {$endif NoOpt}
  2038. { Perform target-specific processing if necessary }
  2039. postprocess_code;
  2040. { Add end symbol and debug info }
  2041. { this must be done after the pcrelativedata is appended else the distance calculation of
  2042. insertpcrelativedata will be wrong, further the pc indirect data is part of the procedure
  2043. so it should be inserted before the end symbol (FK)
  2044. }
  2045. current_filepos:=exitpos;
  2046. hlcg.gen_proc_symbol_end(templist);
  2047. aktproccode.concatlist(templist);
  2048. { insert line debuginfo }
  2049. if (cs_debuginfo in current_settings.moduleswitches) or
  2050. (cs_use_lineinfo in current_settings.globalswitches) then
  2051. current_debuginfo.insertlineinfo(aktproccode);
  2052. finish_eh;
  2053. hlcg.record_generated_code_for_procdef(current_procinfo.procdef,aktproccode,aktlocaldata);
  2054. { now generate code for any exception filters (they need the tempgen) }
  2055. generate_code_exceptfilters;
  2056. { only now we can remove the temps }
  2057. if (procdef.proctypeoption<>potype_exceptfilter) then
  2058. begin
  2059. tg.resettempgen;
  2060. tg.free;
  2061. tg:=nil;
  2062. end;
  2063. { stop tempgen and ra }
  2064. hlcg.done_register_allocators;
  2065. destroy_hlcodegen;
  2066. end;
  2067. dfabuilder.free;
  2068. { restore symtablestack }
  2069. remove_from_symtablestack;
  2070. { restore }
  2071. templist.free;
  2072. current_settings.maxfpuregisters:=oldmaxfpuregisters;
  2073. current_filepos:=oldfilepos;
  2074. current_structdef:=old_current_structdef;
  2075. current_procinfo:=old_current_procinfo;
  2076. end;
  2077. procedure tcgprocinfo.add_to_symtablestack;
  2078. begin
  2079. { insert symtables for the class, but only if it is no nested function }
  2080. if assigned(procdef.struct) and
  2081. not(assigned(parent) and
  2082. assigned(parent.procdef) and
  2083. assigned(parent.procdef.struct)) then
  2084. push_nested_hierarchy(procdef.struct);
  2085. { insert parasymtable in symtablestack when parsing
  2086. a function }
  2087. if procdef.parast.symtablelevel>=normal_function_level then
  2088. symtablestack.push(procdef.parast);
  2089. { insert localsymtable, except for the main procedure
  2090. (in that case the localst is the unit's static symtable,
  2091. which is already on the stack) }
  2092. if procdef.localst.symtablelevel>=normal_function_level then
  2093. symtablestack.push(procdef.localst);
  2094. end;
  2095. procedure tcgprocinfo.remove_from_symtablestack;
  2096. begin
  2097. { remove localsymtable }
  2098. if procdef.localst.symtablelevel>=normal_function_level then
  2099. symtablestack.pop(procdef.localst);
  2100. { remove parasymtable }
  2101. if procdef.parast.symtablelevel>=normal_function_level then
  2102. symtablestack.pop(procdef.parast);
  2103. { remove symtables for the class, but only if it is no nested function }
  2104. if assigned(procdef.struct) and
  2105. not(assigned(parent) and
  2106. assigned(parent.procdef) and
  2107. assigned(parent.procdef.struct)) then
  2108. pop_nested_hierarchy(procdef.struct);
  2109. end;
  2110. procedure tcgprocinfo.resetprocdef;
  2111. begin
  2112. { remove code tree, if not inline procedure }
  2113. if assigned(code) then
  2114. begin
  2115. { the inline procedure has already got a copy of the tree
  2116. stored in procdef.inlininginfo }
  2117. code.free;
  2118. code:=nil;
  2119. end;
  2120. end;
  2121. procedure tcgprocinfo.parse_body;
  2122. var
  2123. old_current_procinfo : tprocinfo;
  2124. old_block_type : tblock_type;
  2125. st : TSymtable;
  2126. old_current_structdef: tabstractrecorddef;
  2127. old_current_genericdef,
  2128. old_current_specializedef: tstoreddef;
  2129. parentfpinitblock: tnode;
  2130. old_parse_generic: boolean;
  2131. recordtokens : boolean;
  2132. begin
  2133. old_current_procinfo:=current_procinfo;
  2134. old_block_type:=block_type;
  2135. old_current_structdef:=current_structdef;
  2136. old_current_genericdef:=current_genericdef;
  2137. old_current_specializedef:=current_specializedef;
  2138. old_parse_generic:=parse_generic;
  2139. current_procinfo:=self;
  2140. current_structdef:=procdef.struct;
  2141. { check if the definitions of certain types are available which might not be available in older rtls and
  2142. which are assigned "on the fly" in types_dec }
  2143. {$ifndef jvm}
  2144. if not assigned(rec_exceptaddr) then
  2145. Message1(cg_f_internal_type_not_found,'TEXCEPTADDR');
  2146. if not assigned(rec_tguid) then
  2147. Message1(cg_f_internal_type_not_found,'TGUID');
  2148. if not assigned(rec_jmp_buf) then
  2149. Message1(cg_f_internal_type_not_found,'JMP_BUF');
  2150. {$endif}
  2151. { if the procdef is truly a generic (thus takes parameters itself) then
  2152. /that/ is our genericdef, not the - potentially - generic struct }
  2153. if procdef.is_generic then
  2154. begin
  2155. current_genericdef:=procdef;
  2156. parse_generic:=true;
  2157. end
  2158. else if assigned(current_structdef) and (df_generic in current_structdef.defoptions) then
  2159. begin
  2160. current_genericdef:=current_structdef;
  2161. parse_generic:=true;
  2162. end;
  2163. if assigned(current_structdef) and (df_specialization in current_structdef.defoptions) then
  2164. current_specializedef:=current_structdef;
  2165. { calculate the lexical level }
  2166. if procdef.parast.symtablelevel>maxnesting then
  2167. Message(parser_e_too_much_lexlevel);
  2168. block_type:=bt_body;
  2169. {$ifdef state_tracking}
  2170. { aktstate:=Tstate_storage.create;}
  2171. {$endif state_tracking}
  2172. { allocate the symbol for this procedure }
  2173. alloc_proc_symbol(procdef);
  2174. { add parast/localst to symtablestack }
  2175. add_to_symtablestack;
  2176. { save entry info }
  2177. entrypos:=current_filepos;
  2178. entryswitches:=current_settings.localswitches;
  2179. recordtokens:=procdef.is_generic or
  2180. (
  2181. assigned(procdef.struct) and
  2182. (df_generic in procdef.struct.defoptions) and
  2183. assigned(procdef.owner) and
  2184. (procdef.owner.defowner=procdef.struct)
  2185. );
  2186. if recordtokens then
  2187. begin
  2188. { start token recorder for generic template }
  2189. procdef.initgeneric;
  2190. current_scanner.startrecordtokens(procdef.generictokenbuf);
  2191. end;
  2192. { parse the code ... }
  2193. code:=block(current_module.islibrary);
  2194. if recordtokens then
  2195. begin
  2196. { stop token recorder for generic template }
  2197. current_scanner.stoprecordtokens;
  2198. { Give an error for accesses in the static symtable that aren't visible
  2199. outside the current unit }
  2200. st:=procdef.owner;
  2201. while (st.symtabletype in [ObjectSymtable,recordsymtable]) do
  2202. st:=st.defowner.owner;
  2203. if (pi_uses_static_symtable in flags) and
  2204. (st.symtabletype<>staticsymtable) then
  2205. Message(parser_e_global_generic_references_static);
  2206. end;
  2207. { save exit info }
  2208. exitswitches:=current_settings.localswitches;
  2209. exitpos:=last_endtoken_filepos;
  2210. { the procedure is now defined }
  2211. procdef.forwarddef:=false;
  2212. procdef.is_implemented:=true;
  2213. if assigned(code) then
  2214. begin
  2215. { get a better entry point }
  2216. entrypos:=code.fileinfo;
  2217. { Finish type checking pass }
  2218. do_typecheckpass(code);
  2219. if assigned(procdef.parentfpinitblock) then
  2220. begin
  2221. if assigned(tblocknode(procdef.parentfpinitblock).left) then
  2222. begin
  2223. parentfpinitblock:=procdef.parentfpinitblock;
  2224. do_typecheckpass(parentfpinitblock);
  2225. procdef.parentfpinitblock:=parentfpinitblock;
  2226. end
  2227. end;
  2228. end;
  2229. { Check for unused labels, forwards, symbols for procedures. Static
  2230. symtable is checked in pmodules.
  2231. The check must be done after the typecheckpass }
  2232. if (Errorcount=0) and
  2233. (tstoredsymtable(procdef.localst).symtabletype<>staticsymtable) then
  2234. begin
  2235. { check if forwards are resolved }
  2236. tstoredsymtable(procdef.localst).check_forwards;
  2237. { check if all labels are used }
  2238. tstoredsymtable(procdef.localst).checklabels;
  2239. { check for unused symbols, but only if there is no asm block }
  2240. if not(pi_has_assembler_block in flags) then
  2241. begin
  2242. tstoredsymtable(procdef.localst).allsymbolsused;
  2243. tstoredsymtable(procdef.parast).allsymbolsused;
  2244. end;
  2245. end;
  2246. if (po_inline in procdef.procoptions) and
  2247. { Can we inline this procedure? }
  2248. checknodeinlining(procdef) then
  2249. CreateInlineInfo;
  2250. { Print the node to tree.log }
  2251. if paraprintnodetree <> 0 then
  2252. printproc( 'after parsing');
  2253. {$ifdef DEBUG_NODE_XML}
  2254. { Methods of generic classes don't get any code generated, so output
  2255. the node tree here }
  2256. if (df_generic in procdef.defoptions) then
  2257. XMLPrintProc(True);
  2258. {$endif DEBUG_NODE_XML}
  2259. { ... remove symbol tables }
  2260. remove_from_symtablestack;
  2261. {$ifdef state_tracking}
  2262. { aktstate.destroy;}
  2263. {$endif state_tracking}
  2264. current_structdef:=old_current_structdef;
  2265. current_genericdef:=old_current_genericdef;
  2266. current_specializedef:=old_current_specializedef;
  2267. current_procinfo:=old_current_procinfo;
  2268. parse_generic:=old_parse_generic;
  2269. { Restore old state }
  2270. block_type:=old_block_type;
  2271. end;
  2272. {****************************************************************************
  2273. PROCEDURE/FUNCTION PARSING
  2274. ****************************************************************************}
  2275. procedure check_init_paras(p:TObject;arg:pointer);
  2276. begin
  2277. if tsym(p).typ<>paravarsym then
  2278. exit;
  2279. with tparavarsym(p) do
  2280. if (is_managed_type(vardef) and
  2281. (varspez in [vs_value,vs_out])) or
  2282. (is_shortstring(vardef) and
  2283. (varspez=vs_value)) then
  2284. include(current_procinfo.flags,pi_do_call);
  2285. end;
  2286. procedure read_proc_body(old_current_procinfo:tprocinfo;pd:tprocdef);
  2287. {
  2288. Parses the procedure directives, then parses the procedure body, then
  2289. generates the code for it
  2290. }
  2291. var
  2292. oldfailtokenmode : tmodeswitches;
  2293. isnestedproc : boolean;
  2294. begin
  2295. Message1(parser_d_procedure_start,pd.fullprocname(false));
  2296. oldfailtokenmode:=[];
  2297. { create a new procedure }
  2298. current_procinfo:=cprocinfo.create(old_current_procinfo);
  2299. current_module.procinfo:=current_procinfo;
  2300. current_procinfo.procdef:=pd;
  2301. isnestedproc:=(current_procinfo.procdef.parast.symtablelevel>normal_function_level);
  2302. { Insert mangledname }
  2303. pd.aliasnames.insert(pd.mangledname);
  2304. { Handle Export of this procedure }
  2305. if (po_exports in pd.procoptions) and
  2306. (target_info.system in [system_i386_os2,system_i386_emx]) then
  2307. begin
  2308. pd.aliasnames.insert(pd.procsym.realname);
  2309. if cs_link_deffile in current_settings.globalswitches then
  2310. deffile.AddExport(pd.mangledname);
  2311. end;
  2312. { Insert result variables in the localst }
  2313. insert_funcret_local(pd);
  2314. { check if there are para's which require initing -> set }
  2315. { pi_do_call (if not yet set) }
  2316. if not(pi_do_call in current_procinfo.flags) then
  2317. pd.parast.SymList.ForEachCall(@check_init_paras,nil);
  2318. { set _FAIL as keyword if constructor }
  2319. if (pd.proctypeoption=potype_constructor) then
  2320. begin
  2321. oldfailtokenmode:=tokeninfo^[_FAIL].keyword;
  2322. tokeninfo^[_FAIL].keyword:=alllanguagemodes;
  2323. end;
  2324. tcgprocinfo(current_procinfo).parse_body;
  2325. { reset _FAIL as _SELF normal }
  2326. if (pd.proctypeoption=potype_constructor) then
  2327. tokeninfo^[_FAIL].keyword:=oldfailtokenmode;
  2328. { When it's a nested procedure then defer the code generation,
  2329. when back at normal function level then generate the code
  2330. for all defered nested procedures and the current procedure }
  2331. if not isnestedproc then
  2332. begin
  2333. if not(df_generic in current_procinfo.procdef.defoptions) then
  2334. begin
  2335. { also generate the bodies for all previously done
  2336. specializations so that we might inline them }
  2337. generate_specialization_procs;
  2338. tcgprocinfo(current_procinfo).generate_code_tree;
  2339. end;
  2340. end;
  2341. { release procinfo }
  2342. if tprocinfo(current_module.procinfo)<>current_procinfo then
  2343. internalerror(200304274);
  2344. current_module.procinfo:=current_procinfo.parent;
  2345. { For specialization we didn't record the last semicolon. Moving this parsing
  2346. into the parse_body routine is not done because of having better file position
  2347. information available }
  2348. if not current_procinfo.procdef.is_specialization and
  2349. (
  2350. not assigned(current_procinfo.procdef.struct) or
  2351. not (df_specialization in current_procinfo.procdef.struct.defoptions)
  2352. or not (
  2353. assigned(current_procinfo.procdef.owner) and
  2354. (current_procinfo.procdef.owner.defowner=current_procinfo.procdef.struct)
  2355. )
  2356. ) then
  2357. consume(_SEMICOLON);
  2358. if not isnestedproc then
  2359. { current_procinfo is checked for nil later on }
  2360. freeandnil(current_procinfo);
  2361. end;
  2362. procedure read_proc_body(pd:tprocdef);
  2363. var
  2364. old_module_procinfo : tobject;
  2365. old_current_procinfo : tprocinfo;
  2366. begin
  2367. old_current_procinfo:=current_procinfo;
  2368. old_module_procinfo:=current_module.procinfo;
  2369. current_procinfo:=nil;
  2370. current_module.procinfo:=nil;
  2371. read_proc_body(nil,pd);
  2372. current_procinfo:=old_current_procinfo;
  2373. current_module.procinfo:=old_module_procinfo;
  2374. end;
  2375. procedure read_proc(isclassmethod:boolean; usefwpd: tprocdef; isgeneric:boolean);
  2376. {
  2377. Parses the procedure directives, then parses the procedure body, then
  2378. generates the code for it
  2379. }
  2380. var
  2381. old_current_procinfo : tprocinfo;
  2382. old_current_structdef: tabstractrecorddef;
  2383. old_current_genericdef,
  2384. old_current_specializedef: tstoreddef;
  2385. pdflags : tpdflags;
  2386. pd,firstpd : tprocdef;
  2387. {$ifdef genericdef_for_nested}
  2388. def : tprocdef;
  2389. srsym : tsym;
  2390. i : longint;
  2391. {$endif genericdef_for_nested}
  2392. begin
  2393. { save old state }
  2394. old_current_procinfo:=current_procinfo;
  2395. old_current_structdef:=current_structdef;
  2396. old_current_genericdef:=current_genericdef;
  2397. old_current_specializedef:=current_specializedef;
  2398. { reset current_procinfo.procdef to nil to be sure that nothing is writing
  2399. to another procdef }
  2400. current_procinfo:=nil;
  2401. current_structdef:=nil;
  2402. current_genericdef:=nil;
  2403. current_specializedef:=nil;
  2404. if not assigned(usefwpd) then
  2405. { parse procedure declaration }
  2406. pd:=parse_proc_dec(isclassmethod,old_current_structdef,isgeneric)
  2407. else
  2408. pd:=usefwpd;
  2409. { set the default function options }
  2410. if parse_only then
  2411. begin
  2412. pd.forwarddef:=true;
  2413. { set also the interface flag, for better error message when the
  2414. implementation doesn't match this header }
  2415. pd.interfacedef:=true;
  2416. include(pd.procoptions,po_global);
  2417. pdflags:=[pd_interface];
  2418. end
  2419. else
  2420. begin
  2421. pdflags:=[pd_body];
  2422. if (not current_module.in_interface) then
  2423. include(pdflags,pd_implemen);
  2424. if (not current_module.is_unit) or
  2425. create_smartlink_library then
  2426. include(pd.procoptions,po_global);
  2427. pd.forwarddef:=false;
  2428. end;
  2429. if not assigned(usefwpd) then
  2430. begin
  2431. { parse the directives that may follow }
  2432. parse_proc_directives(pd,pdflags);
  2433. { hint directives, these can be separated by semicolons here,
  2434. that needs to be handled here with a loop (PFV) }
  2435. while try_consume_hintdirective(pd.symoptions,pd.deprecatedmsg) do
  2436. Consume(_SEMICOLON);
  2437. { Set calling convention }
  2438. if parse_only then
  2439. handle_calling_convention(pd,hcc_default_actions_intf)
  2440. else
  2441. handle_calling_convention(pd,hcc_default_actions_impl)
  2442. end;
  2443. { search for forward declarations }
  2444. if not proc_add_definition(pd) then
  2445. begin
  2446. { One may not implement a method of a type declared in a different unit }
  2447. if assigned(pd.struct) and
  2448. (pd.struct.symtable.moduleid<>current_module.moduleid) and
  2449. not pd.is_specialization then
  2450. begin
  2451. MessagePos1(pd.fileinfo,parser_e_method_for_type_in_other_unit,pd.struct.typesymbolprettyname);
  2452. end
  2453. { A method must be forward defined (in the object declaration) }
  2454. else if assigned(pd.struct) and
  2455. (not assigned(old_current_structdef)) then
  2456. begin
  2457. MessagePos1(pd.fileinfo,parser_e_header_dont_match_any_member,pd.fullprocname(false));
  2458. tprocsym(pd.procsym).write_parameter_lists(pd);
  2459. end
  2460. else
  2461. begin
  2462. { Give a better error if there is a forward def in the interface and only
  2463. a single implementation }
  2464. firstpd:=tprocdef(tprocsym(pd.procsym).ProcdefList[0]);
  2465. if (not pd.forwarddef) and
  2466. (not pd.interfacedef) and
  2467. (tprocsym(pd.procsym).ProcdefList.Count>1) and
  2468. firstpd.forwarddef and
  2469. firstpd.interfacedef and
  2470. not(tprocsym(pd.procsym).ProcdefList.Count>2) and
  2471. { don't give an error if it may be an overload }
  2472. not(m_fpc in current_settings.modeswitches) and
  2473. (not(po_overload in pd.procoptions) or
  2474. not(po_overload in firstpd.procoptions)) then
  2475. begin
  2476. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  2477. tprocsym(pd.procsym).write_parameter_lists(pd);
  2478. end
  2479. else
  2480. begin
  2481. if pd.is_generic and not assigned(pd.struct) then
  2482. tprocsym(pd.procsym).owner.includeoption(sto_has_generic);
  2483. end;
  2484. end;
  2485. end;
  2486. { Set mangled name }
  2487. proc_set_mangledname(pd);
  2488. { inherit generic flags from parent routine }
  2489. if assigned(old_current_procinfo) and
  2490. (old_current_procinfo.procdef.defoptions*[df_specialization,df_generic]<>[]) then
  2491. begin
  2492. if df_generic in old_current_procinfo.procdef.defoptions then
  2493. include(pd.defoptions,df_generic);
  2494. if df_specialization in old_current_procinfo.procdef.defoptions then
  2495. begin
  2496. include(pd.defoptions,df_specialization);
  2497. { the procdefs encountered here are nested procdefs of which
  2498. their complete definition also resides inside the current token
  2499. stream, thus access to their genericdef is not required }
  2500. {$ifdef genericdef_for_nested}
  2501. { find the corresponding routine in the generic routine }
  2502. if not assigned(old_current_procinfo.procdef.genericdef) then
  2503. internalerror(2016121701);
  2504. srsym:=tsym(tprocdef(old_current_procinfo.procdef.genericdef).getsymtable(gs_local).find(pd.procsym.name));
  2505. if not assigned(srsym) or (srsym.typ<>procsym) then
  2506. internalerror(2016121702);
  2507. { in practice the generic procdef should be at the same index
  2508. as the index of the current procdef, but as there *might* be
  2509. differences between the amount of defs generated for the
  2510. specialization and the generic search for the def using
  2511. parameter comparison }
  2512. for i:=0 to tprocsym(srsym).procdeflist.count-1 do
  2513. begin
  2514. def:=tprocdef(tprocsym(srsym).procdeflist[i]);
  2515. if (compare_paras(def.paras,pd.paras,cp_none,[cpo_ignorehidden,cpo_openequalisexact,cpo_ignoreuniv])=te_exact) and
  2516. (compare_defs(def.returndef,pd.returndef,nothingn)=te_exact) then
  2517. begin
  2518. pd.genericdef:=def;
  2519. break;
  2520. end;
  2521. end;
  2522. if not assigned(pd.genericdef) then
  2523. internalerror(2016121703);
  2524. {$endif}
  2525. end;
  2526. end;
  2527. { compile procedure when a body is needed }
  2528. if (pd_body in pdflags) then
  2529. begin
  2530. read_proc_body(old_current_procinfo,pd);
  2531. end
  2532. else
  2533. begin
  2534. { Handle imports }
  2535. if (po_external in pd.procoptions) then
  2536. begin
  2537. import_external_proc(pd);
  2538. {$ifdef cpuhighleveltarget}
  2539. { it's hard to factor this out in a virtual method, because the
  2540. generic version (the one inside this ifdef) doesn't fit in
  2541. hlcgobj but in symcreat or here, while the other version
  2542. doesn't fit in symcreat (since it uses the code generator).
  2543. Maybe we need another class for this kind of code that could
  2544. either be symcreat- or hlcgobj-based
  2545. }
  2546. if (not pd.forwarddef) and
  2547. (pd.hasforward) and
  2548. (proc_get_importname(pd)<>'') then
  2549. begin
  2550. { we cannot handle the callee-side of variadic functions (and
  2551. even if we could, e.g. LLVM cannot call through to something
  2552. else in that case) }
  2553. if is_c_variadic(pd) then
  2554. Message1(parser_e_callthrough_varargs,pd.fullprocname(false));
  2555. call_through_new_name(pd,proc_get_importname(pd));
  2556. include(pd.implprocoptions,pio_thunk);
  2557. end
  2558. else
  2559. {$endif cpuhighleveltarget}
  2560. begin
  2561. create_hlcodegen;
  2562. hlcg.handle_external_proc(
  2563. current_asmdata.asmlists[al_procedures],
  2564. pd,
  2565. proc_get_importname(pd));
  2566. destroy_hlcodegen;
  2567. end
  2568. end;
  2569. end;
  2570. { always register public functions that are only declared in the
  2571. implementation section as they might be called using an external
  2572. declaration from another unit }
  2573. if (po_global in pd.procoptions) and
  2574. not pd.interfacedef and
  2575. ([df_generic,df_specialization]*pd.defoptions=[]) then
  2576. begin
  2577. pd.register_def;
  2578. pd.procsym.register_sym;
  2579. end;
  2580. { make sure that references to forward-declared functions are not }
  2581. { treated as references to external symbols, needed for darwin. }
  2582. { make sure we don't change the binding of real external symbols }
  2583. if (([po_external,po_weakexternal]*pd.procoptions)=[]) and (pocall_internproc<>pd.proccalloption) then
  2584. current_asmdata.DefineProcAsmSymbol(pd,pd.mangledname,pd.needsglobalasmsym);
  2585. current_structdef:=old_current_structdef;
  2586. current_genericdef:=old_current_genericdef;
  2587. current_specializedef:=old_current_specializedef;
  2588. current_procinfo:=old_current_procinfo;
  2589. end;
  2590. procedure import_external_proc(pd:tprocdef);
  2591. var
  2592. name : string;
  2593. begin
  2594. if not (po_external in pd.procoptions) then
  2595. internalerror(2015121101);
  2596. { Import DLL specified? }
  2597. if assigned(pd.import_dll) then
  2598. begin
  2599. if assigned (pd.import_name) then
  2600. current_module.AddExternalImport(pd.import_dll^,
  2601. pd.import_name^,proc_get_importname(pd),
  2602. pd.import_nr,false,false)
  2603. else
  2604. current_module.AddExternalImport(pd.import_dll^,
  2605. proc_get_importname(pd),proc_get_importname(pd),
  2606. pd.import_nr,false,true);
  2607. end
  2608. else
  2609. begin
  2610. name:=proc_get_importname(pd);
  2611. { add import name to external list for DLL scanning }
  2612. if tf_has_dllscanner in target_info.flags then
  2613. current_module.dllscannerinputlist.Add(name,pd);
  2614. { needed for units that use functions in packages this way }
  2615. current_module.add_extern_asmsym(name,AB_EXTERNAL,AT_FUNCTION);
  2616. end;
  2617. end;
  2618. {****************************************************************************
  2619. DECLARATION PARSING
  2620. ****************************************************************************}
  2621. { search in symtablestack for not complete classes }
  2622. procedure check_forward_class(p:TObject;arg:pointer);
  2623. begin
  2624. if (tsym(p).typ=typesym) and
  2625. (ttypesym(p).typedef.typ=objectdef) and
  2626. (oo_is_forward in tobjectdef(ttypesym(p).typedef).objectoptions) then
  2627. MessagePos1(tsym(p).fileinfo,sym_e_forward_type_not_resolved,tsym(p).realname);
  2628. end;
  2629. {$ifdef DEBUG_NODE_XML}
  2630. procedure XMLInitializeNodeFile(RootName, ModuleName: shortstring);
  2631. var
  2632. T: Text;
  2633. begin
  2634. Assign(T, current_module.ppxfilename);
  2635. {$push} {$I-}
  2636. Rewrite(T);
  2637. if IOResult<>0 then
  2638. begin
  2639. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  2640. current_module.ppxfilefail := True;
  2641. Exit;
  2642. end;
  2643. {$pop}
  2644. { Mark the node dump file as available for writing }
  2645. current_module.ppxfilefail := False;
  2646. WriteLn(T, '<?xml version="1.0" encoding="utf-8"?>');
  2647. WriteLn(T, '<', RootName, ' name="', ModuleName, '">');
  2648. Close(T);
  2649. printnodeindention := printnodespacing;
  2650. end;
  2651. procedure XMLFinalizeNodeFile(RootName: shortstring);
  2652. var
  2653. T: Text;
  2654. begin
  2655. if current_module.ppxfilefail then
  2656. Exit;
  2657. current_module.ppxfilefail := True; { File is now considered closed no matter what happens }
  2658. Assign(T, current_module.ppxfilename);
  2659. {$push} {$I-}
  2660. Append(T);
  2661. if IOResult<>0 then
  2662. begin
  2663. Message1(exec_e_cant_create_archivefile,current_module.ppxfilename);
  2664. Exit;
  2665. end;
  2666. {$pop}
  2667. WriteLn(T, '</', RootName, '>');
  2668. Close(T);
  2669. end;
  2670. {$endif DEBUG_NODE_XML}
  2671. procedure read_declarations(islibrary : boolean);
  2672. var
  2673. hadgeneric : boolean;
  2674. procedure handle_unexpected_had_generic;
  2675. begin
  2676. if hadgeneric then
  2677. begin
  2678. Message(parser_e_procedure_or_function_expected);
  2679. hadgeneric:=false;
  2680. end;
  2681. end;
  2682. var
  2683. is_classdef:boolean;
  2684. begin
  2685. is_classdef:=false;
  2686. hadgeneric:=false;
  2687. repeat
  2688. if not assigned(current_procinfo) then
  2689. internalerror(200304251);
  2690. case token of
  2691. _LABEL:
  2692. begin
  2693. handle_unexpected_had_generic;
  2694. label_dec;
  2695. end;
  2696. _CONST:
  2697. begin
  2698. handle_unexpected_had_generic;
  2699. const_dec(hadgeneric);
  2700. end;
  2701. _TYPE:
  2702. begin
  2703. handle_unexpected_had_generic;
  2704. type_dec(hadgeneric);
  2705. end;
  2706. _VAR:
  2707. begin
  2708. handle_unexpected_had_generic;
  2709. var_dec(hadgeneric);
  2710. end;
  2711. _THREADVAR:
  2712. begin
  2713. handle_unexpected_had_generic;
  2714. threadvar_dec(hadgeneric);
  2715. end;
  2716. _CLASS:
  2717. begin
  2718. is_classdef:=false;
  2719. if try_to_consume(_CLASS) then
  2720. begin
  2721. { class modifier is only allowed for procedures, functions, }
  2722. { constructors, destructors }
  2723. if not((token in [_FUNCTION,_PROCEDURE,_DESTRUCTOR,_OPERATOR]) or (token=_CONSTRUCTOR)) and
  2724. not((token=_ID) and (idtoken=_OPERATOR)) then
  2725. Message(parser_e_procedure_or_function_expected);
  2726. if is_interface(current_structdef) then
  2727. Message(parser_e_no_static_method_in_interfaces)
  2728. else
  2729. { class methods are also allowed for Objective-C protocols }
  2730. is_classdef:=true;
  2731. end;
  2732. end;
  2733. _CONSTRUCTOR,
  2734. _DESTRUCTOR,
  2735. _FUNCTION,
  2736. _PROCEDURE,
  2737. _OPERATOR:
  2738. begin
  2739. if hadgeneric and not (token in [_PROCEDURE,_FUNCTION]) then
  2740. begin
  2741. Message(parser_e_procedure_or_function_expected);
  2742. hadgeneric:=false;
  2743. end;
  2744. read_proc(is_classdef,nil,hadgeneric);
  2745. is_classdef:=false;
  2746. hadgeneric:=false;
  2747. end;
  2748. _EXPORTS:
  2749. begin
  2750. handle_unexpected_had_generic;
  2751. if (current_procinfo.procdef.localst.symtablelevel>main_program_level) then
  2752. begin
  2753. Message(parser_e_syntax_error);
  2754. consume_all_until(_SEMICOLON);
  2755. end
  2756. else if islibrary or
  2757. (target_info.system in systems_unit_program_exports) then
  2758. read_exports
  2759. else
  2760. begin
  2761. Message(parser_w_unsupported_feature);
  2762. consume(_BEGIN);
  2763. end;
  2764. end;
  2765. _PROPERTY:
  2766. begin
  2767. handle_unexpected_had_generic;
  2768. if (m_fpc in current_settings.modeswitches) then
  2769. property_dec
  2770. else
  2771. break;
  2772. end;
  2773. else
  2774. begin
  2775. case idtoken of
  2776. _RESOURCESTRING:
  2777. begin
  2778. handle_unexpected_had_generic;
  2779. { m_class is needed, because the resourcestring
  2780. loading is in the ObjPas unit }
  2781. { if (m_class in current_settings.modeswitches) then}
  2782. resourcestring_dec(hadgeneric)
  2783. { else
  2784. break;}
  2785. end;
  2786. _OPERATOR:
  2787. begin
  2788. handle_unexpected_had_generic;
  2789. if is_classdef then
  2790. begin
  2791. read_proc(is_classdef,nil,false);
  2792. is_classdef:=false;
  2793. end
  2794. else
  2795. break;
  2796. end;
  2797. _GENERIC:
  2798. begin
  2799. handle_unexpected_had_generic;
  2800. if not (m_delphi in current_settings.modeswitches) then
  2801. begin
  2802. consume(_ID);
  2803. hadgeneric:=true;
  2804. end
  2805. else
  2806. break;
  2807. end
  2808. else
  2809. break;
  2810. end;
  2811. end;
  2812. end;
  2813. until false;
  2814. { add implementations for synthetic method declarations added by
  2815. the compiler (not for unit/program init functions, their localst
  2816. is the staticst -> would duplicate the work done in pmodules) }
  2817. if current_procinfo.procdef.localst.symtabletype=localsymtable then
  2818. add_synthetic_method_implementations(current_procinfo.procdef.localst);
  2819. { check for incomplete class definitions, this is only required
  2820. for fpc modes }
  2821. if (m_fpc in current_settings.modeswitches) then
  2822. current_procinfo.procdef.localst.SymList.ForEachCall(@check_forward_class,nil);
  2823. end;
  2824. procedure read_interface_declarations;
  2825. var
  2826. hadgeneric : boolean;
  2827. procedure handle_unexpected_had_generic;
  2828. begin
  2829. if hadgeneric then
  2830. begin
  2831. Message(parser_e_procedure_or_function_expected);
  2832. hadgeneric:=false;
  2833. end;
  2834. end;
  2835. begin
  2836. hadgeneric:=false;
  2837. repeat
  2838. case token of
  2839. _CONST :
  2840. begin
  2841. handle_unexpected_had_generic;
  2842. const_dec(hadgeneric);
  2843. end;
  2844. _TYPE :
  2845. begin
  2846. handle_unexpected_had_generic;
  2847. type_dec(hadgeneric);
  2848. end;
  2849. _VAR :
  2850. begin
  2851. handle_unexpected_had_generic;
  2852. var_dec(hadgeneric);
  2853. end;
  2854. _THREADVAR :
  2855. begin
  2856. handle_unexpected_had_generic;
  2857. threadvar_dec(hadgeneric);
  2858. end;
  2859. _FUNCTION,
  2860. _PROCEDURE,
  2861. _OPERATOR :
  2862. begin
  2863. if hadgeneric and not (token in [_FUNCTION, _PROCEDURE]) then
  2864. begin
  2865. message(parser_e_procedure_or_function_expected);
  2866. hadgeneric:=false;
  2867. end;
  2868. read_proc(false,nil,hadgeneric);
  2869. hadgeneric:=false;
  2870. end;
  2871. else
  2872. begin
  2873. case idtoken of
  2874. _RESOURCESTRING :
  2875. begin
  2876. handle_unexpected_had_generic;
  2877. resourcestring_dec(hadgeneric);
  2878. end;
  2879. _PROPERTY:
  2880. begin
  2881. handle_unexpected_had_generic;
  2882. if (m_fpc in current_settings.modeswitches) then
  2883. property_dec
  2884. else
  2885. break;
  2886. end;
  2887. _GENERIC:
  2888. begin
  2889. handle_unexpected_had_generic;
  2890. if not (m_delphi in current_settings.modeswitches) then
  2891. begin
  2892. hadgeneric:=true;
  2893. consume(_ID);
  2894. end
  2895. else
  2896. break;
  2897. end
  2898. else
  2899. break;
  2900. end;
  2901. end;
  2902. end;
  2903. until false;
  2904. { check for incomplete class definitions, this is only required
  2905. for fpc modes }
  2906. if (m_fpc in current_settings.modeswitches) then
  2907. symtablestack.top.SymList.ForEachCall(@check_forward_class,nil);
  2908. end;
  2909. end.