inst_fingerprinter.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/sem_ir/inst_fingerprinter.h"
  5. #include <array>
  6. #include <utility>
  7. #include <variant>
  8. #include "common/concepts.h"
  9. #include "common/ostream.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/StableHashing.h"
  13. #include "toolchain/base/value_ids.h"
  14. #include "toolchain/sem_ir/entity_with_params_base.h"
  15. #include "toolchain/sem_ir/ids.h"
  16. #include "toolchain/sem_ir/typed_insts.h"
  17. namespace Carbon::SemIR {
  18. namespace {
  19. struct Worklist {
  20. // The file containing the instruction we're currently processing.
  21. const File* sem_ir = nullptr;
  22. // The instructions we need to compute fingerprints for.
  23. llvm::SmallVector<
  24. std::pair<const File*, std::variant<InstId, InstBlockId, ImplId>>>
  25. todo;
  26. // The contents of the current instruction as accumulated so far. This is used
  27. // to build a Merkle tree containing a fingerprint for the current
  28. // instruction.
  29. llvm::SmallVector<llvm::stable_hash> contents = {};
  30. // Known cached instruction fingerprints. Each item in `todo` will be added to
  31. // the cache if not already present.
  32. Map<std::pair<const File*, InstId>, uint64_t>* fingerprints;
  33. // Finish fingerprinting and compute the fingerprint.
  34. auto Finish() -> uint64_t { return llvm::stable_hash_combine(contents); }
  35. // Add an invalid marker to the contents. This is used when the entity
  36. // contains a `None` ID. This uses an arbitrary fixed value that is assumed
  37. // to be unlikely to collide with a valid value.
  38. auto AddInvalid() -> void { contents.push_back(-1); }
  39. // Add a string to the contents.
  40. auto AddString(llvm::StringRef string) -> void {
  41. contents.push_back(llvm::stable_hash_name(string));
  42. }
  43. // Each of the following `Add` functions adds a typed argument to the contents
  44. // of the current instruction. If we don't yet have a fingerprint for the
  45. // argument, it instead adds that argument to the worklist instead.
  46. auto Add(InstKind kind) -> void {
  47. // TODO: Precompute or cache the hash of instruction IR names, or pick a
  48. // scheme that doesn't change when IR names change.
  49. AddString(kind.ir_name());
  50. }
  51. auto Add(IdentifierId ident_id) -> void {
  52. AddString(sem_ir->identifiers().Get(ident_id));
  53. }
  54. auto Add(StringLiteralValueId lit_id) -> void {
  55. AddString(sem_ir->string_literal_values().Get(lit_id));
  56. }
  57. auto Add(NameId name_id) -> void {
  58. AddString(sem_ir->names().GetIRBaseName(name_id));
  59. }
  60. auto Add(EntityNameId entity_name_id) -> void {
  61. if (!entity_name_id.has_value()) {
  62. AddInvalid();
  63. return;
  64. }
  65. const auto& entity_name = sem_ir->entity_names().Get(entity_name_id);
  66. if (entity_name.bind_index().has_value()) {
  67. Add(entity_name.bind_index());
  68. // Don't include the name. While it is part of the canonical identity of a
  69. // compile-time binding, renaming it (and its uses) is a compatible change
  70. // that we would like to not affect the fingerprint.
  71. //
  72. // Also don't include the `is_template` flag. Changing that flag should
  73. // also be a compatible change from the perspective of users of a generic.
  74. } else {
  75. Add(entity_name.name_id);
  76. }
  77. // TODO: Should we include the parent index?
  78. }
  79. auto AddInFile(const File* file, InstId inner_id) -> void {
  80. if (!inner_id.has_value()) {
  81. AddInvalid();
  82. return;
  83. }
  84. if (auto lookup = fingerprints->Lookup(std::pair(file, inner_id))) {
  85. contents.push_back(lookup.value());
  86. } else {
  87. todo.push_back({file, inner_id});
  88. }
  89. }
  90. auto Add(InstId inner_id) -> void { AddInFile(sem_ir, inner_id); }
  91. auto Add(ConstantId constant_id) -> void {
  92. if (!constant_id.has_value()) {
  93. AddInvalid();
  94. return;
  95. }
  96. Add(sem_ir->constant_values().GetInstId(constant_id));
  97. }
  98. auto Add(TypeId type_id) -> void {
  99. if (!type_id.has_value()) {
  100. AddInvalid();
  101. return;
  102. }
  103. Add(sem_ir->types().GetInstId(type_id));
  104. }
  105. template <typename T>
  106. auto AddBlock(llvm::ArrayRef<T> block) -> void {
  107. contents.push_back(block.size());
  108. for (auto inner_id : block) {
  109. Add(inner_id);
  110. }
  111. }
  112. auto Add(InstBlockId inst_block_id) -> void {
  113. if (!inst_block_id.has_value()) {
  114. AddInvalid();
  115. return;
  116. }
  117. AddBlock(sem_ir->inst_blocks().Get(inst_block_id));
  118. }
  119. auto Add(StructTypeField field) -> void {
  120. Add(field.name_id);
  121. Add(field.type_inst_id);
  122. }
  123. auto Add(StructTypeFieldsId struct_type_fields_id) -> void {
  124. if (!struct_type_fields_id.has_value()) {
  125. AddInvalid();
  126. return;
  127. }
  128. AddBlock(sem_ir->struct_type_fields().Get(struct_type_fields_id));
  129. }
  130. auto Add(NameScopeId name_scope_id) -> void {
  131. if (!name_scope_id.has_value()) {
  132. AddInvalid();
  133. return;
  134. }
  135. const auto& scope = sem_ir->name_scopes().Get(name_scope_id);
  136. Add(scope.name_id());
  137. if (!sem_ir->name_scopes().IsPackage(name_scope_id) &&
  138. scope.parent_scope_id().has_value()) {
  139. Add(sem_ir->name_scopes().Get(scope.parent_scope_id()).inst_id());
  140. }
  141. }
  142. template <typename EntityT = EntityWithParamsBase>
  143. auto AddEntity(const std::type_identity_t<EntityT>& entity) -> void {
  144. Add(entity.name_id);
  145. if (entity.parent_scope_id.has_value()) {
  146. Add(sem_ir->name_scopes().Get(entity.parent_scope_id).inst_id());
  147. }
  148. }
  149. auto Add(FunctionId function_id) -> void {
  150. AddEntity(sem_ir->functions().Get(function_id));
  151. }
  152. auto Add(ClassId class_id) -> void {
  153. AddEntity(sem_ir->classes().Get(class_id));
  154. }
  155. auto Add(InterfaceId interface_id) -> void {
  156. AddEntity(sem_ir->interfaces().Get(interface_id));
  157. }
  158. auto Add(AssociatedConstantId assoc_const_id) -> void {
  159. AddEntity<AssociatedConstant>(
  160. sem_ir->associated_constants().Get(assoc_const_id));
  161. }
  162. auto Add(ImplId impl_id) -> void {
  163. const auto& impl = sem_ir->impls().Get(impl_id);
  164. Add(sem_ir->constant_values().Get(impl.self_id));
  165. Add(sem_ir->constant_values().Get(impl.constraint_id));
  166. Add(impl.parent_scope_id);
  167. }
  168. auto Add(DeclInstBlockId /*block_id*/) -> void {
  169. // Intentionally exclude decl blocks from fingerprinting. Changes to the
  170. // decl block don't change the identity of the declaration.
  171. }
  172. auto Add(LabelId /*block_id*/) -> void {
  173. CARBON_FATAL("Should never fingerprint a label");
  174. }
  175. auto Add(FacetTypeId facet_type_id) -> void {
  176. const auto& facet_type = sem_ir->facet_types().Get(facet_type_id);
  177. for (auto [interface_id, specific_id] : facet_type.extend_constraints) {
  178. Add(interface_id);
  179. Add(specific_id);
  180. }
  181. for (auto [interface_id, specific_id] : facet_type.self_impls_constraints) {
  182. Add(interface_id);
  183. Add(specific_id);
  184. }
  185. for (auto [lhs_id, rhs_id] : facet_type.rewrite_constraints) {
  186. Add(lhs_id);
  187. Add(rhs_id);
  188. }
  189. contents.push_back(facet_type.other_requirements);
  190. }
  191. auto Add(GenericId generic_id) -> void {
  192. if (!generic_id.has_value()) {
  193. AddInvalid();
  194. return;
  195. }
  196. Add(sem_ir->generics().Get(generic_id).decl_id);
  197. }
  198. auto Add(SpecificId specific_id) -> void {
  199. if (!specific_id.has_value()) {
  200. AddInvalid();
  201. return;
  202. }
  203. const auto& specific = sem_ir->specifics().Get(specific_id);
  204. Add(specific.generic_id);
  205. Add(specific.args_id);
  206. }
  207. auto Add(SpecificInterfaceId specific_interface_id) -> void {
  208. if (!specific_interface_id.has_value()) {
  209. AddInvalid();
  210. return;
  211. }
  212. const auto& interface =
  213. sem_ir->specific_interfaces().Get(specific_interface_id);
  214. Add(interface.interface_id);
  215. Add(interface.specific_id);
  216. }
  217. auto Add(const llvm::APInt& value) -> void {
  218. contents.push_back(value.getBitWidth());
  219. for (auto word : llvm::seq((value.getBitWidth() + 63) / 64)) {
  220. // TODO: Is there a better way to copy the words from an APInt?
  221. contents.push_back(value.extractBitsAsZExtValue(64, 64 * word));
  222. }
  223. }
  224. auto Add(IntId int_id) -> void { Add(sem_ir->ints().Get(int_id)); }
  225. auto Add(FloatId float_id) -> void {
  226. Add(sem_ir->floats().Get(float_id).bitcastToAPInt());
  227. }
  228. auto Add(PackageNameId package_id) -> void {
  229. if (auto ident_id = package_id.AsIdentifierId(); ident_id.has_value()) {
  230. AddString(sem_ir->identifiers().Get(ident_id));
  231. } else {
  232. // TODO: May collide with a user package of the same name. Consider using
  233. // a different value.
  234. AddString(package_id.AsSpecialName());
  235. }
  236. }
  237. auto Add(LibraryNameId lib_name_id) -> void {
  238. if (lib_name_id == LibraryNameId::Default) {
  239. AddString("");
  240. } else if (lib_name_id == LibraryNameId::Error) {
  241. AddString("<error>");
  242. } else if (lib_name_id.has_value()) {
  243. Add(lib_name_id.AsStringLiteralValueId());
  244. } else {
  245. AddInvalid();
  246. }
  247. }
  248. auto Add(ImportIRId ir_id) -> void {
  249. const auto* ir = sem_ir->import_irs().Get(ir_id).sem_ir;
  250. Add(ir->package_id());
  251. Add(ir->library_id());
  252. }
  253. auto Add(ImportIRInstId ir_inst_id) -> void {
  254. auto ir_inst = sem_ir->import_ir_insts().Get(ir_inst_id);
  255. AddInFile(sem_ir->import_irs().Get(ir_inst.ir_id()).sem_ir,
  256. ir_inst.inst_id());
  257. }
  258. template <typename T>
  259. requires(SameAsOneOf<T, BoolValue, CompileTimeBindIndex, ElementIndex,
  260. FloatKind, IntKind, CallParamIndex>)
  261. auto Add(T arg) -> void {
  262. // Index-like ID: just include the value directly.
  263. contents.push_back(arg.index);
  264. }
  265. template <typename T>
  266. requires(SameAsOneOf<T, AnyRawId, ExprRegionId, LocId, RealId>)
  267. auto Add(T /*arg*/) -> void {
  268. CARBON_FATAL("Unexpected instruction operand kind {0}", typeid(T).name());
  269. }
  270. using AddFnT = auto(Worklist& worklist, int32_t arg) -> void;
  271. // Returns a lookup table to add an argument of the given kind. Requires a
  272. // null IdKind as a parameter in order to get the type pack.
  273. template <typename... Types>
  274. static constexpr auto MakeAddTable(TypeEnum<Types...>* /*id_kind*/)
  275. -> std::array<AddFnT*, IdKind::NumValues> {
  276. std::array<AddFnT*, IdKind::NumValues> table = {};
  277. ((table[IdKind::template For<Types>.ToIndex()] =
  278. [](Worklist& worklist, int32_t arg) {
  279. worklist.Add(Inst::FromRaw<Types>(arg));
  280. }),
  281. ...);
  282. table[IdKind::Invalid.ToIndex()] = [](Worklist& /*worklist*/,
  283. int32_t /*arg*/) {
  284. CARBON_FATAL("Unexpected invalid argument kind");
  285. };
  286. table[IdKind::None.ToIndex()] = [](Worklist& /*worklist*/,
  287. int32_t /*arg*/) {};
  288. return table;
  289. }
  290. // Add an instruction argument to the contents of the current instruction.
  291. auto AddWithKind(Inst::ArgAndKind arg) -> void {
  292. static constexpr auto Table = MakeAddTable(static_cast<IdKind*>(nullptr));
  293. Table[arg.kind().ToIndex()](*this, arg.value());
  294. }
  295. // Ensure all the instructions on the todo list have fingerprints. To avoid a
  296. // re-lookup, returns the fingerprint of the first instruction on the todo
  297. // list, and requires the todo list to be non-empty.
  298. auto Run() -> uint64_t {
  299. CARBON_CHECK(!todo.empty());
  300. while (true) {
  301. const size_t init_size = todo.size();
  302. auto [next_sem_ir, next] = todo.back();
  303. sem_ir = next_sem_ir;
  304. contents.clear();
  305. if (!std::holds_alternative<InstId>(next)) {
  306. // Add the contents of the `next` instruction so they all contribute to
  307. // the `contents`.
  308. if (auto* impl_id = std::get_if<ImplId>(&next)) {
  309. Add(*impl_id);
  310. } else if (auto* inst_block_id = std::get_if<InstBlockId>(&next)) {
  311. Add(*inst_block_id);
  312. }
  313. // If we didn't add any more work, then we have a fingerprint for the
  314. // `next` instruction, otherwise we wait until that work is completed.
  315. // If the `next` is the last thing in `todo`, we return the fingerprint.
  316. // Otherwise we would just discard it because we don't currently cache
  317. // the fingerprint for things other than `InstId`, but we really only
  318. // expect other `next` types to be at the bottom of the `todo` stack
  319. // since they are not added to `todo` during Run().
  320. if (todo.size() == init_size) {
  321. auto fingerprint = Finish();
  322. todo.pop_back();
  323. CARBON_CHECK(todo.empty(),
  324. "A non-InstId was inserted into `todo` during Run()");
  325. return fingerprint;
  326. }
  327. // Move on to processing the instructions added above; we will come
  328. // back to this branch once they are done.
  329. continue;
  330. }
  331. auto next_inst_id = std::get<InstId>(next);
  332. // If we already have a fingerprint for this instruction, we have nothing
  333. // to do. Just pop it from `todo`.
  334. if (auto lookup =
  335. fingerprints->Lookup(std::pair(next_sem_ir, next_inst_id))) {
  336. todo.pop_back();
  337. if (todo.empty()) {
  338. return lookup.value();
  339. }
  340. continue;
  341. }
  342. // Keep this instruction in `todo` for now. If we add more work, we'll
  343. // finish that work and process this instruction again, and if not, we'll
  344. // pop the instruction at the end of the loop.
  345. auto inst = next_sem_ir->insts().Get(next_inst_id);
  346. // Add the instruction's fields to the contents.
  347. Add(inst.kind());
  348. // Don't include the type if it's `type` or `<error>`, because those types
  349. // are self-referential.
  350. if (inst.type_id() != TypeType::TypeId &&
  351. inst.type_id() != ErrorInst::TypeId) {
  352. Add(inst.type_id());
  353. }
  354. AddWithKind(inst.arg0_and_kind());
  355. AddWithKind(inst.arg1_and_kind());
  356. // If we didn't add any work, we have a fingerprint for this instruction;
  357. // pop it from the todo list. Otherwise, we leave it on the todo list so
  358. // we can compute its fingerprint once we've finished the work we added.
  359. if (todo.size() == init_size) {
  360. uint64_t fingerprint = Finish();
  361. fingerprints->Insert(std::pair(next_sem_ir, next_inst_id), fingerprint);
  362. todo.pop_back();
  363. if (todo.empty()) {
  364. return fingerprint;
  365. }
  366. }
  367. }
  368. }
  369. };
  370. } // namespace
  371. auto InstFingerprinter::GetOrCompute(const File* file, InstId inst_id)
  372. -> uint64_t {
  373. Worklist worklist = {.todo = {{file, inst_id}},
  374. .fingerprints = &fingerprints_};
  375. return worklist.Run();
  376. }
  377. auto InstFingerprinter::GetOrCompute(const File* file,
  378. InstBlockId inst_block_id) -> uint64_t {
  379. Worklist worklist = {.todo = {{file, inst_block_id}},
  380. .fingerprints = &fingerprints_};
  381. return worklist.Run();
  382. }
  383. auto InstFingerprinter::GetOrCompute(const File* file, ImplId impl_id)
  384. -> uint64_t {
  385. Worklist worklist = {.todo = {{file, impl_id}},
  386. .fingerprints = &fingerprints_};
  387. return worklist.Run();
  388. }
  389. } // namespace Carbon::SemIR