psub.pas 91 KB

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