file.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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 "common/check.h"
  6. #include "llvm/ADT/STLExtras.h"
  7. #include "llvm/ADT/SmallVector.h"
  8. #include "toolchain/base/kind_switch.h"
  9. #include "toolchain/base/shared_value_stores.h"
  10. #include "toolchain/base/yaml.h"
  11. #include "toolchain/parse/node_ids.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/inst.h"
  14. #include "toolchain/sem_ir/inst_kind.h"
  15. #include "toolchain/sem_ir/typed_insts.h"
  16. namespace Carbon::SemIR {
  17. File::File(const Parse::Tree* parse_tree, CheckIRId check_ir_id,
  18. const std::optional<Parse::Tree::PackagingDecl>& packaging_decl,
  19. SharedValueStores& value_stores, std::string filename)
  20. : parse_tree_(parse_tree),
  21. check_ir_id_(check_ir_id),
  22. package_id_(packaging_decl ? packaging_decl->names.package_id
  23. : PackageNameId::None),
  24. library_id_(packaging_decl ? LibraryNameId::ForStringLiteralValueId(
  25. packaging_decl->names.library_id)
  26. : LibraryNameId::Default),
  27. value_stores_(&value_stores),
  28. filename_(std::move(filename)),
  29. impls_(*this),
  30. type_blocks_(allocator_),
  31. constant_values_(ConstantId::NotConstant),
  32. inst_blocks_(allocator_),
  33. constants_(this) {
  34. // `type` and the error type are both complete & concrete types.
  35. types_.SetComplete(TypeType::SingletonTypeId,
  36. {.value_repr = {.kind = ValueRepr::Copy,
  37. .type_id = TypeType::SingletonTypeId}});
  38. types_.SetComplete(ErrorInst::SingletonTypeId,
  39. {.value_repr = {.kind = ValueRepr::Copy,
  40. .type_id = ErrorInst::SingletonTypeId}});
  41. insts_.Reserve(SingletonInstKinds.size());
  42. for (auto kind : SingletonInstKinds) {
  43. auto inst_id =
  44. insts_.AddInNoBlock(LocIdAndInst::NoLoc(Inst::MakeSingleton(kind)));
  45. constant_values_.Set(inst_id,
  46. SemIR::ConstantId::ForConcreteConstant(inst_id));
  47. }
  48. }
  49. auto File::Verify() const -> ErrorOr<Success> {
  50. // Invariants don't necessarily hold for invalid IR.
  51. if (has_errors_) {
  52. return Success();
  53. }
  54. // Check that every code block has a terminator sequence that appears at the
  55. // end of the block.
  56. for (const Function& function : functions_.array_ref()) {
  57. for (InstBlockId block_id : function.body_block_ids) {
  58. TerminatorKind prior_kind = TerminatorKind::NotTerminator;
  59. for (InstId inst_id : inst_blocks().Get(block_id)) {
  60. TerminatorKind inst_kind =
  61. insts().Get(inst_id).kind().terminator_kind();
  62. if (prior_kind == TerminatorKind::Terminator) {
  63. return Error(llvm::formatv("Inst {0} in block {1} follows terminator",
  64. inst_id, block_id));
  65. }
  66. if (prior_kind > inst_kind) {
  67. return Error(
  68. llvm::formatv("Non-terminator inst {0} in block {1} follows "
  69. "terminator sequence",
  70. inst_id, block_id));
  71. }
  72. prior_kind = inst_kind;
  73. }
  74. if (prior_kind != TerminatorKind::Terminator) {
  75. return Error(llvm::formatv("No terminator in block {0}", block_id));
  76. }
  77. }
  78. }
  79. // TODO: Check that an instruction only references other instructions that are
  80. // either global or that dominate it.
  81. return Success();
  82. }
  83. auto File::OutputYaml(bool include_singletons) const -> Yaml::OutputMapping {
  84. return Yaml::OutputMapping([this, include_singletons](
  85. Yaml::OutputMapping::Map map) {
  86. map.Add("filename", filename_);
  87. map.Add(
  88. "sem_ir", Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  89. map.Add("import_irs", import_irs_.OutputYaml());
  90. map.Add("import_ir_insts", import_ir_insts_.OutputYaml());
  91. map.Add("name_scopes", name_scopes_.OutputYaml());
  92. map.Add("entity_names", entity_names_.OutputYaml());
  93. map.Add("functions", functions_.OutputYaml());
  94. map.Add("classes", classes_.OutputYaml());
  95. map.Add("generics", generics_.OutputYaml());
  96. map.Add("specifics", specifics_.OutputYaml());
  97. map.Add("struct_type_fields", struct_type_fields_.OutputYaml());
  98. map.Add("types", types_.OutputYaml());
  99. map.Add("type_blocks", type_blocks_.OutputYaml());
  100. map.Add("insts",
  101. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  102. for (auto [id, inst] : insts_.enumerate()) {
  103. if (!include_singletons && IsSingletonInstId(id)) {
  104. continue;
  105. }
  106. map.Add(PrintToString(id), Yaml::OutputScalar(inst));
  107. }
  108. }));
  109. map.Add("constant_values",
  110. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  111. for (auto [id, _] : insts_.enumerate()) {
  112. if (!include_singletons && IsSingletonInstId(id)) {
  113. continue;
  114. }
  115. auto value = constant_values_.Get(id);
  116. if (!value.has_value() || value.is_constant()) {
  117. map.Add(PrintToString(id), Yaml::OutputScalar(value));
  118. }
  119. }
  120. }));
  121. map.Add(
  122. "symbolic_constants",
  123. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  124. for (const auto& [i, symbolic] :
  125. llvm::enumerate(constant_values().symbolic_constants())) {
  126. map.Add(
  127. PrintToString(ConstantId::ForSymbolicConstantIndex(i)),
  128. Yaml::OutputScalar(symbolic));
  129. }
  130. }));
  131. map.Add("inst_blocks", inst_blocks_.OutputYaml());
  132. }));
  133. });
  134. }
  135. auto File::CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  136. -> void {
  137. mem_usage.Collect(MemUsage::ConcatLabel(label, "allocator_"), allocator_);
  138. mem_usage.Collect(MemUsage::ConcatLabel(label, "entity_names_"),
  139. entity_names_);
  140. mem_usage.Collect(MemUsage::ConcatLabel(label, "functions_"), functions_);
  141. mem_usage.Collect(MemUsage::ConcatLabel(label, "classes_"), classes_);
  142. mem_usage.Collect(MemUsage::ConcatLabel(label, "interfaces_"), interfaces_);
  143. mem_usage.Collect(MemUsage::ConcatLabel(label, "impls_"), impls_);
  144. mem_usage.Collect(MemUsage::ConcatLabel(label, "generics_"), generics_);
  145. mem_usage.Collect(MemUsage::ConcatLabel(label, "specifics_"), specifics_);
  146. mem_usage.Collect(MemUsage::ConcatLabel(label, "import_irs_"), import_irs_);
  147. mem_usage.Collect(MemUsage::ConcatLabel(label, "import_ir_insts_"),
  148. import_ir_insts_);
  149. mem_usage.Collect(MemUsage::ConcatLabel(label, "struct_type_fields_"),
  150. struct_type_fields_);
  151. mem_usage.Collect(MemUsage::ConcatLabel(label, "type_blocks_"), type_blocks_);
  152. mem_usage.Collect(MemUsage::ConcatLabel(label, "insts_"), insts_);
  153. mem_usage.Collect(MemUsage::ConcatLabel(label, "name_scopes_"), name_scopes_);
  154. mem_usage.Collect(MemUsage::ConcatLabel(label, "constant_values_"),
  155. constant_values_);
  156. mem_usage.Collect(MemUsage::ConcatLabel(label, "inst_blocks_"), inst_blocks_);
  157. mem_usage.Collect(MemUsage::ConcatLabel(label, "constants_"), constants_);
  158. mem_usage.Collect(MemUsage::ConcatLabel(label, "types_"), types_);
  159. }
  160. auto GetExprCategory(const File& file, InstId inst_id) -> ExprCategory {
  161. const File* ir = &file;
  162. // The overall expression category if the current instruction is a value
  163. // expression.
  164. ExprCategory value_category = ExprCategory::Value;
  165. while (true) {
  166. auto untyped_inst = ir->insts().Get(inst_id);
  167. CARBON_KIND_SWITCH(untyped_inst) {
  168. case AdaptDecl::Kind:
  169. case AddrPattern::Kind:
  170. case Assign::Kind:
  171. case BaseDecl::Kind:
  172. case BindingPattern::Kind:
  173. case Branch::Kind:
  174. case BranchIf::Kind:
  175. case BranchWithArg::Kind:
  176. case FieldDecl::Kind:
  177. case FunctionDecl::Kind:
  178. case ImplDecl::Kind:
  179. case NameBindingDecl::Kind:
  180. case Namespace::Kind:
  181. case OutParamPattern::Kind:
  182. case RequirementEquivalent::Kind:
  183. case RequirementImpls::Kind:
  184. case RequirementRewrite::Kind:
  185. case Return::Kind:
  186. case ReturnSlotPattern::Kind:
  187. case ReturnExpr::Kind:
  188. case TuplePattern::Kind:
  189. case VarPattern::Kind:
  190. case Vtable::Kind:
  191. return ExprCategory::NotExpr;
  192. case ImportRefUnloaded::Kind:
  193. case ImportRefLoaded::Kind: {
  194. auto import_ir_inst = ir->import_ir_insts().Get(
  195. untyped_inst.As<SemIR::AnyImportRef>().import_ir_inst_id);
  196. ir = ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  197. inst_id = import_ir_inst.inst_id;
  198. continue;
  199. }
  200. case CARBON_KIND(AsCompatible inst): {
  201. inst_id = inst.source_id;
  202. continue;
  203. }
  204. case CARBON_KIND(BindAlias inst): {
  205. inst_id = inst.value_id;
  206. continue;
  207. }
  208. case CARBON_KIND(ExportDecl inst): {
  209. inst_id = inst.value_id;
  210. continue;
  211. }
  212. case CARBON_KIND(NameRef inst): {
  213. inst_id = inst.value_id;
  214. continue;
  215. }
  216. case CARBON_KIND(Converted inst): {
  217. inst_id = inst.result_id;
  218. continue;
  219. }
  220. case CARBON_KIND(SpecificConstant inst): {
  221. inst_id = inst.inst_id;
  222. continue;
  223. }
  224. case AddrOf::Kind:
  225. case ArrayType::Kind:
  226. case AssociatedConstantDecl::Kind:
  227. case AssociatedEntity::Kind:
  228. case AssociatedEntityType::Kind:
  229. case AutoType::Kind:
  230. case BindSymbolicName::Kind:
  231. case BindValue::Kind:
  232. case BlockArg::Kind:
  233. case BoolLiteral::Kind:
  234. case BoolType::Kind:
  235. case BoundMethod::Kind:
  236. case BoundMethodType::Kind:
  237. case ClassDecl::Kind:
  238. case ClassType::Kind:
  239. case CompleteTypeWitness::Kind:
  240. case ConstType::Kind:
  241. case FacetAccessType::Kind:
  242. case FacetAccessWitness::Kind:
  243. case FacetType::Kind:
  244. case FacetValue::Kind:
  245. case FloatLiteral::Kind:
  246. case FloatType::Kind:
  247. case FunctionType::Kind:
  248. case FunctionTypeWithSelfType::Kind:
  249. case GenericClassType::Kind:
  250. case GenericInterfaceType::Kind:
  251. case ImplWitness::Kind:
  252. case ImplWitnessAccess::Kind:
  253. case ImportCppDecl::Kind:
  254. case ImportDecl::Kind:
  255. case IntLiteralType::Kind:
  256. case IntType::Kind:
  257. case IntValue::Kind:
  258. case InterfaceDecl::Kind:
  259. case LegacyFloatType::Kind:
  260. case NamespaceType::Kind:
  261. case PointerType::Kind:
  262. case RequireCompleteType::Kind:
  263. case SpecificFunction::Kind:
  264. case SpecificFunctionType::Kind:
  265. case StringLiteral::Kind:
  266. case StringType::Kind:
  267. case StructType::Kind:
  268. case StructValue::Kind:
  269. case SymbolicBindingPattern::Kind:
  270. case TupleType::Kind:
  271. case TupleValue::Kind:
  272. case TypeType::Kind:
  273. case UnaryOperatorNot::Kind:
  274. case UnboundElementType::Kind:
  275. case ValueOfInitializer::Kind:
  276. case ValueParam::Kind:
  277. case ValueParamPattern::Kind:
  278. case VtableType::Kind:
  279. case WhereExpr::Kind:
  280. case WitnessType::Kind:
  281. return value_category;
  282. case ErrorInst::Kind:
  283. return ExprCategory::Error;
  284. case CARBON_KIND(BindName inst): {
  285. // TODO: Don't rely on value_id for expression category, since it may
  286. // not be valid yet. This workaround only works because we don't support
  287. // `var` in function signatures yet.
  288. if (!inst.value_id.has_value()) {
  289. return value_category;
  290. }
  291. inst_id = inst.value_id;
  292. continue;
  293. }
  294. case CARBON_KIND(ArrayIndex inst): {
  295. inst_id = inst.array_id;
  296. continue;
  297. }
  298. case VtablePtr::Kind:
  299. return ExprCategory::EphemeralRef;
  300. case CARBON_KIND(ClassElementAccess inst): {
  301. inst_id = inst.base_id;
  302. // A value of class type is a pointer to an object representation.
  303. // Therefore, if the base is a value, the result is an ephemeral
  304. // reference.
  305. value_category = ExprCategory::EphemeralRef;
  306. continue;
  307. }
  308. case CARBON_KIND(StructAccess inst): {
  309. inst_id = inst.struct_id;
  310. continue;
  311. }
  312. case CARBON_KIND(TupleAccess inst): {
  313. inst_id = inst.tuple_id;
  314. continue;
  315. }
  316. case CARBON_KIND(SpliceBlock inst): {
  317. inst_id = inst.result_id;
  318. continue;
  319. }
  320. case StructLiteral::Kind:
  321. case TupleLiteral::Kind:
  322. return ExprCategory::Mixed;
  323. case ArrayInit::Kind:
  324. case Call::Kind:
  325. case InitializeFrom::Kind:
  326. case ClassInit::Kind:
  327. case StructInit::Kind:
  328. case TupleInit::Kind:
  329. return ExprCategory::Initializing;
  330. case Deref::Kind:
  331. case VarStorage::Kind:
  332. case ReturnSlot::Kind:
  333. return ExprCategory::DurableRef;
  334. case Temporary::Kind:
  335. case TemporaryStorage::Kind:
  336. case ValueAsRef::Kind:
  337. return ExprCategory::EphemeralRef;
  338. case OutParam::Kind:
  339. // TODO: Consider introducing a separate category for OutParam:
  340. // unlike other DurableRefs, it permits initialization.
  341. return ExprCategory::DurableRef;
  342. }
  343. }
  344. }
  345. } // namespace Carbon::SemIR