inst_fingerprinter.cpp 17 KB

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