file.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. : IdentifierId::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 types.
  35. types_.SetValueRepr(
  36. TypeType::SingletonTypeId,
  37. {.kind = ValueRepr::Copy, .type_id = TypeType::SingletonTypeId});
  38. types_.SetValueRepr(
  39. ErrorInst::SingletonTypeId,
  40. {.kind = ValueRepr::Copy, .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::ForTemplateConstant(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(
  101. "insts", Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  102. int start = include_singletons ? 0 : SingletonInstKinds.size();
  103. for (int i : llvm::seq(start, insts_.size())) {
  104. auto id = InstId(i);
  105. map.Add(PrintToString(id),
  106. Yaml::OutputScalar(insts_.Get(id)));
  107. }
  108. }));
  109. map.Add("constant_values",
  110. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  111. int start =
  112. include_singletons ? 0 : SingletonInstKinds.size();
  113. for (int i : llvm::seq(start, insts_.size())) {
  114. auto id = InstId(i);
  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 Vtable::Kind:
  188. case ReturnExpr::Kind:
  189. case VarPattern::Kind:
  190. return ExprCategory::NotExpr;
  191. case ImportRefUnloaded::Kind:
  192. case ImportRefLoaded::Kind: {
  193. auto import_ir_inst = ir->import_ir_insts().Get(
  194. untyped_inst.As<SemIR::AnyImportRef>().import_ir_inst_id);
  195. ir = ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  196. inst_id = import_ir_inst.inst_id;
  197. continue;
  198. }
  199. case CARBON_KIND(AsCompatible inst): {
  200. inst_id = inst.source_id;
  201. continue;
  202. }
  203. case CARBON_KIND(BindAlias inst): {
  204. inst_id = inst.value_id;
  205. continue;
  206. }
  207. case CARBON_KIND(ExportDecl inst): {
  208. inst_id = inst.value_id;
  209. continue;
  210. }
  211. case CARBON_KIND(NameRef inst): {
  212. inst_id = inst.value_id;
  213. continue;
  214. }
  215. case CARBON_KIND(Converted inst): {
  216. inst_id = inst.result_id;
  217. continue;
  218. }
  219. case CARBON_KIND(SpecificConstant inst): {
  220. inst_id = inst.inst_id;
  221. continue;
  222. }
  223. case AddrOf::Kind:
  224. case ArrayType::Kind:
  225. case AssociatedConstantDecl::Kind:
  226. case AssociatedEntity::Kind:
  227. case AssociatedEntityType::Kind:
  228. case AutoType::Kind:
  229. case BindSymbolicName::Kind:
  230. case BindValue::Kind:
  231. case BlockArg::Kind:
  232. case BoolLiteral::Kind:
  233. case BoolType::Kind:
  234. case BoundMethod::Kind:
  235. case BoundMethodType::Kind:
  236. case ClassDecl::Kind:
  237. case ClassType::Kind:
  238. case CompleteTypeWitness::Kind:
  239. case ConstType::Kind:
  240. case FacetAccessType::Kind:
  241. case FacetAccessWitness::Kind:
  242. case FacetType::Kind:
  243. case FacetValue::Kind:
  244. case FloatLiteral::Kind:
  245. case FloatType::Kind:
  246. case FunctionType::Kind:
  247. case FunctionTypeWithSelfType::Kind:
  248. case GenericClassType::Kind:
  249. case GenericInterfaceType::Kind:
  250. case ImplWitness::Kind:
  251. case ImplWitnessAccess::Kind:
  252. case ImportDecl::Kind:
  253. case IntLiteralType::Kind:
  254. case IntType::Kind:
  255. case IntValue::Kind:
  256. case InterfaceDecl::Kind:
  257. case LegacyFloatType::Kind:
  258. case NamespaceType::Kind:
  259. case PointerType::Kind:
  260. case RequireCompleteType::Kind:
  261. case SpecificFunction::Kind:
  262. case SpecificFunctionType::Kind:
  263. case StringLiteral::Kind:
  264. case StringType::Kind:
  265. case StructType::Kind:
  266. case StructValue::Kind:
  267. case SymbolicBindingPattern::Kind:
  268. case TupleType::Kind:
  269. case TupleValue::Kind:
  270. case TypeType::Kind:
  271. case UnaryOperatorNot::Kind:
  272. case UnboundElementType::Kind:
  273. case ValueOfInitializer::Kind:
  274. case ValueParam::Kind:
  275. case ValueParamPattern::Kind:
  276. case VtableType::Kind:
  277. case WhereExpr::Kind:
  278. case WitnessType::Kind:
  279. return value_category;
  280. case ErrorInst::Kind:
  281. return ExprCategory::Error;
  282. case CARBON_KIND(BindName inst): {
  283. // TODO: Don't rely on value_id for expression category, since it may
  284. // not be valid yet. This workaround only works because we don't support
  285. // `var` in function signatures yet.
  286. if (!inst.value_id.has_value()) {
  287. return value_category;
  288. }
  289. inst_id = inst.value_id;
  290. continue;
  291. }
  292. case CARBON_KIND(ArrayIndex inst): {
  293. inst_id = inst.array_id;
  294. continue;
  295. }
  296. case VtablePtr::Kind:
  297. return ExprCategory::EphemeralRef;
  298. case CARBON_KIND(ClassElementAccess inst): {
  299. inst_id = inst.base_id;
  300. // A value of class type is a pointer to an object representation.
  301. // Therefore, if the base is a value, the result is an ephemeral
  302. // reference.
  303. value_category = ExprCategory::EphemeralRef;
  304. continue;
  305. }
  306. case CARBON_KIND(StructAccess inst): {
  307. inst_id = inst.struct_id;
  308. continue;
  309. }
  310. case CARBON_KIND(TupleAccess inst): {
  311. inst_id = inst.tuple_id;
  312. continue;
  313. }
  314. case CARBON_KIND(SpliceBlock inst): {
  315. inst_id = inst.result_id;
  316. continue;
  317. }
  318. case StructLiteral::Kind:
  319. case TupleLiteral::Kind:
  320. return ExprCategory::Mixed;
  321. case ArrayInit::Kind:
  322. case Call::Kind:
  323. case InitializeFrom::Kind:
  324. case ClassInit::Kind:
  325. case StructInit::Kind:
  326. case TupleInit::Kind:
  327. return ExprCategory::Initializing;
  328. case Deref::Kind:
  329. case VarStorage::Kind:
  330. case ReturnSlot::Kind:
  331. return ExprCategory::DurableRef;
  332. case Temporary::Kind:
  333. case TemporaryStorage::Kind:
  334. case ValueAsRef::Kind:
  335. return ExprCategory::EphemeralRef;
  336. case OutParam::Kind:
  337. // TODO: Consider introducing a separate category for OutParam:
  338. // unlike other DurableRefs, it permits initialization.
  339. return ExprCategory::DurableRef;
  340. }
  341. }
  342. }
  343. } // namespace Carbon::SemIR