2
0

psub.pas 106 KB

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