inst_fingerprinter.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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().GetTypeInstId(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. // See also: https://github.com/carbon-language/carbon-lang/issues/6728
  208. }
  209. auto Add(ClassId class_id) -> void {
  210. AddEntity(sem_ir->classes().Get(class_id));
  211. }
  212. auto Add(VtableId vtable_id) -> void {
  213. const auto& vtable = sem_ir->vtables().Get(vtable_id);
  214. if (vtable.class_id.has_value()) {
  215. Add(vtable.class_id);
  216. }
  217. Add(vtable.virtual_functions_id);
  218. }
  219. auto Add(InterfaceId interface_id) -> void {
  220. AddEntity(sem_ir->interfaces().Get(interface_id));
  221. }
  222. auto Add(NamedConstraintId named_constraint_id) -> void {
  223. AddEntity(sem_ir->named_constraints().Get(named_constraint_id));
  224. }
  225. auto Add(RequireImplsId require_id) -> void {
  226. CARBON_CHECK(require_id.has_value());
  227. const auto& require = sem_ir->require_impls().Get(require_id);
  228. Add(sem_ir->constant_values().Get(require.self_id));
  229. Add(sem_ir->constant_values().Get(require.facet_type_inst_id));
  230. contents.push_back(require.extend_self);
  231. Add(require.parent_scope_id);
  232. }
  233. auto Add(AssociatedConstantId assoc_const_id) -> void {
  234. AddEntity<AssociatedConstant>(
  235. sem_ir->associated_constants().Get(assoc_const_id));
  236. }
  237. auto Add(ImplId impl_id) -> void {
  238. if (!impl_id.has_value()) {
  239. AddInvalid();
  240. return;
  241. }
  242. const auto& impl = sem_ir->impls().Get(impl_id);
  243. Add(sem_ir->constant_values().Get(impl.self_id));
  244. Add(sem_ir->constant_values().Get(impl.constraint_id));
  245. Add(impl.parent_scope_id);
  246. }
  247. auto Add(DeclInstBlockId /*block_id*/) -> void {
  248. // Intentionally exclude decl blocks from fingerprinting. Changes to the
  249. // decl block don't change the identity of the declaration.
  250. }
  251. auto Add(LabelId /*block_id*/) -> void {
  252. CARBON_FATAL("Should never fingerprint a label");
  253. }
  254. auto Add(FacetTypeId facet_type_id) -> void {
  255. const auto& facet_type = sem_ir->facet_types().Get(facet_type_id);
  256. auto add_constraints = [&](auto constraints) {
  257. contents.push_back(constraints.size());
  258. for (auto [first, second] : constraints) {
  259. Add(first);
  260. Add(second);
  261. }
  262. };
  263. add_constraints(facet_type.extend_constraints);
  264. add_constraints(facet_type.self_impls_constraints);
  265. add_constraints(facet_type.rewrite_constraints);
  266. contents.push_back(facet_type.other_requirements);
  267. }
  268. auto Add(GenericId generic_id) -> void {
  269. if (!generic_id.has_value()) {
  270. AddInvalid();
  271. return;
  272. }
  273. Add(sem_ir->generics().Get(generic_id).decl_id);
  274. }
  275. auto Add(SpecificId specific_id) -> void {
  276. if (!specific_id.has_value()) {
  277. AddInvalid();
  278. return;
  279. }
  280. const auto& specific = sem_ir->specifics().Get(specific_id);
  281. Add(specific.generic_id);
  282. Add(specific.args_id);
  283. }
  284. auto Add(SpecificInterfaceId specific_interface_id) -> void {
  285. if (!specific_interface_id.has_value()) {
  286. AddInvalid();
  287. return;
  288. }
  289. const auto& interface =
  290. sem_ir->specific_interfaces().Get(specific_interface_id);
  291. Add(interface.interface_id);
  292. Add(interface.specific_id);
  293. }
  294. auto Add(const llvm::APInt& value) -> void {
  295. unsigned width = value.getBitWidth();
  296. contents.push_back(width);
  297. for (auto word : llvm::seq((width + 63) / 64)) {
  298. // TODO: Is there a better way to copy the words from an APInt?
  299. unsigned start = 64 * word;
  300. contents.push_back(
  301. value.extractBitsAsZExtValue(std::min(64U, width - start), start));
  302. }
  303. }
  304. auto Add(IntId int_id) -> void { Add(sem_ir->ints().Get(int_id)); }
  305. auto Add(FloatId float_id) -> void {
  306. Add(sem_ir->floats().Get(float_id).bitcastToAPInt());
  307. }
  308. auto Add(RealId real_id) -> void {
  309. const auto& real = sem_ir->reals().Get(real_id);
  310. Add(real.mantissa);
  311. Add(real.exponent);
  312. contents.push_back(real.is_decimal);
  313. }
  314. auto Add(PackageNameId package_id) -> void {
  315. if (auto ident_id = package_id.AsIdentifierId(); ident_id.has_value()) {
  316. AddString(sem_ir->identifiers().Get(ident_id));
  317. } else {
  318. // TODO: May collide with a user package of the same name. Consider using
  319. // a different value.
  320. AddString(package_id.AsSpecialName());
  321. }
  322. }
  323. auto Add(LibraryNameId lib_name_id) -> void {
  324. if (lib_name_id == LibraryNameId::Default) {
  325. AddString("");
  326. } else if (lib_name_id == LibraryNameId::Error) {
  327. AddString("<error>");
  328. } else if (lib_name_id.has_value()) {
  329. Add(lib_name_id.AsStringLiteralValueId());
  330. } else {
  331. AddInvalid();
  332. }
  333. }
  334. auto Add(ImportIRId ir_id) -> void {
  335. const auto* ir = sem_ir->import_irs().Get(ir_id).sem_ir;
  336. Add(ir->package_id());
  337. Add(ir->library_id());
  338. }
  339. auto Add(ImportIRInstId ir_inst_id) -> void {
  340. auto ir_inst = sem_ir->import_ir_insts().Get(ir_inst_id);
  341. AddInFile(sem_ir->import_irs().Get(ir_inst.ir_id()).sem_ir,
  342. ir_inst.inst_id());
  343. }
  344. template <typename T>
  345. requires(SameAsOneOf<T, BoolValue, CharId, CompileTimeBindIndex,
  346. ElementIndex, FloatKind, IntKind, CallParamIndex>)
  347. auto Add(T arg) -> void {
  348. // Index-like ID: just include the value directly.
  349. contents.push_back(arg.index);
  350. }
  351. template <typename T>
  352. requires(SameAsOneOf<T, AnyRawId, ExprRegionId, LocId>)
  353. auto Add(T /*arg*/) -> void {
  354. CARBON_FATAL("Unexpected instruction operand kind {0}", typeid(T).name());
  355. }
  356. using AddFnT = auto(Worklist& worklist, int32_t arg) -> void;
  357. // Returns the arg handler for an `IdKind`.
  358. template <typename... Types>
  359. static auto GetAddFn(TypeEnum<Types...> id_kind) -> AddFnT* {
  360. static constexpr std::array<AddFnT*, IdKind::NumValues> Table = {
  361. [](Worklist& worklist, int32_t arg) {
  362. worklist.Add(Inst::FromRaw<Types>(arg));
  363. }...,
  364. // Invalid and None handling (ordering-sensitive).
  365. [](auto...) { CARBON_FATAL("Unexpected invalid IdKind"); },
  366. [](auto...) {},
  367. };
  368. return Table[id_kind.ToIndex()];
  369. }
  370. // Add an instruction argument to the contents of the current instruction.
  371. auto AddWithKind(Inst::ArgAndKind arg) -> void {
  372. GetAddFn(arg.kind())(*this, arg.value());
  373. }
  374. // Ensure all the instructions on the todo list have fingerprints. To avoid a
  375. // re-lookup, returns the fingerprint of the first instruction on the todo
  376. // list, and requires the todo list to be non-empty.
  377. auto Run() -> uint64_t {
  378. CARBON_CHECK(!todo.empty());
  379. while (true) {
  380. const size_t init_size = todo.size();
  381. auto [next_sem_ir, next] = todo.back();
  382. sem_ir = next_sem_ir;
  383. contents.clear();
  384. if (!std::holds_alternative<InstId>(next)) {
  385. // Add the contents of the `next` instruction so they all contribute to
  386. // the `contents`.
  387. CARBON_KIND_SWITCH(next) {
  388. case CARBON_KIND(InstId _):
  389. CARBON_FATAL("InstId is checked for above.");
  390. case CARBON_KIND(ImplId impl_id):
  391. Add(impl_id);
  392. break;
  393. case CARBON_KIND(InstBlockId inst_block_id):
  394. Add(inst_block_id);
  395. break;
  396. case CARBON_KIND(CppOverloadSetId overload_set_id):
  397. Add(overload_set_id);
  398. break;
  399. }
  400. // If we didn't add any more work, then we have a fingerprint for the
  401. // `next` instruction, otherwise we wait until that work is completed.
  402. // If the `next` is the last thing in `todo`, we return the fingerprint.
  403. // Otherwise we would just discard it because we don't currently cache
  404. // the fingerprint for things other than `InstId`, but we really only
  405. // expect other `next` types to be at the bottom of the `todo` stack
  406. // since they are not added to `todo` during Run().
  407. if (todo.size() == init_size) {
  408. auto fingerprint = Finish();
  409. todo.pop_back();
  410. CARBON_CHECK(todo.empty(),
  411. "A non-InstId was inserted into `todo` during Run()");
  412. return fingerprint;
  413. }
  414. // Move on to processing the instructions added above; we will come
  415. // back to this branch once they are done.
  416. continue;
  417. }
  418. auto next_inst_id = std::get<InstId>(next);
  419. // If we already have a fingerprint for this instruction, we have nothing
  420. // to do. Just pop it from `todo`.
  421. if (auto fingerprint = GetFingerprint(next_sem_ir, next_inst_id)) {
  422. todo.pop_back();
  423. if (todo.empty()) {
  424. return fingerprint;
  425. }
  426. continue;
  427. }
  428. // Keep this instruction in `todo` for now. If we add more work, we'll
  429. // finish that work and process this instruction again, and if not, we'll
  430. // pop the instruction at the end of the loop.
  431. auto inst = next_sem_ir->insts().Get(next_inst_id);
  432. // Add the instruction's fields to the contents.
  433. Add(inst.kind());
  434. // Don't include the type if it's `type` or `<error>`, because those types
  435. // are self-referential.
  436. if (inst.type_id() != TypeType::TypeId &&
  437. inst.type_id() != ErrorInst::TypeId) {
  438. Add(inst.type_id());
  439. }
  440. AddWithKind(inst.arg0_and_kind());
  441. AddWithKind(inst.arg1_and_kind());
  442. // If we didn't add any work, we have a fingerprint for this instruction;
  443. // pop it from the todo list. Otherwise, we leave it on the todo list so
  444. // we can compute its fingerprint once we've finished the work we added.
  445. if (todo.size() == init_size) {
  446. uint64_t fingerprint = Finish();
  447. SetFingerprint(next_sem_ir, next_inst_id, fingerprint);
  448. todo.pop_back();
  449. if (todo.empty()) {
  450. return fingerprint;
  451. }
  452. }
  453. }
  454. }
  455. };
  456. } // namespace
  457. auto InstFingerprinter::GetOrCompute(const File* file, InstId inst_id)
  458. -> uint64_t {
  459. Worklist worklist = {.todo = {{file, inst_id}},
  460. .fingerprints = &fingerprints_};
  461. return worklist.Run();
  462. }
  463. auto InstFingerprinter::GetOrCompute(const File* file,
  464. InstBlockId inst_block_id) -> uint64_t {
  465. Worklist worklist = {.todo = {{file, inst_block_id}},
  466. .fingerprints = &fingerprints_};
  467. return worklist.Run();
  468. }
  469. auto InstFingerprinter::GetOrCompute(const File* file, ImplId impl_id)
  470. -> uint64_t {
  471. Worklist worklist = {.todo = {{file, impl_id}},
  472. .fingerprints = &fingerprints_};
  473. return worklist.Run();
  474. }
  475. auto InstFingerprinter::GetOrCompute(const File* file,
  476. CppOverloadSetId overload_set_id)
  477. -> uint64_t {
  478. Worklist worklist = {.todo = {{file, overload_set_id}},
  479. .fingerprints = &fingerprints_};
  480. return worklist.Run();
  481. }
  482. } // namespace Carbon::SemIR