file.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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/file.h"
  5. #include <optional>
  6. #include <string>
  7. #include <utility>
  8. #include "clang/AST/Mangle.h"
  9. #include "common/check.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "toolchain/base/kind_switch.h"
  13. #include "toolchain/base/shared_value_stores.h"
  14. #include "toolchain/base/yaml.h"
  15. #include "toolchain/parse/node_ids.h"
  16. #include "toolchain/sem_ir/ids.h"
  17. #include "toolchain/sem_ir/inst.h"
  18. #include "toolchain/sem_ir/inst_kind.h"
  19. #include "toolchain/sem_ir/typed_insts.h"
  20. namespace Carbon::SemIR {
  21. File::File(const Parse::Tree* parse_tree, CheckIRId check_ir_id,
  22. const std::optional<Parse::Tree::PackagingDecl>& packaging_decl,
  23. SharedValueStores& value_stores, std::string filename)
  24. : parse_tree_(parse_tree),
  25. check_ir_id_(check_ir_id),
  26. package_id_(packaging_decl ? packaging_decl->names.package_id
  27. : PackageNameId::None),
  28. library_id_(packaging_decl ? LibraryNameId::ForStringLiteralValueId(
  29. packaging_decl->names.library_id)
  30. : LibraryNameId::Default),
  31. value_stores_(&value_stores),
  32. filename_(std::move(filename)),
  33. entity_names_(check_ir_id),
  34. cpp_global_vars_(check_ir_id),
  35. functions_(check_ir_id),
  36. cpp_overload_sets_(check_ir_id),
  37. classes_(check_ir_id),
  38. interfaces_(check_ir_id),
  39. named_constraints_(check_ir_id),
  40. // 1 reserved id for `RequireImplsBlockId::Empty`.
  41. require_impls_blocks_(allocator_, IdTag(check_ir_id.index, 1)),
  42. associated_constants_(check_ir_id),
  43. facet_types_(check_ir_id),
  44. identified_facet_types_(&facet_types_),
  45. impls_(*this),
  46. specific_interfaces_(check_ir_id),
  47. generics_(check_ir_id),
  48. specifics_(check_ir_id),
  49. // The `2` prevents adding a tag for the global ids
  50. // `ImportIRId::{ApiForImpl,Cpp}`.
  51. import_irs_(IdTag(check_ir_id.index, 2)),
  52. clang_decls_(check_ir_id),
  53. // The `+1` prevents adding a tag to the global `NameSpace::PackageInstId`
  54. // instruction. It's not a "singleton" instruction, but it's a unique
  55. // instruction id that comes right after the singletons.
  56. insts_(this, SingletonInstKinds.size() + 1),
  57. vtables_(check_ir_id),
  58. constant_values_(ConstantId::NotConstant, &insts_),
  59. inst_blocks_(allocator_, check_ir_id),
  60. constants_(this),
  61. // 1 reserved id for `StructTypeFieldsId::Empty`.
  62. struct_type_fields_(allocator_, IdTag(check_ir_id.index, 1)),
  63. // 1 reserved id for `CustomLayoutId::Empty`.
  64. custom_layouts_(allocator_, IdTag(check_ir_id.index, 1)),
  65. expr_regions_(check_ir_id),
  66. clang_source_locs_(check_ir_id) {
  67. // `type` and the error type are both complete & concrete types.
  68. types_.SetComplete(
  69. TypeType::TypeId,
  70. {.value_repr = {.kind = ValueRepr::Copy, .type_id = TypeType::TypeId}});
  71. types_.SetComplete(
  72. ErrorInst::TypeId,
  73. {.value_repr = {.kind = ValueRepr::Copy, .type_id = ErrorInst::TypeId}});
  74. insts_.Reserve(SingletonInstKinds.size());
  75. for (auto kind : SingletonInstKinds) {
  76. auto inst_id =
  77. insts_.AddInNoBlock(LocIdAndInst::NoLoc(Inst::MakeSingleton(kind)));
  78. constant_values_.Set(inst_id, ConstantId::ForConcreteConstant(inst_id));
  79. }
  80. }
  81. File::~File() = default;
  82. auto File::Verify() const -> ErrorOr<Success> {
  83. // Invariants don't necessarily hold for invalid IR.
  84. if (has_errors_) {
  85. return Success();
  86. }
  87. // Check that every code block has a terminator sequence that appears at the
  88. // end of the block.
  89. for (const Function& function : functions_.values()) {
  90. for (InstBlockId block_id : function.body_block_ids) {
  91. TerminatorKind prior_kind = TerminatorKind::NotTerminator;
  92. for (InstId inst_id : inst_blocks().Get(block_id)) {
  93. TerminatorKind inst_kind =
  94. insts().Get(inst_id).kind().terminator_kind();
  95. if (prior_kind == TerminatorKind::Terminator) {
  96. return Error(llvm::formatv("Inst {0} in block {1} follows terminator",
  97. inst_id, block_id));
  98. }
  99. if (prior_kind > inst_kind) {
  100. return Error(
  101. llvm::formatv("Non-terminator inst {0} in block {1} follows "
  102. "terminator sequence",
  103. inst_id, block_id));
  104. }
  105. prior_kind = inst_kind;
  106. }
  107. if (prior_kind != TerminatorKind::Terminator) {
  108. return Error(llvm::formatv("No terminator in block {0}", block_id));
  109. }
  110. }
  111. }
  112. // TODO: Check that an instruction only references other instructions that are
  113. // either global or that dominate it.
  114. return Success();
  115. }
  116. auto File::OutputYaml(bool include_singletons) const -> Yaml::OutputMapping {
  117. return Yaml::OutputMapping([this, include_singletons](
  118. Yaml::OutputMapping::Map map) {
  119. map.Add("filename", filename_);
  120. map.Add("sem_ir", Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  121. map.Add("import_irs", import_irs_.OutputYaml());
  122. map.Add("import_ir_insts", import_ir_insts_.OutputYaml());
  123. map.Add("clang_decls", clang_decls_.OutputYaml());
  124. map.Add("name_scopes", name_scopes_.OutputYaml());
  125. map.Add("entity_names", entity_names_.OutputYaml());
  126. map.Add("cpp_global_vars", cpp_global_vars_.OutputYaml());
  127. map.Add("functions", functions_.OutputYaml());
  128. map.Add("classes", classes_.OutputYaml());
  129. map.Add("generics", generics_.OutputYaml());
  130. map.Add("specifics", specifics_.OutputYaml());
  131. map.Add("struct_type_fields", struct_type_fields_.OutputYaml());
  132. map.Add("types", types_.OutputYaml());
  133. map.Add("insts",
  134. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  135. for (auto [id, inst] : insts_.enumerate()) {
  136. if (!include_singletons && IsSingletonInstId(id)) {
  137. continue;
  138. }
  139. map.Add(PrintToString(id), Yaml::OutputScalar(inst));
  140. }
  141. }));
  142. map.Add("constant_values",
  143. constant_values_.OutputYaml(include_singletons));
  144. map.Add("inst_blocks", inst_blocks_.OutputYaml());
  145. }));
  146. });
  147. }
  148. auto File::CollectRefTagsNeeded() const -> Set<SemIR::InstId> {
  149. CARBON_CHECK(!has_errors_);
  150. Set<SemIR::InstId> ref_tags_needed;
  151. for (auto [id, inst] : insts_.enumerate()) {
  152. if (inst.kind() != SemIR::InstKind::Call) {
  153. continue;
  154. }
  155. auto call_inst = inst.As<SemIR::Call>();
  156. auto callee = SemIR::GetCallee(*this, call_inst.callee_id);
  157. CARBON_KIND_SWITCH(callee) {
  158. case CARBON_KIND(SemIR::CalleeError _):
  159. break;
  160. case CARBON_KIND(SemIR::CalleeNonFunction _):
  161. break;
  162. case CARBON_KIND(SemIR::CalleeCppOverloadSet _): {
  163. // TODO: Perform validation here once we model C++ ref parameters as
  164. // Carbon ref parameters.
  165. break;
  166. }
  167. case CARBON_KIND(SemIR::CalleeFunction fn): {
  168. auto function = functions_.Get(fn.function_id);
  169. auto args = inst_blocks_.GetOrEmpty(call_inst.args_id);
  170. for (auto param_id : llvm::concat<const InstId>(
  171. inst_blocks_.GetOrEmpty(function.implicit_param_patterns_id),
  172. inst_blocks_.GetOrEmpty(function.param_patterns_id))) {
  173. if (auto ref_param_pattern =
  174. insts_.TryGetAs<SemIR::RefParamPattern>(param_id)) {
  175. ref_tags_needed.Insert(args[ref_param_pattern->index.index]);
  176. }
  177. }
  178. break;
  179. }
  180. }
  181. }
  182. return ref_tags_needed;
  183. }
  184. auto File::CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  185. -> void {
  186. mem_usage.Collect(MemUsage::ConcatLabel(label, "allocator_"), allocator_);
  187. mem_usage.Collect(MemUsage::ConcatLabel(label, "entity_names_"),
  188. entity_names_);
  189. mem_usage.Collect(MemUsage::ConcatLabel(label, "cpp_global_vars_"),
  190. cpp_global_vars_);
  191. mem_usage.Collect(MemUsage::ConcatLabel(label, "functions_"), functions_);
  192. mem_usage.Collect(MemUsage::ConcatLabel(label, "classes_"), classes_);
  193. mem_usage.Collect(MemUsage::ConcatLabel(label, "interfaces_"), interfaces_);
  194. mem_usage.Collect(MemUsage::ConcatLabel(label, "impls_"), impls_);
  195. mem_usage.Collect(MemUsage::ConcatLabel(label, "generics_"), generics_);
  196. mem_usage.Collect(MemUsage::ConcatLabel(label, "specifics_"), specifics_);
  197. mem_usage.Collect(MemUsage::ConcatLabel(label, "import_irs_"), import_irs_);
  198. mem_usage.Collect(MemUsage::ConcatLabel(label, "import_ir_insts_"),
  199. import_ir_insts_);
  200. mem_usage.Collect(MemUsage::ConcatLabel(label, "clang_decls_"), clang_decls_);
  201. mem_usage.Collect(MemUsage::ConcatLabel(label, "struct_type_fields_"),
  202. struct_type_fields_);
  203. mem_usage.Collect(MemUsage::ConcatLabel(label, "insts_"), insts_);
  204. mem_usage.Collect(MemUsage::ConcatLabel(label, "name_scopes_"), name_scopes_);
  205. mem_usage.Collect(MemUsage::ConcatLabel(label, "constant_values_"),
  206. constant_values_);
  207. mem_usage.Collect(MemUsage::ConcatLabel(label, "inst_blocks_"), inst_blocks_);
  208. mem_usage.Collect(MemUsage::ConcatLabel(label, "constants_"), constants_);
  209. mem_usage.Collect(MemUsage::ConcatLabel(label, "types_"), types_);
  210. }
  211. auto File::set_clang_ast_unit(clang::ASTUnit* clang_ast_unit) -> void {
  212. clang_ast_unit_ = clang_ast_unit;
  213. clang_mangle_context_.reset(
  214. clang_ast_unit->getASTContext().createMangleContext());
  215. }
  216. } // namespace Carbon::SemIR