psub.pas 108 KB

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