psub.pas 84 KB

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