psub.pas 116 KB

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