inst_fingerprinter.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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/fixed_size_value_store.h"
  14. #include "toolchain/base/kind_switch.h"
  15. #include "toolchain/base/value_ids.h"
  16. #include "toolchain/sem_ir/cpp_overload_set.h"
  17. #include "toolchain/sem_ir/entity_with_params_base.h"
  18. #include "toolchain/sem_ir/ids.h"
  19. #include "toolchain/sem_ir/typed_insts.h"
  20. namespace Carbon::SemIR {
  21. namespace {
  22. struct Worklist {
  23. using FingerprintStore =
  24. FixedSizeValueStore<InstId, uint64_t, Tag<CheckIRId>>;
  25. using FilesFingerprintStores =
  26. FixedSizeValueStore<CheckIRId, FingerprintStore>;
  27. // The file containing the instruction we're currently processing.
  28. const File* sem_ir = nullptr;
  29. // The instructions we need to compute fingerprints for.
  30. llvm::SmallVector<std::pair<
  31. const File*, std::variant<InstId, InstBlockId, ImplId, CppOverloadSetId>>>
  32. todo;
  33. // The contents of the current instruction as accumulated so far. This is used
  34. // to build a Merkle tree containing a fingerprint for the current
  35. // instruction.
  36. llvm::SmallVector<llvm::stable_hash> contents = {};
  37. // Known cached instruction fingerprints. Each item in `todo` will be added to
  38. // the cache if not already present.
  39. FilesFingerprintStores* fingerprints;
  40. // Finish fingerprinting and compute the fingerprint.
  41. auto Finish() -> uint64_t { return llvm::stable_hash_combine(contents); }
  42. // Gets the known fingerprint from the cache, or returns 0.
  43. auto GetFingerprint(const File* file, InstId inst_id) -> uint64_t {
  44. auto& store = fingerprints->Get(file->check_ir_id());
  45. if (store.size() == 0) {
  46. return 0;
  47. }
  48. // These InstIds are constant values, so not in the ValueStore. We use a
  49. // constant (negative) fingerprint for them.
  50. if (inst_id == InstId::InitTombstone ||
  51. inst_id == InstId::ImplWitnessTablePlaceholder) {
  52. return inst_id.index;
  53. }
  54. return store.Get(inst_id);
  55. }
  56. // Sets the fingerprint for an instruction in the cache. Since 0 is used to
  57. // indicate empty, we map 0 to another fixed value.
  58. auto SetFingerprint(const File* file, InstId inst_id, uint64_t fingerprint) {
  59. auto& store = fingerprints->Get(file->check_ir_id());
  60. if (store.size() == 0) {
  61. store = FingerprintStore::MakeWithExplicitSize(
  62. file->insts().size(), file->insts().GetIdTag(), 0);
  63. }
  64. store.Set(inst_id, fingerprint ? fingerprint : 1);
  65. }
  66. // Add an invalid marker to the contents. This is used when the entity
  67. // contains a `None` ID. This uses an arbitrary fixed value that is assumed
  68. // to be unlikely to collide with a valid value.
  69. auto AddInvalid() -> void { contents.push_back(-1); }
  70. // Add a string to the contents.
  71. auto AddString(llvm::StringRef string) -> void {
  72. contents.push_back(llvm::stable_hash_name(string));
  73. }
  74. // Each of the following `Add` functions adds a typed argument to the contents
  75. // of the current instruction. If we don't yet have a fingerprint for the
  76. // argument, it instead adds that argument to the worklist instead.
  77. auto Add(InstKind kind) -> void {
  78. // TODO: Precompute or cache the hash of instruction IR names, or pick a
  79. // scheme that doesn't change when IR names change.
  80. AddString(kind.ir_name());
  81. }
  82. auto Add(IdentifierId ident_id) -> void {
  83. AddString(sem_ir->identifiers().Get(ident_id));
  84. }
  85. auto Add(StringLiteralValueId lit_id) -> void {
  86. AddString(sem_ir->string_literal_values().Get(lit_id));
  87. }
  88. auto Add(NameId name_id) -> void {
  89. AddString(sem_ir->names().GetIRBaseName(name_id));
  90. }
  91. auto Add(EntityNameId entity_name_id) -> void {
  92. if (!entity_name_id.has_value()) {
  93. AddInvalid();
  94. return;
  95. }
  96. const auto& entity_name = sem_ir->entity_names().Get(entity_name_id);
  97. if (entity_name.bind_index().has_value()) {
  98. Add(entity_name.bind_index());
  99. // Don't include the name. While it is part of the canonical identity of a
  100. // compile-time binding, renaming it (and its uses) is a compatible change
  101. // that we would like to not affect the fingerprint.
  102. //
  103. // Also don't include the `is_template` flag. Changing that flag should
  104. // also be a compatible change from the perspective of users of a generic.
  105. } else {
  106. Add(entity_name.name_id);
  107. }
  108. Add(entity_name.parent_scope_id);
  109. }
  110. auto AddInFile(const File* file, InstId inner_id) -> void {
  111. if (!inner_id.has_value()) {
  112. AddInvalid();
  113. return;
  114. }
  115. if (auto fingerprint = GetFingerprint(file, inner_id)) {
  116. contents.push_back(fingerprint);
  117. return;
  118. }
  119. todo.push_back({file, inner_id});
  120. }
  121. auto Add(InstId inner_id) -> void { AddInFile(sem_ir, inner_id); }
  122. auto Add(ConstantId constant_id) -> void {
  123. if (!constant_id.has_value()) {
  124. AddInvalid();
  125. return;
  126. }
  127. Add(sem_ir->constant_values().GetInstId(constant_id));
  128. }
  129. auto Add(TypeId type_id) -> void {
  130. if (!type_id.has_value()) {
  131. AddInvalid();
  132. return;
  133. }
  134. Add(sem_ir->types().GetInstId(type_id));
  135. }
  136. template <typename T>
  137. auto AddBlock(llvm::ArrayRef<T> block) -> void {
  138. contents.push_back(block.size());
  139. for (auto inner_id : block) {
  140. Add(inner_id);
  141. }
  142. }
  143. auto Add(InstBlockId inst_block_id) -> void {
  144. if (!inst_block_id.has_value()) {
  145. AddInvalid();
  146. return;
  147. }
  148. AddBlock(sem_ir->inst_blocks().Get(inst_block_id));
  149. }
  150. auto Add(StructTypeField field) -> void {
  151. Add(field.name_id);
  152. Add(field.type_inst_id);
  153. }
  154. auto Add(StructTypeFieldsId struct_type_fields_id) -> void {
  155. if (!struct_type_fields_id.has_value()) {
  156. AddInvalid();
  157. return;
  158. }
  159. AddBlock(sem_ir->struct_type_fields().Get(struct_type_fields_id));
  160. }
  161. auto Add(CustomLayoutId custom_layout_id) -> void {
  162. if (!custom_layout_id.has_value()) {
  163. AddInvalid();
  164. return;
  165. }
  166. auto block = sem_ir->custom_layouts().Get(custom_layout_id);
  167. contents.push_back(block.size());
  168. contents.insert(contents.end(), block.begin(), block.end());
  169. }
  170. auto Add(NameScopeId name_scope_id) -> void {
  171. if (!name_scope_id.has_value()) {
  172. AddInvalid();
  173. return;
  174. }
  175. const auto& scope = sem_ir->name_scopes().Get(name_scope_id);
  176. Add(scope.name_id());
  177. // For non-package scopes, add the parent scope.
  178. if (!scope.is_imported_package() && scope.parent_scope_id().has_value()) {
  179. Add(sem_ir->name_scopes().Get(scope.parent_scope_id()).inst_id());
  180. }
  181. }
  182. template <typename EntityT = EntityWithParamsBase>
  183. auto AddEntity(const std::type_identity_t<EntityT>& entity) -> void {
  184. Add(entity.name_id);
  185. if (entity.parent_scope_id.has_value()) {
  186. Add(sem_ir->name_scopes().Get(entity.parent_scope_id).inst_id());
  187. }
  188. }
  189. auto Add(FunctionId function_id) -> void {
  190. AddEntity(sem_ir->functions().Get(function_id));
  191. }
  192. auto Add(CppOverloadSetId cpp_overload_set_id) -> void {
  193. const CppOverloadSet& cpp_overload_set =
  194. sem_ir->cpp_overload_sets().Get(cpp_overload_set_id);
  195. Add(cpp_overload_set.name_id);
  196. if (cpp_overload_set.parent_scope_id.has_value()) {
  197. Add(sem_ir->name_scopes()
  198. .Get(cpp_overload_set.parent_scope_id)
  199. .inst_id());
  200. }
  201. }
  202. auto Add(ClangDeclId /*decl_id*/) -> void {
  203. // TODO: For `CppTemplateNameType` we don't need to fingerprint the
  204. // `decl_id`, because fingerprinting the `NameId` is sufficient to identify
  205. // the template, but this won't necessarily be true for other
  206. // `ClangDeclId`s.
  207. }
  208. auto Add(ClassId class_id) -> void {
  209. AddEntity(sem_ir->classes().Get(class_id));
  210. }
  211. auto Add(VtableId vtable_id) -> void {
  212. const auto& vtable = sem_ir->vtables().Get(vtable_id);
  213. if (vtable.class_id.has_value()) {
  214. Add(vtable.class_id);
  215. }
  216. Add(vtable.virtual_functions_id);
  217. }
  218. auto Add(InterfaceId interface_id) -> void {
  219. AddEntity(sem_ir->interfaces().Get(interface_id));
  220. }
  221. auto Add(NamedConstraintId named_constraint_id) -> void {
  222. AddEntity(sem_ir->named_constraints().Get(named_constraint_id));
  223. }
  224. auto Add(RequireImplsId require_id) -> void {
  225. CARBON_CHECK(require_id.has_value());
  226. const auto& require = sem_ir->require_impls().Get(require_id);
  227. Add(sem_ir->constant_values().Get(require.self_id));
  228. Add(sem_ir->constant_values().Get(require.facet_type_inst_id));
  229. contents.push_back(require.extend_self);
  230. Add(require.parent_scope_id);
  231. }
  232. auto Add(AssociatedConstantId assoc_const_id) -> void {
  233. AddEntity<AssociatedConstant>(
  234. sem_ir->associated_constants().Get(assoc_const_id));
  235. }
  236. auto Add(ImplId impl_id) -> void {
  237. if (!impl_id.has_value()) {
  238. AddInvalid();
  239. return;
  240. }
  241. const auto& impl = sem_ir->impls().Get(impl_id);
  242. Add(sem_ir->constant_values().Get(impl.self_id));
  243. Add(sem_ir->constant_values().Get(impl.constraint_id));
  244. Add(impl.parent_scope_id);
  245. }
  246. auto Add(DeclInstBlockId /*block_id*/) -> void {
  247. // Intentionally exclude decl blocks from fingerprinting. Changes to the
  248. // decl block don't change the identity of the declaration.
  249. }
  250. auto Add(LabelId /*block_id*/) -> void {
  251. CARBON_FATAL("Should never fingerprint a label");
  252. }
  253. auto Add(FacetTypeId facet_type_id) -> void {
  254. const auto& facet_type = sem_ir->facet_types().Get(facet_type_id);
  255. auto add_constraints = [&](auto constraints) {
  256. contents.push_back(constraints.size());
  257. for (auto [first, second] : constraints) {
  258. Add(first);
  259. Add(second);
  260. }
  261. };
  262. add_constraints(facet_type.extend_constraints);
  263. add_constraints(facet_type.self_impls_constraints);
  264. add_constraints(facet_type.rewrite_constraints);
  265. contents.push_back(facet_type.other_requirements);
  266. }
  267. auto Add(GenericId generic_id) -> void {
  268. if (!generic_id.has_value()) {
  269. AddInvalid();
  270. return;
  271. }
  272. Add(sem_ir->generics().Get(generic_id).decl_id);
  273. }
  274. auto Add(SpecificId specific_id) -> void {
  275. if (!specific_id.has_value()) {
  276. AddInvalid();
  277. return;
  278. }
  279. const auto& specific = sem_ir->specifics().Get(specific_id);
  280. Add(specific.generic_id);
  281. Add(specific.args_id);
  282. }
  283. auto Add(SpecificInterfaceId specific_interface_id) -> void {
  284. if (!specific_interface_id.has_value()) {
  285. AddInvalid();
  286. return;
  287. }
  288. const auto& interface =
  289. sem_ir->specific_interfaces().Get(specific_interface_id);
  290. Add(interface.interface_id);
  291. Add(interface.specific_id);
  292. }
  293. auto Add(const llvm::APInt& value) -> void {
  294. unsigned width = value.getBitWidth();
  295. contents.push_back(width);
  296. for (auto word : llvm::seq((width + 63) / 64)) {
  297. // TODO: Is there a better way to copy the words from an APInt?
  298. unsigned start = 64 * word;
  299. contents.push_back(
  300. value.extractBitsAsZExtValue(std::min(64U, width - start), start));
  301. }
  302. }
  303. auto Add(IntId int_id) -> void { Add(sem_ir->ints().Get(int_id)); }
  304. auto Add(FloatId float_id) -> void {
  305. Add(sem_ir->floats().Get(float_id).bitcastToAPInt());
  306. }
  307. auto Add(RealId real_id) -> void {
  308. const auto& real = sem_ir->reals().Get(real_id);
  309. Add(real.mantissa);
  310. Add(real.exponent);
  311. contents.push_back(real.is_decimal);
  312. }
  313. auto Add(PackageNameId package_id) -> void {
  314. if (auto ident_id = package_id.AsIdentifierId(); ident_id.has_value()) {
  315. AddString(sem_ir->identifiers().Get(ident_id));
  316. } else {
  317. // TODO: May collide with a user package of the same name. Consider using
  318. // a different value.
  319. AddString(package_id.AsSpecialName());
  320. }
  321. }
  322. auto Add(LibraryNameId lib_name_id) -> void {
  323. if (lib_name_id == LibraryNameId::Default) {
  324. AddString("");
  325. } else if (lib_name_id == LibraryNameId::Error) {
  326. AddString("<error>");
  327. } else if (lib_name_id.has_value()) {
  328. Add(lib_name_id.AsStringLiteralValueId());
  329. } else {
  330. AddInvalid();
  331. }
  332. }
  333. auto Add(ImportIRId ir_id) -> void {
  334. const auto* ir = sem_ir->import_irs().Get(ir_id).sem_ir;
  335. Add(ir->package_id());
  336. Add(ir->library_id());
  337. }
  338. auto Add(ImportIRInstId ir_inst_id) -> void {
  339. auto ir_inst = sem_ir->import_ir_insts().Get(ir_inst_id);
  340. AddInFile(sem_ir->import_irs().Get(ir_inst.ir_id()).sem_ir,
  341. ir_inst.inst_id());
  342. }
  343. template <typename T>
  344. requires(SameAsOneOf<T, BoolValue, CharId, CompileTimeBindIndex,
  345. ElementIndex, FloatKind, IntKind, CallParamIndex>)
  346. auto Add(T arg) -> void {
  347. // Index-like ID: just include the value directly.
  348. contents.push_back(arg.index);
  349. }
  350. template <typename T>
  351. requires(SameAsOneOf<T, AnyRawId, ExprRegionId, LocId>)
  352. auto Add(T /*arg*/) -> void {
  353. CARBON_FATAL("Unexpected instruction operand kind {0}", typeid(T).name());
  354. }
  355. using AddFnT = auto(Worklist& worklist, int32_t arg) -> void;
  356. // Returns the arg handler for an `IdKind`.
  357. template <typename... Types>
  358. static auto GetAddFn(TypeEnum<Types...> id_kind) -> AddFnT* {
  359. static constexpr std::array<AddFnT*, IdKind::NumValues> Table = {
  360. [](Worklist& worklist, int32_t arg) {
  361. worklist.Add(Inst::FromRaw<Types>(arg));
  362. }...,
  363. // Invalid and None handling (ordering-sensitive).
  364. [](auto...) { CARBON_FATAL("Unexpected invalid IdKind"); },
  365. [](auto...) {},
  366. };
  367. return Table[id_kind.ToIndex()];
  368. }
  369. // Add an instruction argument to the contents of the current instruction.
  370. auto AddWithKind(Inst::ArgAndKind arg) -> void {
  371. GetAddFn(arg.kind())(*this, arg.value());
  372. }
  373. // Ensure all the instructions on the todo list have fingerprints. To avoid a
  374. // re-lookup, returns the fingerprint of the first instruction on the todo
  375. // list, and requires the todo list to be non-empty.
  376. auto Run() -> uint64_t {
  377. CARBON_CHECK(!todo.empty());
  378. while (true) {
  379. const size_t init_size = todo.size();
  380. auto [next_sem_ir, next] = todo.back();
  381. sem_ir = next_sem_ir;
  382. contents.clear();
  383. if (!std::holds_alternative<InstId>(next)) {
  384. // Add the contents of the `next` instruction so they all contribute to
  385. // the `contents`.
  386. CARBON_KIND_SWITCH(next) {
  387. case CARBON_KIND(InstId _):
  388. CARBON_FATAL("InstId is checked for above.");
  389. case CARBON_KIND(ImplId impl_id):
  390. Add(impl_id);
  391. break;
  392. case CARBON_KIND(InstBlockId inst_block_id):
  393. Add(inst_block_id);
  394. break;
  395. case CARBON_KIND(CppOverloadSetId overload_set_id):
  396. Add(overload_set_id);
  397. break;
  398. }
  399. // If we didn't add any more work, then we have a fingerprint for the
  400. // `next` instruction, otherwise we wait until that work is completed.
  401. // If the `next` is the last thing in `todo`, we return the fingerprint.
  402. // Otherwise we would just discard it because we don't currently cache
  403. // the fingerprint for things other than `InstId`, but we really only
  404. // expect other `next` types to be at the bottom of the `todo` stack
  405. // since they are not added to `todo` during Run().
  406. if (todo.size() == init_size) {
  407. auto fingerprint = Finish();
  408. todo.pop_back();
  409. CARBON_CHECK(todo.empty(),
  410. "A non-InstId was inserted into `todo` during Run()");
  411. return fingerprint;
  412. }
  413. // Move on to processing the instructions added above; we will come
  414. // back to this branch once they are done.
  415. continue;
  416. }
  417. auto next_inst_id = std::get<InstId>(next);
  418. // If we already have a fingerprint for this instruction, we have nothing
  419. // to do. Just pop it from `todo`.
  420. if (auto fingerprint = GetFingerprint(next_sem_ir, next_inst_id)) {
  421. todo.pop_back();
  422. if (todo.empty()) {
  423. return fingerprint;
  424. }
  425. continue;
  426. }
  427. // Keep this instruction in `todo` for now. If we add more work, we'll
  428. // finish that work and process this instruction again, and if not, we'll
  429. // pop the instruction at the end of the loop.
  430. auto inst = next_sem_ir->insts().Get(next_inst_id);
  431. // Add the instruction's fields to the contents.
  432. Add(inst.kind());
  433. // Don't include the type if it's `type` or `<error>`, because those types
  434. // are self-referential.
  435. if (inst.type_id() != TypeType::TypeId &&
  436. inst.type_id() != ErrorInst::TypeId) {
  437. Add(inst.type_id());
  438. }
  439. AddWithKind(inst.arg0_and_kind());
  440. AddWithKind(inst.arg1_and_kind());
  441. // If we didn't add any work, we have a fingerprint for this instruction;
  442. // pop it from the todo list. Otherwise, we leave it on the todo list so
  443. // we can compute its fingerprint once we've finished the work we added.
  444. if (todo.size() == init_size) {
  445. uint64_t fingerprint = Finish();
  446. SetFingerprint(next_sem_ir, next_inst_id, fingerprint);
  447. todo.pop_back();
  448. if (todo.empty()) {
  449. return fingerprint;
  450. }
  451. }
  452. }
  453. }
  454. };
  455. } // namespace
  456. auto InstFingerprinter::GetOrCompute(const File* file, InstId inst_id)
  457. -> uint64_t {
  458. Worklist worklist = {.todo = {{file, inst_id}},
  459. .fingerprints = &fingerprints_};
  460. return worklist.Run();
  461. }
  462. auto InstFingerprinter::GetOrCompute(const File* file,
  463. InstBlockId inst_block_id) -> uint64_t {
  464. Worklist worklist = {.todo = {{file, inst_block_id}},
  465. .fingerprints = &fingerprints_};
  466. return worklist.Run();
  467. }
  468. auto InstFingerprinter::GetOrCompute(const File* file, ImplId impl_id)
  469. -> uint64_t {
  470. Worklist worklist = {.todo = {{file, impl_id}},
  471. .fingerprints = &fingerprints_};
  472. return worklist.Run();
  473. }
  474. auto InstFingerprinter::GetOrCompute(const File* file,
  475. CppOverloadSetId overload_set_id)
  476. -> uint64_t {
  477. Worklist worklist = {.todo = {{file, overload_set_id}},
  478. .fingerprints = &fingerprints_};
  479. return worklist.Run();
  480. }
  481. } // namespace Carbon::SemIR