diff.cpp 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969
  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_LITERAL_FLOAT:
  1762. // Always float.
  1763. *number_bit_width = 32;
  1764. return SPV_NUMBER_FLOATING;
  1765. case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER:
  1766. case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:
  1767. switch (inst.opcode()) {
  1768. case spv::Op::OpSwitch:
  1769. case spv::Op::OpConstant:
  1770. case spv::Op::OpSpecConstant:
  1771. // Same kind of number as the selector (OpSwitch) or the type
  1772. // (Op*Constant).
  1773. return GetTypeNumberKind(id_to, inst.GetSingleWordOperand(0),
  1774. number_bit_width);
  1775. default:
  1776. assert(false && "Unreachable");
  1777. break;
  1778. }
  1779. break;
  1780. default:
  1781. break;
  1782. }
  1783. return SPV_NUMBER_NONE;
  1784. }
  1785. spv_number_kind_t Differ::GetTypeNumberKind(const IdInstructions& id_to,
  1786. uint32_t id,
  1787. uint32_t* number_bit_width) {
  1788. const opt::Instruction* type_inst = GetInst(id_to, id);
  1789. if (!spvOpcodeIsScalarType(type_inst->opcode())) {
  1790. type_inst = GetInst(id_to, type_inst->type_id());
  1791. }
  1792. switch (type_inst->opcode()) {
  1793. case spv::Op::OpTypeInt:
  1794. *number_bit_width = type_inst->GetSingleWordOperand(1);
  1795. return type_inst->GetSingleWordOperand(2) == 0 ? SPV_NUMBER_UNSIGNED_INT
  1796. : SPV_NUMBER_SIGNED_INT;
  1797. break;
  1798. case spv::Op::OpTypeFloat:
  1799. *number_bit_width = type_inst->GetSingleWordOperand(1);
  1800. return SPV_NUMBER_FLOATING;
  1801. default:
  1802. assert(false && "Unreachable");
  1803. return SPV_NUMBER_NONE;
  1804. }
  1805. }
  1806. void Differ::MatchCapabilities() {
  1807. MatchPreambleInstructions(src_->capabilities(), dst_->capabilities());
  1808. }
  1809. void Differ::MatchExtensions() {
  1810. MatchPreambleInstructions(src_->extensions(), dst_->extensions());
  1811. }
  1812. void Differ::MatchExtInstImportIds() {
  1813. // Bunch all of this section's ids as potential matches.
  1814. PotentialIdMap potential_id_map;
  1815. auto get_result_id = [](const opt::Instruction& inst) {
  1816. return inst.result_id();
  1817. };
  1818. auto accept_all = [](const opt::Instruction&) { return true; };
  1819. PoolPotentialIds(src_->ext_inst_imports(), potential_id_map.src_ids, true,
  1820. accept_all, get_result_id);
  1821. PoolPotentialIds(dst_->ext_inst_imports(), potential_id_map.dst_ids, false,
  1822. accept_all, get_result_id);
  1823. // Then match the ids.
  1824. MatchIds(potential_id_map, [](const opt::Instruction* src_inst,
  1825. const opt::Instruction* dst_inst) {
  1826. // Match OpExtInstImport by exact name, which is operand 1
  1827. const opt::Operand& src_name = src_inst->GetOperand(1);
  1828. const opt::Operand& dst_name = dst_inst->GetOperand(1);
  1829. return src_name.AsString() == dst_name.AsString();
  1830. });
  1831. }
  1832. void Differ::MatchMemoryModel() {
  1833. // Always match the memory model instructions, there is always a single one of
  1834. // it.
  1835. id_map_.MapInsts(src_->GetMemoryModel(), dst_->GetMemoryModel());
  1836. }
  1837. void Differ::MatchEntryPointIds() {
  1838. // Match OpEntryPoint ids (at index 1) by ExecutionModel (at index 0) and
  1839. // possibly name (at index 2). OpEntryPoint doesn't produce a result id, so
  1840. // this function doesn't use the helpers the other functions use.
  1841. // Map from execution model to OpEntryPoint instructions of that model.
  1842. using ExecutionModelMap =
  1843. std::unordered_map<uint32_t, std::vector<const opt::Instruction*>>;
  1844. ExecutionModelMap src_entry_points_map;
  1845. ExecutionModelMap dst_entry_points_map;
  1846. std::set<uint32_t> all_execution_models;
  1847. for (const opt::Instruction& src_inst : src_->entry_points()) {
  1848. uint32_t execution_model = src_inst.GetSingleWordOperand(0);
  1849. src_entry_points_map[execution_model].push_back(&src_inst);
  1850. all_execution_models.insert(execution_model);
  1851. }
  1852. for (const opt::Instruction& dst_inst : dst_->entry_points()) {
  1853. uint32_t execution_model = dst_inst.GetSingleWordOperand(0);
  1854. dst_entry_points_map[execution_model].push_back(&dst_inst);
  1855. all_execution_models.insert(execution_model);
  1856. }
  1857. // Go through each model and match the ids.
  1858. for (const uint32_t execution_model : all_execution_models) {
  1859. auto& src_insts = src_entry_points_map[execution_model];
  1860. auto& dst_insts = dst_entry_points_map[execution_model];
  1861. // If there is only one entry point in src and dst with that model, match
  1862. // them unconditionally.
  1863. if (src_insts.size() == 1 && dst_insts.size() == 1) {
  1864. uint32_t src_id = src_insts[0]->GetSingleWordOperand(1);
  1865. uint32_t dst_id = dst_insts[0]->GetSingleWordOperand(1);
  1866. id_map_.MapIds(src_id, dst_id);
  1867. id_map_.MapInsts(src_insts[0], dst_insts[0]);
  1868. continue;
  1869. }
  1870. // Otherwise match them by name.
  1871. for (const opt::Instruction* src_inst : src_insts) {
  1872. for (const opt::Instruction* dst_inst : dst_insts) {
  1873. if (id_map_.IsDstMapped(dst_inst)) continue;
  1874. const opt::Operand& src_name = src_inst->GetOperand(2);
  1875. const opt::Operand& dst_name = dst_inst->GetOperand(2);
  1876. if (src_name.AsString() == dst_name.AsString()) {
  1877. uint32_t src_id = src_inst->GetSingleWordOperand(1);
  1878. uint32_t dst_id = dst_inst->GetSingleWordOperand(1);
  1879. id_map_.MapIds(src_id, dst_id);
  1880. id_map_.MapInsts(src_inst, dst_inst);
  1881. break;
  1882. }
  1883. }
  1884. }
  1885. }
  1886. }
  1887. void Differ::MatchExecutionModes() {
  1888. MatchPreambleInstructions(src_->execution_modes(), dst_->execution_modes());
  1889. }
  1890. void Differ::MatchTypeForwardPointers() {
  1891. // Bunch all of type forward pointers as potential matches.
  1892. PotentialIdMap potential_id_map;
  1893. auto get_pointer_type_id = [](const opt::Instruction& inst) {
  1894. return inst.GetSingleWordOperand(0);
  1895. };
  1896. auto accept_type_forward_pointer_ops = [](const opt::Instruction& inst) {
  1897. return inst.opcode() == spv::Op::OpTypeForwardPointer;
  1898. };
  1899. PoolPotentialIds(src_->types_values(), potential_id_map.src_ids, true,
  1900. accept_type_forward_pointer_ops, get_pointer_type_id);
  1901. PoolPotentialIds(dst_->types_values(), potential_id_map.dst_ids, false,
  1902. accept_type_forward_pointer_ops, get_pointer_type_id);
  1903. // Matching types with cyclical references (i.e. in the style of linked lists)
  1904. // can get very complex. Currently, the diff tool matches types bottom up, so
  1905. // on every instruction it expects to know if its operands are already matched
  1906. // or not. With cyclical references, it cannot know that. Type matching may
  1907. // need significant modifications to be able to support this use case.
  1908. //
  1909. // Currently, forwarded types are only matched by storage class and debug
  1910. // info, with minimal matching of the type being forwarded:
  1911. //
  1912. // - Group by class
  1913. // - Group by OpType being pointed to
  1914. // - Group by debug info
  1915. // - If same name and unique, match
  1916. // - If leftover is unique, match
  1917. // Group forwarded pointers by storage class first and loop over them.
  1918. GroupIdsAndMatch<spv::StorageClass>(
  1919. potential_id_map.src_ids, potential_id_map.dst_ids,
  1920. spv::StorageClass::Max, &Differ::GroupIdsHelperGetTypePointerStorageClass,
  1921. [this](const IdGroup& src_group_by_storage_class,
  1922. const IdGroup& dst_group_by_storage_class) {
  1923. // Group them further by the type they are pointing to and loop over
  1924. // them.
  1925. GroupIdsAndMatch<spv::Op>(
  1926. src_group_by_storage_class, dst_group_by_storage_class,
  1927. spv::Op::Max, &Differ::GroupIdsHelperGetTypePointerTypeOp,
  1928. [this](const IdGroup& src_group_by_type_op,
  1929. const IdGroup& dst_group_by_type_op) {
  1930. // Group them even further by debug info, if possible and match by
  1931. // debug name.
  1932. MatchTypeForwardPointersByName(src_group_by_type_op,
  1933. dst_group_by_type_op);
  1934. // Match the leftovers only if they lack debug info and there is
  1935. // only one instance of them.
  1936. MatchTypeForwardPointersByTypeOp(src_group_by_type_op,
  1937. dst_group_by_type_op);
  1938. });
  1939. });
  1940. // Match the instructions that forward declare the same type themselves
  1941. for (uint32_t src_id : potential_id_map.src_ids) {
  1942. uint32_t dst_id = id_map_.MappedDstId(src_id);
  1943. if (dst_id == 0) continue;
  1944. const opt::Instruction* src_forward_inst =
  1945. GetForwardPointerInst(src_id_to_, src_id);
  1946. const opt::Instruction* dst_forward_inst =
  1947. GetForwardPointerInst(dst_id_to_, dst_id);
  1948. assert(src_forward_inst);
  1949. assert(dst_forward_inst);
  1950. id_map_.MapInsts(src_forward_inst, dst_forward_inst);
  1951. }
  1952. }
  1953. void Differ::MatchTypeIds() {
  1954. // Bunch all of type ids as potential matches.
  1955. PotentialIdMap potential_id_map;
  1956. auto get_result_id = [](const opt::Instruction& inst) {
  1957. return inst.result_id();
  1958. };
  1959. auto accept_type_ops = [](const opt::Instruction& inst) {
  1960. return spvOpcodeGeneratesType(inst.opcode());
  1961. };
  1962. PoolPotentialIds(src_->types_values(), potential_id_map.src_ids, true,
  1963. accept_type_ops, get_result_id);
  1964. PoolPotentialIds(dst_->types_values(), potential_id_map.dst_ids, false,
  1965. accept_type_ops, get_result_id);
  1966. // Then match the ids. Start with exact matches, then match the leftover with
  1967. // gradually loosening degrees of strictness. For example, in the absence of
  1968. // debug info, two block types will be matched if they differ only in a few of
  1969. // the fields.
  1970. for (uint32_t flexibility = 0; flexibility < 2; ++flexibility) {
  1971. MatchIds(potential_id_map, [this, flexibility](
  1972. const opt::Instruction* src_inst,
  1973. const opt::Instruction* dst_inst) {
  1974. const spv::Op src_op = src_inst->opcode();
  1975. const spv::Op dst_op = dst_inst->opcode();
  1976. // Don't match if the opcode is not the same.
  1977. if (src_op != dst_op) {
  1978. return false;
  1979. }
  1980. switch (src_op) {
  1981. case spv::Op::OpTypeVoid:
  1982. case spv::Op::OpTypeBool:
  1983. case spv::Op::OpTypeSampler:
  1984. case spv::Op::OpTypeAccelerationStructureNV:
  1985. case spv::Op::OpTypeRayQueryKHR:
  1986. // the above types have no operands and are unique, match them.
  1987. return true;
  1988. case spv::Op::OpTypeInt:
  1989. case spv::Op::OpTypeFloat:
  1990. case spv::Op::OpTypeVector:
  1991. case spv::Op::OpTypeMatrix:
  1992. case spv::Op::OpTypeSampledImage:
  1993. case spv::Op::OpTypeRuntimeArray:
  1994. case spv::Op::OpTypePointer:
  1995. // Match these instructions when all operands match.
  1996. assert(src_inst->NumInOperandWords() ==
  1997. dst_inst->NumInOperandWords());
  1998. return DoOperandsMatch(src_inst, dst_inst, 0,
  1999. src_inst->NumInOperandWords());
  2000. case spv::Op::OpTypeFunction:
  2001. case spv::Op::OpTypeImage:
  2002. // Match function types only if they have the same number of operands,
  2003. // and they all match.
  2004. // Match image types similarly, expecting the optional final parameter
  2005. // to match (if provided in both)
  2006. if (src_inst->NumInOperandWords() != dst_inst->NumInOperandWords()) {
  2007. return false;
  2008. }
  2009. return DoOperandsMatch(src_inst, dst_inst, 0,
  2010. src_inst->NumInOperandWords());
  2011. case spv::Op::OpTypeArray:
  2012. // Match arrays only if the element type and length match. The length
  2013. // is an id of a constant, so the actual constant it's defining is
  2014. // compared instead.
  2015. if (!DoOperandsMatch(src_inst, dst_inst, 0, 1)) {
  2016. return false;
  2017. }
  2018. if (AreIdenticalUintConstants(src_inst->GetSingleWordInOperand(1),
  2019. dst_inst->GetSingleWordInOperand(1))) {
  2020. return true;
  2021. }
  2022. // If size is not OpConstant, expect the ids to match exactly (for
  2023. // example if a spec contant is used).
  2024. return DoOperandsMatch(src_inst, dst_inst, 1, 1);
  2025. case spv::Op::OpTypeStruct:
  2026. return MatchOpTypeStruct(src_inst, dst_inst, flexibility);
  2027. default:
  2028. return false;
  2029. }
  2030. });
  2031. }
  2032. }
  2033. void Differ::MatchConstants() {
  2034. // Bunch all of constant ids as potential matches.
  2035. PotentialIdMap potential_id_map;
  2036. auto get_result_id = [](const opt::Instruction& inst) {
  2037. return inst.result_id();
  2038. };
  2039. auto accept_type_ops = [](const opt::Instruction& inst) {
  2040. return spvOpcodeIsConstant(inst.opcode());
  2041. };
  2042. PoolPotentialIds(src_->types_values(), potential_id_map.src_ids, true,
  2043. accept_type_ops, get_result_id);
  2044. PoolPotentialIds(dst_->types_values(), potential_id_map.dst_ids, false,
  2045. accept_type_ops, get_result_id);
  2046. // Then match the ids. Constants are matched exactly, except for float types
  2047. // that are first matched exactly, then leftovers are matched with a small
  2048. // error.
  2049. for (uint32_t flexibility = 0; flexibility < 2; ++flexibility) {
  2050. MatchIds(potential_id_map, [this, flexibility](
  2051. const opt::Instruction* src_inst,
  2052. const opt::Instruction* dst_inst) {
  2053. const spv::Op src_op = src_inst->opcode();
  2054. const spv::Op dst_op = dst_inst->opcode();
  2055. // Don't match if the opcode is not the same.
  2056. if (src_op != dst_op) {
  2057. return false;
  2058. }
  2059. switch (src_op) {
  2060. case spv::Op::OpConstantTrue:
  2061. case spv::Op::OpConstantFalse:
  2062. // true and false are unique, match them.
  2063. return true;
  2064. case spv::Op::OpConstant:
  2065. return MatchOpConstant(src_inst, dst_inst, flexibility);
  2066. case spv::Op::OpConstantComposite:
  2067. case spv::Op::OpSpecConstantComposite:
  2068. // Composite constants must match in type and value.
  2069. //
  2070. // TODO: match OpConstantNull with OpConstantComposite with all zeros
  2071. // at flexibility == 1
  2072. // TODO: match constants from structs that have been flexibly-matched.
  2073. if (src_inst->NumInOperandWords() != dst_inst->NumInOperandWords()) {
  2074. return false;
  2075. }
  2076. return DoesOperandMatch(src_inst->GetOperand(0),
  2077. dst_inst->GetOperand(0)) &&
  2078. DoOperandsMatch(src_inst, dst_inst, 0,
  2079. src_inst->NumInOperandWords());
  2080. case spv::Op::OpConstantSampler:
  2081. // Match sampler constants exactly.
  2082. // TODO: Allow flexibility in parameters to better diff shaders where
  2083. // the sampler param has changed.
  2084. assert(src_inst->NumInOperandWords() ==
  2085. dst_inst->NumInOperandWords());
  2086. return DoOperandsMatch(src_inst, dst_inst, 0,
  2087. src_inst->NumInOperandWords());
  2088. case spv::Op::OpConstantNull:
  2089. // Match null constants as long as the type matches.
  2090. return DoesOperandMatch(src_inst->GetOperand(0),
  2091. dst_inst->GetOperand(0));
  2092. case spv::Op::OpSpecConstantTrue:
  2093. case spv::Op::OpSpecConstantFalse:
  2094. case spv::Op::OpSpecConstant:
  2095. case spv::Op::OpSpecConstantOp:
  2096. // Match spec constants by name if available, then by the SpecId
  2097. // decoration.
  2098. return MatchOpSpecConstant(src_inst, dst_inst);
  2099. default:
  2100. return false;
  2101. }
  2102. });
  2103. }
  2104. }
  2105. void Differ::MatchVariableIds() {
  2106. // Bunch all of variable ids as potential matches.
  2107. PotentialIdMap potential_id_map;
  2108. auto get_result_id = [](const opt::Instruction& inst) {
  2109. return inst.result_id();
  2110. };
  2111. auto accept_type_ops = [](const opt::Instruction& inst) {
  2112. return inst.opcode() == spv::Op::OpVariable;
  2113. };
  2114. PoolPotentialIds(src_->types_values(), potential_id_map.src_ids, true,
  2115. accept_type_ops, get_result_id);
  2116. PoolPotentialIds(dst_->types_values(), potential_id_map.dst_ids, false,
  2117. accept_type_ops, get_result_id);
  2118. // Then match the ids. Start with exact matches, then match the leftover with
  2119. // gradually loosening degrees of strictness. For example, in the absence of
  2120. // debug info, two otherwise identical variables will be matched if one of
  2121. // them has a Private storage class and the other doesn't.
  2122. for (uint32_t flexibility = 0; flexibility < 2; ++flexibility) {
  2123. MatchIds(potential_id_map,
  2124. [this, flexibility](const opt::Instruction* src_inst,
  2125. const opt::Instruction* dst_inst) {
  2126. assert(src_inst->opcode() == spv::Op::OpVariable);
  2127. assert(dst_inst->opcode() == spv::Op::OpVariable);
  2128. return MatchOpVariable(src_inst, dst_inst, flexibility);
  2129. });
  2130. }
  2131. }
  2132. void Differ::MatchFunctions() {
  2133. IdGroup src_func_ids;
  2134. IdGroup dst_func_ids;
  2135. for (const auto& func : src_funcs_) {
  2136. src_func_ids.push_back(func.first);
  2137. }
  2138. for (const auto& func : dst_funcs_) {
  2139. dst_func_ids.push_back(func.first);
  2140. }
  2141. // Base the matching of functions on debug info when available.
  2142. GroupIdsAndMatch<std::string>(
  2143. src_func_ids, dst_func_ids, "", &Differ::GetSanitizedName,
  2144. [this](const IdGroup& src_group, const IdGroup& dst_group) {
  2145. // If there is a single function with this name in src and dst, it's a
  2146. // definite match.
  2147. if (src_group.size() == 1 && dst_group.size() == 1) {
  2148. id_map_.MapIds(src_group[0], dst_group[0]);
  2149. return;
  2150. }
  2151. // If there are multiple functions with the same name, group them by
  2152. // type, and match only if the types match (and are unique).
  2153. GroupIdsAndMatch<uint32_t>(src_group, dst_group, 0,
  2154. &Differ::GroupIdsHelperGetTypeId,
  2155. [this](const IdGroup& src_group_by_type_id,
  2156. const IdGroup& dst_group_by_type_id) {
  2157. if (src_group_by_type_id.size() == 1 &&
  2158. dst_group_by_type_id.size() == 1) {
  2159. id_map_.MapIds(src_group_by_type_id[0],
  2160. dst_group_by_type_id[0]);
  2161. }
  2162. });
  2163. });
  2164. // Any functions that are left are pooled together and matched as if unnamed,
  2165. // with the only exception that two functions with mismatching names are not
  2166. // matched.
  2167. //
  2168. // Before that however, the diff of the functions that are matched are taken
  2169. // and processed, so that more of the global variables can be matched before
  2170. // attempting to match the rest of the functions. They can contribute to the
  2171. // precision of the diff of those functions.
  2172. for (const uint32_t src_func_id : src_func_ids) {
  2173. const uint32_t dst_func_id = id_map_.MappedDstId(src_func_id);
  2174. if (dst_func_id == 0) {
  2175. continue;
  2176. }
  2177. // Since these functions are definite matches, match their parameters for a
  2178. // better diff.
  2179. MatchFunctionParamIds(src_funcs_[src_func_id], dst_funcs_[dst_func_id]);
  2180. // Take the diff of the two functions.
  2181. DiffMatch src_match_result, dst_match_result;
  2182. MatchFunctionBodies(src_func_insts_[src_func_id],
  2183. dst_func_insts_[dst_func_id], &src_match_result,
  2184. &dst_match_result);
  2185. // Match ids between the two function bodies; which can also result in
  2186. // global variables getting matched.
  2187. MatchIdsInFunctionBodies(src_func_insts_[src_func_id],
  2188. dst_func_insts_[dst_func_id], src_match_result,
  2189. dst_match_result, 0);
  2190. }
  2191. // Best effort match functions with matching type.
  2192. GroupIdsAndMatch<uint32_t>(
  2193. src_func_ids, dst_func_ids, 0, &Differ::GroupIdsHelperGetTypeId,
  2194. [this](const IdGroup& src_group_by_type_id,
  2195. const IdGroup& dst_group_by_type_id) {
  2196. BestEffortMatchFunctions(src_group_by_type_id, dst_group_by_type_id,
  2197. src_func_insts_, dst_func_insts_);
  2198. });
  2199. // Any function that's left, best effort match them.
  2200. BestEffortMatchFunctions(src_func_ids, dst_func_ids, src_func_insts_,
  2201. dst_func_insts_);
  2202. }
  2203. void Differ::MatchDebugs1() {
  2204. // This section in cludes: OpString, OpSourceExtension, OpSource,
  2205. // OpSourceContinued
  2206. MatchDebugAndAnnotationInstructions(src_->debugs1(), dst_->debugs1());
  2207. }
  2208. void Differ::MatchDebugs2() {
  2209. // This section includes: OpName, OpMemberName
  2210. MatchDebugAndAnnotationInstructions(src_->debugs2(), dst_->debugs2());
  2211. }
  2212. void Differ::MatchDebugs3() {
  2213. // This section includes: OpModuleProcessed
  2214. MatchDebugAndAnnotationInstructions(src_->debugs3(), dst_->debugs3());
  2215. }
  2216. void Differ::MatchExtInstDebugInfo() {
  2217. // This section includes OpExtInst for DebugInfo extension
  2218. MatchDebugAndAnnotationInstructions(src_->ext_inst_debuginfo(),
  2219. dst_->ext_inst_debuginfo());
  2220. }
  2221. void Differ::MatchAnnotations() {
  2222. // This section includes OpDecorate and family.
  2223. MatchDebugAndAnnotationInstructions(src_->annotations(), dst_->annotations());
  2224. }
  2225. const opt::Instruction* Differ::MappedDstInst(
  2226. const opt::Instruction* src_inst) {
  2227. return MappedInstImpl(src_inst, id_map_.SrcToDstMap(), dst_id_to_);
  2228. }
  2229. const opt::Instruction* Differ::MappedSrcInst(
  2230. const opt::Instruction* dst_inst) {
  2231. return MappedInstImpl(dst_inst, id_map_.DstToSrcMap(), src_id_to_);
  2232. }
  2233. const opt::Instruction* Differ::MappedInstImpl(
  2234. const opt::Instruction* inst, const IdMap& to_other,
  2235. const IdInstructions& other_id_to) {
  2236. if (inst->HasResultId()) {
  2237. if (to_other.IsMapped(inst->result_id())) {
  2238. const uint32_t other_result_id = to_other.MappedId(inst->result_id());
  2239. assert(other_result_id < other_id_to.inst_map_.size());
  2240. return other_id_to.inst_map_[other_result_id];
  2241. }
  2242. return nullptr;
  2243. }
  2244. return to_other.MappedInst(inst);
  2245. }
  2246. void Differ::OutputLine(std::function<bool()> are_lines_identical,
  2247. std::function<void()> output_src_line,
  2248. std::function<void()> output_dst_line) {
  2249. if (are_lines_identical()) {
  2250. out_ << " ";
  2251. output_src_line();
  2252. } else {
  2253. OutputRed();
  2254. out_ << "-";
  2255. output_src_line();
  2256. OutputGreen();
  2257. out_ << "+";
  2258. output_dst_line();
  2259. OutputResetColor();
  2260. }
  2261. }
  2262. const opt::Instruction* IterInst(opt::Module::const_inst_iterator& iter) {
  2263. return &*iter;
  2264. }
  2265. const opt::Instruction* IterInst(InstructionList::const_iterator& iter) {
  2266. return *iter;
  2267. }
  2268. template <typename InstList>
  2269. void Differ::OutputSection(
  2270. const InstList& src_insts, const InstList& dst_insts,
  2271. std::function<void(const opt::Instruction&, const IdInstructions&,
  2272. const opt::Instruction&)>
  2273. write_inst) {
  2274. auto src_iter = src_insts.begin();
  2275. auto dst_iter = dst_insts.begin();
  2276. // - While src_inst doesn't have a match, output it with -
  2277. // - While dst_inst doesn't have a match, output it with +
  2278. // - Now src_inst and dst_inst both have matches; might not match each other!
  2279. // * If section is unordered, just process src_inst and its match (dst_inst
  2280. // or not),
  2281. // dst_inst will eventually be processed when its match is seen.
  2282. // * If section is ordered, also just process src_inst and its match. Its
  2283. // match must
  2284. // necessarily be dst_inst.
  2285. while (src_iter != src_insts.end() || dst_iter != dst_insts.end()) {
  2286. OutputRed();
  2287. while (src_iter != src_insts.end() &&
  2288. MappedDstInst(IterInst(src_iter)) == nullptr) {
  2289. out_ << "-";
  2290. write_inst(*IterInst(src_iter), src_id_to_, *IterInst(src_iter));
  2291. ++src_iter;
  2292. }
  2293. OutputGreen();
  2294. while (dst_iter != dst_insts.end() &&
  2295. MappedSrcInst(IterInst(dst_iter)) == nullptr) {
  2296. out_ << "+";
  2297. write_inst(ToMappedSrcIds(*IterInst(dst_iter)), dst_id_to_,
  2298. *IterInst(dst_iter));
  2299. ++dst_iter;
  2300. }
  2301. OutputResetColor();
  2302. if (src_iter != src_insts.end() && dst_iter != dst_insts.end()) {
  2303. const opt::Instruction* src_inst = IterInst(src_iter);
  2304. const opt::Instruction* matched_dst_inst = MappedDstInst(src_inst);
  2305. assert(matched_dst_inst != nullptr);
  2306. assert(MappedSrcInst(IterInst(dst_iter)) != nullptr);
  2307. OutputLine(
  2308. [this, src_inst, matched_dst_inst]() {
  2309. return DoInstructionsMatch(src_inst, matched_dst_inst);
  2310. },
  2311. [this, src_inst, &write_inst]() {
  2312. write_inst(*src_inst, src_id_to_, *src_inst);
  2313. },
  2314. [this, matched_dst_inst, &write_inst]() {
  2315. write_inst(ToMappedSrcIds(*matched_dst_inst), dst_id_to_,
  2316. *matched_dst_inst);
  2317. });
  2318. ++src_iter;
  2319. ++dst_iter;
  2320. }
  2321. }
  2322. }
  2323. void Differ::ToParsedInstruction(
  2324. const opt::Instruction& inst, const IdInstructions& id_to,
  2325. const opt::Instruction& original_inst,
  2326. spv_parsed_instruction_t* parsed_inst,
  2327. std::vector<spv_parsed_operand_t>& parsed_operands,
  2328. std::vector<uint32_t>& inst_binary) {
  2329. inst.ToBinaryWithoutAttachedDebugInsts(&inst_binary);
  2330. parsed_operands.resize(inst.NumOperands());
  2331. parsed_inst->words = inst_binary.data();
  2332. parsed_inst->num_words = static_cast<uint16_t>(inst_binary.size());
  2333. parsed_inst->opcode = static_cast<uint16_t>(inst.opcode());
  2334. parsed_inst->ext_inst_type =
  2335. inst.opcode() == spv::Op::OpExtInst
  2336. ? GetExtInstType(id_to, original_inst.GetSingleWordInOperand(0))
  2337. : SPV_EXT_INST_TYPE_NONE;
  2338. parsed_inst->type_id =
  2339. inst.HasResultType() ? inst.GetSingleWordOperand(0) : 0;
  2340. parsed_inst->result_id = inst.HasResultId() ? inst.result_id() : 0;
  2341. parsed_inst->operands = parsed_operands.data();
  2342. parsed_inst->num_operands = static_cast<uint16_t>(parsed_operands.size());
  2343. // Word 0 is always op and num_words, so operands start at offset 1.
  2344. uint32_t offset = 1;
  2345. for (uint16_t operand_index = 0; operand_index < parsed_inst->num_operands;
  2346. ++operand_index) {
  2347. const opt::Operand& operand = inst.GetOperand(operand_index);
  2348. spv_parsed_operand_t& parsed_operand = parsed_operands[operand_index];
  2349. parsed_operand.offset = static_cast<uint16_t>(offset);
  2350. parsed_operand.num_words = static_cast<uint16_t>(operand.words.size());
  2351. parsed_operand.type = operand.type;
  2352. parsed_operand.number_kind = GetNumberKind(
  2353. id_to, original_inst, operand_index, &parsed_operand.number_bit_width);
  2354. offset += parsed_operand.num_words;
  2355. }
  2356. }
  2357. opt::Instruction Differ::ToMappedSrcIds(const opt::Instruction& dst_inst) {
  2358. // Create an identical instruction to dst_inst, except ids are changed to the
  2359. // mapped one.
  2360. opt::Instruction mapped_inst = dst_inst;
  2361. for (uint32_t operand_index = 0; operand_index < mapped_inst.NumOperands();
  2362. ++operand_index) {
  2363. opt::Operand& operand = mapped_inst.GetOperand(operand_index);
  2364. if (spvIsIdType(operand.type)) {
  2365. assert(id_map_.IsDstMapped(operand.AsId()));
  2366. operand.words[0] = id_map_.MappedSrcId(operand.AsId());
  2367. }
  2368. }
  2369. return mapped_inst;
  2370. }
  2371. spv_result_t Differ::Output() {
  2372. id_map_.MapUnmatchedIds(
  2373. [this](uint32_t src_id) { return src_id_to_.IsDefined(src_id); },
  2374. [this](uint32_t dst_id) { return dst_id_to_.IsDefined(dst_id); });
  2375. src_id_to_.inst_map_.resize(id_map_.SrcToDstMap().IdBound(), nullptr);
  2376. dst_id_to_.inst_map_.resize(id_map_.DstToSrcMap().IdBound(), nullptr);
  2377. const spv_target_env target_env = SPV_ENV_UNIVERSAL_1_6;
  2378. spv_opcode_table opcode_table;
  2379. spv_operand_table operand_table;
  2380. spv_ext_inst_table ext_inst_table;
  2381. spv_result_t result;
  2382. result = spvOpcodeTableGet(&opcode_table, target_env);
  2383. if (result != SPV_SUCCESS) return result;
  2384. result = spvOperandTableGet(&operand_table, target_env);
  2385. if (result != SPV_SUCCESS) return result;
  2386. result = spvExtInstTableGet(&ext_inst_table, target_env);
  2387. if (result != SPV_SUCCESS) return result;
  2388. spv_context_t context{
  2389. target_env,
  2390. opcode_table,
  2391. operand_table,
  2392. ext_inst_table,
  2393. };
  2394. const AssemblyGrammar grammar(&context);
  2395. if (!grammar.isValid()) return SPV_ERROR_INVALID_TABLE;
  2396. uint32_t disassembly_options = SPV_BINARY_TO_TEXT_OPTION_PRINT;
  2397. if (options_.indent) {
  2398. disassembly_options |= SPV_BINARY_TO_TEXT_OPTION_INDENT;
  2399. }
  2400. NameMapper name_mapper = GetTrivialNameMapper();
  2401. disassemble::InstructionDisassembler dis(grammar, out_, disassembly_options,
  2402. name_mapper);
  2403. if (!options_.no_header) {
  2404. // Output the header
  2405. // TODO: when using diff with text, the assembler overrides the version and
  2406. // generator, so these aren't reflected correctly in the output. Could
  2407. // potentially extract this info from the header comment.
  2408. OutputLine([]() { return true; }, [&dis]() { dis.EmitHeaderSpirv(); },
  2409. []() { assert(false && "Unreachable"); });
  2410. OutputLine([this]() { return src_->version() == dst_->version(); },
  2411. [this, &dis]() { dis.EmitHeaderVersion(src_->version()); },
  2412. [this, &dis]() { dis.EmitHeaderVersion(dst_->version()); });
  2413. OutputLine([this]() { return src_->generator() == dst_->generator(); },
  2414. [this, &dis]() { dis.EmitHeaderGenerator(src_->generator()); },
  2415. [this, &dis]() { dis.EmitHeaderGenerator(dst_->generator()); });
  2416. OutputLine(
  2417. [this]() { return src_->IdBound() == id_map_.SrcToDstMap().IdBound(); },
  2418. [this, &dis]() { dis.EmitHeaderIdBound(src_->IdBound()); },
  2419. [this, &dis]() {
  2420. dis.EmitHeaderIdBound(id_map_.SrcToDstMap().IdBound());
  2421. });
  2422. OutputLine([this]() { return src_->schema() == dst_->schema(); },
  2423. [this, &dis]() { dis.EmitHeaderSchema(src_->schema()); },
  2424. [this, &dis]() { dis.EmitHeaderSchema(dst_->schema()); });
  2425. }
  2426. // For each section, iterate both modules and output the disassembly.
  2427. auto write_inst = [this, &dis](const opt::Instruction& inst,
  2428. const IdInstructions& id_to,
  2429. const opt::Instruction& original_inst) {
  2430. spv_parsed_instruction_t parsed_inst;
  2431. std::vector<spv_parsed_operand_t> parsed_operands;
  2432. std::vector<uint32_t> inst_binary;
  2433. ToParsedInstruction(inst, id_to, original_inst, &parsed_inst,
  2434. parsed_operands, inst_binary);
  2435. dis.EmitInstruction(parsed_inst, 0);
  2436. };
  2437. OutputSection(src_->capabilities(), dst_->capabilities(), write_inst);
  2438. OutputSection(src_->extensions(), dst_->extensions(), write_inst);
  2439. OutputSection(src_->ext_inst_imports(), dst_->ext_inst_imports(), write_inst);
  2440. // There is only one memory model.
  2441. OutputLine(
  2442. [this]() {
  2443. return DoInstructionsMatch(src_->GetMemoryModel(),
  2444. dst_->GetMemoryModel());
  2445. },
  2446. [this, &write_inst]() {
  2447. write_inst(*src_->GetMemoryModel(), src_id_to_,
  2448. *src_->GetMemoryModel());
  2449. },
  2450. [this, &write_inst]() {
  2451. write_inst(*dst_->GetMemoryModel(), dst_id_to_,
  2452. *dst_->GetMemoryModel());
  2453. });
  2454. OutputSection(src_->entry_points(), dst_->entry_points(), write_inst);
  2455. OutputSection(src_->execution_modes(), dst_->execution_modes(), write_inst);
  2456. OutputSection(src_->debugs1(), dst_->debugs1(), write_inst);
  2457. OutputSection(src_->debugs2(), dst_->debugs2(), write_inst);
  2458. OutputSection(src_->debugs3(), dst_->debugs3(), write_inst);
  2459. OutputSection(src_->ext_inst_debuginfo(), dst_->ext_inst_debuginfo(),
  2460. write_inst);
  2461. OutputSection(src_->annotations(), dst_->annotations(), write_inst);
  2462. OutputSection(src_->types_values(), dst_->types_values(), write_inst);
  2463. // Get the body of all the functions.
  2464. FunctionInstMap src_func_header_insts;
  2465. FunctionInstMap dst_func_header_insts;
  2466. GetFunctionHeaderInstructions(src_, &src_func_header_insts);
  2467. GetFunctionHeaderInstructions(dst_, &dst_func_header_insts);
  2468. for (const auto& src_func : src_func_insts_) {
  2469. const uint32_t src_func_id = src_func.first;
  2470. const InstructionList& src_insts = src_func.second;
  2471. const InstructionList& src_header_insts =
  2472. src_func_header_insts[src_func_id];
  2473. const uint32_t dst_func_id = id_map_.MappedDstId(src_func_id);
  2474. if (dst_func_insts_.find(dst_func_id) == dst_func_insts_.end()) {
  2475. OutputSection(src_header_insts, InstructionList(), write_inst);
  2476. OutputSection(src_insts, InstructionList(), write_inst);
  2477. continue;
  2478. }
  2479. const InstructionList& dst_insts = dst_func_insts_[dst_func_id];
  2480. const InstructionList& dst_header_insts =
  2481. dst_func_header_insts[dst_func_id];
  2482. OutputSection(src_header_insts, dst_header_insts, write_inst);
  2483. OutputSection(src_insts, dst_insts, write_inst);
  2484. }
  2485. for (const auto& dst_func : dst_func_insts_) {
  2486. const uint32_t dst_func_id = dst_func.first;
  2487. const InstructionList& dst_insts = dst_func.second;
  2488. const InstructionList& dst_header_insts =
  2489. dst_func_header_insts[dst_func_id];
  2490. const uint32_t src_func_id = id_map_.MappedSrcId(dst_func_id);
  2491. if (src_func_insts_.find(src_func_id) == src_func_insts_.end()) {
  2492. OutputSection(InstructionList(), dst_header_insts, write_inst);
  2493. OutputSection(InstructionList(), dst_insts, write_inst);
  2494. }
  2495. }
  2496. out_ << std::flush;
  2497. return SPV_SUCCESS;
  2498. }
  2499. } // anonymous namespace
  2500. spv_result_t Diff(opt::IRContext* src, opt::IRContext* dst, std::ostream& out,
  2501. Options options) {
  2502. // High level algorithm:
  2503. //
  2504. // - Some sections of SPIR-V don't deal with ids; instructions in those
  2505. // sections are matched identically. For example OpCapability instructions.
  2506. // - Some sections produce ids, and they can be trivially matched by their
  2507. // parameters. For example OpExtInstImport instructions.
  2508. // - Some sections annotate ids. These are matched at the end, after the ids
  2509. // themselves are matched. For example OpName or OpDecorate instructions.
  2510. // - Some sections produce ids that depend on other ids and they can be
  2511. // recursively matched. For example OpType* instructions.
  2512. // - Some sections produce ids that are not trivially matched. For these ids,
  2513. // the debug info is used when possible, or a best guess (such as through
  2514. // decorations) is used. For example OpVariable instructions.
  2515. // - Matching functions is done with multiple attempts:
  2516. // * Functions with identical debug names are matched if there are no
  2517. // overloads.
  2518. // * Otherwise, functions with identical debug names and types are matched.
  2519. // * The rest of the functions are best-effort matched, first in groups of
  2520. // identical type, then any with any.
  2521. // * The best-effort matching takes the diff of every pair of functions in
  2522. // a group and selects the top matches that also meet a similarity
  2523. // index.
  2524. // * Once a pair of functions are matched, the fuzzy diff of the
  2525. // instructions is used to match the instructions in the function body.
  2526. // The fuzzy diff makes sure that sufficiently similar instructions are
  2527. // matched and that yet-to-be-matched result ids don't result in a larger
  2528. // diff.
  2529. //
  2530. // Once the instructions are matched between the src and dst SPIR-V, the src
  2531. // is traversed and its disassembly is output. In the process, any unmatched
  2532. // instruction is prefixed with -, and any unmatched instruction in dst in the
  2533. // same section is output prefixed with +. To avoid confusion, the
  2534. // instructions in dst are output with matching ids in src so the output
  2535. // assembly is consistent.
  2536. Differ differ(src, dst, out, options);
  2537. // First, match instructions between the different non-annotation sections of
  2538. // the SPIR-V.
  2539. differ.MatchCapabilities();
  2540. differ.MatchExtensions();
  2541. differ.MatchExtInstImportIds();
  2542. differ.MatchMemoryModel();
  2543. differ.MatchEntryPointIds();
  2544. differ.MatchExecutionModes();
  2545. differ.MatchTypeForwardPointers();
  2546. differ.MatchTypeIds();
  2547. differ.MatchConstants();
  2548. differ.MatchVariableIds();
  2549. differ.MatchFunctions();
  2550. // Match instructions that annotate previously-matched ids.
  2551. differ.MatchDebugs1();
  2552. differ.MatchDebugs2();
  2553. differ.MatchDebugs3();
  2554. differ.MatchExtInstDebugInfo();
  2555. differ.MatchAnnotations();
  2556. // Show the disassembly with the diff.
  2557. //
  2558. // TODO: Based on an option, output either based on src or dst, i.e. the diff
  2559. // can show the ids and instruction/function order either from src or dst.
  2560. spv_result_t result = differ.Output();
  2561. differ.DumpIdMap();
  2562. return result;
  2563. }
  2564. } // namespace diff
  2565. } // namespace spvtools