optvirt.pas 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. {
  2. Copyright (c) 2008 by Jonas Maebe
  3. Virtual methods optimizations (devirtualization)
  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 optvirt;
  18. {$i fpcdefs.inc}
  19. interface
  20. uses
  21. globtype,
  22. cclasses,
  23. symtype,symdef,
  24. wpobase;
  25. type
  26. { node in an inheritance tree, contains a link to the parent type (if any) and to all
  27. child types
  28. }
  29. tinheritancetreenode = class
  30. private
  31. fdef: tobjectdef;
  32. fparent: tinheritancetreenode;
  33. fchilds: tfpobjectlist;
  34. finstantiated: boolean;
  35. function getchild(index: longint): tinheritancetreenode;
  36. public
  37. constructor create(_parent: tinheritancetreenode; _def: tobjectdef; _instantiated: boolean);
  38. { destroys both this node and all of its siblings }
  39. destructor destroy; override;
  40. function childcount: longint;
  41. function haschilds: boolean;
  42. property childs[index: longint]: tinheritancetreenode read getchild;
  43. property parent: tinheritancetreenode read fparent;
  44. property def: tobjectdef read fdef;
  45. property instantiated: boolean read finstantiated write finstantiated;
  46. { if def is not yet a child of this node, add it. In all cases, return node containing
  47. this def (either new or existing one
  48. }
  49. function maybeaddchild(_def: tobjectdef; _instantiated: boolean): tinheritancetreenode;
  50. end;
  51. tinheritancetreecallback = procedure(node: tinheritancetreenode; arg: pointer) of object;
  52. tinheritancetree = class
  53. private
  54. { just a regular node with parent = nil }
  55. froots: tinheritancetreenode;
  56. classrefdefs: tfpobjectlist;
  57. procedure foreachnodefromroot(root: tinheritancetreenode; proctocall: tinheritancetreecallback; arg: pointer);
  58. function registerinstantiatedobjectdefrecursive(def: tobjectdef; instantiated: boolean): tinheritancetreenode;
  59. procedure markvmethods(node: tinheritancetreenode; p: pointer);
  60. procedure printobjectvmtinfo(node: tinheritancetreenode; arg: pointer);
  61. public
  62. constructor create;
  63. destructor destroy; override;
  64. { adds an objectdef (the def itself, and all of its parents that do not yet exist) to
  65. the tree, and returns the leaf node
  66. }
  67. procedure registerinstantiatedobjdef(def: tdef);
  68. procedure registerinstantiatedclassrefdef(def: tdef);
  69. procedure checkforclassrefinheritance(def: tdef);
  70. procedure foreachnode(proctocall: tinheritancetreecallback; arg: pointer);
  71. procedure foreachleafnode(proctocall: tinheritancetreecallback; arg: pointer);
  72. procedure optimizevirtualmethods;
  73. procedure printvmtinfo;
  74. end;
  75. { devirtualisation information for a class }
  76. tclassdevirtinfo = class(tfphashobject)
  77. private
  78. { array (indexed by vmt entry nr) of replacement statically callable method names }
  79. fstaticmethodnames: tfplist;
  80. { is this class instantiated by the program? }
  81. finstantiated: boolean;
  82. function isstaticvmtentry(vmtindex: longint; out replacementname: pshortstring): boolean;
  83. public
  84. constructor create(hashobjectlist:tfphashobjectlist;const n: shortstring; instantiated: boolean);
  85. destructor destroy; override;
  86. property instantiated: boolean read finstantiated;
  87. procedure addstaticmethod(vmtindex: longint; const replacementname: shortstring);
  88. end;
  89. { devirtualisation information for all classes in a unit }
  90. tunitdevirtinfo = class(tfphashobject)
  91. private
  92. { hashtable of classes }
  93. fclasses: tfphashobjectlist;
  94. public
  95. constructor create(hashobjectlist:tfphashobjectlist;const n: shortstring);reintroduce;
  96. destructor destroy; override;
  97. function addclass(const n: shortstring; instantiated: boolean): tclassdevirtinfo;
  98. function findclass(const n: shortstring): tclassdevirtinfo;
  99. end;
  100. { devirtualisation information for all units in a program }
  101. { tprogdevirtinfo }
  102. tprogdevirtinfo = class(twpodevirtualisationhandler)
  103. private
  104. { hashtable of tunitdevirtinfo (which contain tclassdevirtinfo) }
  105. funits: tfphashobjectlist;
  106. procedure converttreenode(node: tinheritancetreenode; arg: pointer);
  107. function addunitifnew(const n: shortstring): tunitdevirtinfo;
  108. function findunit(const n: shortstring): tunitdevirtinfo;
  109. function getstaticname(forvmtentry: boolean; objdef, procdef: tdef; out staticname: string): boolean;
  110. public
  111. constructor create; override;
  112. destructor destroy; override;
  113. class function getwpotype: twpotype; override;
  114. class function generatesinfoforwposwitches: twpoptimizerswitches; override;
  115. class function performswpoforswitches: twpoptimizerswitches; override;
  116. class function sectionname: shortstring; override;
  117. { information collection }
  118. procedure constructfromcompilerstate; override;
  119. procedure storewpofilesection(writer: twposectionwriterintf); override;
  120. { information providing }
  121. procedure loadfromwpofilesection(reader: twposectionreaderintf); override;
  122. function staticnameforcallingvirtualmethod(objdef, procdef: tdef; out staticname: string): boolean; override;
  123. function staticnameforvmtentry(objdef, procdef: tdef; out staticname: string): boolean; override;
  124. end;
  125. implementation
  126. uses
  127. cutils,
  128. fmodule,
  129. symconst,
  130. symbase,
  131. symtable,
  132. nobj,
  133. verbose;
  134. const
  135. DEVIRT_SECTION_NAME = 'contextinsensitive_devirtualization';
  136. { *************************** tinheritancetreenode ************************* }
  137. constructor tinheritancetreenode.create(_parent: tinheritancetreenode; _def: tobjectdef; _instantiated: boolean);
  138. begin
  139. fparent:=_parent;
  140. fdef:=_def;
  141. finstantiated:=_instantiated;
  142. end;
  143. destructor tinheritancetreenode.destroy;
  144. begin
  145. { fchilds owns its members, so it will free them too }
  146. fchilds.free;
  147. inherited destroy;
  148. end;
  149. function tinheritancetreenode.childcount: longint;
  150. begin
  151. if assigned(fchilds) then
  152. result:=fchilds.count
  153. else
  154. result:=0;
  155. end;
  156. function tinheritancetreenode.haschilds: boolean;
  157. begin
  158. result:=assigned(fchilds)
  159. end;
  160. function tinheritancetreenode.getchild(index: longint): tinheritancetreenode;
  161. begin
  162. result:=tinheritancetreenode(fchilds[index]);
  163. end;
  164. function tinheritancetreenode.maybeaddchild(_def: tobjectdef; _instantiated: boolean): tinheritancetreenode;
  165. var
  166. i: longint;
  167. begin
  168. { sanity check }
  169. if assigned(_def.childof) then
  170. begin
  171. if (_def.childof<>def) then
  172. internalerror(2008092201);
  173. end
  174. else if assigned(fparent) then
  175. internalerror(2008092202);
  176. if not assigned(fchilds) then
  177. fchilds:=tfpobjectlist.create(true);
  178. { def already a child -> return }
  179. for i := 0 to fchilds.count-1 do
  180. if (tinheritancetreenode(fchilds[i]).def=_def) then
  181. begin
  182. result:=tinheritancetreenode(fchilds[i]);
  183. result.finstantiated:=result.finstantiated or _instantiated;
  184. exit;
  185. end;
  186. { not found, add new child }
  187. result:=tinheritancetreenode.create(self,_def,_instantiated);
  188. fchilds.add(result);
  189. end;
  190. { *************************** tinheritancetree ************************* }
  191. constructor tinheritancetree.create;
  192. begin
  193. froots:=tinheritancetreenode.create(nil,nil,false);
  194. classrefdefs:=tfpobjectlist.create(false);
  195. end;
  196. destructor tinheritancetree.destroy;
  197. begin
  198. froots.free;
  199. classrefdefs.free;
  200. inherited destroy;
  201. end;
  202. function tinheritancetree.registerinstantiatedobjectdefrecursive(def: tobjectdef; instantiated: boolean): tinheritancetreenode;
  203. begin
  204. if assigned(def.childof) then
  205. begin
  206. { recursively add parent, of which we have no info about whether or not it is
  207. instantiated at this point -> default to false (will be overridden by "true"
  208. if this class is instantioted, since then registerinstantiatedobjdef() will
  209. be called for this class as well)
  210. }
  211. result:=registerinstantiatedobjectdefrecursive(def.childof,false);
  212. { and add ourselves to the parent }
  213. result:=result.maybeaddchild(def,instantiated);
  214. end
  215. else
  216. { add ourselves to the roots }
  217. result:=froots.maybeaddchild(def,instantiated);
  218. end;
  219. procedure tinheritancetree.registerinstantiatedobjdef(def: tdef);
  220. begin
  221. { add the def }
  222. if (def.typ=objectdef) then
  223. registerinstantiatedobjectdefrecursive(tobjectdef(def),true)
  224. else
  225. internalerror(2008092401);
  226. end;
  227. procedure tinheritancetree.registerinstantiatedclassrefdef(def: tdef);
  228. begin
  229. { queue for later checking (these are the objectdefs
  230. to which the classrefdefs point) }
  231. if (def.typ=objectdef) then
  232. classrefdefs.add(def)
  233. else
  234. internalerror(2008101401);
  235. end;
  236. procedure tinheritancetree.checkforclassrefinheritance(def: tdef);
  237. var
  238. i: longint;
  239. begin
  240. if (def.typ=objectdef) then
  241. begin
  242. {$ifdef debug_devirt}
  243. write(' Checking for classrefdef inheritance of ',def.typename);
  244. {$endif debug_devirt}
  245. for i:=0 to classrefdefs.count-1 do
  246. if tobjectdef(def).is_related(tobjectdef(classrefdefs[i])) then
  247. begin
  248. {$ifdef debug_devirt}
  249. writeln('... Found: inherits from Class Of ',tobjectdef(classrefdefs[i]).typename);
  250. {$endif debug_devirt}
  251. registerinstantiatedobjdef(def);
  252. exit;
  253. end;
  254. {$ifdef debug_devirt}
  255. writeln('... Not found!');
  256. {$endif debug_devirt}
  257. end;
  258. end;
  259. procedure tinheritancetree.foreachnodefromroot(root: tinheritancetreenode; proctocall: tinheritancetreecallback; arg: pointer);
  260. procedure process(const node: tinheritancetreenode);
  261. var
  262. i: longint;
  263. begin
  264. for i:=0 to node.childcount-1 do
  265. if node.childs[i].haschilds then
  266. begin
  267. proctocall(node.childs[i],arg);
  268. process(node.childs[i])
  269. end
  270. else
  271. proctocall(node.childs[i],arg);
  272. end;
  273. begin
  274. process(root);
  275. end;
  276. procedure tinheritancetree.foreachnode(proctocall: tinheritancetreecallback; arg: pointer);
  277. begin
  278. foreachnodefromroot(froots,proctocall,arg);
  279. end;
  280. procedure tinheritancetree.foreachleafnode(proctocall: tinheritancetreecallback; arg: pointer);
  281. procedure process(const node: tinheritancetreenode);
  282. var
  283. i: longint;
  284. begin
  285. for i:=0 to node.childcount-1 do
  286. if node.childs[i].haschilds then
  287. process(node.childs[i])
  288. else
  289. proctocall(node.childs[i],arg);
  290. end;
  291. begin
  292. process(froots);
  293. end;
  294. procedure tinheritancetree.markvmethods(node: tinheritancetreenode; p: pointer);
  295. var
  296. currnode: tinheritancetreenode;
  297. pd: tobject;
  298. i: longint;
  299. makeallvirtual: boolean;
  300. begin
  301. {$IFDEF DEBUG_DEVIRT}
  302. writeln('processing leaf node ',node.def.typename);
  303. {$ENDIF}
  304. { todo: also process interfaces (ImplementedInterfaces) }
  305. if not assigned(node.def.vmtentries) then
  306. exit;
  307. { process all vmt entries for this class/object }
  308. for i:=0 to node.def.vmtentries.count-1 do
  309. begin
  310. currnode:=node;
  311. pd:=currnode.def.vmtentries[i];
  312. { abstract methods cannot be called directly }
  313. if (po_abstractmethod in tprocdef(pd).procoptions) then
  314. continue;
  315. {$IFDEF DEBUG_DEVIRT}
  316. writeln(' method ',tprocdef(pd).typename);
  317. {$ENDIF}
  318. { Now mark all virtual methods static that are the same in parent
  319. classes as in this instantiated child class (only instantiated
  320. classes can be leaf nodes, since only instantiated classes were
  321. added to the tree).
  322. If a first child does not override a parent method while a
  323. a second one does, the first will mark it as statically
  324. callable, but the second will set it to not statically callable.
  325. In the opposite situation, the first will mark it as not
  326. statically callable and the second will leave it alone.
  327. }
  328. makeallvirtual:=false;
  329. repeat
  330. { this parent may not have any virtual methods }
  331. if not assigned(currnode.def.vmtentries) or
  332. { stop when this method does not exist in a parent }
  333. (currnode.def.vmtentries.count<=i) then
  334. break;
  335. if not assigned(currnode.def.vmcallstaticinfo) then
  336. currnode.def.vmcallstaticinfo:=allocmem(currnode.def.vmtentries.count*sizeof(tvmcallstatic));
  337. { same procdef as in all instantiated childs? (yes or don't know) }
  338. if (currnode.def.vmcallstaticinfo^[i] in [vmcs_default,vmcs_yes]) then
  339. begin
  340. { methods in uninstantiated classes can be made static if
  341. they are the same in all instantiated derived classes
  342. }
  343. if ((currnode.def.vmtentries[i]=pd) or
  344. (not currnode.instantiated and
  345. (currnode.def.vmcallstaticinfo^[i]=vmcs_default))) and
  346. not makeallvirtual then
  347. begin
  348. {$IFDEF DEBUG_DEVIRT}
  349. writeln(' marking as static for ',currnode.def.typename);
  350. {$ENDIF}
  351. currnode.def.vmcallstaticinfo^[i]:=vmcs_yes;
  352. { this is in case of a non-instantiated parent of an instantiated child:
  353. the method declared in the child will always be called here
  354. }
  355. currnode.def.vmtentries[i]:=pd;
  356. end
  357. else
  358. begin
  359. {$IFDEF DEBUG_DEVIRT}
  360. writeln(' marking as non-static for ',currnode.def.typename);
  361. {$ENDIF}
  362. { this vmt entry must also remain virtual for all parents }
  363. makeallvirtual:=true;
  364. currnode.def.vmcallstaticinfo^[i]:=vmcs_no;
  365. end;
  366. currnode:=currnode.parent;
  367. end
  368. else
  369. begin
  370. {$IFDEF DEBUG_DEVIRT}
  371. writeln(' not processing parents, already non-static for ',currnode.def.typename);
  372. {$ENDIF}
  373. { parents are already set to vmcs_no, so no need to continue }
  374. currnode:=nil;
  375. end;
  376. until not assigned(currnode) or
  377. not assigned(currnode.def);
  378. end;
  379. end;
  380. procedure tinheritancetree.optimizevirtualmethods;
  381. begin
  382. foreachleafnode(@markvmethods,nil);
  383. end;
  384. procedure tinheritancetree.printobjectvmtinfo(node: tinheritancetreenode; arg: pointer);
  385. var
  386. i,
  387. totaldevirtualised,
  388. totalvirtual: ptrint;
  389. begin
  390. totaldevirtualised:=0;
  391. totalvirtual:=0;
  392. writeln(node.def.typename);
  393. if not assigned(node.def.vmtentries) then
  394. begin
  395. writeln(' No virtual methods!');
  396. exit;
  397. end;
  398. for i:=0 to node.def.vmtentries.count-1 do
  399. if (po_virtualmethod in tabstractprocdef(node.def.vmtentries[i]).procoptions) then
  400. begin
  401. inc(totalvirtual);
  402. if (node.def.vmcallstaticinfo^[i]=vmcs_yes) then
  403. begin
  404. inc(totaldevirtualised);
  405. writeln(' Devirtualised: ',tabstractprocdef(node.def.vmtentries[i]).typename);
  406. end;
  407. end;
  408. writeln('Total devirtualised: ',totaldevirtualised,'/',totalvirtual);
  409. writeln;
  410. end;
  411. procedure tinheritancetree.printvmtinfo;
  412. begin
  413. foreachnode(@printobjectvmtinfo,nil);
  414. end;
  415. { helper routines: decompose an object & procdef combo into a unitname, class name and vmtentry number
  416. (unit name where the objectdef is declared, class name of the objectdef, vmtentry number of the
  417. procdef -- procdef does not necessarily belong to objectdef, it may also belong to a descendant
  418. or parent)
  419. }
  420. procedure defunitclassname(objdef: tobjectdef; out unitname, classname: pshortstring);
  421. const
  422. mainprogname: string[2] = 'P$';
  423. var
  424. mainsymtab,
  425. objparentsymtab : tsymtable;
  426. begin
  427. objparentsymtab:=objdef.symtable;
  428. mainsymtab:=objparentsymtab.defowner.owner;
  429. { main symtable must be static or global }
  430. if not(mainsymtab.symtabletype in [staticsymtable,globalsymtable]) then
  431. internalerror(200204175);
  432. if (TSymtable(main_module.localsymtable)=mainsymtab) and
  433. (not main_module.is_unit) then
  434. { same convention as for mangled names }
  435. unitname:=@mainprogname
  436. else
  437. unitname:=mainsymtab.name;
  438. classname:=tobjectdef(objparentsymtab.defowner).objname;
  439. end;
  440. procedure defsdecompose(objdef: tobjectdef; procdef: tprocdef; out unitname, classname: pshortstring; out vmtentry: longint);
  441. begin
  442. defunitclassname(objdef,unitname,classname);
  443. vmtentry:=procdef.extnumber;
  444. { if it's $ffff, this is not a valid virtual method }
  445. if (vmtentry=$ffff) then
  446. internalerror(2008100509);
  447. end;
  448. { tclassdevirtinfo }
  449. constructor tclassdevirtinfo.create(hashobjectlist:tfphashobjectlist;const n: shortstring; instantiated: boolean);
  450. begin
  451. inherited create(hashobjectlist,n);
  452. finstantiated:=instantiated;
  453. fstaticmethodnames:=tfplist.create;
  454. end;
  455. destructor tclassdevirtinfo.destroy;
  456. var
  457. i: longint;
  458. begin
  459. for i:=0 to fstaticmethodnames.count-1 do
  460. if assigned(fstaticmethodnames[i]) then
  461. freemem(fstaticmethodnames[i]);
  462. fstaticmethodnames.free;
  463. inherited destroy;
  464. end;
  465. procedure tclassdevirtinfo.addstaticmethod(vmtindex: longint;
  466. const replacementname: shortstring);
  467. begin
  468. if (vmtindex>=fstaticmethodnames.count) then
  469. fstaticmethodnames.Count:=vmtindex+10;
  470. fstaticmethodnames[vmtindex]:=stringdup(replacementname);
  471. end;
  472. function tclassdevirtinfo.isstaticvmtentry(vmtindex: longint; out
  473. replacementname: pshortstring): boolean;
  474. begin
  475. result:=false;
  476. if (vmtindex>=fstaticmethodnames.count) then
  477. exit;
  478. replacementname:=fstaticmethodnames[vmtindex];
  479. result:=assigned(replacementname);
  480. end;
  481. { tunitdevirtinfo }
  482. constructor tunitdevirtinfo.create(hashobjectlist:tfphashobjectlist;const n: shortstring);
  483. begin
  484. inherited create(hashobjectlist,n);
  485. fclasses:=tfphashobjectlist.create(true);
  486. end;
  487. destructor tunitdevirtinfo.destroy;
  488. begin
  489. fclasses.free;
  490. inherited destroy;
  491. end;
  492. function tunitdevirtinfo.addclass(const n: shortstring; instantiated: boolean): tclassdevirtinfo;
  493. begin
  494. result:=findclass(n);
  495. { can't have two classes with the same name in a single unit }
  496. if assigned(result) then
  497. internalerror(2008100501);
  498. result:=tclassdevirtinfo.create(fclasses,n,instantiated);
  499. end;
  500. function tunitdevirtinfo.findclass(const n: shortstring): tclassdevirtinfo;
  501. begin
  502. result:=tclassdevirtinfo(fclasses.find(n));
  503. end;
  504. { tprogdevirtinfo }
  505. procedure tprogdevirtinfo.converttreenode(node: tinheritancetreenode; arg: pointer);
  506. var
  507. i: longint;
  508. unitid, classid: pshortstring;
  509. unitdevirtinfo: tunitdevirtinfo;
  510. classdevirtinfo: tclassdevirtinfo;
  511. begin
  512. if (not node.instantiated) and
  513. not assigned(node.def.vmtentries) then
  514. exit;
  515. { always add a class entry for an instantiated class, so we can
  516. fill the vmt's of non-instantiated classes with calls to
  517. FPC_ABSTRACTERROR during the optimisation phase
  518. }
  519. defunitclassname(node.def,unitid,classid);
  520. unitdevirtinfo:=addunitifnew(unitid^);
  521. classdevirtinfo:=unitdevirtinfo.addclass(classid^,node.instantiated);
  522. if not assigned(node.def.vmtentries) then
  523. exit;
  524. for i:=0 to node.def.vmtentries.count-1 do
  525. if (po_virtualmethod in tabstractprocdef(node.def.vmtentries[i]).procoptions) and
  526. (node.def.vmcallstaticinfo^[i]=vmcs_yes) then
  527. begin
  528. { add info about devirtualised vmt entry }
  529. classdevirtinfo.addstaticmethod(i,tprocdef(node.def.vmtentries[i]).mangledname);
  530. end;
  531. end;
  532. constructor tprogdevirtinfo.create;
  533. begin
  534. inherited create;
  535. end;
  536. destructor tprogdevirtinfo.destroy;
  537. begin
  538. funits.free;
  539. inherited destroy;
  540. end;
  541. class function tprogdevirtinfo.getwpotype: twpotype;
  542. begin
  543. result:=wpo_devirtualization_context_insensitive;
  544. end;
  545. class function tprogdevirtinfo.generatesinfoforwposwitches: twpoptimizerswitches;
  546. begin
  547. result:=[cs_wpo_devirtualize_calls,cs_wpo_optimize_vmts];
  548. end;
  549. class function tprogdevirtinfo.performswpoforswitches: twpoptimizerswitches;
  550. begin
  551. result:=[cs_wpo_devirtualize_calls,cs_wpo_optimize_vmts];
  552. end;
  553. class function tprogdevirtinfo.sectionname: shortstring;
  554. begin
  555. result:=DEVIRT_SECTION_NAME;
  556. end;
  557. procedure reset_all_impl_defs;
  558. procedure reset_used_unit_impl_defs(hp:tmodule);
  559. var
  560. pu : tused_unit;
  561. begin
  562. pu:=tused_unit(hp.used_units.first);
  563. while assigned(pu) do
  564. begin
  565. if not pu.u.is_reset then
  566. begin
  567. { prevent infinte loop for circular dependencies }
  568. pu.u.is_reset:=true;
  569. if assigned(pu.u.localsymtable) then
  570. begin
  571. tstaticsymtable(pu.u.localsymtable).reset_all_defs;
  572. reset_used_unit_impl_defs(pu.u);
  573. end;
  574. end;
  575. pu:=tused_unit(pu.next);
  576. end;
  577. end;
  578. var
  579. hp2 : tmodule;
  580. begin
  581. hp2:=tmodule(loaded_units.first);
  582. while assigned(hp2) do
  583. begin
  584. hp2.is_reset:=false;
  585. hp2:=tmodule(hp2.next);
  586. end;
  587. reset_used_unit_impl_defs(current_module);
  588. end;
  589. procedure tprogdevirtinfo.constructfromcompilerstate;
  590. var
  591. hp: tmodule;
  592. i: longint;
  593. inheritancetree: tinheritancetree;
  594. begin
  595. { the compiler already resets all interface defs after every unit
  596. compilation, but not the implementation defs (because this is only
  597. done for the purpose of writing debug info, and you can never see
  598. a type defined in the implementation of one unit in another unit).
  599. Here, we want to record all classes constructed anywhere in the
  600. program, also if those class(ref) types are defined in the
  601. implementation of a unit. So reset the state of all defs in
  602. implementation sections before starting the collection process. }
  603. reset_all_impl_defs;
  604. { register all instantiated class/object types }
  605. hp:=tmodule(loaded_units.first);
  606. while assigned(hp) do
  607. begin
  608. if assigned(hp.wpoinfo.createdobjtypes) then
  609. for i:=0 to hp.wpoinfo.createdobjtypes.count-1 do
  610. tdef(hp.wpoinfo.createdobjtypes[i]).register_created_object_type;
  611. if assigned(hp.wpoinfo.createdclassrefobjtypes) then
  612. for i:=0 to hp.wpoinfo.createdclassrefobjtypes.count-1 do
  613. tobjectdef(hp.wpoinfo.createdclassrefobjtypes[i]).register_created_classref_type;
  614. if assigned(hp.wpoinfo.maybecreatedbyclassrefdeftypes) then
  615. for i:=0 to hp.wpoinfo.maybecreatedbyclassrefdeftypes.count-1 do
  616. tobjectdef(hp.wpoinfo.maybecreatedbyclassrefdeftypes[i]).register_maybe_created_object_type;
  617. hp:=tmodule(hp.next);
  618. end;
  619. inheritancetree:=tinheritancetree.create;
  620. { add all constructed class/object types to the tree }
  621. {$IFDEF DEBUG_DEVIRT}
  622. writeln('constructed object/class/classreftypes in ',current_module.realmodulename^);
  623. {$ENDIF}
  624. for i := 0 to current_module.wpoinfo.createdobjtypes.count-1 do
  625. begin
  626. inheritancetree.registerinstantiatedobjdef(tdef(current_module.wpoinfo.createdobjtypes[i]));
  627. {$IFDEF DEBUG_DEVIRT}
  628. write(' ',tdef(current_module.wpoinfo.createdobjtypes[i]).GetTypeName);
  629. {$ENDIF}
  630. case tdef(current_module.wpoinfo.createdobjtypes[i]).typ of
  631. objectdef:
  632. case tobjectdef(current_module.wpoinfo.createdobjtypes[i]).objecttype of
  633. odt_object:
  634. {$IFDEF DEBUG_DEVIRT}
  635. writeln(' (object)')
  636. {$ENDIF}
  637. ;
  638. odt_class:
  639. {$IFDEF DEBUG_DEVIRT}
  640. writeln(' (class)')
  641. {$ENDIF}
  642. ;
  643. else
  644. internalerror(2008092101);
  645. end;
  646. else
  647. internalerror(2008092102);
  648. end;
  649. end;
  650. { register all instantiated classrefdefs with the tree }
  651. for i := 0 to current_module.wpoinfo.createdclassrefobjtypes.count-1 do
  652. begin
  653. inheritancetree.registerinstantiatedclassrefdef(tdef(current_module.wpoinfo.createdclassrefobjtypes[i]));
  654. {$IFDEF DEBUG_DEVIRT}
  655. write(' Class Of ',tdef(current_module.wpoinfo.createdclassrefobjtypes[i]).GetTypeName);
  656. {$ENDIF}
  657. case tdef(current_module.wpoinfo.createdclassrefobjtypes[i]).typ of
  658. objectdef:
  659. {$IFDEF DEBUG_DEVIRT}
  660. writeln(' (classrefdef)')
  661. {$ENDIF}
  662. ;
  663. else
  664. internalerror(2008101101);
  665. end;
  666. end;
  667. { now add all objectdefs that are referred somewhere (via a
  668. loadvmtaddr node) and that are derived from an instantiated
  669. classrefdef to the tree (as they can, in theory, all
  670. be instantiated as well)
  671. }
  672. for i := 0 to current_module.wpoinfo.maybecreatedbyclassrefdeftypes.count-1 do
  673. begin
  674. inheritancetree.checkforclassrefinheritance(tdef(current_module.wpoinfo.maybecreatedbyclassrefdeftypes[i]));
  675. {$IFDEF DEBUG_DEVIRT}
  676. write(' Class Of ',tdef(current_module.wpoinfo.maybecreatedbyclassrefdeftypes[i]).GetTypeName);
  677. {$ENDIF}
  678. case tdef(current_module.wpoinfo.maybecreatedbyclassrefdeftypes[i]).typ of
  679. objectdef:
  680. {$IFDEF DEBUG_DEVIRT}
  681. writeln(' (classrefdef)')
  682. {$ENDIF}
  683. ;
  684. else
  685. internalerror(2008101101);
  686. end;
  687. end;
  688. inheritancetree.optimizevirtualmethods;
  689. {$ifdef DEBUG_DEVIRT}
  690. inheritancetree.printvmtinfo;
  691. {$endif DEBUG_DEVIRT}
  692. inheritancetree.foreachnode(@converttreenode,nil);
  693. inheritancetree.free;
  694. end;
  695. function tprogdevirtinfo.addunitifnew(const n: shortstring): tunitdevirtinfo;
  696. begin
  697. if assigned(funits) then
  698. result:=findunit(n)
  699. else
  700. begin
  701. funits:=tfphashobjectlist.create;
  702. result:=nil;
  703. end;
  704. if not assigned(result) then
  705. begin
  706. result:=tunitdevirtinfo.create(funits,n);
  707. end;
  708. end;
  709. function tprogdevirtinfo.findunit(const n: shortstring): tunitdevirtinfo;
  710. begin
  711. result:=tunitdevirtinfo(funits.find(n));
  712. end;
  713. procedure tprogdevirtinfo.loadfromwpofilesection(reader: twposectionreaderintf);
  714. var
  715. unitid,
  716. classid,
  717. vmtentryname: string;
  718. vmttype: string[15];
  719. vmtentrynrstr: string[7];
  720. classinstantiated: string[1];
  721. vmtentry, error: longint;
  722. unitdevirtinfo: tunitdevirtinfo;
  723. classdevirtinfo: tclassdevirtinfo;
  724. instantiated: boolean;
  725. begin
  726. { format:
  727. # unitname^
  728. unit1^
  729. # classname&
  730. class1&
  731. # instantiated?
  732. 1
  733. # vmt type (base or some interface)
  734. basevmt
  735. # vmt entry nr
  736. 0
  737. # name of routine to call instead
  738. staticvmtentryforslot0
  739. 5
  740. staticvmtentryforslot5
  741. intfvmt1
  742. 0
  743. staticvmtentryforslot0
  744. # non-instantiated class (but if we encounter a variable of this
  745. # type, we can optimise class to vmtentry 1)
  746. class2&
  747. 0
  748. basevmt
  749. 1
  750. staticvmtentryforslot1
  751. # instantiated class without optimisable virtual methods
  752. class3&
  753. 1
  754. unit2^
  755. 1
  756. class3&
  757. ...
  758. currently, only basevmt is supported (no interfaces yet)
  759. }
  760. { could be empty if no classes or so }
  761. if not reader.sectiongetnextline(unitid) then
  762. exit;
  763. repeat
  764. if (unitid='') or
  765. (unitid[length(unitid)]<>'^') then
  766. internalerror(2008100502);
  767. { cut off the trailing ^ }
  768. setlength(unitid,length(unitid)-1);
  769. unitdevirtinfo:=addunitifnew(unitid);
  770. { now read classes }
  771. if not reader.sectiongetnextline(classid) then
  772. internalerror(2008100505);
  773. repeat
  774. if (classid='') or
  775. (classid[length(classid)]<>'&') then
  776. internalerror(2008100503);
  777. { instantiated? }
  778. if not reader.sectiongetnextline(classinstantiated) then
  779. internalerror(2008101901);
  780. instantiated:=classinstantiated='1';
  781. { cut off the trailing & }
  782. setlength(classid,length(classid)-1);
  783. classdevirtinfo:=unitdevirtinfo.addclass(classid,instantiated);
  784. if not reader.sectiongetnextline(vmttype) then
  785. internalerror(2008100506);
  786. { any optimisable virtual methods? }
  787. if (vmttype<>'') then
  788. begin
  789. { interface info is not yet supported }
  790. if (vmttype<>'basevmt') then
  791. internalerror(2008100507);
  792. { read all vmt entries for this class }
  793. while reader.sectiongetnextline(vmtentrynrstr) and
  794. (vmtentrynrstr<>'') do
  795. begin
  796. val(vmtentrynrstr,vmtentry,error);
  797. if (error<>0) then
  798. internalerror(2008100504);
  799. if not reader.sectiongetnextline(vmtentryname) or
  800. (vmtentryname='') then
  801. internalerror(2008100508);
  802. classdevirtinfo.addstaticmethod(vmtentry,vmtentryname);
  803. end;
  804. end;
  805. { end of section -> exit }
  806. if not(reader.sectiongetnextline(classid)) then
  807. exit;
  808. until (classid='') or
  809. (classid[length(classid)]='^');
  810. { next unit, or error }
  811. unitid:=classid;
  812. until false;
  813. end;
  814. procedure tprogdevirtinfo.storewpofilesection(writer: twposectionwriterintf);
  815. var
  816. unitcount,
  817. classcount,
  818. vmtentrycount: longint;
  819. unitdevirtinfo: tunitdevirtinfo;
  820. classdevirtinfo: tclassdevirtinfo;
  821. first: boolean;
  822. begin
  823. { if there are no optimised virtual methods, we have stored no info }
  824. if not assigned(funits) then
  825. exit;
  826. writer.startsection(DEVIRT_SECTION_NAME);
  827. for unitcount:=0 to funits.count-1 do
  828. begin
  829. unitdevirtinfo:=tunitdevirtinfo(funits[unitcount]);
  830. writer.sectionputline(unitdevirtinfo.name+'^');
  831. for classcount:=0 to unitdevirtinfo.fclasses.count-1 do
  832. begin
  833. classdevirtinfo:=tclassdevirtinfo(tunitdevirtinfo(funits[unitcount]).fclasses[classcount]);
  834. writer.sectionputline(classdevirtinfo.name+'&');
  835. writer.sectionputline(tostr(ord(classdevirtinfo.instantiated)));
  836. first:=true;
  837. for vmtentrycount:=0 to classdevirtinfo.fstaticmethodnames.count-1 do
  838. if assigned(classdevirtinfo.fstaticmethodnames[vmtentrycount]) then
  839. begin
  840. if first then
  841. begin
  842. writer.sectionputline('basevmt');
  843. first:=false;
  844. end;
  845. writer.sectionputline(tostr(vmtentrycount));
  846. writer.sectionputline(pshortstring(classdevirtinfo.fstaticmethodnames[vmtentrycount])^);
  847. end;
  848. writer.sectionputline('');
  849. end;
  850. end;
  851. end;
  852. function tprogdevirtinfo.getstaticname(forvmtentry: boolean; objdef, procdef: tdef; out staticname: string): boolean;
  853. var
  854. unitid,
  855. classid,
  856. newname: pshortstring;
  857. unitdevirtinfo: tunitdevirtinfo;
  858. classdevirtinfo: tclassdevirtinfo;
  859. vmtentry: longint;
  860. realobjdef: tobjectdef;
  861. begin
  862. { class methods are in the regular vmt, so we can handle classrefs
  863. the same way as plain objectdefs
  864. }
  865. if (objdef.typ=classrefdef) then
  866. realobjdef:=tobjectdef(tclassrefdef(objdef).pointeddef)
  867. else if (objdef.typ=objectdef) and
  868. (tobjectdef(objdef).objecttype in [odt_class,odt_object]) then
  869. realobjdef:=tobjectdef(objdef)
  870. else
  871. begin
  872. { we don't support interfaces yet }
  873. result:=false;
  874. exit;
  875. end;
  876. { get the component names for the class/procdef combo }
  877. defsdecompose(realobjdef,tprocdef(procdef),unitid,classid,vmtentry);
  878. { do we have any info for this unit? }
  879. unitdevirtinfo:=findunit(unitid^);
  880. result:=false;
  881. if not assigned(unitdevirtinfo) then
  882. exit;
  883. { and for this class? }
  884. classdevirtinfo:=unitdevirtinfo.findclass(classid^);
  885. if not assigned(classdevirtinfo) then
  886. exit;
  887. { if it's for a vmtentry of an objdef and the objdef is
  888. not instantiated, then we can fill the vmt with pointers
  889. to FPC_ABSTRACTERROR
  890. }
  891. if forvmtentry and
  892. (objdef.typ=objectdef) and
  893. not classdevirtinfo.instantiated and
  894. { virtual class methods can be called even if the class is not instantiated }
  895. not(po_classmethod in tprocdef(procdef).procoptions) then
  896. begin
  897. staticname:='FPC_ABSTRACTERROR';
  898. result:=true;
  899. end
  900. else
  901. begin
  902. { now check whether it can be devirtualised, and if so to what }
  903. result:=classdevirtinfo.isstaticvmtentry(vmtentry,newname);
  904. if result then
  905. staticname:=newname^;
  906. end;
  907. end;
  908. function tprogdevirtinfo.staticnameforcallingvirtualmethod(objdef, procdef: tdef; out staticname: string): boolean;
  909. begin
  910. result:=getstaticname(false,objdef,procdef,staticname);
  911. end;
  912. function tprogdevirtinfo.staticnameforvmtentry(objdef, procdef: tdef; out staticname: string): boolean;
  913. begin
  914. result:=getstaticname(true,objdef,procdef,staticname);
  915. end;
  916. end.