inst_fingerprinter.cpp 16 KB

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