psub.pas 92 KB

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