inst_fingerprinter.cpp 18 KB

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