psub.pas 91 KB

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