nobj.pas 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl
  3. Routines for the code generation of data structures
  4. like VMT, Messages, VTables, Interfaces descs
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software
  15. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  16. ****************************************************************************
  17. }
  18. unit nobj;
  19. {$i fpcdefs.inc}
  20. interface
  21. uses
  22. cutils,cclasses,
  23. globtype,
  24. symdef,symsym
  25. ;
  26. type
  27. TVMTBuilder=class
  28. private
  29. _Class : tobjectdef;
  30. handledprotocols: tfpobjectlist;
  31. function is_new_vmt_entry(pd:tprocdef; out overridesclasshelper: boolean):boolean;
  32. procedure add_new_vmt_entry(pd:tprocdef; allowoverridingmethod: boolean);
  33. function check_msg_str(vmtpd, pd: tprocdef):boolean;
  34. function intf_search_procdef_by_name(proc: tprocdef;const name: string): tprocdef;
  35. procedure intf_get_procdefs(ImplIntf:TImplementedInterface;IntfDef:TObjectDef);
  36. procedure intf_get_procdefs_recursive(ImplIntf:TImplementedInterface;IntfDef:TObjectDef);
  37. procedure prot_get_procdefs_recursive(ImplProt:TImplementedInterface;ProtDef:TObjectDef);
  38. procedure intf_optimize_vtbls;
  39. procedure intf_allocate_vtbls;
  40. procedure generate_vmt_def;
  41. public
  42. constructor create(c:tobjectdef);
  43. procedure generate_vmt;
  44. procedure build_interface_mappings;
  45. end;
  46. implementation
  47. uses
  48. globals,verbose,systems,
  49. node,
  50. symbase,symtable,symconst,symtype,symcpu,
  51. defcmp,
  52. pparautl;
  53. {*****************************************************************************
  54. TVMTBuilder
  55. *****************************************************************************}
  56. constructor TVMTBuilder.create(c:tobjectdef);
  57. begin
  58. inherited Create;
  59. _Class:=c;
  60. end;
  61. procedure TVMTBuilder.add_new_vmt_entry(pd:tprocdef; allowoverridingmethod: boolean);
  62. var
  63. i : longint;
  64. vmtentry : pvmtentry;
  65. vmtpd : tprocdef;
  66. begin
  67. { new entry is needed, override was not possible }
  68. { Allowed when overriding a category method for a parent class in a
  69. descendent Objective-C class }
  70. if not allowoverridingmethod and
  71. (po_overridingmethod in pd.procoptions) then
  72. MessagePos1(pd.fileinfo,parser_e_nothing_to_be_overridden,pd.fullprocname(false));
  73. { check that all methods have overload directive }
  74. if not(m_fpc in current_settings.modeswitches) then
  75. begin
  76. for i:=0 to _class.vmtentries.count-1 do
  77. begin
  78. vmtentry:=pvmtentry(_class.vmtentries[i]);
  79. vmtpd:=tprocdef(vmtentry^.procdef);
  80. if (vmtpd.procsym=pd.procsym) and
  81. (not(po_overload in pd.procoptions) or
  82. not(po_overload in vmtpd.procoptions)) then
  83. begin
  84. MessagePos1(pd.fileinfo,parser_e_no_overload_for_all_procs,pd.procsym.realname);
  85. { recover }
  86. include(vmtpd.procoptions,po_overload);
  87. include(pd.procoptions,po_overload);
  88. end;
  89. end;
  90. end;
  91. { Register virtual method and give it a number }
  92. if (po_virtualmethod in pd.procoptions) then
  93. begin
  94. { store vmt entry number in procdef }
  95. if (pd.extnumber<>$ffff) and
  96. (pd.extnumber<>_class.VMTEntries.Count) then
  97. internalerror(200810283);
  98. pd.extnumber:=_class.VMTEntries.Count;
  99. new(vmtentry);
  100. vmtentry^.procdef:=pd;
  101. vmtentry^.procdefderef.reset;
  102. vmtentry^.visibility:=pd.visibility;
  103. _class.VMTEntries.Add(vmtentry);
  104. end;
  105. end;
  106. function TVMTBuilder.check_msg_str(vmtpd, pd: tprocdef): boolean;
  107. begin
  108. result:=true;
  109. if not(is_objc_class_or_protocol(_class)) then
  110. begin
  111. { the only requirement for normal methods is that both either
  112. have a message string or not (the value is irrelevant) }
  113. if ((pd.procoptions * [po_msgstr]) <> (vmtpd.procoptions * [po_msgstr])) then
  114. begin
  115. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  116. tprocsym(vmtpd.procsym).write_parameter_lists(pd);
  117. result:=false;
  118. end
  119. end
  120. else
  121. begin
  122. { the compiler should have ensured that the protocol or parent
  123. class method has a message name specified }
  124. if not(po_msgstr in vmtpd.procoptions) then
  125. internalerror(2009070601);
  126. if not(po_msgstr in pd.procoptions) then
  127. begin
  128. { copy the protocol's/parent class' message name to the one in
  129. the class if none has been specified there }
  130. include(pd.procoptions,po_msgstr);
  131. pd.messageinf.str:=stringdup(vmtpd.messageinf.str^);
  132. end
  133. else
  134. begin
  135. { if both have a message name, make sure they are equal }
  136. if (vmtpd.messageinf.str^<>pd.messageinf.str^) then
  137. begin
  138. MessagePos2(pd.fileinfo,parser_e_objc_message_name_changed,vmtpd.messageinf.str^,pd.messageinf.str^);
  139. result:=false;
  140. end;
  141. end;
  142. end;
  143. end;
  144. function TVMTBuilder.is_new_vmt_entry(pd:tprocdef; out overridesclasshelper: boolean):boolean;
  145. const
  146. po_comp = [po_classmethod,po_virtualmethod,po_staticmethod,po_interrupt,po_iocheck,po_msgint,
  147. po_exports,po_varargs,po_explicitparaloc,po_nostackframe];
  148. var
  149. i : longint;
  150. hasequalpara,
  151. hasoverloads,
  152. pdoverload : boolean;
  153. srsym : tsym;
  154. st : tsymtable;
  155. // returns true if we can stop checking, false if we have to continue
  156. function found_entry(var vmtpd: tprocdef; var vmtentryvis: tvisibility; updatevalues: boolean): boolean;
  157. {$ifdef jvm}
  158. var
  159. javanewtreeok: boolean;
  160. {$endif jvm}
  161. begin
  162. result:=false;
  163. { ignore hidden entries (e.g. virtual overridden by a static) that are not visible anymore }
  164. if vmtentryvis=vis_hidden then
  165. exit;
  166. { ignore different names }
  167. if vmtpd.procsym.name<>pd.procsym.name then
  168. exit;
  169. { hide private methods that are not visible anymore. For this check we
  170. must override the visibility with the highest value in the override chain.
  171. This is required for case (see tw3292) with protected-private-protected where the
  172. same vmtentry is used (PFV) }
  173. if not is_visible_for_object(vmtpd.owner,vmtentryvis,_class) then
  174. exit;
  175. { inherit overload }
  176. if (po_overload in vmtpd.procoptions) then
  177. begin
  178. include(pd.procoptions,po_overload);
  179. pdoverload:=true;
  180. end;
  181. { compare parameter types only, no specifiers yet }
  182. hasequalpara:=(compare_paras(vmtpd.paras,pd.paras,cp_none,[cpo_ignoreuniv,cpo_ignorehidden])>=te_equal);
  183. { check that we are not trying to override a final method }
  184. { in Java, new virtual inheritance trees can never be started ->
  185. treat all methods as "overriding" in the context of this check
  186. (Java does check whether the mangled names are identical, so if they
  187. are not we can stil get away with it) }
  188. if (po_finalmethod in vmtpd.procoptions) and
  189. hasequalpara and
  190. ((po_overridingmethod in pd.procoptions) or
  191. (is_javaclass(_class) and
  192. (pd.mangledname=vmtpd.mangledname))) and
  193. (is_class(_class) or is_objectpascal_helper(_class) or is_javaclass(_class)) then
  194. MessagePos1(pd.fileinfo,parser_e_final_can_no_be_overridden,pd.fullprocname(false))
  195. else
  196. { old definition has virtual
  197. new definition has no virtual or override }
  198. if (po_virtualmethod in vmtpd.procoptions) and
  199. (
  200. not(po_virtualmethod in pd.procoptions) or
  201. (
  202. { new one does not have reintroduce in case of an objccategory }
  203. (is_objccategory(_class) and
  204. not(po_reintroduce in pd.procoptions)) or
  205. { new one does not have override in case of objpas/objc/java class/intf/proto }
  206. ((is_class_or_interface_or_objc_or_java(_class) or is_objectpascal_helper(_class)) and
  207. not is_objccategory(_class) and
  208. not(po_overridingmethod in pd.procoptions)
  209. )
  210. )
  211. ) then
  212. begin
  213. if (
  214. not(pdoverload or hasoverloads) or
  215. hasequalpara
  216. ) then
  217. begin
  218. {$ifdef jvm}
  219. { if the mangled names are different, the inheritance trees
  220. are different too in Java; exception: when the parent method
  221. is a virtual class method or virtual constructor, because
  222. those are looked up dynamicall by name }
  223. javanewtreeok:=
  224. is_java_class_or_interface(_class) and
  225. (tcpuprocdef(pd).jvmmangledbasename(false)<>tcpuprocdef(vmtpd).jvmmangledbasename(false)) and
  226. ((vmtpd.proctypeoption<>potype_constructor) and
  227. not(po_staticmethod in vmtpd.procoptions));
  228. {$endif}
  229. if not(po_reintroduce in pd.procoptions) and
  230. not(po_java_nonvirtual in vmtpd.procoptions) then
  231. if not(is_objc_class_or_protocol(_class))
  232. {$ifdef jvm}
  233. and (not is_java_class_or_interface(_class) or
  234. javanewtreeok)
  235. {$endif jvm}
  236. then
  237. MessagePos1(pd.fileinfo,parser_w_should_use_override,pd.fullprocname(false))
  238. else
  239. begin
  240. { In Objective-C, you cannot create a new VMT entry to
  241. start a new inheritance tree. We therefore give an
  242. error when the class is implemented in Pascal, to
  243. avoid confusion due to things working differently
  244. with Object Pascal classes.
  245. In case of external classes, we only give a hint,
  246. because requiring override everywhere may make
  247. automated header translation tools too complex.
  248. The same goes for Java. }
  249. {$ifndef jvm}
  250. if hasequalpara then
  251. {$endif}
  252. begin
  253. if not(oo_is_external in _class.objectoptions) then
  254. if not is_objccategory(_class) then
  255. MessagePos1(pd.fileinfo,parser_e_must_use_override,FullTypeName(tdef(vmtpd.owner.defowner),nil))
  256. else
  257. MessagePos1(pd.fileinfo,parser_e_must_use_reintroduce_objc,FullTypeName(tdef(vmtpd.owner.defowner),nil))
  258. { there may be a lot of these in auto-translated
  259. headers, so only calculate the fulltypename if
  260. the hint will be shown }
  261. else if CheckVerbosity(V_Hint) then
  262. if not is_objccategory(_class) then
  263. MessagePos1(pd.fileinfo,parser_h_should_use_override,FullTypeName(tdef(vmtpd.owner.defowner),nil))
  264. else
  265. MessagePos1(pd.fileinfo,parser_h_should_use_reintroduce_objc,FullTypeName(tdef(vmtpd.owner.defowner),nil));
  266. end;
  267. { no new entry, but copy the message name if any from
  268. the procdef in the parent class }
  269. if not is_objc_class_or_protocol(_class) or
  270. hasequalpara then
  271. check_msg_str(vmtpd,pd);
  272. if updatevalues then
  273. begin
  274. { in case of Java, copy the real name from the parent,
  275. since overriding "Destroy" with "destroy" is not
  276. going to work very well }
  277. if is_java_class_or_interface(_class) and
  278. (pd.procsym.realname<>vmtpd.procsym.realname) then
  279. pd.procsym.realname:=vmtpd.procsym.realname;
  280. { in case we are overriding an abstract method,
  281. decrease the number of abstract methods in this class }
  282. if (po_abstractmethod in vmtpd.procoptions) then
  283. dec(tobjectdef(pd.owner.defowner).abstractcnt);
  284. if (vmtpd.extnumber<>i) then
  285. internalerror(2011083101);
  286. pd.extnumber:=vmtpd.extnumber;
  287. vmtpd:=pd;
  288. end;
  289. result:=true;
  290. exit;
  291. {$ifdef jvm}
  292. end
  293. else
  294. if not javanewtreeok and
  295. is_java_class_or_interface(_class) then
  296. begin
  297. { mangled names are the same -> can only override }
  298. MessagePos1(pd.fileinfo,parser_e_must_use_override,FullTypeName(tdef(vmtpd.owner.defowner),nil))
  299. {$endif jvm}
  300. end;
  301. { disable/hide old VMT entry }
  302. if updatevalues then
  303. vmtentryvis:=vis_hidden;
  304. end;
  305. end
  306. { both are virtual? }
  307. else if (po_virtualmethod in pd.procoptions) and
  308. (po_virtualmethod in vmtpd.procoptions) then
  309. begin
  310. { same parameter and return types (parameter specifiers will be checked below) }
  311. if hasequalpara and
  312. compatible_childmethod_resultdef(vmtpd.returndef,pd.returndef) then
  313. begin
  314. { inherite calling convention when it was explicit and the
  315. current definition has none explicit set }
  316. if (po_hascallingconvention in vmtpd.procoptions) and
  317. not(po_hascallingconvention in pd.procoptions) then
  318. begin
  319. pd.proccalloption:=vmtpd.proccalloption;
  320. include(pd.procoptions,po_hascallingconvention);
  321. end;
  322. { All parameter specifiers and some procedure the flags have to match
  323. except abstract and override }
  324. if (compare_paras(vmtpd.paras,pd.paras,cp_all,[cpo_ignoreuniv,cpo_ignorehidden])<te_equal) or
  325. (vmtpd.proccalloption<>pd.proccalloption) or
  326. (vmtpd.proctypeoption<>pd.proctypeoption) or
  327. ((vmtpd.procoptions*po_comp)<>(pd.procoptions*po_comp)) then
  328. begin
  329. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,pd.fullprocname(false));
  330. tprocsym(vmtpd.procsym).write_parameter_lists(pd);
  331. end;
  332. check_msg_str(vmtpd,pd);
  333. { Give a note if the new visibility is lower. For a higher
  334. visibility update the vmt info }
  335. if vmtentryvis>pd.visibility then
  336. begin
  337. if po_auto_raised_visibility in vmtpd.procoptions then
  338. begin
  339. if updatevalues then
  340. begin
  341. pd.visibility:=vmtentryvis;
  342. { this one's visibility is now also auto-raised }
  343. include(pd.procoptions,po_auto_raised_visibility);
  344. end
  345. end
  346. else
  347. {$ifdef jvm}
  348. MessagePos4(pd.fileinfo,parser_e_method_lower_visibility,
  349. {$else jvm}
  350. MessagePos4(pd.fileinfo,parser_n_ignore_lower_visibility,
  351. {$endif jvm}
  352. pd.fullprocname(false),
  353. visibilityname[pd.visibility],tobjectdef(vmtpd.owner.defowner).objrealname^,visibilityname[vmtentryvis])
  354. end
  355. else if pd.visibility>vmtentryvis then
  356. begin
  357. if updatevalues then
  358. vmtentryvis:=pd.visibility;
  359. end;
  360. { override old virtual method in VMT }
  361. if updatevalues then
  362. begin
  363. { in case we are overriding an abstract method,
  364. decrease the number of abstract methods in this class }
  365. if (po_overridingmethod in pd.procoptions) and
  366. (po_abstractmethod in vmtpd.procoptions) then
  367. dec(tobjectdef(pd.owner.defowner).abstractcnt);
  368. if (vmtpd.extnumber<>i) then
  369. internalerror(200611084);
  370. pd.extnumber:=vmtpd.extnumber;
  371. { in case of Java, copy the real name from the parent,
  372. since overriding "Destroy" with "destroy" is not
  373. going to work very well }
  374. if is_java_class_or_interface(_class) and
  375. (pd.procsym.realname<>vmtpd.procsym.realname) then
  376. pd.procsym.realname:=vmtpd.procsym.realname;
  377. vmtpd:=pd;
  378. end;
  379. result:=true;
  380. exit;
  381. end
  382. { different parameters }
  383. else
  384. begin
  385. { when we got an override directive then can search futher for
  386. the procedure to override.
  387. If we are starting a new virtual tree then hide the old tree }
  388. if not(po_overridingmethod in pd.procoptions) and
  389. not(pdoverload or hasoverloads) then
  390. begin
  391. if not(po_reintroduce in pd.procoptions) then
  392. begin
  393. if not is_object(_class) and
  394. not is_objc_class_or_protocol(_class) and
  395. not is_java_class_or_interface(_class) then
  396. MessagePos1(pd.fileinfo,parser_w_should_use_override,pd.fullprocname(false))
  397. else
  398. { objects don't allow starting a new virtual tree
  399. and neither do Objective-C or Java }
  400. MessagePos1(pd.fileinfo,parser_e_header_dont_match_forward,vmtpd.fullprocname(false));
  401. end;
  402. { disable/hide old VMT entry }
  403. if updatevalues then
  404. vmtentryvis:=vis_hidden;
  405. end;
  406. end;
  407. end;
  408. end;
  409. function found_category_method(st: tsymtable): boolean;
  410. var
  411. entrycount: longint;
  412. cat: tobjectdef;
  413. vmtpd: tprocdef;
  414. vmtvis: tvisibility;
  415. begin
  416. result:=false;
  417. if is_objccategory(tdef(st.defowner)) then
  418. begin
  419. cat:=tobjectdef(st.defowner);
  420. { go through all of the category's methods to find the
  421. vmtentry corresponding to the procdef we are handling }
  422. for entrycount:=0 to cat.vmtentries.Count-1 do
  423. begin
  424. vmtpd:=pvmtentry(cat.vmtentries[entrycount])^.procdef;
  425. vmtvis:=pvmtentry(cat.vmtentries[entrycount])^.visibility;
  426. { don't change the vmtentry of the category }
  427. if found_entry(vmtpd,vmtvis,false) then
  428. begin
  429. result:=true;
  430. exit;
  431. end;
  432. end;
  433. end;
  434. end;
  435. begin
  436. result:=false;
  437. overridesclasshelper:=false;
  438. { Load other values for easier readability }
  439. hasoverloads:=(tprocsym(pd.procsym).ProcdefList.Count>1);
  440. pdoverload:=(po_overload in pd.procoptions);
  441. { compare with all stored definitions }
  442. for i:=0 to _class.vmtentries.Count-1 do
  443. begin
  444. if found_entry(pvmtentry(_class.vmtentries[i])^.procdef, pvmtentry(_class.vmtentries[i])^.visibility,true) then
  445. exit;
  446. end;
  447. { in case of Objective-C, also check the categories that apply to this
  448. class' *parent* for methods to override (don't allow class X to
  449. "override" a method added by a category to class X itself, since in
  450. that case the category method will in fact replace class X'
  451. "overriding" method }
  452. if is_objcclass(_class) and
  453. assigned(_class.childof) and
  454. search_objc_helper(_class.childof,pd.procsym.name,srsym,st) then
  455. begin
  456. overridesclasshelper:=found_category_method(st);
  457. end;
  458. { No entry found, we need to create a new entry }
  459. result:=true;
  460. end;
  461. function TVMTBuilder.intf_search_procdef_by_name(proc: tprocdef;const name: string): tprocdef;
  462. const
  463. po_comp = [po_classmethod,po_staticmethod,po_interrupt,po_iocheck,po_msgint,
  464. po_exports,po_varargs,po_explicitparaloc,po_nostackframe];
  465. var
  466. implprocdef : Tprocdef;
  467. i: cardinal;
  468. hclass : tobjectdef;
  469. hashedid : THashedIDString;
  470. srsym : tsym;
  471. overload: boolean;
  472. begin
  473. result:=nil;
  474. hashedid.id:=name;
  475. hclass:=_class;
  476. while assigned(hclass) do
  477. begin
  478. srsym:=tsym(hclass.symtable.FindWithHash(hashedid));
  479. if assigned(srsym) and
  480. (srsym.typ=procsym) and
  481. ((hclass=_class) or
  482. is_visible_for_object(srsym,_class)) then
  483. begin
  484. overload:=false;
  485. for i:=0 to Tprocsym(srsym).ProcdefList.Count-1 do
  486. begin
  487. implprocdef:=tprocdef(tprocsym(srsym).ProcdefList[i]);
  488. if po_overload in implprocdef.procoptions then
  489. overload:=true;
  490. if (implprocdef.procsym=tprocsym(srsym)) and
  491. (compare_paras(proc.paras,implprocdef.paras,cp_all,[cpo_ignorehidden,cpo_ignoreuniv])>=te_equal) and
  492. (compare_defs(proc.returndef,implprocdef.returndef,nothingn)>=te_equal) and
  493. (proc.proccalloption=implprocdef.proccalloption) and
  494. (proc.proctypeoption=implprocdef.proctypeoption) and
  495. ((proc.procoptions*po_comp)=((implprocdef.procoptions+[po_virtualmethod])*po_comp)) and
  496. check_msg_str(proc,implprocdef) then
  497. begin
  498. { does the interface increase the visibility of the
  499. implementing method? }
  500. if implprocdef.visibility<proc.visibility then
  501. {$ifdef jvm}
  502. MessagePos2(implprocdef.fileinfo,type_e_interface_lower_visibility,proc.fullprocname(false),implprocdef.fullprocname(false));
  503. {$else}
  504. MessagePos2(implprocdef.fileinfo,type_w_interface_lower_visibility,proc.fullprocname(false),implprocdef.fullprocname(false));
  505. {$endif}
  506. result:=implprocdef;
  507. exit;
  508. end;
  509. end;
  510. { like with normal procdef resolution (in htypechk), stop if
  511. we encounter a proc without the overload directive }
  512. if not overload then
  513. exit;
  514. end;
  515. hclass:=hclass.childof;
  516. end;
  517. end;
  518. procedure TVMTBuilder.intf_get_procdefs(ImplIntf:TImplementedInterface;IntfDef:TObjectDef);
  519. var
  520. i : longint;
  521. def : tdef;
  522. hs,
  523. prefix,
  524. mappedname: string;
  525. implprocdef: tprocdef;
  526. begin
  527. prefix:=ImplIntf.IntfDef.symtable.name^+'.';
  528. for i:=0 to IntfDef.symtable.DefList.Count-1 do
  529. begin
  530. def:=tdef(IntfDef.symtable.DefList[i]);
  531. if assigned(def) and
  532. (def.typ=procdef) then
  533. begin
  534. { Find implementing procdef
  535. 1. Check for mapped name
  536. 2. Use symbol name, but only if there's no mapping,
  537. or we're processing ancestor of interface.
  538. When modifying this code, ensure that webtbs/tw11862, webtbs/tw4950
  539. and webtbf/tw19591 stay correct. }
  540. implprocdef:=nil;
  541. hs:=prefix+tprocdef(def).procsym.name;
  542. mappedname:=ImplIntf.GetMapping(hs);
  543. if mappedname<>'' then
  544. implprocdef:=intf_search_procdef_by_name(tprocdef(def),mappedname);
  545. if not assigned(implprocdef) then
  546. if (mappedname='') or (ImplIntf.IntfDef<>IntfDef) then
  547. implprocdef:=intf_search_procdef_by_name(tprocdef(def),tprocdef(def).procsym.name);
  548. { Add procdef to the implemented interface }
  549. if assigned(implprocdef) then
  550. begin
  551. if (tobjectdef(implprocdef.struct).objecttype<>odt_objcclass) then
  552. begin
  553. { in case of Java, copy the real name from the parent,
  554. since overriding "Destroy" with "destroy" is not
  555. going to work very well }
  556. if is_javaclass(implprocdef.struct) and
  557. (implprocdef.procsym.realname<>tprocdef(def).procsym.realname) then
  558. implprocdef.procsym.realname:=tprocdef(def).procsym.realname;
  559. ImplIntf.AddImplProc(implprocdef);
  560. end
  561. else
  562. begin
  563. { If no message name has been specified for the method
  564. in the objcclass, copy it from the protocol
  565. definition. }
  566. if not(po_msgstr in tprocdef(def).procoptions) then
  567. begin
  568. include(tprocdef(def).procoptions,po_msgstr);
  569. implprocdef.messageinf.str:=stringdup(tprocdef(def).messageinf.str^);
  570. end
  571. else
  572. begin
  573. { If a message name has been specified in the
  574. objcclass, it has to match the message name in the
  575. protocol definition. }
  576. if (implprocdef.messageinf.str^<>tprocdef(def).messageinf.str^) then
  577. MessagePos2(implprocdef.fileinfo,parser_e_objc_message_name_changed,tprocdef(def).messageinf.str^,implprocdef.messageinf.str^);
  578. end;
  579. end;
  580. end
  581. else
  582. if (ImplIntf.IType=etStandard) and
  583. not(po_optional in tprocdef(def).procoptions) then
  584. MessagePos1(_Class.typesym.fileinfo,sym_e_no_matching_implementation_found,tprocdef(def).fullprocname(false));
  585. end;
  586. end;
  587. end;
  588. procedure TVMTBuilder.intf_get_procdefs_recursive(ImplIntf:TImplementedInterface;IntfDef:TObjectDef);
  589. begin
  590. if assigned(IntfDef.childof) then
  591. intf_get_procdefs_recursive(ImplIntf,IntfDef.childof);
  592. intf_get_procdefs(ImplIntf,IntfDef);
  593. end;
  594. procedure TVMTBuilder.prot_get_procdefs_recursive(ImplProt:TImplementedInterface;ProtDef:TObjectDef);
  595. var
  596. i: longint;
  597. begin
  598. { don't check the same protocol twice }
  599. if handledprotocols.IndexOf(ProtDef)<>-1 then
  600. exit;
  601. handledprotocols.add(ProtDef);
  602. for i:=0 to ProtDef.ImplementedInterfaces.count-1 do
  603. prot_get_procdefs_recursive(ImplProt,TImplementedInterface(ProtDef.ImplementedInterfaces[i]).intfdef);
  604. intf_get_procdefs(ImplProt,ProtDef);
  605. end;
  606. procedure TVMTBuilder.intf_optimize_vtbls;
  607. type
  608. tcompintfentry = record
  609. weight: longint;
  610. compintf: longint;
  611. end;
  612. { Max 1000 interface in the class header interfaces it's enough imho }
  613. tcompintfs = array[0..1000] of tcompintfentry;
  614. pcompintfs = ^tcompintfs;
  615. tequals = array[0..1000] of longint;
  616. pequals = ^tequals;
  617. timpls = array[0..1000] of longint;
  618. pimpls = ^timpls;
  619. var
  620. aequals: pequals;
  621. compats: pcompintfs;
  622. impls: pimpls;
  623. ImplIntfCount,
  624. w,i,j,k: longint;
  625. ImplIntfI,
  626. ImplIntfJ : TImplementedInterface;
  627. cij: boolean;
  628. cji: boolean;
  629. begin
  630. ImplIntfCount:=_class.ImplementedInterfaces.count;
  631. if ImplIntfCount>=High(tequals) then
  632. Internalerror(200006135);
  633. getmem(compats,sizeof(tcompintfentry)*ImplIntfCount);
  634. getmem(aequals,sizeof(longint)*ImplIntfCount);
  635. getmem(impls,sizeof(longint)*ImplIntfCount);
  636. filldword(compats^,(sizeof(tcompintfentry) div sizeof(dword))*ImplIntfCount,dword(-1));
  637. filldword(aequals^,ImplIntfCount,dword(-1));
  638. filldword(impls^,ImplIntfCount,dword(-1));
  639. { ismergepossible is a containing relation
  640. meaning of ismergepossible(a,b,w) =
  641. if implementorfunction map of a is contained implementorfunction map of b
  642. imp(a,b) and imp(b,c) => imp(a,c) ; imp(a,b) and imp(b,a) => a == b
  643. }
  644. { the order is very important for correct allocation }
  645. for i:=0 to ImplIntfCount-1 do
  646. begin
  647. for j:=i+1 to ImplIntfCount-1 do
  648. begin
  649. ImplIntfI:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  650. ImplIntfJ:=TImplementedInterface(_class.ImplementedInterfaces[j]);
  651. cij:=ImplIntfI.IsImplMergePossible(ImplIntfJ,w);
  652. cji:=ImplIntfJ.IsImplMergePossible(ImplIntfI,w);
  653. if cij and cji then { i equal j }
  654. begin
  655. { get minimum index of equal }
  656. if aequals^[j]=-1 then
  657. aequals^[j]:=i;
  658. end
  659. else if cij then
  660. begin
  661. { get minimum index of maximum weight }
  662. if compats^[i].weight<w then
  663. begin
  664. compats^[i].weight:=w;
  665. compats^[i].compintf:=j;
  666. end;
  667. end
  668. else if cji then
  669. begin
  670. { get minimum index of maximum weight }
  671. if (compats^[j].weight<w) then
  672. begin
  673. compats^[j].weight:=w;
  674. compats^[j].compintf:=i;
  675. end;
  676. end;
  677. end;
  678. end;
  679. { Reset, no replacements by default }
  680. for i:=0 to ImplIntfCount-1 do
  681. impls^[i]:=i;
  682. { Replace vtbls when equal or compat, repeat
  683. until there are no replacements possible anymore. This is
  684. needed for the cases like:
  685. First loop: 2->3, 3->1
  686. Second loop: 2->1 (because 3 was replaced with 1)
  687. }
  688. repeat
  689. k:=0;
  690. for i:=0 to ImplIntfCount-1 do
  691. begin
  692. if compats^[impls^[i]].compintf<>-1 then
  693. impls^[i]:=compats^[impls^[i]].compintf
  694. else if aequals^[impls^[i]]<>-1 then
  695. impls^[i]:=aequals^[impls^[i]]
  696. else
  697. inc(k);
  698. end;
  699. until k=ImplIntfCount;
  700. { Update the VtblImplIntf }
  701. for i:=0 to ImplIntfCount-1 do
  702. begin
  703. ImplIntfI:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  704. ImplIntfI.VtblImplIntf:=TImplementedInterface(_class.ImplementedInterfaces[impls^[i]]);
  705. end;
  706. freemem(compats);
  707. freemem(aequals);
  708. freemem(impls);
  709. end;
  710. procedure TVMTBuilder.intf_allocate_vtbls;
  711. var
  712. i : longint;
  713. ImplIntf : TImplementedInterface;
  714. begin
  715. { Allocation vtbl space }
  716. for i:=0 to _class.ImplementedInterfaces.count-1 do
  717. begin
  718. ImplIntf:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  719. { if it implements itself and if it's not implemented by delegation }
  720. if (ImplIntf.VtblImplIntf=ImplIntf) and (ImplIntf.IType=etStandard) then
  721. begin
  722. { allocate a pointer in the object memory }
  723. with tObjectSymtable(_class.symtable) do
  724. begin
  725. datasize:=align(datasize,voidpointertype.alignment);
  726. ImplIntf.Ioffset:=datasize;
  727. datasize:=datasize+voidpointertype.size;
  728. end;
  729. end;
  730. end;
  731. { Update ioffset of current interface with the ioffset from
  732. the interface that is reused to implements this interface }
  733. for i:=0 to _class.ImplementedInterfaces.count-1 do
  734. begin
  735. ImplIntf:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  736. if ImplIntf.VtblImplIntf<>ImplIntf then
  737. ImplIntf.IOffset:=ImplIntf.VtblImplIntf.IOffset;
  738. end;
  739. end;
  740. procedure TVMTBuilder.generate_vmt_def;
  741. var
  742. i: longint;
  743. vmtdef: trecorddef;
  744. systemvmt: tdef;
  745. sym: tsym;
  746. vmtdefname: TIDString;
  747. begin
  748. { these types don't have an actual VMT, we only use the other methods
  749. in TVMTBuilder to determine duplicates/overrides }
  750. if _class.objecttype in [
  751. odt_helper,
  752. odt_objcclass,
  753. odt_objccategory,
  754. odt_objcprotocol,
  755. odt_javaclass,
  756. odt_interfacecom_property,
  757. odt_interfacecom_function,
  758. odt_interfacejava] then
  759. exit;
  760. { don't generate VMT for generics (only use duplicates/overrides detection) }
  761. { Note: don't use is_generic here as we also need to check nested non-
  762. generic classes }
  763. if df_generic in _class.defoptions then
  764. exit;
  765. { todo in the future }
  766. if _class.objecttype = odt_cppclass then
  767. exit;
  768. { the VMT definition may already exist in case of generics }
  769. vmtdefname:=internaltypeprefixName[itp_vmtdef]+_class.mangledparaname;
  770. if assigned(try_search_current_module_type(vmtdefname)) then
  771. exit;
  772. { create VMT type definition }
  773. vmtdef:=crecorddef.create_global_internal(
  774. vmtdefname,
  775. 0,
  776. target_info.alignment.recordalignmin);
  777. {$ifdef llvm}
  778. { in case of a class declared in the implementation section of unit
  779. whose method is called from an inline routine -- LLVM needs to be able
  780. to access the vmt def to create signatures }
  781. vmtdef.register_def;
  782. {$endif}
  783. { standard VMT fields }
  784. case _Class.objecttype of
  785. odt_class:
  786. begin
  787. systemvmt:=search_system_type('TVMT').typedef;
  788. if not assigned(systemvmt) then
  789. Message1(cg_f_internal_type_not_found,'TVMT');
  790. { does the TVMT type look like we expect? (so that this code is
  791. easily triggered in case the definition of the VMT would
  792. change) }
  793. if (systemvmt.typ<>recorddef) or
  794. (trecorddef(systemvmt).symtable.SymList.count<>27) then
  795. Message1(cg_f_internal_type_does_not_match,'TVMT');
  796. { system.tvmt is a record that represents the VMT of TObject,
  797. including its virtual methods. We only want the non-method
  798. fields, as the methods will be added automatically based on
  799. the VMT we generated here only add the 12 first fields }
  800. for i:=0 to 11 do
  801. begin
  802. sym:=tsym(trecorddef(systemvmt).symtable.SymList[i]);
  803. if sym.typ in [procsym,propertysym] then
  804. continue;
  805. if sym.typ<>fieldvarsym then
  806. internalerror(2015052602);
  807. vmtdef.add_field_by_def('',tfieldvarsym(sym).vardef);
  808. end;
  809. end;
  810. odt_interfacecom,odt_interfacecorba,odt_dispinterface:
  811. { nothing }
  812. ;
  813. odt_object:
  814. begin
  815. { size, -size, parent vmt [, dmt ] (same names as for class) }
  816. vmtdef.add_field_by_def('vInstanceSize',sizesinttype);
  817. vmtdef.add_field_by_def('vInstanceSize2',sizesinttype);
  818. vmtdef.add_field_by_def('vParent',voidpointertype);
  819. {$ifdef WITHDMT}
  820. vmtdef.add_field_by_def('',voidpointertype);
  821. {$endif WITHDMT}
  822. end;
  823. else
  824. internalerror(2015052605);
  825. end;
  826. { now add the methods }
  827. for i:=0 to _class.vmtentries.count-1 do
  828. vmtdef.add_field_by_def('',
  829. cprocvardef.getreusableprocaddr(pvmtentry(_class.vmtentries[i])^.procdef)
  830. );
  831. { the VMT ends with a nil pointer }
  832. vmtdef.add_field_by_def('',voidcodepointertype);
  833. end;
  834. procedure TVMTBuilder.generate_vmt;
  835. var
  836. i : longint;
  837. def : tdef;
  838. old_current_structdef : tabstractrecorddef;
  839. overridesclasshelper : boolean;
  840. begin
  841. old_current_structdef:=current_structdef;
  842. current_structdef:=_class;
  843. _class.resetvmtentries;
  844. { inherit (copy) VMT from parent object }
  845. if assigned(_class.childof) then
  846. begin
  847. if not assigned(_class.childof.vmtentries) then
  848. internalerror(200810281);
  849. _class.copyvmtentries(_class.childof);
  850. end;
  851. { process all procdefs, we must process the defs to
  852. keep the same order as that is written in the source
  853. to be compatible with the indexes in the interface vtable (PFV) }
  854. for i:=0 to _class.symtable.DefList.Count-1 do
  855. begin
  856. def:=tdef(_class.symtable.DefList[i]);
  857. if def.typ=procdef then
  858. begin
  859. { VMT entry }
  860. if is_new_vmt_entry(tprocdef(def),overridesclasshelper) then
  861. add_new_vmt_entry(tprocdef(def),overridesclasshelper);
  862. end;
  863. end;
  864. insert_struct_hidden_paras(_class);
  865. build_interface_mappings;
  866. if assigned(_class.ImplementedInterfaces) and
  867. not(is_objc_class_or_protocol(_class)) and
  868. not(is_java_class_or_interface(_class)) then
  869. begin
  870. { Optimize interface tables to reuse wrappers }
  871. intf_optimize_vtbls;
  872. { Allocate interface tables }
  873. intf_allocate_vtbls;
  874. end;
  875. generate_vmt_def;
  876. current_structdef:=old_current_structdef;
  877. end;
  878. procedure TVMTBuilder.build_interface_mappings;
  879. var
  880. ImplIntf : TImplementedInterface;
  881. i: longint;
  882. begin
  883. { Find Procdefs implementing the interfaces (both Objective-C protocols
  884. and Java interfaces can have multiple parent interfaces, but in that
  885. case obviously no implementations are required) }
  886. if assigned(_class.ImplementedInterfaces) and
  887. not(_class.objecttype in [odt_objcprotocol,odt_interfacejava]) and
  888. // abstract java classes do not have to implement all interface
  889. // methods. todo: check that non-abstract descendents do!
  890. not((_class.objecttype=odt_javaclass) and (oo_is_abstract in _class.objectoptions)) then
  891. begin
  892. { Collect implementor functions into the tImplementedInterface.procdefs }
  893. case _class.objecttype of
  894. odt_class:
  895. begin
  896. for i:=0 to _class.ImplementedInterfaces.count-1 do
  897. begin
  898. ImplIntf:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  899. intf_get_procdefs_recursive(ImplIntf,ImplIntf.IntfDef)
  900. end;
  901. end;
  902. odt_objcclass,
  903. odt_javaclass:
  904. begin
  905. { Object Pascal interfaces are afterwards optimized via the
  906. intf_optimize_vtbls() method, but we can't do this for
  907. protocols/Java interfaces -> check for duplicates here
  908. already. }
  909. handledprotocols:=tfpobjectlist.create(false);
  910. for i:=0 to _class.ImplementedInterfaces.count-1 do
  911. begin
  912. ImplIntf:=TImplementedInterface(_class.ImplementedInterfaces[i]);
  913. prot_get_procdefs_recursive(ImplIntf,ImplIntf.IntfDef);
  914. end;
  915. handledprotocols.free;
  916. end
  917. else
  918. internalerror(2009091801);
  919. end
  920. end;
  921. end;
  922. end.