optvirt.pas 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  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. hp:=tmodule(hp.next);
  615. end;
  616. inheritancetree:=tinheritancetree.create;
  617. {$IFDEF DEBUG_DEVIRT}
  618. writeln('constructed object/class/classreftypes in ',current_module.realmodulename^);
  619. {$ENDIF}
  620. for i := 0 to current_module.wpoinfo.createdobjtypes.count-1 do
  621. begin
  622. inheritancetree.registerinstantiatedobjdef(tdef(current_module.wpoinfo.createdobjtypes[i]));
  623. {$IFDEF DEBUG_DEVIRT}
  624. write(' ',tdef(current_module.wpoinfo.createdobjtypes[i]).GetTypeName);
  625. {$ENDIF}
  626. case tdef(current_module.wpoinfo.createdobjtypes[i]).typ of
  627. objectdef:
  628. case tobjectdef(current_module.wpoinfo.createdobjtypes[i]).objecttype of
  629. odt_object:
  630. {$IFDEF DEBUG_DEVIRT}
  631. writeln(' (object)')
  632. {$ENDIF}
  633. ;
  634. odt_class:
  635. {$IFDEF DEBUG_DEVIRT}
  636. writeln(' (class)')
  637. {$ENDIF}
  638. ;
  639. else
  640. internalerror(2008092101);
  641. end;
  642. else
  643. internalerror(2008092102);
  644. end;
  645. end;
  646. for i := 0 to current_module.wpoinfo.createdclassrefobjtypes.count-1 do
  647. begin
  648. inheritancetree.registerinstantiatedclassrefdef(tdef(current_module.wpoinfo.createdclassrefobjtypes[i]));
  649. {$IFDEF DEBUG_DEVIRT}
  650. write(' Class Of ',tdef(current_module.wpoinfo.createdclassrefobjtypes[i]).GetTypeName);
  651. {$ENDIF}
  652. case tdef(current_module.wpoinfo.createdclassrefobjtypes[i]).typ of
  653. objectdef:
  654. {$IFDEF DEBUG_DEVIRT}
  655. writeln(' (classrefdef)')
  656. {$ENDIF}
  657. ;
  658. else
  659. internalerror(2008101101);
  660. end;
  661. end;
  662. { now add all objectdefs derived from the instantiated
  663. classrefdefs to the tree (as they can, in theory, all
  664. be instantiated as well)
  665. }
  666. hp:=tmodule(loaded_units.first);
  667. while assigned(hp) do
  668. begin
  669. { we cannot just walk over the module's deflists, because a bunch of
  670. the defs in there don't exist anymore (when destroyed, they're
  671. removed from their symtable but not from the module's deflist)
  672. procedure-local (or class-local) class definitions do not (yet)
  673. exit, so it's enough to just walk the global and local symtables
  674. }
  675. { globalsymtable (interface), is nil for main program itself }
  676. if assigned(hp.globalsymtable) then
  677. for i:=0 to hp.globalsymtable.deflist.count-1 do
  678. inheritancetree.checkforclassrefinheritance(tdef(hp.globalsymtable.deflist[i]));
  679. { staticsymtable (implementation), is nil for units with nothing
  680. in the implementation }
  681. if assigned(hp.localsymtable) then
  682. for i:=0 to hp.localsymtable.deflist.count-1 do
  683. inheritancetree.checkforclassrefinheritance(tdef(hp.localsymtable.deflist[i]));
  684. hp:=tmodule(hp.next);
  685. end;
  686. inheritancetree.optimizevirtualmethods;
  687. {$ifdef DEBUG_DEVIRT}
  688. inheritancetree.printvmtinfo;
  689. {$endif DEBUG_DEVIRT}
  690. inheritancetree.foreachnode(@converttreenode,nil);
  691. inheritancetree.free;
  692. end;
  693. function tprogdevirtinfo.addunitifnew(const n: shortstring): tunitdevirtinfo;
  694. begin
  695. if assigned(funits) then
  696. result:=findunit(n)
  697. else
  698. begin
  699. funits:=tfphashobjectlist.create;
  700. result:=nil;
  701. end;
  702. if not assigned(result) then
  703. begin
  704. result:=tunitdevirtinfo.create(funits,n);
  705. end;
  706. end;
  707. function tprogdevirtinfo.findunit(const n: shortstring): tunitdevirtinfo;
  708. begin
  709. result:=tunitdevirtinfo(funits.find(n));
  710. end;
  711. procedure tprogdevirtinfo.loadfromwpofilesection(reader: twposectionreaderintf);
  712. var
  713. unitid,
  714. classid,
  715. vmtentryname: string;
  716. vmttype: string[15];
  717. vmtentrynrstr: string[7];
  718. classinstantiated: string[1];
  719. vmtentry, error: longint;
  720. unitdevirtinfo: tunitdevirtinfo;
  721. classdevirtinfo: tclassdevirtinfo;
  722. instantiated: boolean;
  723. begin
  724. { format:
  725. # unitname^
  726. unit1^
  727. # classname&
  728. class1&
  729. # instantiated?
  730. 1
  731. # vmt type (base or some interface)
  732. basevmt
  733. # vmt entry nr
  734. 0
  735. # name of routine to call instead
  736. staticvmtentryforslot0
  737. 5
  738. staticvmtentryforslot5
  739. intfvmt1
  740. 0
  741. staticvmtentryforslot0
  742. # non-instantiated class (but if we encounter a variable of this
  743. # type, we can optimise class to vmtentry 1)
  744. class2&
  745. 0
  746. basevmt
  747. 1
  748. staticvmtentryforslot1
  749. # instantiated class without optimisable virtual methods
  750. class3&
  751. 1
  752. unit2^
  753. 1
  754. class3&
  755. ...
  756. currently, only basevmt is supported (no interfaces yet)
  757. }
  758. { could be empty if no classes or so }
  759. if not reader.sectiongetnextline(unitid) then
  760. exit;
  761. repeat
  762. if (unitid='') or
  763. (unitid[length(unitid)]<>'^') then
  764. internalerror(2008100502);
  765. { cut off the trailing ^ }
  766. setlength(unitid,length(unitid)-1);
  767. unitdevirtinfo:=addunitifnew(unitid);
  768. { now read classes }
  769. if not reader.sectiongetnextline(classid) then
  770. internalerror(2008100505);
  771. repeat
  772. if (classid='') or
  773. (classid[length(classid)]<>'&') then
  774. internalerror(2008100503);
  775. { instantiated? }
  776. if not reader.sectiongetnextline(classinstantiated) then
  777. internalerror(2008101901);
  778. instantiated:=classinstantiated='1';
  779. { cut off the trailing & }
  780. setlength(classid,length(classid)-1);
  781. classdevirtinfo:=unitdevirtinfo.addclass(classid,instantiated);
  782. if not reader.sectiongetnextline(vmttype) then
  783. internalerror(2008100506);
  784. { any optimisable virtual methods? }
  785. if (vmttype<>'') then
  786. begin
  787. { interface info is not yet supported }
  788. if (vmttype<>'basevmt') then
  789. internalerror(2008100507);
  790. { read all vmt entries for this class }
  791. while reader.sectiongetnextline(vmtentrynrstr) and
  792. (vmtentrynrstr<>'') do
  793. begin
  794. val(vmtentrynrstr,vmtentry,error);
  795. if (error<>0) then
  796. internalerror(2008100504);
  797. if not reader.sectiongetnextline(vmtentryname) or
  798. (vmtentryname='') then
  799. internalerror(2008100508);
  800. classdevirtinfo.addstaticmethod(vmtentry,vmtentryname);
  801. end;
  802. end;
  803. { end of section -> exit }
  804. if not(reader.sectiongetnextline(classid)) then
  805. exit;
  806. until (classid='') or
  807. (classid[length(classid)]='^');
  808. { next unit, or error }
  809. unitid:=classid;
  810. until false;
  811. end;
  812. procedure tprogdevirtinfo.storewpofilesection(writer: twposectionwriterintf);
  813. var
  814. unitcount,
  815. classcount,
  816. vmtentrycount: longint;
  817. unitdevirtinfo: tunitdevirtinfo;
  818. classdevirtinfo: tclassdevirtinfo;
  819. first: boolean;
  820. begin
  821. { if there are no optimised virtual methods, we have stored no info }
  822. if not assigned(funits) then
  823. exit;
  824. writer.startsection(DEVIRT_SECTION_NAME);
  825. for unitcount:=0 to funits.count-1 do
  826. begin
  827. unitdevirtinfo:=tunitdevirtinfo(funits[unitcount]);
  828. writer.sectionputline(unitdevirtinfo.name+'^');
  829. for classcount:=0 to unitdevirtinfo.fclasses.count-1 do
  830. begin
  831. classdevirtinfo:=tclassdevirtinfo(tunitdevirtinfo(funits[unitcount]).fclasses[classcount]);
  832. writer.sectionputline(classdevirtinfo.name+'&');
  833. writer.sectionputline(tostr(ord(classdevirtinfo.instantiated)));
  834. first:=true;
  835. for vmtentrycount:=0 to classdevirtinfo.fstaticmethodnames.count-1 do
  836. if assigned(classdevirtinfo.fstaticmethodnames[vmtentrycount]) then
  837. begin
  838. if first then
  839. begin
  840. writer.sectionputline('basevmt');
  841. first:=false;
  842. end;
  843. writer.sectionputline(tostr(vmtentrycount));
  844. writer.sectionputline(pshortstring(classdevirtinfo.fstaticmethodnames[vmtentrycount])^);
  845. end;
  846. writer.sectionputline('');
  847. end;
  848. end;
  849. end;
  850. function tprogdevirtinfo.getstaticname(forvmtentry: boolean; objdef, procdef: tdef; out staticname: string): boolean;
  851. var
  852. unitid,
  853. classid,
  854. newname: pshortstring;
  855. unitdevirtinfo: tunitdevirtinfo;
  856. classdevirtinfo: tclassdevirtinfo;
  857. vmtentry: longint;
  858. realobjdef: tobjectdef;
  859. begin
  860. { class methods are in the regular vmt, so we can handle classrefs
  861. the same way as plain objectdefs
  862. }
  863. if (objdef.typ=classrefdef) then
  864. realobjdef:=tobjectdef(tclassrefdef(objdef).pointeddef)
  865. else if (objdef.typ=objectdef) and
  866. (tobjectdef(objdef).objecttype in [odt_class,odt_object]) then
  867. realobjdef:=tobjectdef(objdef)
  868. else
  869. begin
  870. { we don't support interfaces yet }
  871. result:=false;
  872. exit;
  873. end;
  874. { get the component names for the class/procdef combo }
  875. defsdecompose(realobjdef,tprocdef(procdef),unitid,classid,vmtentry);
  876. { do we have any info for this unit? }
  877. unitdevirtinfo:=findunit(unitid^);
  878. result:=false;
  879. if not assigned(unitdevirtinfo) then
  880. exit;
  881. { and for this class? }
  882. classdevirtinfo:=unitdevirtinfo.findclass(classid^);
  883. if not assigned(classdevirtinfo) then
  884. exit;
  885. { if it's for a vmtentry of an objdef and the objdef is
  886. not instantiated, then we can fill the vmt with pointers
  887. to FPC_ABSTRACTERROR
  888. }
  889. if forvmtentry and
  890. (objdef.typ=objectdef) and
  891. not classdevirtinfo.instantiated and
  892. { virtual class methods can be called even if the class is not instantiated }
  893. not(po_classmethod in tprocdef(procdef).procoptions) then
  894. begin
  895. staticname:='FPC_ABSTRACTERROR';
  896. result:=true;
  897. end
  898. else
  899. begin
  900. { now check whether it can be devirtualised, and if so to what }
  901. result:=classdevirtinfo.isstaticvmtentry(vmtentry,newname);
  902. if result then
  903. staticname:=newname^;
  904. end;
  905. end;
  906. function tprogdevirtinfo.staticnameforcallingvirtualmethod(objdef, procdef: tdef; out staticname: string): boolean;
  907. begin
  908. result:=getstaticname(false,objdef,procdef,staticname);
  909. end;
  910. function tprogdevirtinfo.staticnameforvmtentry(objdef, procdef: tdef; out staticname: string): boolean;
  911. begin
  912. result:=getstaticname(true,objdef,procdef,staticname);
  913. end;
  914. end.