inst_fingerprinter.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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(CustomLayoutId custom_layout_id) -> void {
  131. if (!custom_layout_id.has_value()) {
  132. AddInvalid();
  133. return;
  134. }
  135. auto block = sem_ir->custom_layouts().Get(custom_layout_id);
  136. contents.push_back(block.size());
  137. contents.insert(contents.end(), block.begin(), block.end());
  138. }
  139. auto Add(NameScopeId name_scope_id) -> void {
  140. if (!name_scope_id.has_value()) {
  141. AddInvalid();
  142. return;
  143. }
  144. const auto& scope = sem_ir->name_scopes().Get(name_scope_id);
  145. Add(scope.name_id());
  146. if (!sem_ir->name_scopes().IsPackage(name_scope_id) &&
  147. scope.parent_scope_id().has_value()) {
  148. Add(sem_ir->name_scopes().Get(scope.parent_scope_id()).inst_id());
  149. }
  150. }
  151. template <typename EntityT = EntityWithParamsBase>
  152. auto AddEntity(const std::type_identity_t<EntityT>& entity) -> void {
  153. Add(entity.name_id);
  154. if (entity.parent_scope_id.has_value()) {
  155. Add(sem_ir->name_scopes().Get(entity.parent_scope_id).inst_id());
  156. }
  157. }
  158. auto Add(FunctionId function_id) -> void {
  159. AddEntity(sem_ir->functions().Get(function_id));
  160. }
  161. auto Add(ClassId class_id) -> void {
  162. AddEntity(sem_ir->classes().Get(class_id));
  163. }
  164. auto Add(VtableId vtable_id) -> void {
  165. const auto& vtable = sem_ir->vtables().Get(vtable_id);
  166. if (vtable.class_id.has_value()) {
  167. Add(vtable.class_id);
  168. }
  169. Add(vtable.virtual_functions_id);
  170. }
  171. auto Add(InterfaceId interface_id) -> void {
  172. AddEntity(sem_ir->interfaces().Get(interface_id));
  173. }
  174. auto Add(AssociatedConstantId assoc_const_id) -> void {
  175. AddEntity<AssociatedConstant>(
  176. sem_ir->associated_constants().Get(assoc_const_id));
  177. }
  178. auto Add(ImplId impl_id) -> void {
  179. const auto& impl = sem_ir->impls().Get(impl_id);
  180. Add(sem_ir->constant_values().Get(impl.self_id));
  181. Add(sem_ir->constant_values().Get(impl.constraint_id));
  182. Add(impl.parent_scope_id);
  183. }
  184. auto Add(DeclInstBlockId /*block_id*/) -> void {
  185. // Intentionally exclude decl blocks from fingerprinting. Changes to the
  186. // decl block don't change the identity of the declaration.
  187. }
  188. auto Add(LabelId /*block_id*/) -> void {
  189. CARBON_FATAL("Should never fingerprint a label");
  190. }
  191. auto Add(FacetTypeId facet_type_id) -> void {
  192. const auto& facet_type = sem_ir->facet_types().Get(facet_type_id);
  193. for (auto [interface_id, specific_id] : facet_type.extend_constraints) {
  194. Add(interface_id);
  195. Add(specific_id);
  196. }
  197. for (auto [interface_id, specific_id] : facet_type.self_impls_constraints) {
  198. Add(interface_id);
  199. Add(specific_id);
  200. }
  201. for (auto [lhs_id, rhs_id] : facet_type.rewrite_constraints) {
  202. Add(lhs_id);
  203. Add(rhs_id);
  204. }
  205. contents.push_back(facet_type.other_requirements);
  206. }
  207. auto Add(GenericId generic_id) -> void {
  208. if (!generic_id.has_value()) {
  209. AddInvalid();
  210. return;
  211. }
  212. Add(sem_ir->generics().Get(generic_id).decl_id);
  213. }
  214. auto Add(SpecificId specific_id) -> void {
  215. if (!specific_id.has_value()) {
  216. AddInvalid();
  217. return;
  218. }
  219. const auto& specific = sem_ir->specifics().Get(specific_id);
  220. Add(specific.generic_id);
  221. Add(specific.args_id);
  222. }
  223. auto Add(SpecificInterfaceId specific_interface_id) -> void {
  224. if (!specific_interface_id.has_value()) {
  225. AddInvalid();
  226. return;
  227. }
  228. const auto& interface =
  229. sem_ir->specific_interfaces().Get(specific_interface_id);
  230. Add(interface.interface_id);
  231. Add(interface.specific_id);
  232. }
  233. auto Add(const llvm::APInt& value) -> void {
  234. contents.push_back(value.getBitWidth());
  235. for (auto word : llvm::seq((value.getBitWidth() + 63) / 64)) {
  236. // TODO: Is there a better way to copy the words from an APInt?
  237. contents.push_back(value.extractBitsAsZExtValue(64, 64 * word));
  238. }
  239. }
  240. auto Add(IntId int_id) -> void { Add(sem_ir->ints().Get(int_id)); }
  241. auto Add(FloatId float_id) -> void {
  242. Add(sem_ir->floats().Get(float_id).bitcastToAPInt());
  243. }
  244. auto Add(PackageNameId package_id) -> void {
  245. if (auto ident_id = package_id.AsIdentifierId(); ident_id.has_value()) {
  246. AddString(sem_ir->identifiers().Get(ident_id));
  247. } else {
  248. // TODO: May collide with a user package of the same name. Consider using
  249. // a different value.
  250. AddString(package_id.AsSpecialName());
  251. }
  252. }
  253. auto Add(LibraryNameId lib_name_id) -> void {
  254. if (lib_name_id == LibraryNameId::Default) {
  255. AddString("");
  256. } else if (lib_name_id == LibraryNameId::Error) {
  257. AddString("<error>");
  258. } else if (lib_name_id.has_value()) {
  259. Add(lib_name_id.AsStringLiteralValueId());
  260. } else {
  261. AddInvalid();
  262. }
  263. }
  264. auto Add(ImportIRId ir_id) -> void {
  265. const auto* ir = sem_ir->import_irs().Get(ir_id).sem_ir;
  266. Add(ir->package_id());
  267. Add(ir->library_id());
  268. }
  269. auto Add(ImportIRInstId ir_inst_id) -> void {
  270. auto ir_inst = sem_ir->import_ir_insts().Get(ir_inst_id);
  271. AddInFile(sem_ir->import_irs().Get(ir_inst.ir_id()).sem_ir,
  272. ir_inst.inst_id());
  273. }
  274. template <typename T>
  275. requires(SameAsOneOf<T, BoolValue, CompileTimeBindIndex, ElementIndex,
  276. FloatKind, IntKind, CallParamIndex>)
  277. auto Add(T arg) -> void {
  278. // Index-like ID: just include the value directly.
  279. contents.push_back(arg.index);
  280. }
  281. template <typename T>
  282. requires(SameAsOneOf<T, AnyRawId, ExprRegionId, LocId, RealId>)
  283. auto Add(T /*arg*/) -> void {
  284. CARBON_FATAL("Unexpected instruction operand kind {0}", typeid(T).name());
  285. }
  286. using AddFnT = auto(Worklist& worklist, int32_t arg) -> void;
  287. // Returns the arg handler for an `IdKind`.
  288. template <typename... Types>
  289. static auto GetAddFn(TypeEnum<Types...> id_kind) -> AddFnT* {
  290. static constexpr std::array<AddFnT*, IdKind::NumValues> Table = {
  291. [](Worklist& worklist, int32_t arg) {
  292. worklist.Add(Inst::FromRaw<Types>(arg));
  293. }...,
  294. // Invalid and None handling (ordering-sensitive).
  295. [](auto...) { CARBON_FATAL("Unexpected invalid IdKind"); },
  296. [](auto...) {},
  297. };
  298. return Table[id_kind.ToIndex()];
  299. }
  300. // Add an instruction argument to the contents of the current instruction.
  301. auto AddWithKind(Inst::ArgAndKind arg) -> void {
  302. GetAddFn(arg.kind())(*this, arg.value());
  303. }
  304. // Ensure all the instructions on the todo list have fingerprints. To avoid a
  305. // re-lookup, returns the fingerprint of the first instruction on the todo
  306. // list, and requires the todo list to be non-empty.
  307. auto Run() -> uint64_t {
  308. CARBON_CHECK(!todo.empty());
  309. while (true) {
  310. const size_t init_size = todo.size();
  311. auto [next_sem_ir, next] = todo.back();
  312. sem_ir = next_sem_ir;
  313. contents.clear();
  314. if (!std::holds_alternative<InstId>(next)) {
  315. // Add the contents of the `next` instruction so they all contribute to
  316. // the `contents`.
  317. if (auto* impl_id = std::get_if<ImplId>(&next)) {
  318. Add(*impl_id);
  319. } else if (auto* inst_block_id = std::get_if<InstBlockId>(&next)) {
  320. Add(*inst_block_id);
  321. }
  322. // If we didn't add any more work, then we have a fingerprint for the
  323. // `next` instruction, otherwise we wait until that work is completed.
  324. // If the `next` is the last thing in `todo`, we return the fingerprint.
  325. // Otherwise we would just discard it because we don't currently cache
  326. // the fingerprint for things other than `InstId`, but we really only
  327. // expect other `next` types to be at the bottom of the `todo` stack
  328. // since they are not added to `todo` during Run().
  329. if (todo.size() == init_size) {
  330. auto fingerprint = Finish();
  331. todo.pop_back();
  332. CARBON_CHECK(todo.empty(),
  333. "A non-InstId was inserted into `todo` during Run()");
  334. return fingerprint;
  335. }
  336. // Move on to processing the instructions added above; we will come
  337. // back to this branch once they are done.
  338. continue;
  339. }
  340. auto next_inst_id = std::get<InstId>(next);
  341. // If we already have a fingerprint for this instruction, we have nothing
  342. // to do. Just pop it from `todo`.
  343. if (auto lookup =
  344. fingerprints->Lookup(std::pair(next_sem_ir, next_inst_id))) {
  345. todo.pop_back();
  346. if (todo.empty()) {
  347. return lookup.value();
  348. }
  349. continue;
  350. }
  351. // Keep this instruction in `todo` for now. If we add more work, we'll
  352. // finish that work and process this instruction again, and if not, we'll
  353. // pop the instruction at the end of the loop.
  354. auto inst = next_sem_ir->insts().Get(next_inst_id);
  355. // Add the instruction's fields to the contents.
  356. Add(inst.kind());
  357. // Don't include the type if it's `type` or `<error>`, because those types
  358. // are self-referential.
  359. if (inst.type_id() != TypeType::TypeId &&
  360. inst.type_id() != ErrorInst::TypeId) {
  361. Add(inst.type_id());
  362. }
  363. AddWithKind(inst.arg0_and_kind());
  364. AddWithKind(inst.arg1_and_kind());
  365. // If we didn't add any work, we have a fingerprint for this instruction;
  366. // pop it from the todo list. Otherwise, we leave it on the todo list so
  367. // we can compute its fingerprint once we've finished the work we added.
  368. if (todo.size() == init_size) {
  369. uint64_t fingerprint = Finish();
  370. fingerprints->Insert(std::pair(next_sem_ir, next_inst_id), fingerprint);
  371. todo.pop_back();
  372. if (todo.empty()) {
  373. return fingerprint;
  374. }
  375. }
  376. }
  377. }
  378. };
  379. } // namespace
  380. auto InstFingerprinter::GetOrCompute(const File* file, InstId inst_id)
  381. -> uint64_t {
  382. Worklist worklist = {.todo = {{file, inst_id}},
  383. .fingerprints = &fingerprints_};
  384. return worklist.Run();
  385. }
  386. auto InstFingerprinter::GetOrCompute(const File* file,
  387. InstBlockId inst_block_id) -> uint64_t {
  388. Worklist worklist = {.todo = {{file, inst_block_id}},
  389. .fingerprints = &fingerprints_};
  390. return worklist.Run();
  391. }
  392. auto InstFingerprinter::GetOrCompute(const File* file, ImplId impl_id)
  393. -> uint64_t {
  394. Worklist worklist = {.todo = {{file, impl_id}},
  395. .fingerprints = &fingerprints_};
  396. return worklist.Run();
  397. }
  398. } // namespace Carbon::SemIR