file.cpp 13 KB

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