psub.pas 126 KB

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