psub.pas 90 KB

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