diff.cpp 110 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965
  1. // Copyright (c) 2022 Google LLC.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "source/diff/diff.h"
  15. #include "source/diff/lcs.h"
  16. #include "source/disassemble.h"
  17. #include "source/ext_inst.h"
  18. #include "source/latest_version_spirv_header.h"
  19. #include "source/print.h"
  20. #include "spirv-tools/libspirv.hpp"
  21. namespace spvtools {
  22. namespace diff {
  23. namespace {
  24. // A map from an id to the instruction that defines it.
  25. using IdToInstructionMap = std::vector<const opt::Instruction*>;
  26. // A map from an id to the instructions that decorate it, or name it, etc.
  27. using IdToInfoMap = std::vector<std::vector<const opt::Instruction*>>;
  28. // A map from an instruction to another, used for instructions without id.
  29. using InstructionToInstructionMap =
  30. std::unordered_map<const opt::Instruction*, const opt::Instruction*>;
  31. // A flat list of instructions in a function for easier iteration.
  32. using InstructionList = std::vector<const opt::Instruction*>;
  33. // A map from a function to its list of instructions.
  34. using FunctionInstMap = std::map<uint32_t, InstructionList>;
  35. // A list of ids with some similar property, for example functions with the same
  36. // name.
  37. using IdGroup = std::vector<uint32_t>;
  38. // A map of names to ids with the same name. This is an ordered map so
  39. // different implementations produce identical results.
  40. using IdGroupMapByName = std::map<std::string, IdGroup>;
  41. using IdGroupMapByTypeId = std::map<uint32_t, IdGroup>;
  42. using IdGroupMapByOp = std::map<spv::Op, IdGroup>;
  43. using IdGroupMapByStorageClass = std::map<spv::StorageClass, IdGroup>;
  44. // A set of potential id mappings that haven't been resolved yet. Any id in src
  45. // may map in any id in dst. Note that ids are added in the same order as they
  46. // appear in src and dst to facilitate matching dependent instructions. For
  47. // example, this guarantees that when matching OpTypeVector, the basic type of
  48. // the vector is already (potentially) matched.
  49. struct PotentialIdMap {
  50. std::vector<uint32_t> src_ids;
  51. std::vector<uint32_t> dst_ids;
  52. };
  53. void CompactIds(std::vector<uint32_t>& ids) {
  54. size_t write_index = 0;
  55. for (size_t i = 0; i < ids.size(); ++i) {
  56. if (ids[i] != 0) {
  57. ids[write_index++] = ids[i];
  58. }
  59. }
  60. ids.resize(write_index);
  61. }
  62. // A mapping between src and dst ids.
  63. class IdMap {
  64. public:
  65. IdMap(size_t id_bound) { id_map_.resize(id_bound, 0); }
  66. void MapIds(uint32_t from, uint32_t to) {
  67. assert(from != 0);
  68. assert(to != 0);
  69. assert(from < id_map_.size());
  70. assert(id_map_[from] == 0);
  71. id_map_[from] = to;
  72. }
  73. uint32_t MappedId(uint32_t from) const {
  74. assert(from != 0);
  75. return from < id_map_.size() ? id_map_[from] : 0;
  76. }
  77. const opt::Instruction* MappedInst(const opt::Instruction* from_inst) const {
  78. assert(from_inst != nullptr);
  79. assert(!from_inst->HasResultId());
  80. auto mapped = inst_map_.find(from_inst);
  81. if (mapped == inst_map_.end()) {
  82. return nullptr;
  83. }
  84. return mapped->second;
  85. }
  86. bool IsMapped(uint32_t from) const {
  87. assert(from != 0);
  88. return from < id_map_.size() && id_map_[from] != 0;
  89. }
  90. bool IsMapped(const opt::Instruction* from_inst) const {
  91. assert(from_inst != nullptr);
  92. assert(!from_inst->HasResultId());
  93. return inst_map_.find(from_inst) != inst_map_.end();
  94. }
  95. // Some instructions don't have result ids. Those are mapped by pointer.
  96. void MapInsts(const opt::Instruction* from_inst,
  97. const opt::Instruction* to_inst) {
  98. assert(from_inst != nullptr);
  99. assert(to_inst != nullptr);
  100. assert(inst_map_.find(from_inst) == inst_map_.end());
  101. inst_map_[from_inst] = to_inst;
  102. }
  103. uint32_t IdBound() const { return static_cast<uint32_t>(id_map_.size()); }
  104. // Generate a fresh id in this mapping's domain.
  105. uint32_t MakeFreshId() {
  106. id_map_.push_back(0);
  107. return static_cast<uint32_t>(id_map_.size()) - 1;
  108. }
  109. private:
  110. // Given an id, returns the corresponding id in the other module, or 0 if not
  111. // matched yet.
  112. std::vector<uint32_t> id_map_;
  113. // Same for instructions that don't have an id.
  114. InstructionToInstructionMap inst_map_;
  115. };
  116. // Two way mapping of ids.
  117. class SrcDstIdMap {
  118. public:
  119. SrcDstIdMap(size_t src_id_bound, size_t dst_id_bound)
  120. : src_to_dst_(src_id_bound), dst_to_src_(dst_id_bound) {}
  121. void MapIds(uint32_t src, uint32_t dst) {
  122. src_to_dst_.MapIds(src, dst);
  123. dst_to_src_.MapIds(dst, src);
  124. }
  125. uint32_t MappedDstId(uint32_t src) {
  126. uint32_t dst = src_to_dst_.MappedId(src);
  127. assert(dst == 0 || dst_to_src_.MappedId(dst) == src);
  128. return dst;
  129. }
  130. uint32_t MappedSrcId(uint32_t dst) {
  131. uint32_t src = dst_to_src_.MappedId(dst);
  132. assert(src == 0 || src_to_dst_.MappedId(src) == dst);
  133. return src;
  134. }
  135. bool IsSrcMapped(uint32_t src) { return src_to_dst_.IsMapped(src); }
  136. bool IsDstMapped(uint32_t dst) { return dst_to_src_.IsMapped(dst); }
  137. bool IsDstMapped(const opt::Instruction* dst_inst) {
  138. return dst_to_src_.IsMapped(dst_inst);
  139. }
  140. // Map any ids in src and dst that have not been mapped to new ids in dst and
  141. // src respectively. Use src_insn_defined and dst_insn_defined to ignore ids
  142. // that are simply never defined. (Since we assume the inputs are valid
  143. // SPIR-V, this implies they are also never used.)
  144. void MapUnmatchedIds(std::function<bool(uint32_t)> src_insn_defined,
  145. std::function<bool(uint32_t)> dst_insn_defined);
  146. // Some instructions don't have result ids. Those are mapped by pointer.
  147. void MapInsts(const opt::Instruction* src_inst,
  148. const opt::Instruction* dst_inst) {
  149. assert(src_inst->HasResultId() == dst_inst->HasResultId());
  150. if (src_inst->HasResultId()) {
  151. MapIds(src_inst->result_id(), dst_inst->result_id());
  152. } else {
  153. src_to_dst_.MapInsts(src_inst, dst_inst);
  154. dst_to_src_.MapInsts(dst_inst, src_inst);
  155. }
  156. }
  157. const IdMap& SrcToDstMap() const { return src_to_dst_; }
  158. const IdMap& DstToSrcMap() const { return dst_to_src_; }
  159. private:
  160. IdMap src_to_dst_;
  161. IdMap dst_to_src_;
  162. };
  163. struct IdInstructions {
  164. IdInstructions(const opt::Module* module)
  165. : inst_map_(module->IdBound(), nullptr),
  166. name_map_(module->IdBound()),
  167. decoration_map_(module->IdBound()),
  168. forward_pointer_map_(module->IdBound()) {
  169. // Map ids from all sections to instructions that define them.
  170. MapIdsToInstruction(module->ext_inst_imports());
  171. MapIdsToInstruction(module->types_values());
  172. for (const opt::Function& function : *module) {
  173. function.ForEachInst(
  174. [this](const opt::Instruction* inst) {
  175. if (inst->HasResultId()) {
  176. MapIdToInstruction(inst->result_id(), inst);
  177. }
  178. },
  179. true, true);
  180. }
  181. // Gather decorations applied to ids that could be useful in matching them
  182. // between src and dst modules.
  183. MapIdsToInfos(module->debugs2());
  184. MapIdsToInfos(module->annotations());
  185. MapIdsToInfos(module->types_values());
  186. }
  187. void MapIdToInstruction(uint32_t id, const opt::Instruction* inst);
  188. // Return true if id is mapped to any instruction, false otherwise.
  189. bool IsDefined(uint32_t id) {
  190. return id < inst_map_.size() && inst_map_[id] != nullptr;
  191. }
  192. void MapIdsToInstruction(
  193. opt::IteratorRange<opt::Module::const_inst_iterator> section);
  194. void MapIdsToInfos(
  195. opt::IteratorRange<opt::Module::const_inst_iterator> section);
  196. IdToInstructionMap inst_map_;
  197. IdToInfoMap name_map_;
  198. IdToInfoMap decoration_map_;
  199. IdToInstructionMap forward_pointer_map_;
  200. };
  201. class Differ {
  202. public:
  203. Differ(opt::IRContext* src, opt::IRContext* dst, std::ostream& out,
  204. Options options)
  205. : src_context_(src),
  206. dst_context_(dst),
  207. src_(src->module()),
  208. dst_(dst->module()),
  209. options_(options),
  210. out_(out),
  211. src_id_to_(src_),
  212. dst_id_to_(dst_),
  213. id_map_(src_->IdBound(), dst_->IdBound()) {
  214. // Cache function bodies in canonicalization order.
  215. GetFunctionBodies(src_context_, &src_funcs_, &src_func_insts_);
  216. GetFunctionBodies(dst_context_, &dst_funcs_, &dst_func_insts_);
  217. }
  218. // Match ids or instructions of different sections.
  219. void MatchCapabilities();
  220. void MatchExtensions();
  221. void MatchExtInstImportIds();
  222. void MatchMemoryModel();
  223. void MatchEntryPointIds();
  224. void MatchExecutionModes();
  225. void MatchTypeForwardPointers();
  226. void MatchTypeIds();
  227. void MatchConstants();
  228. void MatchVariableIds();
  229. void MatchFunctions();
  230. // Debug info and annotations are matched only after ids are matched.
  231. void MatchDebugs1();
  232. void MatchDebugs2();
  233. void MatchDebugs3();
  234. void MatchExtInstDebugInfo();
  235. void MatchAnnotations();
  236. // Output the diff.
  237. spv_result_t Output();
  238. void DumpIdMap() {
  239. if (!options_.dump_id_map) {
  240. return;
  241. }
  242. out_ << " Src -> Dst\n";
  243. for (uint32_t src_id = 1; src_id < src_->IdBound(); ++src_id) {
  244. uint32_t dst_id = id_map_.MappedDstId(src_id);
  245. if (src_id_to_.inst_map_[src_id] != nullptr && dst_id != 0)
  246. out_ << std::setw(4) << src_id << " -> " << std::setw(4) << dst_id
  247. << " [" << spvOpcodeString(src_id_to_.inst_map_[src_id]->opcode())
  248. << "]\n";
  249. }
  250. }
  251. private:
  252. // Helper functions that match ids between src and dst
  253. void PoolPotentialIds(
  254. opt::IteratorRange<opt::Module::const_inst_iterator> section,
  255. std::vector<uint32_t>& ids, bool is_src,
  256. std::function<bool(const opt::Instruction&)> filter,
  257. std::function<uint32_t(const opt::Instruction&)> get_id);
  258. void MatchIds(
  259. PotentialIdMap& potential,
  260. std::function<bool(const opt::Instruction*, const opt::Instruction*)>
  261. match);
  262. // Helper functions that match id-less instructions between src and dst.
  263. void MatchPreambleInstructions(
  264. opt::IteratorRange<opt::Module::const_inst_iterator> src_insts,
  265. opt::IteratorRange<opt::Module::const_inst_iterator> dst_insts);
  266. InstructionList SortPreambleInstructions(
  267. const opt::Module* module,
  268. opt::IteratorRange<opt::Module::const_inst_iterator> insts);
  269. int ComparePreambleInstructions(const opt::Instruction* a,
  270. const opt::Instruction* b,
  271. const opt::Module* src_inst_module,
  272. const opt::Module* dst_inst_module);
  273. // Helper functions that match debug and annotation instructions of already
  274. // matched ids.
  275. void MatchDebugAndAnnotationInstructions(
  276. opt::IteratorRange<opt::Module::const_inst_iterator> src_insts,
  277. opt::IteratorRange<opt::Module::const_inst_iterator> dst_insts);
  278. // Get various properties from an id. These Helper functions are passed to
  279. // `GroupIds` and `GroupIdsAndMatch` below (as the `get_group` argument).
  280. uint32_t GroupIdsHelperGetTypeId(const IdInstructions& id_to, uint32_t id);
  281. spv::StorageClass GroupIdsHelperGetTypePointerStorageClass(
  282. const IdInstructions& id_to, uint32_t id);
  283. spv::Op GroupIdsHelperGetTypePointerTypeOp(const IdInstructions& id_to,
  284. uint32_t id);
  285. // Given a list of ids, groups them based on some value. The `get_group`
  286. // function extracts a piece of information corresponding to each id, and the
  287. // ids are bucketed based on that (and output in `groups`). This is useful to
  288. // attempt to match ids between src and dst only when said property is
  289. // identical.
  290. template <typename T>
  291. void GroupIds(const IdGroup& ids, bool is_src, std::map<T, IdGroup>* groups,
  292. T (Differ::*get_group)(const IdInstructions&, uint32_t));
  293. // Calls GroupIds to bucket ids in src and dst based on a property returned by
  294. // `get_group`. This function then calls `match_group` for each bucket (i.e.
  295. // "group") with identical values for said property.
  296. //
  297. // For example, say src and dst ids have the following properties
  298. // correspondingly:
  299. //
  300. // - src ids' properties: {id0: A, id1: A, id2: B, id3: C, id4: B}
  301. // - dst ids' properties: {id0': B, id1': C, id2': B, id3': D, id4': B}
  302. //
  303. // Then `match_group` is called 2 times:
  304. //
  305. // - Once with: ([id2, id4], [id0', id2', id4']) corresponding to B
  306. // - Once with: ([id3], [id2']) corresponding to C
  307. //
  308. // Ids corresponding to A and D cannot match based on this property.
  309. template <typename T>
  310. void GroupIdsAndMatch(
  311. const IdGroup& src_ids, const IdGroup& dst_ids, T invalid_group_key,
  312. T (Differ::*get_group)(const IdInstructions&, uint32_t),
  313. std::function<void(const IdGroup& src_group, const IdGroup& dst_group)>
  314. match_group);
  315. // Bucket `src_ids` and `dst_ids` by the key ids returned by `get_group`, and
  316. // then call `match_group` on pairs of buckets whose key ids are matched with
  317. // each other.
  318. //
  319. // For example, suppose we want to pair up groups of instructions with the
  320. // same type. Naturally, the source instructions refer to their types by their
  321. // ids in the source, and the destination instructions use destination type
  322. // ids, so simply comparing source and destination type ids as integers, as
  323. // `GroupIdsAndMatch` would do, is meaningless. But if a prior call to
  324. // `MatchTypeIds` has established type matches between the two modules, then
  325. // we can consult those to pair source and destination buckets whose types are
  326. // equivalent.
  327. //
  328. // Suppose our input groups are as follows:
  329. //
  330. // - src_ids: { 1 -> 100, 2 -> 300, 3 -> 100, 4 -> 200 }
  331. // - dst_ids: { 5 -> 10, 6 -> 20, 7 -> 10, 8 -> 300 }
  332. //
  333. // Here, `X -> Y` means that the instruction with SPIR-V id `X` is a member of
  334. // the group, and `Y` is the id of its type. If we use
  335. // `Differ::GroupIdsHelperGetTypeId` for `get_group`, then
  336. // `get_group(X) == Y`.
  337. //
  338. // These instructions are bucketed by type as follows:
  339. //
  340. // - source: [1, 3] -> 100
  341. // [4] -> 200
  342. // [2] -> 300
  343. //
  344. // - destination: [5, 7] -> 10
  345. // [6] -> 20
  346. // [8] -> 300
  347. //
  348. // Now suppose that we have previously matched up src type 100 with dst type
  349. // 10, and src type 200 with dst type 20, but no other types are matched.
  350. //
  351. // Then `match_group` is called twice:
  352. // - Once with ([1,3], [5, 7]), corresponding to 100/10
  353. // - Once with ([4],[6]), corresponding to 200/20
  354. //
  355. // The source type 300 isn't matched with anything, so the fact that there's a
  356. // destination type 300 is irrelevant, and thus 2 and 8 are never passed to
  357. // `match_group`.
  358. //
  359. // This function isn't specific to types; it simply buckets by the ids
  360. // returned from `get_group`, and consults existing matches to pair up the
  361. // resulting buckets.
  362. void GroupIdsAndMatchByMappedId(
  363. const IdGroup& src_ids, const IdGroup& dst_ids,
  364. uint32_t (Differ::*get_group)(const IdInstructions&, uint32_t),
  365. std::function<void(const IdGroup& src_group, const IdGroup& dst_group)>
  366. match_group);
  367. // Helper functions that determine if two instructions match
  368. bool DoIdsMatch(uint32_t src_id, uint32_t dst_id);
  369. bool DoesOperandMatch(const opt::Operand& src_operand,
  370. const opt::Operand& dst_operand);
  371. bool DoOperandsMatch(const opt::Instruction* src_inst,
  372. const opt::Instruction* dst_inst,
  373. uint32_t in_operand_index_start,
  374. uint32_t in_operand_count);
  375. bool DoInstructionsMatch(const opt::Instruction* src_inst,
  376. const opt::Instruction* dst_inst);
  377. bool DoIdsMatchFuzzy(uint32_t src_id, uint32_t dst_id);
  378. bool DoesOperandMatchFuzzy(const opt::Operand& src_operand,
  379. const opt::Operand& dst_operand);
  380. bool DoInstructionsMatchFuzzy(const opt::Instruction* src_inst,
  381. const opt::Instruction* dst_inst);
  382. bool AreIdenticalUintConstants(uint32_t src_id, uint32_t dst_id);
  383. bool DoDebugAndAnnotationInstructionsMatch(const opt::Instruction* src_inst,
  384. const opt::Instruction* dst_inst);
  385. bool AreVariablesMatchable(uint32_t src_id, uint32_t dst_id,
  386. uint32_t flexibility);
  387. bool MatchOpTypeStruct(const opt::Instruction* src_inst,
  388. const opt::Instruction* dst_inst,
  389. uint32_t flexibility);
  390. bool MatchOpConstant(const opt::Instruction* src_inst,
  391. const opt::Instruction* dst_inst, uint32_t flexibility);
  392. bool MatchOpSpecConstant(const opt::Instruction* src_inst,
  393. const opt::Instruction* dst_inst);
  394. bool MatchOpVariable(const opt::Instruction* src_inst,
  395. const opt::Instruction* dst_inst, uint32_t flexibility);
  396. bool MatchPerVertexType(uint32_t src_type_id, uint32_t dst_type_id);
  397. bool MatchPerVertexVariable(const opt::Instruction* src_inst,
  398. const opt::Instruction* dst_inst);
  399. // Helper functions for matching OpTypeForwardPointer
  400. void MatchTypeForwardPointersByName(const IdGroup& src, const IdGroup& dst);
  401. void MatchTypeForwardPointersByTypeOp(const IdGroup& src, const IdGroup& dst);
  402. // Helper functions for function matching.
  403. using FunctionMap = std::map<uint32_t, const opt::Function*>;
  404. InstructionList GetFunctionBody(opt::IRContext* context,
  405. opt::Function& function);
  406. InstructionList GetFunctionHeader(const opt::Function& function);
  407. void GetFunctionBodies(opt::IRContext* context, FunctionMap* functions,
  408. FunctionInstMap* function_insts);
  409. void GetFunctionHeaderInstructions(const opt::Module* module,
  410. FunctionInstMap* function_insts);
  411. void BestEffortMatchFunctions(const IdGroup& src_func_ids,
  412. const IdGroup& dst_func_ids,
  413. const FunctionInstMap& src_func_insts,
  414. const FunctionInstMap& dst_func_insts);
  415. // Calculates the diff of two function bodies. Note that the matched
  416. // instructions themselves may not be identical; output of exact matches
  417. // should produce the exact instruction while inexact matches should produce a
  418. // diff as well.
  419. //
  420. // Returns the similarity of the two bodies = 2*N_match / (N_src + N_dst)
  421. void MatchFunctionParamIds(const opt::Function* src_func,
  422. const opt::Function* dst_func);
  423. float MatchFunctionBodies(const InstructionList& src_body,
  424. const InstructionList& dst_body,
  425. DiffMatch* src_match_result,
  426. DiffMatch* dst_match_result);
  427. void MatchIdsInFunctionBodies(const InstructionList& src_body,
  428. const InstructionList& dst_body,
  429. const DiffMatch& src_match_result,
  430. const DiffMatch& dst_match_result,
  431. uint32_t flexibility);
  432. void MatchVariablesUsedByMatchedInstructions(const opt::Instruction* src_inst,
  433. const opt::Instruction* dst_inst,
  434. uint32_t flexibility);
  435. // Helper functions to retrieve information pertaining to an id
  436. const opt::Instruction* GetInst(const IdInstructions& id_to, uint32_t id);
  437. uint32_t GetConstantUint(const IdInstructions& id_to, uint32_t constant_id);
  438. spv::ExecutionModel GetExecutionModel(const opt::Module* module,
  439. uint32_t entry_point_id);
  440. bool HasName(const IdInstructions& id_to, uint32_t id);
  441. // Get the OpName associated with an id
  442. std::string GetName(const IdInstructions& id_to, uint32_t id, bool* has_name);
  443. // Get the OpName associated with an id, with argument types stripped for
  444. // functions. Some tools don't encode function argument types in the OpName
  445. // string, and this improves diff between SPIR-V from those tools and others.
  446. std::string GetSanitizedName(const IdInstructions& id_to, uint32_t id);
  447. uint32_t GetVarTypeId(const IdInstructions& id_to, uint32_t var_id,
  448. spv::StorageClass* storage_class);
  449. bool GetDecorationValue(const IdInstructions& id_to, uint32_t id,
  450. spv::Decoration decoration,
  451. uint32_t* decoration_value);
  452. const opt::Instruction* GetForwardPointerInst(const IdInstructions& id_to,
  453. uint32_t id);
  454. bool IsIntType(const IdInstructions& id_to, uint32_t type_id);
  455. bool IsFloatType(const IdInstructions& id_to, uint32_t type_id);
  456. bool IsConstantUint(const IdInstructions& id_to, uint32_t id);
  457. bool IsVariable(const IdInstructions& id_to, uint32_t pointer_id);
  458. bool IsOp(const IdInstructions& id_to, uint32_t id, spv::Op opcode);
  459. bool IsPerVertexType(const IdInstructions& id_to, uint32_t type_id);
  460. bool IsPerVertexVariable(const IdInstructions& id_to, uint32_t type_id);
  461. spv::StorageClass GetPerVertexStorageClass(const opt::Module* module,
  462. uint32_t type_id);
  463. spv_ext_inst_type_t GetExtInstType(const IdInstructions& id_to,
  464. uint32_t set_id);
  465. spv_number_kind_t GetNumberKind(const IdInstructions& id_to,
  466. const opt::Instruction& inst,
  467. uint32_t operand_index,
  468. uint32_t* number_bit_width);
  469. spv_number_kind_t GetTypeNumberKind(const IdInstructions& id_to, uint32_t id,
  470. uint32_t* number_bit_width);
  471. // Helper functions to output a diff line
  472. const opt::Instruction* MappedDstInst(const opt::Instruction* src_inst);
  473. const opt::Instruction* MappedSrcInst(const opt::Instruction* dst_inst);
  474. const opt::Instruction* MappedInstImpl(const opt::Instruction* inst,
  475. const IdMap& to_other,
  476. const IdInstructions& other_id_to);
  477. void OutputLine(std::function<bool()> are_lines_identical,
  478. std::function<void()> output_src_line,
  479. std::function<void()> output_dst_line);
  480. template <typename InstList>
  481. void OutputSection(
  482. const InstList& src_insts, const InstList& dst_insts,
  483. std::function<void(const opt::Instruction&, const IdInstructions&,
  484. const opt::Instruction&)>
  485. write_inst);
  486. void ToParsedInstruction(const opt::Instruction& inst,
  487. const IdInstructions& id_to,
  488. const opt::Instruction& original_inst,
  489. spv_parsed_instruction_t* parsed_inst,
  490. std::vector<spv_parsed_operand_t>& parsed_operands,
  491. std::vector<uint32_t>& inst_binary);
  492. opt::Instruction ToMappedSrcIds(const opt::Instruction& dst_inst);
  493. void OutputRed() {
  494. if (options_.color_output) out_ << spvtools::clr::red{true};
  495. }
  496. void OutputGreen() {
  497. if (options_.color_output) out_ << spvtools::clr::green{true};
  498. }
  499. void OutputResetColor() {
  500. if (options_.color_output) out_ << spvtools::clr::reset{true};
  501. }
  502. opt::IRContext* src_context_;
  503. opt::IRContext* dst_context_;
  504. const opt::Module* src_;
  505. const opt::Module* dst_;
  506. Options options_;
  507. std::ostream& out_;
  508. // Helpers to look up instructions based on id.
  509. IdInstructions src_id_to_;
  510. IdInstructions dst_id_to_;
  511. // The ids that have been matched between src and dst so far.
  512. SrcDstIdMap id_map_;
  513. // List of instructions in function bodies after canonicalization. Cached
  514. // here to avoid duplicate work. More importantly, some maps use
  515. // opt::Instruction pointers so they need to be unique.
  516. FunctionInstMap src_func_insts_;
  517. FunctionInstMap dst_func_insts_;
  518. FunctionMap src_funcs_;
  519. FunctionMap dst_funcs_;
  520. };
  521. void SrcDstIdMap::MapUnmatchedIds(
  522. std::function<bool(uint32_t)> src_insn_defined,
  523. std::function<bool(uint32_t)> dst_insn_defined) {
  524. const uint32_t src_id_bound = static_cast<uint32_t>(src_to_dst_.IdBound());
  525. const uint32_t dst_id_bound = static_cast<uint32_t>(dst_to_src_.IdBound());
  526. for (uint32_t src_id = 1; src_id < src_id_bound; ++src_id) {
  527. if (!src_to_dst_.IsMapped(src_id) && src_insn_defined(src_id)) {
  528. uint32_t fresh_dst_id = dst_to_src_.MakeFreshId();
  529. MapIds(src_id, fresh_dst_id);
  530. }
  531. }
  532. for (uint32_t dst_id = 1; dst_id < dst_id_bound; ++dst_id) {
  533. if (!dst_to_src_.IsMapped(dst_id) && dst_insn_defined(dst_id)) {
  534. uint32_t fresh_src_id = src_to_dst_.MakeFreshId();
  535. MapIds(fresh_src_id, dst_id);
  536. }
  537. }
  538. }
  539. void IdInstructions::MapIdToInstruction(uint32_t id,
  540. const opt::Instruction* inst) {
  541. assert(id != 0);
  542. assert(id < inst_map_.size());
  543. assert(inst_map_[id] == nullptr);
  544. inst_map_[id] = inst;
  545. }
  546. void IdInstructions::MapIdsToInstruction(
  547. opt::IteratorRange<opt::Module::const_inst_iterator> section) {
  548. for (const opt::Instruction& inst : section) {
  549. uint32_t result_id = inst.result_id();
  550. if (result_id == 0) {
  551. continue;
  552. }
  553. MapIdToInstruction(result_id, &inst);
  554. }
  555. }
  556. void IdInstructions::MapIdsToInfos(
  557. opt::IteratorRange<opt::Module::const_inst_iterator> section) {
  558. for (const opt::Instruction& inst : section) {
  559. IdToInfoMap* info_map = nullptr;
  560. uint32_t id_operand = 0;
  561. switch (inst.opcode()) {
  562. case spv::Op::OpName:
  563. info_map = &name_map_;
  564. break;
  565. case spv::Op::OpMemberName:
  566. info_map = &name_map_;
  567. break;
  568. case spv::Op::OpDecorate:
  569. info_map = &decoration_map_;
  570. break;
  571. case spv::Op::OpMemberDecorate:
  572. info_map = &decoration_map_;
  573. break;
  574. case spv::Op::OpTypeForwardPointer: {
  575. uint32_t id = inst.GetSingleWordOperand(0);
  576. assert(id != 0);
  577. assert(id < forward_pointer_map_.size());
  578. forward_pointer_map_[id] = &inst;
  579. continue;
  580. }
  581. default:
  582. // Currently unsupported instruction, don't attempt to use it for
  583. // matching.
  584. break;
  585. }
  586. if (info_map == nullptr) {
  587. continue;
  588. }
  589. uint32_t id = inst.GetOperand(id_operand).AsId();
  590. assert(id != 0);
  591. assert(id < info_map->size());
  592. assert(std::find((*info_map)[id].begin(), (*info_map)[id].end(), &inst) ==
  593. (*info_map)[id].end());
  594. (*info_map)[id].push_back(&inst);
  595. }
  596. }
  597. void Differ::PoolPotentialIds(
  598. opt::IteratorRange<opt::Module::const_inst_iterator> section,
  599. std::vector<uint32_t>& ids, bool is_src,
  600. std::function<bool(const opt::Instruction&)> filter,
  601. std::function<uint32_t(const opt::Instruction&)> get_id) {
  602. for (const opt::Instruction& inst : section) {
  603. if (!filter(inst)) {
  604. continue;
  605. }
  606. uint32_t result_id = get_id(inst);
  607. assert(result_id != 0);
  608. assert(std::find(ids.begin(), ids.end(), result_id) == ids.end());
  609. // Don't include ids that are already matched, for example through
  610. // OpTypeForwardPointer.
  611. const bool is_matched = is_src ? id_map_.IsSrcMapped(result_id)
  612. : id_map_.IsDstMapped(result_id);
  613. if (is_matched) {
  614. continue;
  615. }
  616. ids.push_back(result_id);
  617. }
  618. }
  619. void Differ::MatchIds(
  620. PotentialIdMap& potential,
  621. std::function<bool(const opt::Instruction*, const opt::Instruction*)>
  622. match) {
  623. for (size_t src_index = 0; src_index < potential.src_ids.size();
  624. ++src_index) {
  625. for (size_t dst_index = 0; dst_index < potential.dst_ids.size();
  626. ++dst_index) {
  627. const uint32_t src_id = potential.src_ids[src_index];
  628. const uint32_t dst_id = potential.dst_ids[dst_index];
  629. if (dst_id == 0) {
  630. // Already matched.
  631. continue;
  632. }
  633. const opt::Instruction* src_inst = src_id_to_.inst_map_[src_id];
  634. const opt::Instruction* dst_inst = dst_id_to_.inst_map_[dst_id];
  635. if (match(src_inst, dst_inst)) {
  636. id_map_.MapIds(src_id, dst_id);
  637. // Remove the ids from the potential list.
  638. potential.src_ids[src_index] = 0;
  639. potential.dst_ids[dst_index] = 0;
  640. // Find a match for the next src id.
  641. break;
  642. }
  643. }
  644. }
  645. // Remove matched ids to make the next iteration faster.
  646. CompactIds(potential.src_ids);
  647. CompactIds(potential.dst_ids);
  648. }
  649. void Differ::MatchPreambleInstructions(
  650. opt::IteratorRange<opt::Module::const_inst_iterator> src_insts,
  651. opt::IteratorRange<opt::Module::const_inst_iterator> dst_insts) {
  652. // First, pool all instructions from each section and sort them.
  653. InstructionList sorted_src_insts = SortPreambleInstructions(src_, src_insts);
  654. InstructionList sorted_dst_insts = SortPreambleInstructions(dst_, dst_insts);
  655. // Then walk and match them.
  656. size_t src_cur = 0;
  657. size_t dst_cur = 0;
  658. while (src_cur < sorted_src_insts.size() &&
  659. dst_cur < sorted_dst_insts.size()) {
  660. const opt::Instruction* src_inst = sorted_src_insts[src_cur];
  661. const opt::Instruction* dst_inst = sorted_dst_insts[dst_cur];
  662. int compare = ComparePreambleInstructions(src_inst, dst_inst, src_, dst_);
  663. if (compare == 0) {
  664. id_map_.MapInsts(src_inst, dst_inst);
  665. }
  666. if (compare <= 0) {
  667. ++src_cur;
  668. }
  669. if (compare >= 0) {
  670. ++dst_cur;
  671. }
  672. }
  673. }
  674. InstructionList Differ::SortPreambleInstructions(
  675. const opt::Module* module,
  676. opt::IteratorRange<opt::Module::const_inst_iterator> insts) {
  677. InstructionList sorted;
  678. for (const opt::Instruction& inst : insts) {
  679. sorted.push_back(&inst);
  680. }
  681. std::sort(
  682. sorted.begin(), sorted.end(),
  683. [this, module](const opt::Instruction* a, const opt::Instruction* b) {
  684. return ComparePreambleInstructions(a, b, module, module) < 0;
  685. });
  686. return sorted;
  687. }
  688. int Differ::ComparePreambleInstructions(const opt::Instruction* a,
  689. const opt::Instruction* b,
  690. const opt::Module* src_inst_module,
  691. const opt::Module* dst_inst_module) {
  692. assert(a->opcode() == b->opcode());
  693. assert(!a->HasResultId());
  694. assert(!a->HasResultType());
  695. const uint32_t a_operand_count = a->NumOperands();
  696. const uint32_t b_operand_count = b->NumOperands();
  697. if (a_operand_count < b_operand_count) {
  698. return -1;
  699. }
  700. if (a_operand_count > b_operand_count) {
  701. return 1;
  702. }
  703. // Instead of comparing OpExecutionMode entry point ids as ids, compare them
  704. // through their corresponding execution model. This simplifies traversing
  705. // the sorted list of instructions between src and dst modules.
  706. if (a->opcode() == spv::Op::OpExecutionMode) {
  707. const spv::ExecutionModel src_model =
  708. GetExecutionModel(src_inst_module, a->GetSingleWordOperand(0));
  709. const spv::ExecutionModel dst_model =
  710. GetExecutionModel(dst_inst_module, b->GetSingleWordOperand(0));
  711. if (src_model < dst_model) {
  712. return -1;
  713. }
  714. if (src_model > dst_model) {
  715. return 1;
  716. }
  717. }
  718. // Match every operand of the instruction.
  719. for (uint32_t operand_index = 0; operand_index < a_operand_count;
  720. ++operand_index) {
  721. const opt::Operand& a_operand = a->GetOperand(operand_index);
  722. const opt::Operand& b_operand = b->GetOperand(operand_index);
  723. if (a_operand.type < b_operand.type) {
  724. return -1;
  725. }
  726. if (a_operand.type > b_operand.type) {
  727. return 1;
  728. }
  729. switch (a_operand.type) {
  730. case SPV_OPERAND_TYPE_ID:
  731. // Don't compare ids, there can't be multiple instances of the
  732. // OpExecutionMode with different ids of the same execution model.
  733. break;
  734. case SPV_OPERAND_TYPE_TYPE_ID:
  735. case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
  736. case SPV_OPERAND_TYPE_SCOPE_ID:
  737. assert(false && "Unreachable");
  738. break;
  739. case SPV_OPERAND_TYPE_LITERAL_STRING: {
  740. int str_compare =
  741. strcmp(a_operand.AsString().c_str(), b_operand.AsString().c_str());
  742. if (str_compare != 0) {
  743. return str_compare;
  744. }
  745. break;
  746. }
  747. default:
  748. // Expect literal values to match.
  749. assert(a_operand.words.size() == 1);
  750. assert(b_operand.words.size() == 1);
  751. if (a_operand.words[0] < b_operand.words[0]) {
  752. return -1;
  753. }
  754. if (a_operand.words[0] > b_operand.words[0]) {
  755. return 1;
  756. }
  757. break;
  758. }
  759. }
  760. return 0;
  761. }
  762. void Differ::MatchDebugAndAnnotationInstructions(
  763. opt::IteratorRange<opt::Module::const_inst_iterator> src_insts,
  764. opt::IteratorRange<opt::Module::const_inst_iterator> dst_insts) {
  765. for (const opt::Instruction& src_inst : src_insts) {
  766. for (const opt::Instruction& dst_inst : dst_insts) {
  767. if (MappedSrcInst(&dst_inst) != nullptr) {
  768. continue;
  769. }
  770. // Map instructions as soon as they match. Debug and annotation
  771. // instructions are matched such that there can't be multiple matches.
  772. if (DoDebugAndAnnotationInstructionsMatch(&src_inst, &dst_inst)) {
  773. id_map_.MapInsts(&src_inst, &dst_inst);
  774. break;
  775. }
  776. }
  777. }
  778. }
  779. uint32_t Differ::GroupIdsHelperGetTypeId(const IdInstructions& id_to,
  780. uint32_t id) {
  781. return GetInst(id_to, id)->type_id();
  782. }
  783. spv::StorageClass Differ::GroupIdsHelperGetTypePointerStorageClass(
  784. const IdInstructions& id_to, uint32_t id) {
  785. const opt::Instruction* inst = GetInst(id_to, id);
  786. assert(inst && inst->opcode() == spv::Op::OpTypePointer);
  787. return spv::StorageClass(inst->GetSingleWordInOperand(0));
  788. }
  789. spv::Op Differ::GroupIdsHelperGetTypePointerTypeOp(const IdInstructions& id_to,
  790. uint32_t id) {
  791. const opt::Instruction* inst = GetInst(id_to, id);
  792. assert(inst && inst->opcode() == spv::Op::OpTypePointer);
  793. const uint32_t type_id = inst->GetSingleWordInOperand(1);
  794. const opt::Instruction* type_inst = GetInst(id_to, type_id);
  795. assert(type_inst);
  796. return type_inst->opcode();
  797. }
  798. template <typename T>
  799. void Differ::GroupIds(const IdGroup& ids, bool is_src,
  800. std::map<T, IdGroup>* groups,
  801. T (Differ::*get_group)(const IdInstructions&, uint32_t)) {
  802. assert(groups->empty());
  803. const IdInstructions& id_to = is_src ? src_id_to_ : dst_id_to_;
  804. for (const uint32_t id : ids) {
  805. // Don't include ids that are already matched, for example through
  806. // OpEntryPoint.
  807. const bool is_matched =
  808. is_src ? id_map_.IsSrcMapped(id) : id_map_.IsDstMapped(id);
  809. if (is_matched) {
  810. continue;
  811. }
  812. T group = (this->*get_group)(id_to, id);
  813. (*groups)[group].push_back(id);
  814. }
  815. }
  816. template <typename T>
  817. void Differ::GroupIdsAndMatch(
  818. const IdGroup& src_ids, const IdGroup& dst_ids, T invalid_group_key,
  819. T (Differ::*get_group)(const IdInstructions&, uint32_t),
  820. std::function<void(const IdGroup& src_group, const IdGroup& dst_group)>
  821. match_group) {
  822. // Group the ids based on a key (get_group)
  823. std::map<T, IdGroup> src_groups;
  824. std::map<T, IdGroup> dst_groups;
  825. GroupIds<T>(src_ids, true, &src_groups, get_group);
  826. GroupIds<T>(dst_ids, false, &dst_groups, get_group);
  827. // Iterate over the groups, and match those with identical keys
  828. for (const auto& iter : src_groups) {
  829. const T& key = iter.first;
  830. const IdGroup& src_group = iter.second;
  831. if (key == invalid_group_key) {
  832. continue;
  833. }
  834. const IdGroup& dst_group = dst_groups[key];
  835. // Let the caller match the groups as appropriate.
  836. match_group(src_group, dst_group);
  837. }
  838. }
  839. void Differ::GroupIdsAndMatchByMappedId(
  840. const IdGroup& src_ids, const IdGroup& dst_ids,
  841. uint32_t (Differ::*get_group)(const IdInstructions&, uint32_t),
  842. std::function<void(const IdGroup& src_group, const IdGroup& dst_group)>
  843. match_group) {
  844. // Group the ids based on a key (get_group)
  845. std::map<uint32_t, IdGroup> src_groups;
  846. std::map<uint32_t, IdGroup> dst_groups;
  847. GroupIds<uint32_t>(src_ids, true, &src_groups, get_group);
  848. GroupIds<uint32_t>(dst_ids, false, &dst_groups, get_group);
  849. // Iterate over pairs of groups whose keys map to each other.
  850. for (const auto& iter : src_groups) {
  851. const uint32_t& src_key = iter.first;
  852. const IdGroup& src_group = iter.second;
  853. if (src_key == 0) {
  854. continue;
  855. }
  856. if (id_map_.IsSrcMapped(src_key)) {
  857. const uint32_t& dst_key = id_map_.MappedDstId(src_key);
  858. const IdGroup& dst_group = dst_groups[dst_key];
  859. // Let the caller match the groups as appropriate.
  860. match_group(src_group, dst_group);
  861. }
  862. }
  863. }
  864. bool Differ::DoIdsMatch(uint32_t src_id, uint32_t dst_id) {
  865. assert(dst_id != 0);
  866. return id_map_.MappedDstId(src_id) == dst_id;
  867. }
  868. bool Differ::DoesOperandMatch(const opt::Operand& src_operand,
  869. const opt::Operand& dst_operand) {
  870. assert(src_operand.type == dst_operand.type);
  871. switch (src_operand.type) {
  872. case SPV_OPERAND_TYPE_ID:
  873. case SPV_OPERAND_TYPE_TYPE_ID:
  874. case SPV_OPERAND_TYPE_RESULT_ID:
  875. case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
  876. case SPV_OPERAND_TYPE_SCOPE_ID:
  877. // Match ids only if they are already matched in the id map.
  878. return DoIdsMatch(src_operand.AsId(), dst_operand.AsId());
  879. case SPV_OPERAND_TYPE_LITERAL_STRING:
  880. return src_operand.AsString() == dst_operand.AsString();
  881. default:
  882. // Otherwise expect them to match exactly.
  883. assert(src_operand.type != SPV_OPERAND_TYPE_LITERAL_STRING);
  884. if (src_operand.words.size() != dst_operand.words.size()) {
  885. return false;
  886. }
  887. for (size_t i = 0; i < src_operand.words.size(); ++i) {
  888. if (src_operand.words[i] != dst_operand.words[i]) {
  889. return false;
  890. }
  891. }
  892. return true;
  893. }
  894. }
  895. bool Differ::DoOperandsMatch(const opt::Instruction* src_inst,
  896. const opt::Instruction* dst_inst,
  897. uint32_t in_operand_index_start,
  898. uint32_t in_operand_count) {
  899. // Caller should have returned early for instructions with different opcode.
  900. assert(src_inst->opcode() == dst_inst->opcode());
  901. bool match = true;
  902. for (uint32_t i = 0; i < in_operand_count; ++i) {
  903. const uint32_t in_operand_index = in_operand_index_start + i;
  904. const opt::Operand& src_operand = src_inst->GetInOperand(in_operand_index);
  905. const opt::Operand& dst_operand = dst_inst->GetInOperand(in_operand_index);
  906. match = match && DoesOperandMatch(src_operand, dst_operand);
  907. }
  908. return match;
  909. }
  910. bool Differ::DoInstructionsMatch(const opt::Instruction* src_inst,
  911. const opt::Instruction* dst_inst) {
  912. // Check whether the two instructions are identical, that is the instructions
  913. // themselves are matched, every id is matched, and every other value is
  914. // identical.
  915. if (MappedDstInst(src_inst) != dst_inst) {
  916. return false;
  917. }
  918. assert(src_inst->opcode() == dst_inst->opcode());
  919. if (src_inst->NumOperands() != dst_inst->NumOperands()) {
  920. return false;
  921. }
  922. for (uint32_t operand_index = 0; operand_index < src_inst->NumOperands();
  923. ++operand_index) {
  924. const opt::Operand& src_operand = src_inst->GetOperand(operand_index);
  925. const opt::Operand& dst_operand = dst_inst->GetOperand(operand_index);
  926. if (!DoesOperandMatch(src_operand, dst_operand)) {
  927. return false;
  928. }
  929. }
  930. return true;
  931. }
  932. bool Differ::DoIdsMatchFuzzy(uint32_t src_id, uint32_t dst_id) {
  933. assert(dst_id != 0);
  934. const uint32_t mapped_dst_id = id_map_.MappedDstId(src_id);
  935. // Consider unmatched ids as a match. In function bodies, no result id is
  936. // matched yet and thus they are excluded from instruction matching when used
  937. // as parameters in subsequent instructions.
  938. if (mapped_dst_id == 0 || mapped_dst_id == dst_id) {
  939. return true;
  940. }
  941. // Int and Uint constants are interchangeable, match them in that case.
  942. if (AreIdenticalUintConstants(src_id, dst_id)) {
  943. return true;
  944. }
  945. return false;
  946. }
  947. bool Differ::DoesOperandMatchFuzzy(const opt::Operand& src_operand,
  948. const opt::Operand& dst_operand) {
  949. if (src_operand.type != dst_operand.type) {
  950. return false;
  951. }
  952. assert(src_operand.type != SPV_OPERAND_TYPE_RESULT_ID);
  953. assert(dst_operand.type != SPV_OPERAND_TYPE_RESULT_ID);
  954. switch (src_operand.type) {
  955. case SPV_OPERAND_TYPE_ID:
  956. case SPV_OPERAND_TYPE_TYPE_ID:
  957. case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
  958. case SPV_OPERAND_TYPE_SCOPE_ID:
  959. // Match id operands only if they are already matched in the id map.
  960. return DoIdsMatchFuzzy(src_operand.AsId(), dst_operand.AsId());
  961. default:
  962. // Otherwise allow everything to match.
  963. return true;
  964. }
  965. }
  966. bool Differ::DoInstructionsMatchFuzzy(const opt::Instruction* src_inst,
  967. const opt::Instruction* dst_inst) {
  968. // Similar to DoOperandsMatch, but only checks that ids that have already been
  969. // matched are identical. Ids that are unknown are allowed to match, as well
  970. // as any non-id operand.
  971. if (src_inst->opcode() != dst_inst->opcode()) {
  972. return false;
  973. }
  974. // For external instructions, make sure the set and opcode of the external
  975. // instruction matches too.
  976. if (src_inst->opcode() == spv::Op::OpExtInst) {
  977. if (!DoOperandsMatch(src_inst, dst_inst, 0, 2)) {
  978. return false;
  979. }
  980. }
  981. assert(src_inst->HasResultType() == dst_inst->HasResultType());
  982. if (src_inst->HasResultType() &&
  983. !DoIdsMatchFuzzy(src_inst->type_id(), dst_inst->type_id())) {
  984. return false;
  985. }
  986. // TODO: allow some instructions to match with different instruction lengths,
  987. // for example OpImage* with additional operands.
  988. if (src_inst->NumInOperandWords() != dst_inst->NumInOperandWords()) {
  989. return false;
  990. }
  991. bool match = true;
  992. for (uint32_t in_operand_index = 0;
  993. in_operand_index < src_inst->NumInOperandWords(); ++in_operand_index) {
  994. const opt::Operand& src_operand = src_inst->GetInOperand(in_operand_index);
  995. const opt::Operand& dst_operand = dst_inst->GetInOperand(in_operand_index);
  996. match = match && DoesOperandMatchFuzzy(src_operand, dst_operand);
  997. }
  998. return match;
  999. }
  1000. bool Differ::AreIdenticalUintConstants(uint32_t src_id, uint32_t dst_id) {
  1001. return IsConstantUint(src_id_to_, src_id) &&
  1002. IsConstantUint(dst_id_to_, dst_id) &&
  1003. GetConstantUint(src_id_to_, src_id) ==
  1004. GetConstantUint(dst_id_to_, dst_id);
  1005. }
  1006. bool Differ::DoDebugAndAnnotationInstructionsMatch(
  1007. const opt::Instruction* src_inst, const opt::Instruction* dst_inst) {
  1008. if (src_inst->opcode() != dst_inst->opcode()) {
  1009. return false;
  1010. }
  1011. switch (src_inst->opcode()) {
  1012. case spv::Op::OpString:
  1013. case spv::Op::OpSourceExtension:
  1014. case spv::Op::OpModuleProcessed:
  1015. return DoesOperandMatch(src_inst->GetOperand(0), dst_inst->GetOperand(0));
  1016. case spv::Op::OpSource:
  1017. return DoOperandsMatch(src_inst, dst_inst, 0, 2);
  1018. case spv::Op::OpSourceContinued:
  1019. return true;
  1020. case spv::Op::OpName:
  1021. return DoOperandsMatch(src_inst, dst_inst, 0, 1);
  1022. case spv::Op::OpMemberName:
  1023. return DoOperandsMatch(src_inst, dst_inst, 0, 2);
  1024. case spv::Op::OpDecorate:
  1025. return DoOperandsMatch(src_inst, dst_inst, 0, 2);
  1026. case spv::Op::OpMemberDecorate:
  1027. return DoOperandsMatch(src_inst, dst_inst, 0, 3);
  1028. case spv::Op::OpExtInst:
  1029. case spv::Op::OpDecorationGroup:
  1030. case spv::Op::OpGroupDecorate:
  1031. case spv::Op::OpGroupMemberDecorate:
  1032. return false;
  1033. default:
  1034. return false;
  1035. }
  1036. }
  1037. bool Differ::AreVariablesMatchable(uint32_t src_id, uint32_t dst_id,
  1038. uint32_t flexibility) {
  1039. // Variables must match by their built-in decorations.
  1040. uint32_t src_built_in_decoration = 0, dst_built_in_decoration = 0;
  1041. const bool src_is_built_in = GetDecorationValue(
  1042. src_id_to_, src_id, spv::Decoration::BuiltIn, &src_built_in_decoration);
  1043. const bool dst_is_built_in = GetDecorationValue(
  1044. dst_id_to_, dst_id, spv::Decoration::BuiltIn, &dst_built_in_decoration);
  1045. if (src_is_built_in != dst_is_built_in) {
  1046. return false;
  1047. }
  1048. if (src_is_built_in && src_built_in_decoration != dst_built_in_decoration) {
  1049. return false;
  1050. }
  1051. // Check their types and storage classes.
  1052. spv::StorageClass src_storage_class, dst_storage_class;
  1053. const uint32_t src_type_id =
  1054. GetVarTypeId(src_id_to_, src_id, &src_storage_class);
  1055. const uint32_t dst_type_id =
  1056. GetVarTypeId(dst_id_to_, dst_id, &dst_storage_class);
  1057. if (!DoIdsMatch(src_type_id, dst_type_id)) {
  1058. return false;
  1059. }
  1060. switch (flexibility) {
  1061. case 0:
  1062. if (src_storage_class != dst_storage_class) {
  1063. return false;
  1064. }
  1065. break;
  1066. case 1:
  1067. if (src_storage_class != dst_storage_class) {
  1068. // Allow one of the two to be Private while the other is Input or
  1069. // Output, this allows matching in/out variables that have been turned
  1070. // global as part of linking two stages (as done in ANGLE).
  1071. const bool src_is_io = src_storage_class == spv::StorageClass::Input ||
  1072. src_storage_class == spv::StorageClass::Output;
  1073. const bool dst_is_io = dst_storage_class == spv::StorageClass::Input ||
  1074. dst_storage_class == spv::StorageClass::Output;
  1075. const bool src_is_private =
  1076. src_storage_class == spv::StorageClass::Private;
  1077. const bool dst_is_private =
  1078. dst_storage_class == spv::StorageClass::Private;
  1079. if (!((src_is_io && dst_is_private) || (src_is_private && dst_is_io))) {
  1080. return false;
  1081. }
  1082. }
  1083. break;
  1084. default:
  1085. assert(false && "Unreachable");
  1086. return false;
  1087. }
  1088. // TODO: Is there any other way to check compatiblity of the variables? It's
  1089. // easy to tell when the variables definitely don't match, but there's little
  1090. // information that can be used for a definite match.
  1091. return true;
  1092. }
  1093. bool Differ::MatchOpTypeStruct(const opt::Instruction* src_inst,
  1094. const opt::Instruction* dst_inst,
  1095. uint32_t flexibility) {
  1096. const uint32_t src_type_id = src_inst->result_id();
  1097. const uint32_t dst_type_id = dst_inst->result_id();
  1098. bool src_has_name = false, dst_has_name = false;
  1099. std::string src_name = GetName(src_id_to_, src_type_id, &src_has_name);
  1100. std::string dst_name = GetName(dst_id_to_, dst_type_id, &dst_has_name);
  1101. // If debug info is present, always match the structs by name.
  1102. if (src_has_name && dst_has_name) {
  1103. if (src_name != dst_name) {
  1104. return false;
  1105. }
  1106. // For gl_PerVertex, find the type pointer of this type (array) and make
  1107. // sure the storage classes of src and dst match; geometry and tessellation
  1108. // shaders have two instances of gl_PerVertex.
  1109. if (src_name == "gl_PerVertex") {
  1110. return MatchPerVertexType(src_type_id, dst_type_id);
  1111. }
  1112. return true;
  1113. }
  1114. // If debug info is not present, match the structs by their type.
  1115. // For gl_PerVertex, find the type pointer of this type (array) and match by
  1116. // storage class. The gl_PerVertex struct is itself found by the BuiltIn
  1117. // decorations applied to its members.
  1118. const bool src_is_per_vertex = IsPerVertexType(src_id_to_, src_type_id);
  1119. const bool dst_is_per_vertex = IsPerVertexType(dst_id_to_, dst_type_id);
  1120. if (src_is_per_vertex != dst_is_per_vertex) {
  1121. return false;
  1122. }
  1123. if (src_is_per_vertex) {
  1124. return MatchPerVertexType(src_type_id, dst_type_id);
  1125. }
  1126. switch (flexibility) {
  1127. case 0:
  1128. if (src_inst->NumInOperandWords() != dst_inst->NumInOperandWords()) {
  1129. return false;
  1130. }
  1131. return DoOperandsMatch(src_inst, dst_inst, 0,
  1132. src_inst->NumInOperandWords());
  1133. case 1:
  1134. // TODO: match by taking a diff of the fields, and see if there's a >75%
  1135. // match. Need to then make sure OpMemberName, OpMemberDecorate,
  1136. // OpAccessChain etc are aware of the struct field matching.
  1137. return false;
  1138. default:
  1139. assert(false && "Unreachable");
  1140. return false;
  1141. }
  1142. }
  1143. bool Differ::MatchOpConstant(const opt::Instruction* src_inst,
  1144. const opt::Instruction* dst_inst,
  1145. uint32_t flexibility) {
  1146. // The constants' type must match. In flexibility == 1, match constants of
  1147. // int and uint, as they are generally interchangeable.
  1148. switch (flexibility) {
  1149. case 0:
  1150. if (!DoesOperandMatch(src_inst->GetOperand(0), dst_inst->GetOperand(0))) {
  1151. return false;
  1152. }
  1153. break;
  1154. case 1:
  1155. if (!IsIntType(src_id_to_, src_inst->type_id()) ||
  1156. !IsIntType(dst_id_to_, dst_inst->type_id())) {
  1157. return false;
  1158. }
  1159. break;
  1160. default:
  1161. assert(false && "Unreachable");
  1162. return false;
  1163. }
  1164. const opt::Operand& src_value_operand = src_inst->GetOperand(2);
  1165. const opt::Operand& dst_value_operand = dst_inst->GetOperand(2);
  1166. const uint64_t src_value = src_value_operand.AsLiteralUint64();
  1167. const uint64_t dst_value = dst_value_operand.AsLiteralUint64();
  1168. // If values are identical, it's a match.
  1169. if (src_value == dst_value) {
  1170. return true;
  1171. }
  1172. // Otherwise, only allow flexibility for float types.
  1173. if (IsFloatType(src_id_to_, src_inst->type_id()) && flexibility == 1) {
  1174. // Tolerance is:
  1175. //
  1176. // - For float: allow 4 bits of mantissa as error
  1177. // - For double: allow 6 bits of mantissa as error
  1178. //
  1179. // TODO: the above values are arbitrary and a placeholder; investigate the
  1180. // amount of error resulting from using `printf("%f", f)` and `printf("%lf",
  1181. // d)` and having glslang parse them.
  1182. const uint64_t tolerance = src_value_operand.words.size() == 1 ? 16 : 64;
  1183. return src_value - dst_value < tolerance ||
  1184. dst_value - src_value < tolerance;
  1185. }
  1186. return false;
  1187. }
  1188. bool Differ::MatchOpSpecConstant(const opt::Instruction* src_inst,
  1189. const opt::Instruction* dst_inst) {
  1190. const uint32_t src_id = src_inst->result_id();
  1191. const uint32_t dst_id = dst_inst->result_id();
  1192. bool src_has_name = false, dst_has_name = false;
  1193. std::string src_name = GetName(src_id_to_, src_id, &src_has_name);
  1194. std::string dst_name = GetName(dst_id_to_, dst_id, &dst_has_name);
  1195. // If debug info is present, always match the spec consts by name.
  1196. if (src_has_name && dst_has_name) {
  1197. return src_name == dst_name;
  1198. }
  1199. // Otherwise, match them by SpecId.
  1200. uint32_t src_spec_id, dst_spec_id;
  1201. if (GetDecorationValue(src_id_to_, src_id, spv::Decoration::SpecId,
  1202. &src_spec_id) &&
  1203. GetDecorationValue(dst_id_to_, dst_id, spv::Decoration::SpecId,
  1204. &dst_spec_id)) {
  1205. return src_spec_id == dst_spec_id;
  1206. }
  1207. // There is no SpecId decoration, while not practical, still valid.
  1208. // SpecConstantOp don't have SpecId and can be matched by operands
  1209. if (src_inst->opcode() == spv::Op::OpSpecConstantOp) {
  1210. if (src_inst->NumInOperandWords() == dst_inst->NumInOperandWords()) {
  1211. return DoOperandsMatch(src_inst, dst_inst, 0,
  1212. src_inst->NumInOperandWords());
  1213. }
  1214. }
  1215. return false;
  1216. }
  1217. bool Differ::MatchOpVariable(const opt::Instruction* src_inst,
  1218. const opt::Instruction* dst_inst,
  1219. uint32_t flexibility) {
  1220. const uint32_t src_id = src_inst->result_id();
  1221. const uint32_t dst_id = dst_inst->result_id();
  1222. const bool src_is_pervertex = IsPerVertexVariable(src_id_to_, src_id);
  1223. const bool dst_is_pervertex = IsPerVertexVariable(dst_id_to_, dst_id);
  1224. // For gl_PerVertex, make sure the input and output instances are matched
  1225. // correctly.
  1226. if (src_is_pervertex != dst_is_pervertex) {
  1227. return false;
  1228. }
  1229. if (src_is_pervertex) {
  1230. return MatchPerVertexVariable(src_inst, dst_inst);
  1231. }
  1232. bool src_has_name = false, dst_has_name = false;
  1233. std::string src_name = GetName(src_id_to_, src_id, &src_has_name);
  1234. std::string dst_name = GetName(dst_id_to_, dst_id, &dst_has_name);
  1235. // If debug info is present, always match the variables by name.
  1236. if (src_has_name && dst_has_name) {
  1237. return src_name == dst_name;
  1238. }
  1239. // If debug info is not present, see if the variables can be matched by their
  1240. // built-in decorations.
  1241. uint32_t src_built_in_decoration;
  1242. const bool src_is_built_in = GetDecorationValue(
  1243. src_id_to_, src_id, spv::Decoration::BuiltIn, &src_built_in_decoration);
  1244. if (src_is_built_in && AreVariablesMatchable(src_id, dst_id, flexibility)) {
  1245. return true;
  1246. }
  1247. spv::StorageClass src_storage_class, dst_storage_class;
  1248. GetVarTypeId(src_id_to_, src_id, &src_storage_class);
  1249. GetVarTypeId(dst_id_to_, dst_id, &dst_storage_class);
  1250. if (src_storage_class != dst_storage_class) {
  1251. return false;
  1252. }
  1253. // If variables are decorated with set/binding, match by the value of those
  1254. // decorations.
  1255. if (!options_.ignore_set_binding) {
  1256. uint32_t src_set = 0, dst_set = 0;
  1257. uint32_t src_binding = 0, dst_binding = 0;
  1258. const bool src_has_set = GetDecorationValue(
  1259. src_id_to_, src_id, spv::Decoration::DescriptorSet, &src_set);
  1260. const bool dst_has_set = GetDecorationValue(
  1261. dst_id_to_, dst_id, spv::Decoration::DescriptorSet, &dst_set);
  1262. const bool src_has_binding = GetDecorationValue(
  1263. src_id_to_, src_id, spv::Decoration::Binding, &src_set);
  1264. const bool dst_has_binding = GetDecorationValue(
  1265. dst_id_to_, dst_id, spv::Decoration::Binding, &dst_set);
  1266. if (src_has_set && dst_has_set && src_has_binding && dst_has_binding) {
  1267. return src_set == dst_set && src_binding == dst_binding;
  1268. }
  1269. }
  1270. // If variables are decorated with location, match by the value of that
  1271. // decoration.
  1272. if (!options_.ignore_location) {
  1273. uint32_t src_location, dst_location;
  1274. const bool src_has_location = GetDecorationValue(
  1275. src_id_to_, src_id, spv::Decoration::Location, &src_location);
  1276. const bool dst_has_location = GetDecorationValue(
  1277. dst_id_to_, dst_id, spv::Decoration::Location, &dst_location);
  1278. if (src_has_location && dst_has_location) {
  1279. return src_location == dst_location;
  1280. }
  1281. }
  1282. // Currently, there's no other way to match variables.
  1283. return false;
  1284. }
  1285. bool Differ::MatchPerVertexType(uint32_t src_type_id, uint32_t dst_type_id) {
  1286. // For gl_PerVertex, find the type pointer of this type (array) and make sure
  1287. // the storage classes of src and dst match; geometry and tessellation shaders
  1288. // have two instances of gl_PerVertex.
  1289. spv::StorageClass src_storage_class =
  1290. GetPerVertexStorageClass(src_, src_type_id);
  1291. spv::StorageClass dst_storage_class =
  1292. GetPerVertexStorageClass(dst_, dst_type_id);
  1293. assert(src_storage_class == spv::StorageClass::Input ||
  1294. src_storage_class == spv::StorageClass::Output);
  1295. assert(dst_storage_class == spv::StorageClass::Input ||
  1296. dst_storage_class == spv::StorageClass::Output);
  1297. return src_storage_class == dst_storage_class;
  1298. }
  1299. bool Differ::MatchPerVertexVariable(const opt::Instruction* src_inst,
  1300. const opt::Instruction* dst_inst) {
  1301. spv::StorageClass src_storage_class =
  1302. spv::StorageClass(src_inst->GetSingleWordInOperand(0));
  1303. spv::StorageClass dst_storage_class =
  1304. spv::StorageClass(dst_inst->GetSingleWordInOperand(0));
  1305. return src_storage_class == dst_storage_class;
  1306. }
  1307. void Differ::MatchTypeForwardPointersByName(const IdGroup& src,
  1308. const IdGroup& dst) {
  1309. // Given two sets of compatible groups of OpTypeForwardPointer instructions,
  1310. // attempts to match them by name.
  1311. // Group them by debug info and loop over them.
  1312. GroupIdsAndMatch<std::string>(
  1313. src, dst, "", &Differ::GetSanitizedName,
  1314. [this](const IdGroup& src_group, const IdGroup& dst_group) {
  1315. // Match only if there's a unique forward declaration with this debug
  1316. // name.
  1317. if (src_group.size() == 1 && dst_group.size() == 1) {
  1318. id_map_.MapIds(src_group[0], dst_group[0]);
  1319. }
  1320. });
  1321. }
  1322. void Differ::MatchTypeForwardPointersByTypeOp(const IdGroup& src,
  1323. const IdGroup& dst) {
  1324. // Given two sets of compatible groups of OpTypeForwardPointer instructions,
  1325. // attempts to match them by type op. Must be called after
  1326. // MatchTypeForwardPointersByName to match as many as possible by debug info.
  1327. // Remove ids that are matched with debug info in
  1328. // MatchTypeForwardPointersByName.
  1329. IdGroup src_unmatched_ids;
  1330. IdGroup dst_unmatched_ids;
  1331. std::copy_if(src.begin(), src.end(), std::back_inserter(src_unmatched_ids),
  1332. [this](uint32_t id) { return !id_map_.IsSrcMapped(id); });
  1333. std::copy_if(dst.begin(), dst.end(), std::back_inserter(dst_unmatched_ids),
  1334. [this](uint32_t id) { return !id_map_.IsDstMapped(id); });
  1335. // Match only if there's a unique forward declaration with this
  1336. // storage class and type opcode. If both have debug info, they
  1337. // must not have been matchable.
  1338. if (src_unmatched_ids.size() == 1 && dst_unmatched_ids.size() == 1) {
  1339. uint32_t src_id = src_unmatched_ids[0];
  1340. uint32_t dst_id = dst_unmatched_ids[0];
  1341. if (!HasName(src_id_to_, src_id) || !HasName(dst_id_to_, dst_id)) {
  1342. id_map_.MapIds(src_id, dst_id);
  1343. }
  1344. }
  1345. }
  1346. InstructionList Differ::GetFunctionBody(opt::IRContext* context,
  1347. opt::Function& function) {
  1348. // Canonicalize the blocks of the function to produce better diff, for example
  1349. // to not produce any diff if the src and dst have the same switch/case blocks
  1350. // but with the cases simply reordered.
  1351. std::list<opt::BasicBlock*> order;
  1352. context->cfg()->ComputeStructuredOrder(&function, &*function.begin(), &order);
  1353. // Go over the instructions of the function and add the instructions to a flat
  1354. // list to simplify future iterations.
  1355. InstructionList body;
  1356. for (opt::BasicBlock* block : order) {
  1357. block->ForEachInst(
  1358. [&body](const opt::Instruction* inst) { body.push_back(inst); }, true);
  1359. }
  1360. body.push_back(function.EndInst());
  1361. return body;
  1362. }
  1363. InstructionList Differ::GetFunctionHeader(const opt::Function& function) {
  1364. // Go over the instructions of the function and add the header instructions to
  1365. // a flat list to simplify diff generation.
  1366. InstructionList body;
  1367. function.WhileEachInst(
  1368. [&body](const opt::Instruction* inst) {
  1369. if (inst->opcode() == spv::Op::OpLabel) {
  1370. return false;
  1371. }
  1372. body.push_back(inst);
  1373. return true;
  1374. },
  1375. true, true);
  1376. return body;
  1377. }
  1378. void Differ::GetFunctionBodies(opt::IRContext* context, FunctionMap* functions,
  1379. FunctionInstMap* function_insts) {
  1380. for (opt::Function& function : *context->module()) {
  1381. uint32_t id = function.result_id();
  1382. assert(functions->find(id) == functions->end());
  1383. assert(function_insts->find(id) == function_insts->end());
  1384. (*functions)[id] = &function;
  1385. InstructionList body = GetFunctionBody(context, function);
  1386. (*function_insts)[id] = std::move(body);
  1387. }
  1388. }
  1389. void Differ::GetFunctionHeaderInstructions(const opt::Module* module,
  1390. FunctionInstMap* function_insts) {
  1391. for (opt::Function& function : *module) {
  1392. InstructionList body = GetFunctionHeader(function);
  1393. (*function_insts)[function.result_id()] = std::move(body);
  1394. }
  1395. }
  1396. void Differ::BestEffortMatchFunctions(const IdGroup& src_func_ids,
  1397. const IdGroup& dst_func_ids,
  1398. const FunctionInstMap& src_func_insts,
  1399. const FunctionInstMap& dst_func_insts) {
  1400. struct MatchResult {
  1401. uint32_t src_id;
  1402. uint32_t dst_id;
  1403. DiffMatch src_match;
  1404. DiffMatch dst_match;
  1405. float match_rate;
  1406. bool operator<(const MatchResult& other) const {
  1407. return match_rate > other.match_rate;
  1408. }
  1409. };
  1410. std::vector<MatchResult> all_match_results;
  1411. for (const uint32_t src_func_id : src_func_ids) {
  1412. if (id_map_.IsSrcMapped(src_func_id)) {
  1413. continue;
  1414. }
  1415. const std::string src_name = GetSanitizedName(src_id_to_, src_func_id);
  1416. for (const uint32_t dst_func_id : dst_func_ids) {
  1417. if (id_map_.IsDstMapped(dst_func_id)) {
  1418. continue;
  1419. }
  1420. // Don't match functions that are named, but the names are different.
  1421. const std::string dst_name = GetSanitizedName(dst_id_to_, dst_func_id);
  1422. if (src_name != "" && dst_name != "" && src_name != dst_name) {
  1423. continue;
  1424. }
  1425. DiffMatch src_match_result, dst_match_result;
  1426. float match_rate = MatchFunctionBodies(
  1427. src_func_insts.at(src_func_id), dst_func_insts.at(dst_func_id),
  1428. &src_match_result, &dst_match_result);
  1429. // Only consider the functions a match if there's at least 60% match.
  1430. // This is an arbitrary limit that should be tuned.
  1431. constexpr float pass_match_rate = 0.6f;
  1432. if (match_rate >= pass_match_rate) {
  1433. all_match_results.emplace_back(
  1434. MatchResult{src_func_id, dst_func_id, std::move(src_match_result),
  1435. std::move(dst_match_result), match_rate});
  1436. }
  1437. }
  1438. }
  1439. std::sort(all_match_results.begin(), all_match_results.end());
  1440. for (const MatchResult& match_result : all_match_results) {
  1441. if (id_map_.IsSrcMapped(match_result.src_id) ||
  1442. id_map_.IsDstMapped(match_result.dst_id)) {
  1443. continue;
  1444. }
  1445. id_map_.MapIds(match_result.src_id, match_result.dst_id);
  1446. MatchFunctionParamIds(src_funcs_[match_result.src_id],
  1447. dst_funcs_[match_result.dst_id]);
  1448. MatchIdsInFunctionBodies(src_func_insts.at(match_result.src_id),
  1449. dst_func_insts.at(match_result.dst_id),
  1450. match_result.src_match, match_result.dst_match, 0);
  1451. }
  1452. }
  1453. void Differ::MatchFunctionParamIds(const opt::Function* src_func,
  1454. const opt::Function* dst_func) {
  1455. IdGroup src_params;
  1456. IdGroup dst_params;
  1457. src_func->ForEachParam(
  1458. [&src_params](const opt::Instruction* param) {
  1459. src_params.push_back(param->result_id());
  1460. },
  1461. false);
  1462. dst_func->ForEachParam(
  1463. [&dst_params](const opt::Instruction* param) {
  1464. dst_params.push_back(param->result_id());
  1465. },
  1466. false);
  1467. GroupIdsAndMatch<std::string>(
  1468. src_params, dst_params, "", &Differ::GetSanitizedName,
  1469. [this](const IdGroup& src_group, const IdGroup& dst_group) {
  1470. // There shouldn't be two parameters with the same name, so the ids
  1471. // should match. There is nothing restricting the SPIR-V however to have
  1472. // two parameters with the same name, so be resilient against that.
  1473. if (src_group.size() == 1 && dst_group.size() == 1) {
  1474. id_map_.MapIds(src_group[0], dst_group[0]);
  1475. }
  1476. });
  1477. // Then match the parameters by their type. If there are multiple of them,
  1478. // match them by their order.
  1479. GroupIdsAndMatchByMappedId(
  1480. src_params, dst_params, &Differ::GroupIdsHelperGetTypeId,
  1481. [this](const IdGroup& src_group_by_type_id,
  1482. const IdGroup& dst_group_by_type_id) {
  1483. const size_t shared_param_count =
  1484. std::min(src_group_by_type_id.size(), dst_group_by_type_id.size());
  1485. for (size_t param_index = 0; param_index < shared_param_count;
  1486. ++param_index) {
  1487. id_map_.MapIds(src_group_by_type_id[param_index],
  1488. dst_group_by_type_id[param_index]);
  1489. }
  1490. });
  1491. }
  1492. float Differ::MatchFunctionBodies(const InstructionList& src_body,
  1493. const InstructionList& dst_body,
  1494. DiffMatch* src_match_result,
  1495. DiffMatch* dst_match_result) {
  1496. LongestCommonSubsequence<std::vector<const opt::Instruction*>> lcs(src_body,
  1497. dst_body);
  1498. uint32_t best_match_length = lcs.Get<const opt::Instruction*>(
  1499. [this](const opt::Instruction* src_inst,
  1500. const opt::Instruction* dst_inst) {
  1501. return DoInstructionsMatchFuzzy(src_inst, dst_inst);
  1502. },
  1503. src_match_result, dst_match_result);
  1504. // TODO: take the gaps in between matches and match those again with a relaxed
  1505. // instruction-and-type-only comparison. This can produce a better diff for
  1506. // example if an array index is changed, causing the OpAccessChain id to not
  1507. // match and subsequently every operation that's derived from that id.
  1508. // Usually this mismatch cascades until the next OpStore which doesn't produce
  1509. // an id.
  1510. return static_cast<float>(best_match_length) * 2.0f /
  1511. static_cast<float>(src_body.size() + dst_body.size());
  1512. }
  1513. void Differ::MatchIdsInFunctionBodies(const InstructionList& src_body,
  1514. const InstructionList& dst_body,
  1515. const DiffMatch& src_match_result,
  1516. const DiffMatch& dst_match_result,
  1517. uint32_t flexibility) {
  1518. size_t src_cur = 0;
  1519. size_t dst_cur = 0;
  1520. while (src_cur < src_body.size() && dst_cur < dst_body.size()) {
  1521. if (src_match_result[src_cur] && dst_match_result[dst_cur]) {
  1522. // Match instructions the src and dst instructions.
  1523. //
  1524. // TODO: count the matchings between variables discovered this way and
  1525. // choose the "best match" after all functions have been diffed and all
  1526. // instructions analyzed.
  1527. const opt::Instruction* src_inst = src_body[src_cur++];
  1528. const opt::Instruction* dst_inst = dst_body[dst_cur++];
  1529. // Record the matching between the instructions. This is done only once
  1530. // (hence flexibility == 0). Calls with non-zero flexibility values will
  1531. // only deal with matching other ids based on the operands.
  1532. if (flexibility == 0) {
  1533. id_map_.MapInsts(src_inst, dst_inst);
  1534. }
  1535. // Match any unmatched variables referenced by the instructions.
  1536. MatchVariablesUsedByMatchedInstructions(src_inst, dst_inst, flexibility);
  1537. continue;
  1538. }
  1539. if (!src_match_result[src_cur]) {
  1540. ++src_cur;
  1541. }
  1542. if (!dst_match_result[dst_cur]) {
  1543. ++dst_cur;
  1544. }
  1545. }
  1546. }
  1547. void Differ::MatchVariablesUsedByMatchedInstructions(
  1548. const opt::Instruction* src_inst, const opt::Instruction* dst_inst,
  1549. uint32_t flexibility) {
  1550. // For OpAccessChain, OpLoad and OpStore instructions that reference unmatched
  1551. // variables, match them as a best effort.
  1552. assert(src_inst->opcode() == dst_inst->opcode());
  1553. switch (src_inst->opcode()) {
  1554. default:
  1555. // TODO: match functions based on OpFunctionCall?
  1556. break;
  1557. case spv::Op::OpAccessChain:
  1558. case spv::Op::OpInBoundsAccessChain:
  1559. case spv::Op::OpPtrAccessChain:
  1560. case spv::Op::OpInBoundsPtrAccessChain:
  1561. case spv::Op::OpLoad:
  1562. case spv::Op::OpStore:
  1563. const uint32_t src_pointer_id = src_inst->GetSingleWordInOperand(0);
  1564. const uint32_t dst_pointer_id = dst_inst->GetSingleWordInOperand(0);
  1565. if (IsVariable(src_id_to_, src_pointer_id) &&
  1566. IsVariable(dst_id_to_, dst_pointer_id) &&
  1567. !id_map_.IsSrcMapped(src_pointer_id) &&
  1568. !id_map_.IsDstMapped(dst_pointer_id) &&
  1569. AreVariablesMatchable(src_pointer_id, dst_pointer_id, flexibility)) {
  1570. id_map_.MapIds(src_pointer_id, dst_pointer_id);
  1571. }
  1572. break;
  1573. }
  1574. }
  1575. const opt::Instruction* Differ::GetInst(const IdInstructions& id_to,
  1576. uint32_t id) {
  1577. assert(id != 0);
  1578. assert(id < id_to.inst_map_.size());
  1579. const opt::Instruction* inst = id_to.inst_map_[id];
  1580. assert(inst != nullptr);
  1581. return inst;
  1582. }
  1583. uint32_t Differ::GetConstantUint(const IdInstructions& id_to,
  1584. uint32_t constant_id) {
  1585. const opt::Instruction* constant_inst = GetInst(id_to, constant_id);
  1586. assert(constant_inst->opcode() == spv::Op::OpConstant);
  1587. assert(GetInst(id_to, constant_inst->type_id())->opcode() ==
  1588. spv::Op::OpTypeInt);
  1589. return constant_inst->GetSingleWordInOperand(0);
  1590. }
  1591. spv::ExecutionModel Differ::GetExecutionModel(const opt::Module* module,
  1592. uint32_t entry_point_id) {
  1593. for (const opt::Instruction& inst : module->entry_points()) {
  1594. assert(inst.opcode() == spv::Op::OpEntryPoint);
  1595. if (inst.GetSingleWordOperand(1) == entry_point_id) {
  1596. return spv::ExecutionModel(inst.GetSingleWordOperand(0));
  1597. }
  1598. }
  1599. assert(false && "Unreachable");
  1600. return spv::ExecutionModel(0xFFF);
  1601. }
  1602. bool Differ::HasName(const IdInstructions& id_to, uint32_t id) {
  1603. assert(id != 0);
  1604. assert(id < id_to.name_map_.size());
  1605. for (const opt::Instruction* inst : id_to.name_map_[id]) {
  1606. if (inst->opcode() == spv::Op::OpName) {
  1607. return true;
  1608. }
  1609. }
  1610. return false;
  1611. }
  1612. std::string Differ::GetName(const IdInstructions& id_to, uint32_t id,
  1613. bool* has_name) {
  1614. assert(id != 0);
  1615. assert(id < id_to.name_map_.size());
  1616. for (const opt::Instruction* inst : id_to.name_map_[id]) {
  1617. if (inst->opcode() == spv::Op::OpName) {
  1618. *has_name = true;
  1619. return inst->GetOperand(1).AsString();
  1620. }
  1621. }
  1622. *has_name = false;
  1623. return "";
  1624. }
  1625. std::string Differ::GetSanitizedName(const IdInstructions& id_to, uint32_t id) {
  1626. bool has_name = false;
  1627. std::string name = GetName(id_to, id, &has_name);
  1628. if (!has_name) {
  1629. return "";
  1630. }
  1631. // Remove args from the name, in case this is a function name
  1632. return name.substr(0, name.find('('));
  1633. }
  1634. uint32_t Differ::GetVarTypeId(const IdInstructions& id_to, uint32_t var_id,
  1635. spv::StorageClass* storage_class) {
  1636. const opt::Instruction* var_inst = GetInst(id_to, var_id);
  1637. assert(var_inst->opcode() == spv::Op::OpVariable);
  1638. *storage_class = spv::StorageClass(var_inst->GetSingleWordInOperand(0));
  1639. // Get the type pointer from the variable.
  1640. const uint32_t type_pointer_id = var_inst->type_id();
  1641. const opt::Instruction* type_pointer_inst = GetInst(id_to, type_pointer_id);
  1642. // Get the type from the type pointer.
  1643. return type_pointer_inst->GetSingleWordInOperand(1);
  1644. }
  1645. bool Differ::GetDecorationValue(const IdInstructions& id_to, uint32_t id,
  1646. spv::Decoration decoration,
  1647. uint32_t* decoration_value) {
  1648. assert(id != 0);
  1649. assert(id < id_to.decoration_map_.size());
  1650. for (const opt::Instruction* inst : id_to.decoration_map_[id]) {
  1651. if (inst->opcode() == spv::Op::OpDecorate &&
  1652. inst->GetSingleWordOperand(0) == id &&
  1653. spv::Decoration(inst->GetSingleWordOperand(1)) == decoration) {
  1654. *decoration_value = inst->GetSingleWordOperand(2);
  1655. return true;
  1656. }
  1657. }
  1658. return false;
  1659. }
  1660. const opt::Instruction* Differ::GetForwardPointerInst(
  1661. const IdInstructions& id_to, uint32_t id) {
  1662. assert(id != 0);
  1663. assert(id < id_to.forward_pointer_map_.size());
  1664. return id_to.forward_pointer_map_[id];
  1665. }
  1666. bool Differ::IsIntType(const IdInstructions& id_to, uint32_t type_id) {
  1667. return IsOp(id_to, type_id, spv::Op::OpTypeInt);
  1668. }
  1669. bool Differ::IsFloatType(const IdInstructions& id_to, uint32_t type_id) {
  1670. return IsOp(id_to, type_id, spv::Op::OpTypeFloat);
  1671. }
  1672. bool Differ::IsConstantUint(const IdInstructions& id_to, uint32_t id) {
  1673. const opt::Instruction* constant_inst = GetInst(id_to, id);
  1674. if (constant_inst->opcode() != spv::Op::OpConstant) {
  1675. return false;
  1676. }
  1677. const opt::Instruction* type_inst = GetInst(id_to, constant_inst->type_id());
  1678. return type_inst->opcode() == spv::Op::OpTypeInt;
  1679. }
  1680. bool Differ::IsVariable(const IdInstructions& id_to, uint32_t pointer_id) {
  1681. return IsOp(id_to, pointer_id, spv::Op::OpVariable);
  1682. }
  1683. bool Differ::IsOp(const IdInstructions& id_to, uint32_t id, spv::Op op) {
  1684. return GetInst(id_to, id)->opcode() == op;
  1685. }
  1686. bool Differ::IsPerVertexType(const IdInstructions& id_to, uint32_t type_id) {
  1687. assert(type_id != 0);
  1688. assert(type_id < id_to.decoration_map_.size());
  1689. for (const opt::Instruction* inst : id_to.decoration_map_[type_id]) {
  1690. if (inst->opcode() == spv::Op::OpMemberDecorate &&
  1691. inst->GetSingleWordOperand(0) == type_id &&
  1692. spv::Decoration(inst->GetSingleWordOperand(2)) ==
  1693. spv::Decoration::BuiltIn) {
  1694. spv::BuiltIn built_in = spv::BuiltIn(inst->GetSingleWordOperand(3));
  1695. // Only gl_PerVertex can have, and it can only have, the following
  1696. // built-in decorations.
  1697. return built_in == spv::BuiltIn::Position ||
  1698. built_in == spv::BuiltIn::PointSize ||
  1699. built_in == spv::BuiltIn::ClipDistance ||
  1700. built_in == spv::BuiltIn::CullDistance;
  1701. }
  1702. }
  1703. return false;
  1704. }
  1705. bool Differ::IsPerVertexVariable(const IdInstructions& id_to, uint32_t var_id) {
  1706. // Get the type from the type pointer.
  1707. spv::StorageClass storage_class;
  1708. uint32_t type_id = GetVarTypeId(id_to, var_id, &storage_class);
  1709. const opt::Instruction* type_inst = GetInst(id_to, type_id);
  1710. // If array, get the element type.
  1711. if (type_inst->opcode() == spv::Op::OpTypeArray) {
  1712. type_id = type_inst->GetSingleWordInOperand(0);
  1713. }
  1714. // Now check if the type is gl_PerVertex.
  1715. return IsPerVertexType(id_to, type_id);
  1716. }
  1717. spv::StorageClass Differ::GetPerVertexStorageClass(const opt::Module* module,
  1718. uint32_t type_id) {
  1719. for (const opt::Instruction& inst : module->types_values()) {
  1720. switch (inst.opcode()) {
  1721. case spv::Op::OpTypeArray:
  1722. // The gl_PerVertex instance could be an array, look for a variable of
  1723. // the array type instead.
  1724. if (inst.GetSingleWordInOperand(0) == type_id) {
  1725. type_id = inst.result_id();
  1726. }
  1727. break;
  1728. case spv::Op::OpTypePointer:
  1729. // Find the storage class of the pointer to this type.
  1730. if (inst.GetSingleWordInOperand(1) == type_id) {
  1731. return spv::StorageClass(inst.GetSingleWordInOperand(0));
  1732. }
  1733. break;
  1734. default:
  1735. break;
  1736. }
  1737. }
  1738. // gl_PerVertex is declared, but is unused. Return either of Input or Output
  1739. // classes just so it matches one in the other module. This should be highly
  1740. // unlikely, perhaps except for ancient GS-used-to-emulate-CS scenarios.
  1741. return spv::StorageClass::Output;
  1742. }
  1743. spv_ext_inst_type_t Differ::GetExtInstType(const IdInstructions& id_to,
  1744. uint32_t set_id) {
  1745. const opt::Instruction* set_inst = GetInst(id_to, set_id);
  1746. return spvExtInstImportTypeGet(set_inst->GetInOperand(0).AsString().c_str());
  1747. }
  1748. spv_number_kind_t Differ::GetNumberKind(const IdInstructions& id_to,
  1749. const opt::Instruction& inst,
  1750. uint32_t operand_index,
  1751. uint32_t* number_bit_width) {
  1752. const opt::Operand& operand = inst.GetOperand(operand_index);
  1753. *number_bit_width = 0;
  1754. // A very limited version of Parser::parseOperand.
  1755. switch (operand.type) {
  1756. case SPV_OPERAND_TYPE_LITERAL_INTEGER:
  1757. case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER:
  1758. // Always unsigned integers.
  1759. *number_bit_width = 32;
  1760. return SPV_NUMBER_UNSIGNED_INT;
  1761. case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER:
  1762. case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:
  1763. switch (inst.opcode()) {
  1764. case spv::Op::OpSwitch:
  1765. case spv::Op::OpConstant:
  1766. case spv::Op::OpSpecConstant:
  1767. // Same kind of number as the selector (OpSwitch) or the type
  1768. // (Op*Constant).
  1769. return GetTypeNumberKind(id_to, inst.GetSingleWordOperand(0),
  1770. number_bit_width);
  1771. default:
  1772. assert(false && "Unreachable");
  1773. break;
  1774. }
  1775. break;
  1776. default:
  1777. break;
  1778. }
  1779. return SPV_NUMBER_NONE;
  1780. }
  1781. spv_number_kind_t Differ::GetTypeNumberKind(const IdInstructions& id_to,
  1782. uint32_t id,
  1783. uint32_t* number_bit_width) {
  1784. const opt::Instruction* type_inst = GetInst(id_to, id);
  1785. if (!spvOpcodeIsScalarType(type_inst->opcode())) {
  1786. type_inst = GetInst(id_to, type_inst->type_id());
  1787. }
  1788. switch (type_inst->opcode()) {
  1789. case spv::Op::OpTypeInt:
  1790. *number_bit_width = type_inst->GetSingleWordOperand(1);
  1791. return type_inst->GetSingleWordOperand(2) == 0 ? SPV_NUMBER_UNSIGNED_INT
  1792. : SPV_NUMBER_SIGNED_INT;
  1793. break;
  1794. case spv::Op::OpTypeFloat:
  1795. *number_bit_width = type_inst->GetSingleWordOperand(1);
  1796. return SPV_NUMBER_FLOATING;
  1797. default:
  1798. assert(false && "Unreachable");
  1799. return SPV_NUMBER_NONE;
  1800. }
  1801. }
  1802. void Differ::MatchCapabilities() {
  1803. MatchPreambleInstructions(src_->capabilities(), dst_->capabilities());
  1804. }
  1805. void Differ::MatchExtensions() {
  1806. MatchPreambleInstructions(src_->extensions(), dst_->extensions());
  1807. }
  1808. void Differ::MatchExtInstImportIds() {
  1809. // Bunch all of this section's ids as potential matches.
  1810. PotentialIdMap potential_id_map;
  1811. auto get_result_id = [](const opt::Instruction& inst) {
  1812. return inst.result_id();
  1813. };
  1814. auto accept_all = [](const opt::Instruction&) { return true; };
  1815. PoolPotentialIds(src_->ext_inst_imports(), potential_id_map.src_ids, true,
  1816. accept_all, get_result_id);
  1817. PoolPotentialIds(dst_->ext_inst_imports(), potential_id_map.dst_ids, false,
  1818. accept_all, get_result_id);
  1819. // Then match the ids.
  1820. MatchIds(potential_id_map, [](const opt::Instruction* src_inst,
  1821. const opt::Instruction* dst_inst) {
  1822. // Match OpExtInstImport by exact name, which is operand 1
  1823. const opt::Operand& src_name = src_inst->GetOperand(1);
  1824. const opt::Operand& dst_name = dst_inst->GetOperand(1);
  1825. return src_name.AsString() == dst_name.AsString();
  1826. });
  1827. }
  1828. void Differ::MatchMemoryModel() {
  1829. // Always match the memory model instructions, there is always a single one of
  1830. // it.
  1831. id_map_.MapInsts(src_->GetMemoryModel(), dst_->GetMemoryModel());
  1832. }
  1833. void Differ::MatchEntryPointIds() {
  1834. // Match OpEntryPoint ids (at index 1) by ExecutionModel (at index 0) and
  1835. // possibly name (at index 2). OpEntryPoint doesn't produce a result id, so
  1836. // this function doesn't use the helpers the other functions use.
  1837. // Map from execution model to OpEntryPoint instructions of that model.
  1838. using ExecutionModelMap =
  1839. std::unordered_map<uint32_t, std::vector<const opt::Instruction*>>;
  1840. ExecutionModelMap src_entry_points_map;
  1841. ExecutionModelMap dst_entry_points_map;
  1842. std::set<uint32_t> all_execution_models;
  1843. for (const opt::Instruction& src_inst : src_->entry_points()) {
  1844. uint32_t execution_model = src_inst.GetSingleWordOperand(0);
  1845. src_entry_points_map[execution_model].push_back(&src_inst);
  1846. all_execution_models.insert(execution_model);
  1847. }
  1848. for (const opt::Instruction& dst_inst : dst_->entry_points()) {
  1849. uint32_t execution_model = dst_inst.GetSingleWordOperand(0);
  1850. dst_entry_points_map[execution_model].push_back(&dst_inst);
  1851. all_execution_models.insert(execution_model);
  1852. }
  1853. // Go through each model and match the ids.
  1854. for (const uint32_t execution_model : all_execution_models) {
  1855. auto& src_insts = src_entry_points_map[execution_model];
  1856. auto& dst_insts = dst_entry_points_map[execution_model];
  1857. // If there is only one entry point in src and dst with that model, match
  1858. // them unconditionally.
  1859. if (src_insts.size() == 1 && dst_insts.size() == 1) {
  1860. uint32_t src_id = src_insts[0]->GetSingleWordOperand(1);
  1861. uint32_t dst_id = dst_insts[0]->GetSingleWordOperand(1);
  1862. id_map_.MapIds(src_id, dst_id);
  1863. id_map_.MapInsts(src_insts[0], dst_insts[0]);
  1864. continue;
  1865. }
  1866. // Otherwise match them by name.
  1867. for (const opt::Instruction* src_inst : src_insts) {
  1868. for (const opt::Instruction* dst_inst : dst_insts) {
  1869. if (id_map_.IsDstMapped(dst_inst)) continue;
  1870. const opt::Operand& src_name = src_inst->GetOperand(2);
  1871. const opt::Operand& dst_name = dst_inst->GetOperand(2);
  1872. if (src_name.AsString() == dst_name.AsString()) {
  1873. uint32_t src_id = src_inst->GetSingleWordOperand(1);
  1874. uint32_t dst_id = dst_inst->GetSingleWordOperand(1);
  1875. id_map_.MapIds(src_id, dst_id);
  1876. id_map_.MapInsts(src_inst, dst_inst);
  1877. break;
  1878. }
  1879. }
  1880. }
  1881. }
  1882. }
  1883. void Differ::MatchExecutionModes() {
  1884. MatchPreambleInstructions(src_->execution_modes(), dst_->execution_modes());
  1885. }
  1886. void Differ::MatchTypeForwardPointers() {
  1887. // Bunch all of type forward pointers as potential matches.
  1888. PotentialIdMap potential_id_map;
  1889. auto get_pointer_type_id = [](const opt::Instruction& inst) {
  1890. return inst.GetSingleWordOperand(0);
  1891. };
  1892. auto accept_type_forward_pointer_ops = [](const opt::Instruction& inst) {
  1893. return inst.opcode() == spv::Op::OpTypeForwardPointer;
  1894. };
  1895. PoolPotentialIds(src_->types_values(), potential_id_map.src_ids, true,
  1896. accept_type_forward_pointer_ops, get_pointer_type_id);
  1897. PoolPotentialIds(dst_->types_values(), potential_id_map.dst_ids, false,
  1898. accept_type_forward_pointer_ops, get_pointer_type_id);
  1899. // Matching types with cyclical references (i.e. in the style of linked lists)
  1900. // can get very complex. Currently, the diff tool matches types bottom up, so
  1901. // on every instruction it expects to know if its operands are already matched
  1902. // or not. With cyclical references, it cannot know that. Type matching may
  1903. // need significant modifications to be able to support this use case.
  1904. //
  1905. // Currently, forwarded types are only matched by storage class and debug
  1906. // info, with minimal matching of the type being forwarded:
  1907. //
  1908. // - Group by class
  1909. // - Group by OpType being pointed to
  1910. // - Group by debug info
  1911. // - If same name and unique, match
  1912. // - If leftover is unique, match
  1913. // Group forwarded pointers by storage class first and loop over them.
  1914. GroupIdsAndMatch<spv::StorageClass>(
  1915. potential_id_map.src_ids, potential_id_map.dst_ids,
  1916. spv::StorageClass::Max, &Differ::GroupIdsHelperGetTypePointerStorageClass,
  1917. [this](const IdGroup& src_group_by_storage_class,
  1918. const IdGroup& dst_group_by_storage_class) {
  1919. // Group them further by the type they are pointing to and loop over
  1920. // them.
  1921. GroupIdsAndMatch<spv::Op>(
  1922. src_group_by_storage_class, dst_group_by_storage_class,
  1923. spv::Op::Max, &Differ::GroupIdsHelperGetTypePointerTypeOp,
  1924. [this](const IdGroup& src_group_by_type_op,
  1925. const IdGroup& dst_group_by_type_op) {
  1926. // Group them even further by debug info, if possible and match by
  1927. // debug name.
  1928. MatchTypeForwardPointersByName(src_group_by_type_op,
  1929. dst_group_by_type_op);
  1930. // Match the leftovers only if they lack debug info and there is
  1931. // only one instance of them.
  1932. MatchTypeForwardPointersByTypeOp(src_group_by_type_op,
  1933. dst_group_by_type_op);
  1934. });
  1935. });
  1936. // Match the instructions that forward declare the same type themselves
  1937. for (uint32_t src_id : potential_id_map.src_ids) {
  1938. uint32_t dst_id = id_map_.MappedDstId(src_id);
  1939. if (dst_id == 0) continue;
  1940. const opt::Instruction* src_forward_inst =
  1941. GetForwardPointerInst(src_id_to_, src_id);
  1942. const opt::Instruction* dst_forward_inst =
  1943. GetForwardPointerInst(dst_id_to_, dst_id);
  1944. assert(src_forward_inst);
  1945. assert(dst_forward_inst);
  1946. id_map_.MapInsts(src_forward_inst, dst_forward_inst);
  1947. }
  1948. }
  1949. void Differ::MatchTypeIds() {
  1950. // Bunch all of type ids as potential matches.
  1951. PotentialIdMap potential_id_map;
  1952. auto get_result_id = [](const opt::Instruction& inst) {
  1953. return inst.result_id();
  1954. };
  1955. auto accept_type_ops = [](const opt::Instruction& inst) {
  1956. return spvOpcodeGeneratesType(inst.opcode());
  1957. };
  1958. PoolPotentialIds(src_->types_values(), potential_id_map.src_ids, true,
  1959. accept_type_ops, get_result_id);
  1960. PoolPotentialIds(dst_->types_values(), potential_id_map.dst_ids, false,
  1961. accept_type_ops, get_result_id);
  1962. // Then match the ids. Start with exact matches, then match the leftover with
  1963. // gradually loosening degrees of strictness. For example, in the absence of
  1964. // debug info, two block types will be matched if they differ only in a few of
  1965. // the fields.
  1966. for (uint32_t flexibility = 0; flexibility < 2; ++flexibility) {
  1967. MatchIds(potential_id_map, [this, flexibility](
  1968. const opt::Instruction* src_inst,
  1969. const opt::Instruction* dst_inst) {
  1970. const spv::Op src_op = src_inst->opcode();
  1971. const spv::Op dst_op = dst_inst->opcode();
  1972. // Don't match if the opcode is not the same.
  1973. if (src_op != dst_op) {
  1974. return false;
  1975. }
  1976. switch (src_op) {
  1977. case spv::Op::OpTypeVoid:
  1978. case spv::Op::OpTypeBool:
  1979. case spv::Op::OpTypeSampler:
  1980. case spv::Op::OpTypeAccelerationStructureNV:
  1981. case spv::Op::OpTypeRayQueryKHR:
  1982. // the above types have no operands and are unique, match them.
  1983. return true;
  1984. case spv::Op::OpTypeInt:
  1985. case spv::Op::OpTypeFloat:
  1986. case spv::Op::OpTypeVector:
  1987. case spv::Op::OpTypeMatrix:
  1988. case spv::Op::OpTypeSampledImage:
  1989. case spv::Op::OpTypeRuntimeArray:
  1990. case spv::Op::OpTypePointer:
  1991. // Match these instructions when all operands match.
  1992. assert(src_inst->NumInOperandWords() ==
  1993. dst_inst->NumInOperandWords());
  1994. return DoOperandsMatch(src_inst, dst_inst, 0,
  1995. src_inst->NumInOperandWords());
  1996. case spv::Op::OpTypeFunction:
  1997. case spv::Op::OpTypeImage:
  1998. // Match function types only if they have the same number of operands,
  1999. // and they all match.
  2000. // Match image types similarly, expecting the optional final parameter
  2001. // to match (if provided in both)
  2002. if (src_inst->NumInOperandWords() != dst_inst->NumInOperandWords()) {
  2003. return false;
  2004. }
  2005. return DoOperandsMatch(src_inst, dst_inst, 0,
  2006. src_inst->NumInOperandWords());
  2007. case spv::Op::OpTypeArray:
  2008. // Match arrays only if the element type and length match. The length
  2009. // is an id of a constant, so the actual constant it's defining is
  2010. // compared instead.
  2011. if (!DoOperandsMatch(src_inst, dst_inst, 0, 1)) {
  2012. return false;
  2013. }
  2014. if (AreIdenticalUintConstants(src_inst->GetSingleWordInOperand(1),
  2015. dst_inst->GetSingleWordInOperand(1))) {
  2016. return true;
  2017. }
  2018. // If size is not OpConstant, expect the ids to match exactly (for
  2019. // example if a spec contant is used).
  2020. return DoOperandsMatch(src_inst, dst_inst, 1, 1);
  2021. case spv::Op::OpTypeStruct:
  2022. return MatchOpTypeStruct(src_inst, dst_inst, flexibility);
  2023. default:
  2024. return false;
  2025. }
  2026. });
  2027. }
  2028. }
  2029. void Differ::MatchConstants() {
  2030. // Bunch all of constant ids as potential matches.
  2031. PotentialIdMap potential_id_map;
  2032. auto get_result_id = [](const opt::Instruction& inst) {
  2033. return inst.result_id();
  2034. };
  2035. auto accept_type_ops = [](const opt::Instruction& inst) {
  2036. return spvOpcodeIsConstant(inst.opcode());
  2037. };
  2038. PoolPotentialIds(src_->types_values(), potential_id_map.src_ids, true,
  2039. accept_type_ops, get_result_id);
  2040. PoolPotentialIds(dst_->types_values(), potential_id_map.dst_ids, false,
  2041. accept_type_ops, get_result_id);
  2042. // Then match the ids. Constants are matched exactly, except for float types
  2043. // that are first matched exactly, then leftovers are matched with a small
  2044. // error.
  2045. for (uint32_t flexibility = 0; flexibility < 2; ++flexibility) {
  2046. MatchIds(potential_id_map, [this, flexibility](
  2047. const opt::Instruction* src_inst,
  2048. const opt::Instruction* dst_inst) {
  2049. const spv::Op src_op = src_inst->opcode();
  2050. const spv::Op dst_op = dst_inst->opcode();
  2051. // Don't match if the opcode is not the same.
  2052. if (src_op != dst_op) {
  2053. return false;
  2054. }
  2055. switch (src_op) {
  2056. case spv::Op::OpConstantTrue:
  2057. case spv::Op::OpConstantFalse:
  2058. // true and false are unique, match them.
  2059. return true;
  2060. case spv::Op::OpConstant:
  2061. return MatchOpConstant(src_inst, dst_inst, flexibility);
  2062. case spv::Op::OpConstantComposite:
  2063. case spv::Op::OpSpecConstantComposite:
  2064. // Composite constants must match in type and value.
  2065. //
  2066. // TODO: match OpConstantNull with OpConstantComposite with all zeros
  2067. // at flexibility == 1
  2068. // TODO: match constants from structs that have been flexibly-matched.
  2069. if (src_inst->NumInOperandWords() != dst_inst->NumInOperandWords()) {
  2070. return false;
  2071. }
  2072. return DoesOperandMatch(src_inst->GetOperand(0),
  2073. dst_inst->GetOperand(0)) &&
  2074. DoOperandsMatch(src_inst, dst_inst, 0,
  2075. src_inst->NumInOperandWords());
  2076. case spv::Op::OpConstantSampler:
  2077. // Match sampler constants exactly.
  2078. // TODO: Allow flexibility in parameters to better diff shaders where
  2079. // the sampler param has changed.
  2080. assert(src_inst->NumInOperandWords() ==
  2081. dst_inst->NumInOperandWords());
  2082. return DoOperandsMatch(src_inst, dst_inst, 0,
  2083. src_inst->NumInOperandWords());
  2084. case spv::Op::OpConstantNull:
  2085. // Match null constants as long as the type matches.
  2086. return DoesOperandMatch(src_inst->GetOperand(0),
  2087. dst_inst->GetOperand(0));
  2088. case spv::Op::OpSpecConstantTrue:
  2089. case spv::Op::OpSpecConstantFalse:
  2090. case spv::Op::OpSpecConstant:
  2091. case spv::Op::OpSpecConstantOp:
  2092. // Match spec constants by name if available, then by the SpecId
  2093. // decoration.
  2094. return MatchOpSpecConstant(src_inst, dst_inst);
  2095. default:
  2096. return false;
  2097. }
  2098. });
  2099. }
  2100. }
  2101. void Differ::MatchVariableIds() {
  2102. // Bunch all of variable ids as potential matches.
  2103. PotentialIdMap potential_id_map;
  2104. auto get_result_id = [](const opt::Instruction& inst) {
  2105. return inst.result_id();
  2106. };
  2107. auto accept_type_ops = [](const opt::Instruction& inst) {
  2108. return inst.opcode() == spv::Op::OpVariable;
  2109. };
  2110. PoolPotentialIds(src_->types_values(), potential_id_map.src_ids, true,
  2111. accept_type_ops, get_result_id);
  2112. PoolPotentialIds(dst_->types_values(), potential_id_map.dst_ids, false,
  2113. accept_type_ops, get_result_id);
  2114. // Then match the ids. Start with exact matches, then match the leftover with
  2115. // gradually loosening degrees of strictness. For example, in the absence of
  2116. // debug info, two otherwise identical variables will be matched if one of
  2117. // them has a Private storage class and the other doesn't.
  2118. for (uint32_t flexibility = 0; flexibility < 2; ++flexibility) {
  2119. MatchIds(potential_id_map,
  2120. [this, flexibility](const opt::Instruction* src_inst,
  2121. const opt::Instruction* dst_inst) {
  2122. assert(src_inst->opcode() == spv::Op::OpVariable);
  2123. assert(dst_inst->opcode() == spv::Op::OpVariable);
  2124. return MatchOpVariable(src_inst, dst_inst, flexibility);
  2125. });
  2126. }
  2127. }
  2128. void Differ::MatchFunctions() {
  2129. IdGroup src_func_ids;
  2130. IdGroup dst_func_ids;
  2131. for (const auto& func : src_funcs_) {
  2132. src_func_ids.push_back(func.first);
  2133. }
  2134. for (const auto& func : dst_funcs_) {
  2135. dst_func_ids.push_back(func.first);
  2136. }
  2137. // Base the matching of functions on debug info when available.
  2138. GroupIdsAndMatch<std::string>(
  2139. src_func_ids, dst_func_ids, "", &Differ::GetSanitizedName,
  2140. [this](const IdGroup& src_group, const IdGroup& dst_group) {
  2141. // If there is a single function with this name in src and dst, it's a
  2142. // definite match.
  2143. if (src_group.size() == 1 && dst_group.size() == 1) {
  2144. id_map_.MapIds(src_group[0], dst_group[0]);
  2145. return;
  2146. }
  2147. // If there are multiple functions with the same name, group them by
  2148. // type, and match only if the types match (and are unique).
  2149. GroupIdsAndMatch<uint32_t>(src_group, dst_group, 0,
  2150. &Differ::GroupIdsHelperGetTypeId,
  2151. [this](const IdGroup& src_group_by_type_id,
  2152. const IdGroup& dst_group_by_type_id) {
  2153. if (src_group_by_type_id.size() == 1 &&
  2154. dst_group_by_type_id.size() == 1) {
  2155. id_map_.MapIds(src_group_by_type_id[0],
  2156. dst_group_by_type_id[0]);
  2157. }
  2158. });
  2159. });
  2160. // Any functions that are left are pooled together and matched as if unnamed,
  2161. // with the only exception that two functions with mismatching names are not
  2162. // matched.
  2163. //
  2164. // Before that however, the diff of the functions that are matched are taken
  2165. // and processed, so that more of the global variables can be matched before
  2166. // attempting to match the rest of the functions. They can contribute to the
  2167. // precision of the diff of those functions.
  2168. for (const uint32_t src_func_id : src_func_ids) {
  2169. const uint32_t dst_func_id = id_map_.MappedDstId(src_func_id);
  2170. if (dst_func_id == 0) {
  2171. continue;
  2172. }
  2173. // Since these functions are definite matches, match their parameters for a
  2174. // better diff.
  2175. MatchFunctionParamIds(src_funcs_[src_func_id], dst_funcs_[dst_func_id]);
  2176. // Take the diff of the two functions.
  2177. DiffMatch src_match_result, dst_match_result;
  2178. MatchFunctionBodies(src_func_insts_[src_func_id],
  2179. dst_func_insts_[dst_func_id], &src_match_result,
  2180. &dst_match_result);
  2181. // Match ids between the two function bodies; which can also result in
  2182. // global variables getting matched.
  2183. MatchIdsInFunctionBodies(src_func_insts_[src_func_id],
  2184. dst_func_insts_[dst_func_id], src_match_result,
  2185. dst_match_result, 0);
  2186. }
  2187. // Best effort match functions with matching type.
  2188. GroupIdsAndMatch<uint32_t>(
  2189. src_func_ids, dst_func_ids, 0, &Differ::GroupIdsHelperGetTypeId,
  2190. [this](const IdGroup& src_group_by_type_id,
  2191. const IdGroup& dst_group_by_type_id) {
  2192. BestEffortMatchFunctions(src_group_by_type_id, dst_group_by_type_id,
  2193. src_func_insts_, dst_func_insts_);
  2194. });
  2195. // Any function that's left, best effort match them.
  2196. BestEffortMatchFunctions(src_func_ids, dst_func_ids, src_func_insts_,
  2197. dst_func_insts_);
  2198. }
  2199. void Differ::MatchDebugs1() {
  2200. // This section in cludes: OpString, OpSourceExtension, OpSource,
  2201. // OpSourceContinued
  2202. MatchDebugAndAnnotationInstructions(src_->debugs1(), dst_->debugs1());
  2203. }
  2204. void Differ::MatchDebugs2() {
  2205. // This section includes: OpName, OpMemberName
  2206. MatchDebugAndAnnotationInstructions(src_->debugs2(), dst_->debugs2());
  2207. }
  2208. void Differ::MatchDebugs3() {
  2209. // This section includes: OpModuleProcessed
  2210. MatchDebugAndAnnotationInstructions(src_->debugs3(), dst_->debugs3());
  2211. }
  2212. void Differ::MatchExtInstDebugInfo() {
  2213. // This section includes OpExtInst for DebugInfo extension
  2214. MatchDebugAndAnnotationInstructions(src_->ext_inst_debuginfo(),
  2215. dst_->ext_inst_debuginfo());
  2216. }
  2217. void Differ::MatchAnnotations() {
  2218. // This section includes OpDecorate and family.
  2219. MatchDebugAndAnnotationInstructions(src_->annotations(), dst_->annotations());
  2220. }
  2221. const opt::Instruction* Differ::MappedDstInst(
  2222. const opt::Instruction* src_inst) {
  2223. return MappedInstImpl(src_inst, id_map_.SrcToDstMap(), dst_id_to_);
  2224. }
  2225. const opt::Instruction* Differ::MappedSrcInst(
  2226. const opt::Instruction* dst_inst) {
  2227. return MappedInstImpl(dst_inst, id_map_.DstToSrcMap(), src_id_to_);
  2228. }
  2229. const opt::Instruction* Differ::MappedInstImpl(
  2230. const opt::Instruction* inst, const IdMap& to_other,
  2231. const IdInstructions& other_id_to) {
  2232. if (inst->HasResultId()) {
  2233. if (to_other.IsMapped(inst->result_id())) {
  2234. const uint32_t other_result_id = to_other.MappedId(inst->result_id());
  2235. assert(other_result_id < other_id_to.inst_map_.size());
  2236. return other_id_to.inst_map_[other_result_id];
  2237. }
  2238. return nullptr;
  2239. }
  2240. return to_other.MappedInst(inst);
  2241. }
  2242. void Differ::OutputLine(std::function<bool()> are_lines_identical,
  2243. std::function<void()> output_src_line,
  2244. std::function<void()> output_dst_line) {
  2245. if (are_lines_identical()) {
  2246. out_ << " ";
  2247. output_src_line();
  2248. } else {
  2249. OutputRed();
  2250. out_ << "-";
  2251. output_src_line();
  2252. OutputGreen();
  2253. out_ << "+";
  2254. output_dst_line();
  2255. OutputResetColor();
  2256. }
  2257. }
  2258. const opt::Instruction* IterInst(opt::Module::const_inst_iterator& iter) {
  2259. return &*iter;
  2260. }
  2261. const opt::Instruction* IterInst(InstructionList::const_iterator& iter) {
  2262. return *iter;
  2263. }
  2264. template <typename InstList>
  2265. void Differ::OutputSection(
  2266. const InstList& src_insts, const InstList& dst_insts,
  2267. std::function<void(const opt::Instruction&, const IdInstructions&,
  2268. const opt::Instruction&)>
  2269. write_inst) {
  2270. auto src_iter = src_insts.begin();
  2271. auto dst_iter = dst_insts.begin();
  2272. // - While src_inst doesn't have a match, output it with -
  2273. // - While dst_inst doesn't have a match, output it with +
  2274. // - Now src_inst and dst_inst both have matches; might not match each other!
  2275. // * If section is unordered, just process src_inst and its match (dst_inst
  2276. // or not),
  2277. // dst_inst will eventually be processed when its match is seen.
  2278. // * If section is ordered, also just process src_inst and its match. Its
  2279. // match must
  2280. // necessarily be dst_inst.
  2281. while (src_iter != src_insts.end() || dst_iter != dst_insts.end()) {
  2282. OutputRed();
  2283. while (src_iter != src_insts.end() &&
  2284. MappedDstInst(IterInst(src_iter)) == nullptr) {
  2285. out_ << "-";
  2286. write_inst(*IterInst(src_iter), src_id_to_, *IterInst(src_iter));
  2287. ++src_iter;
  2288. }
  2289. OutputGreen();
  2290. while (dst_iter != dst_insts.end() &&
  2291. MappedSrcInst(IterInst(dst_iter)) == nullptr) {
  2292. out_ << "+";
  2293. write_inst(ToMappedSrcIds(*IterInst(dst_iter)), dst_id_to_,
  2294. *IterInst(dst_iter));
  2295. ++dst_iter;
  2296. }
  2297. OutputResetColor();
  2298. if (src_iter != src_insts.end() && dst_iter != dst_insts.end()) {
  2299. const opt::Instruction* src_inst = IterInst(src_iter);
  2300. const opt::Instruction* matched_dst_inst = MappedDstInst(src_inst);
  2301. assert(matched_dst_inst != nullptr);
  2302. assert(MappedSrcInst(IterInst(dst_iter)) != nullptr);
  2303. OutputLine(
  2304. [this, src_inst, matched_dst_inst]() {
  2305. return DoInstructionsMatch(src_inst, matched_dst_inst);
  2306. },
  2307. [this, src_inst, &write_inst]() {
  2308. write_inst(*src_inst, src_id_to_, *src_inst);
  2309. },
  2310. [this, matched_dst_inst, &write_inst]() {
  2311. write_inst(ToMappedSrcIds(*matched_dst_inst), dst_id_to_,
  2312. *matched_dst_inst);
  2313. });
  2314. ++src_iter;
  2315. ++dst_iter;
  2316. }
  2317. }
  2318. }
  2319. void Differ::ToParsedInstruction(
  2320. const opt::Instruction& inst, const IdInstructions& id_to,
  2321. const opt::Instruction& original_inst,
  2322. spv_parsed_instruction_t* parsed_inst,
  2323. std::vector<spv_parsed_operand_t>& parsed_operands,
  2324. std::vector<uint32_t>& inst_binary) {
  2325. inst.ToBinaryWithoutAttachedDebugInsts(&inst_binary);
  2326. parsed_operands.resize(inst.NumOperands());
  2327. parsed_inst->words = inst_binary.data();
  2328. parsed_inst->num_words = static_cast<uint16_t>(inst_binary.size());
  2329. parsed_inst->opcode = static_cast<uint16_t>(inst.opcode());
  2330. parsed_inst->ext_inst_type =
  2331. inst.opcode() == spv::Op::OpExtInst
  2332. ? GetExtInstType(id_to, original_inst.GetSingleWordInOperand(0))
  2333. : SPV_EXT_INST_TYPE_NONE;
  2334. parsed_inst->type_id =
  2335. inst.HasResultType() ? inst.GetSingleWordOperand(0) : 0;
  2336. parsed_inst->result_id = inst.HasResultId() ? inst.result_id() : 0;
  2337. parsed_inst->operands = parsed_operands.data();
  2338. parsed_inst->num_operands = static_cast<uint16_t>(parsed_operands.size());
  2339. // Word 0 is always op and num_words, so operands start at offset 1.
  2340. uint32_t offset = 1;
  2341. for (uint16_t operand_index = 0; operand_index < parsed_inst->num_operands;
  2342. ++operand_index) {
  2343. const opt::Operand& operand = inst.GetOperand(operand_index);
  2344. spv_parsed_operand_t& parsed_operand = parsed_operands[operand_index];
  2345. parsed_operand.offset = static_cast<uint16_t>(offset);
  2346. parsed_operand.num_words = static_cast<uint16_t>(operand.words.size());
  2347. parsed_operand.type = operand.type;
  2348. parsed_operand.number_kind = GetNumberKind(
  2349. id_to, original_inst, operand_index, &parsed_operand.number_bit_width);
  2350. offset += parsed_operand.num_words;
  2351. }
  2352. }
  2353. opt::Instruction Differ::ToMappedSrcIds(const opt::Instruction& dst_inst) {
  2354. // Create an identical instruction to dst_inst, except ids are changed to the
  2355. // mapped one.
  2356. opt::Instruction mapped_inst = dst_inst;
  2357. for (uint32_t operand_index = 0; operand_index < mapped_inst.NumOperands();
  2358. ++operand_index) {
  2359. opt::Operand& operand = mapped_inst.GetOperand(operand_index);
  2360. if (spvIsIdType(operand.type)) {
  2361. assert(id_map_.IsDstMapped(operand.AsId()));
  2362. operand.words[0] = id_map_.MappedSrcId(operand.AsId());
  2363. }
  2364. }
  2365. return mapped_inst;
  2366. }
  2367. spv_result_t Differ::Output() {
  2368. id_map_.MapUnmatchedIds(
  2369. [this](uint32_t src_id) { return src_id_to_.IsDefined(src_id); },
  2370. [this](uint32_t dst_id) { return dst_id_to_.IsDefined(dst_id); });
  2371. src_id_to_.inst_map_.resize(id_map_.SrcToDstMap().IdBound(), nullptr);
  2372. dst_id_to_.inst_map_.resize(id_map_.DstToSrcMap().IdBound(), nullptr);
  2373. const spv_target_env target_env = SPV_ENV_UNIVERSAL_1_6;
  2374. spv_opcode_table opcode_table;
  2375. spv_operand_table operand_table;
  2376. spv_ext_inst_table ext_inst_table;
  2377. spv_result_t result;
  2378. result = spvOpcodeTableGet(&opcode_table, target_env);
  2379. if (result != SPV_SUCCESS) return result;
  2380. result = spvOperandTableGet(&operand_table, target_env);
  2381. if (result != SPV_SUCCESS) return result;
  2382. result = spvExtInstTableGet(&ext_inst_table, target_env);
  2383. if (result != SPV_SUCCESS) return result;
  2384. spv_context_t context{
  2385. target_env,
  2386. opcode_table,
  2387. operand_table,
  2388. ext_inst_table,
  2389. };
  2390. const AssemblyGrammar grammar(&context);
  2391. if (!grammar.isValid()) return SPV_ERROR_INVALID_TABLE;
  2392. uint32_t disassembly_options = SPV_BINARY_TO_TEXT_OPTION_PRINT;
  2393. if (options_.indent) {
  2394. disassembly_options |= SPV_BINARY_TO_TEXT_OPTION_INDENT;
  2395. }
  2396. NameMapper name_mapper = GetTrivialNameMapper();
  2397. disassemble::InstructionDisassembler dis(grammar, out_, disassembly_options,
  2398. name_mapper);
  2399. if (!options_.no_header) {
  2400. // Output the header
  2401. // TODO: when using diff with text, the assembler overrides the version and
  2402. // generator, so these aren't reflected correctly in the output. Could
  2403. // potentially extract this info from the header comment.
  2404. OutputLine([]() { return true; }, [&dis]() { dis.EmitHeaderSpirv(); },
  2405. []() { assert(false && "Unreachable"); });
  2406. OutputLine([this]() { return src_->version() == dst_->version(); },
  2407. [this, &dis]() { dis.EmitHeaderVersion(src_->version()); },
  2408. [this, &dis]() { dis.EmitHeaderVersion(dst_->version()); });
  2409. OutputLine([this]() { return src_->generator() == dst_->generator(); },
  2410. [this, &dis]() { dis.EmitHeaderGenerator(src_->generator()); },
  2411. [this, &dis]() { dis.EmitHeaderGenerator(dst_->generator()); });
  2412. OutputLine(
  2413. [this]() { return src_->IdBound() == id_map_.SrcToDstMap().IdBound(); },
  2414. [this, &dis]() { dis.EmitHeaderIdBound(src_->IdBound()); },
  2415. [this, &dis]() {
  2416. dis.EmitHeaderIdBound(id_map_.SrcToDstMap().IdBound());
  2417. });
  2418. OutputLine([this]() { return src_->schema() == dst_->schema(); },
  2419. [this, &dis]() { dis.EmitHeaderSchema(src_->schema()); },
  2420. [this, &dis]() { dis.EmitHeaderSchema(dst_->schema()); });
  2421. }
  2422. // For each section, iterate both modules and output the disassembly.
  2423. auto write_inst = [this, &dis](const opt::Instruction& inst,
  2424. const IdInstructions& id_to,
  2425. const opt::Instruction& original_inst) {
  2426. spv_parsed_instruction_t parsed_inst;
  2427. std::vector<spv_parsed_operand_t> parsed_operands;
  2428. std::vector<uint32_t> inst_binary;
  2429. ToParsedInstruction(inst, id_to, original_inst, &parsed_inst,
  2430. parsed_operands, inst_binary);
  2431. dis.EmitInstruction(parsed_inst, 0);
  2432. };
  2433. OutputSection(src_->capabilities(), dst_->capabilities(), write_inst);
  2434. OutputSection(src_->extensions(), dst_->extensions(), write_inst);
  2435. OutputSection(src_->ext_inst_imports(), dst_->ext_inst_imports(), write_inst);
  2436. // There is only one memory model.
  2437. OutputLine(
  2438. [this]() {
  2439. return DoInstructionsMatch(src_->GetMemoryModel(),
  2440. dst_->GetMemoryModel());
  2441. },
  2442. [this, &write_inst]() {
  2443. write_inst(*src_->GetMemoryModel(), src_id_to_,
  2444. *src_->GetMemoryModel());
  2445. },
  2446. [this, &write_inst]() {
  2447. write_inst(*dst_->GetMemoryModel(), dst_id_to_,
  2448. *dst_->GetMemoryModel());
  2449. });
  2450. OutputSection(src_->entry_points(), dst_->entry_points(), write_inst);
  2451. OutputSection(src_->execution_modes(), dst_->execution_modes(), write_inst);
  2452. OutputSection(src_->debugs1(), dst_->debugs1(), write_inst);
  2453. OutputSection(src_->debugs2(), dst_->debugs2(), write_inst);
  2454. OutputSection(src_->debugs3(), dst_->debugs3(), write_inst);
  2455. OutputSection(src_->ext_inst_debuginfo(), dst_->ext_inst_debuginfo(),
  2456. write_inst);
  2457. OutputSection(src_->annotations(), dst_->annotations(), write_inst);
  2458. OutputSection(src_->types_values(), dst_->types_values(), write_inst);
  2459. // Get the body of all the functions.
  2460. FunctionInstMap src_func_header_insts;
  2461. FunctionInstMap dst_func_header_insts;
  2462. GetFunctionHeaderInstructions(src_, &src_func_header_insts);
  2463. GetFunctionHeaderInstructions(dst_, &dst_func_header_insts);
  2464. for (const auto& src_func : src_func_insts_) {
  2465. const uint32_t src_func_id = src_func.first;
  2466. const InstructionList& src_insts = src_func.second;
  2467. const InstructionList& src_header_insts =
  2468. src_func_header_insts[src_func_id];
  2469. const uint32_t dst_func_id = id_map_.MappedDstId(src_func_id);
  2470. if (dst_func_insts_.find(dst_func_id) == dst_func_insts_.end()) {
  2471. OutputSection(src_header_insts, InstructionList(), write_inst);
  2472. OutputSection(src_insts, InstructionList(), write_inst);
  2473. continue;
  2474. }
  2475. const InstructionList& dst_insts = dst_func_insts_[dst_func_id];
  2476. const InstructionList& dst_header_insts =
  2477. dst_func_header_insts[dst_func_id];
  2478. OutputSection(src_header_insts, dst_header_insts, write_inst);
  2479. OutputSection(src_insts, dst_insts, write_inst);
  2480. }
  2481. for (const auto& dst_func : dst_func_insts_) {
  2482. const uint32_t dst_func_id = dst_func.first;
  2483. const InstructionList& dst_insts = dst_func.second;
  2484. const InstructionList& dst_header_insts =
  2485. dst_func_header_insts[dst_func_id];
  2486. const uint32_t src_func_id = id_map_.MappedSrcId(dst_func_id);
  2487. if (src_func_insts_.find(src_func_id) == src_func_insts_.end()) {
  2488. OutputSection(InstructionList(), dst_header_insts, write_inst);
  2489. OutputSection(InstructionList(), dst_insts, write_inst);
  2490. }
  2491. }
  2492. out_ << std::flush;
  2493. return SPV_SUCCESS;
  2494. }
  2495. } // anonymous namespace
  2496. spv_result_t Diff(opt::IRContext* src, opt::IRContext* dst, std::ostream& out,
  2497. Options options) {
  2498. // High level algorithm:
  2499. //
  2500. // - Some sections of SPIR-V don't deal with ids; instructions in those
  2501. // sections are matched identically. For example OpCapability instructions.
  2502. // - Some sections produce ids, and they can be trivially matched by their
  2503. // parameters. For example OpExtInstImport instructions.
  2504. // - Some sections annotate ids. These are matched at the end, after the ids
  2505. // themselves are matched. For example OpName or OpDecorate instructions.
  2506. // - Some sections produce ids that depend on other ids and they can be
  2507. // recursively matched. For example OpType* instructions.
  2508. // - Some sections produce ids that are not trivially matched. For these ids,
  2509. // the debug info is used when possible, or a best guess (such as through
  2510. // decorations) is used. For example OpVariable instructions.
  2511. // - Matching functions is done with multiple attempts:
  2512. // * Functions with identical debug names are matched if there are no
  2513. // overloads.
  2514. // * Otherwise, functions with identical debug names and types are matched.
  2515. // * The rest of the functions are best-effort matched, first in groups of
  2516. // identical type, then any with any.
  2517. // * The best-effort matching takes the diff of every pair of functions in
  2518. // a group and selects the top matches that also meet a similarity
  2519. // index.
  2520. // * Once a pair of functions are matched, the fuzzy diff of the
  2521. // instructions is used to match the instructions in the function body.
  2522. // The fuzzy diff makes sure that sufficiently similar instructions are
  2523. // matched and that yet-to-be-matched result ids don't result in a larger
  2524. // diff.
  2525. //
  2526. // Once the instructions are matched between the src and dst SPIR-V, the src
  2527. // is traversed and its disassembly is output. In the process, any unmatched
  2528. // instruction is prefixed with -, and any unmatched instruction in dst in the
  2529. // same section is output prefixed with +. To avoid confusion, the
  2530. // instructions in dst are output with matching ids in src so the output
  2531. // assembly is consistent.
  2532. Differ differ(src, dst, out, options);
  2533. // First, match instructions between the different non-annotation sections of
  2534. // the SPIR-V.
  2535. differ.MatchCapabilities();
  2536. differ.MatchExtensions();
  2537. differ.MatchExtInstImportIds();
  2538. differ.MatchMemoryModel();
  2539. differ.MatchEntryPointIds();
  2540. differ.MatchExecutionModes();
  2541. differ.MatchTypeForwardPointers();
  2542. differ.MatchTypeIds();
  2543. differ.MatchConstants();
  2544. differ.MatchVariableIds();
  2545. differ.MatchFunctions();
  2546. // Match instructions that annotate previously-matched ids.
  2547. differ.MatchDebugs1();
  2548. differ.MatchDebugs2();
  2549. differ.MatchDebugs3();
  2550. differ.MatchExtInstDebugInfo();
  2551. differ.MatchAnnotations();
  2552. // Show the disassembly with the diff.
  2553. //
  2554. // TODO: Based on an option, output either based on src or dst, i.e. the diff
  2555. // can show the ids and instruction/function order either from src or dst.
  2556. spv_result_t result = differ.Output();
  2557. differ.DumpIdMap();
  2558. return result;
  2559. }
  2560. } // namespace diff
  2561. } // namespace spvtools