psub.pas 131 KB

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