psub.pas 89 KB

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