file.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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/value_store.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. auto Function::GetParamFromParamRefId(const File& sem_ir, InstId param_ref_id)
  19. -> std::pair<InstId, Param> {
  20. auto ref = sem_ir.insts().Get(param_ref_id);
  21. if (auto addr_pattern = ref.TryAs<SemIR::AddrPattern>()) {
  22. param_ref_id = addr_pattern->inner_id;
  23. ref = sem_ir.insts().Get(param_ref_id);
  24. }
  25. if (auto bind_name = ref.TryAs<SemIR::AnyBindName>()) {
  26. param_ref_id = bind_name->value_id;
  27. ref = sem_ir.insts().Get(param_ref_id);
  28. }
  29. return {param_ref_id, ref.As<SemIR::Param>()};
  30. }
  31. auto ValueRepr::Print(llvm::raw_ostream& out) const -> void {
  32. out << "{kind: ";
  33. switch (kind) {
  34. case Unknown:
  35. out << "unknown";
  36. break;
  37. case None:
  38. out << "none";
  39. break;
  40. case Copy:
  41. out << "copy";
  42. break;
  43. case Pointer:
  44. out << "pointer";
  45. break;
  46. case Custom:
  47. out << "custom";
  48. break;
  49. }
  50. out << ", type: " << type_id << "}";
  51. }
  52. auto CompleteTypeInfo::Print(llvm::raw_ostream& out) const -> void {
  53. out << "{value_rep: " << value_repr << "}";
  54. }
  55. File::File(CheckIRId check_ir_id, SharedValueStores& value_stores,
  56. std::string filename)
  57. : check_ir_id_(check_ir_id),
  58. value_stores_(&value_stores),
  59. filename_(std::move(filename)),
  60. type_blocks_(allocator_),
  61. name_scopes_(&insts_),
  62. constant_values_(ConstantId::NotConstant),
  63. inst_blocks_(allocator_),
  64. constants_(*this, allocator_) {
  65. // `type` and the error type are both complete types.
  66. types_.SetValueRepr(TypeId::TypeType,
  67. {.kind = ValueRepr::Copy, .type_id = TypeId::TypeType});
  68. types_.SetValueRepr(TypeId::Error,
  69. {.kind = ValueRepr::Copy, .type_id = TypeId::Error});
  70. insts_.Reserve(BuiltinInstKind::ValidCount);
  71. // Error uses a self-referential type so that it's not accidentally treated as
  72. // a normal type. Every other builtin is a type, including the
  73. // self-referential TypeType.
  74. #define CARBON_SEM_IR_BUILTIN_INST_KIND(Name, ...) \
  75. insts_.AddInNoBlock(LocIdAndInst::NoLoc<BuiltinInst>( \
  76. {.type_id = BuiltinInstKind::Name == BuiltinInstKind::Error \
  77. ? TypeId::Error \
  78. : TypeId::TypeType, \
  79. .builtin_inst_kind = BuiltinInstKind::Name}));
  80. #include "toolchain/sem_ir/builtin_inst_kind.def"
  81. CARBON_CHECK(insts_.size() == BuiltinInstKind::ValidCount)
  82. << "Builtins should produce " << BuiltinInstKind::ValidCount
  83. << " insts, actual: " << insts_.size();
  84. for (auto i : llvm::seq(BuiltinInstKind::ValidCount)) {
  85. auto builtin_id = SemIR::InstId(i);
  86. constant_values_.Set(builtin_id,
  87. SemIR::ConstantId::ForTemplateConstant(builtin_id));
  88. }
  89. }
  90. auto File::Verify() const -> ErrorOr<Success> {
  91. // Invariants don't necessarily hold for invalid IR.
  92. if (has_errors_) {
  93. return Success();
  94. }
  95. // Check that every code block has a terminator sequence that appears at the
  96. // end of the block.
  97. for (const Function& function : functions_.array_ref()) {
  98. for (InstBlockId block_id : function.body_block_ids) {
  99. TerminatorKind prior_kind = TerminatorKind::NotTerminator;
  100. for (InstId inst_id : inst_blocks().Get(block_id)) {
  101. TerminatorKind inst_kind =
  102. insts().Get(inst_id).kind().terminator_kind();
  103. if (prior_kind == TerminatorKind::Terminator) {
  104. return Error(llvm::formatv("Inst {0} in block {1} follows terminator",
  105. inst_id, block_id));
  106. }
  107. if (prior_kind > inst_kind) {
  108. return Error(
  109. llvm::formatv("Non-terminator inst {0} in block {1} follows "
  110. "terminator sequence",
  111. inst_id, block_id));
  112. }
  113. prior_kind = inst_kind;
  114. }
  115. if (prior_kind != TerminatorKind::Terminator) {
  116. return Error(llvm::formatv("No terminator in block {0}", block_id));
  117. }
  118. }
  119. }
  120. // TODO: Check that an instruction only references other instructions that are
  121. // either global or that dominate it.
  122. return Success();
  123. }
  124. auto File::OutputYaml(bool include_builtins) const -> Yaml::OutputMapping {
  125. return Yaml::OutputMapping([this,
  126. include_builtins](Yaml::OutputMapping::Map map) {
  127. map.Add("filename", filename_);
  128. map.Add(
  129. "sem_ir", Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  130. map.Add("import_irs", import_irs_.OutputYaml());
  131. map.Add("import_ir_insts", import_ir_insts_.OutputYaml());
  132. map.Add("name_scopes", name_scopes_.OutputYaml());
  133. map.Add("entity_names", entity_names_.OutputYaml());
  134. map.Add("functions", functions_.OutputYaml());
  135. map.Add("classes", classes_.OutputYaml());
  136. map.Add("generics", generics_.OutputYaml());
  137. map.Add("generic_instances", generic_instances_.OutputYaml());
  138. map.Add("types", types_.OutputYaml());
  139. map.Add("type_blocks", type_blocks_.OutputYaml());
  140. map.Add(
  141. "insts", Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  142. int start = include_builtins ? 0 : BuiltinInstKind::ValidCount;
  143. for (int i : llvm::seq(start, insts_.size())) {
  144. auto id = InstId(i);
  145. map.Add(PrintToString(id),
  146. Yaml::OutputScalar(insts_.Get(id)));
  147. }
  148. }));
  149. map.Add("constant_values",
  150. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  151. int start =
  152. include_builtins ? 0 : BuiltinInstKind::ValidCount;
  153. for (int i : llvm::seq(start, insts_.size())) {
  154. auto id = InstId(i);
  155. auto value = constant_values_.Get(id);
  156. if (!value.is_valid() || value.is_constant()) {
  157. map.Add(PrintToString(id), Yaml::OutputScalar(value));
  158. }
  159. }
  160. }));
  161. map.Add(
  162. "symbolic_constants",
  163. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  164. for (const auto& [i, symbolic] :
  165. llvm::enumerate(constant_values().symbolic_constants())) {
  166. map.Add(
  167. PrintToString(ConstantId::ForSymbolicConstantIndex(i)),
  168. Yaml::OutputScalar(symbolic));
  169. }
  170. }));
  171. map.Add("inst_blocks", inst_blocks_.OutputYaml());
  172. }));
  173. });
  174. }
  175. auto File::CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  176. -> void {
  177. mem_usage.Add(MemUsage::ConcatLabel(label, "allocator_"), allocator_);
  178. mem_usage.Collect(MemUsage::ConcatLabel(label, "entity_names_"),
  179. entity_names_);
  180. mem_usage.Collect(MemUsage::ConcatLabel(label, "functions_"), functions_);
  181. mem_usage.Collect(MemUsage::ConcatLabel(label, "classes_"), classes_);
  182. mem_usage.Collect(MemUsage::ConcatLabel(label, "interfaces_"), interfaces_);
  183. mem_usage.Collect(MemUsage::ConcatLabel(label, "impls_"), impls_);
  184. mem_usage.Collect(MemUsage::ConcatLabel(label, "generics_"), generics_);
  185. mem_usage.Collect(MemUsage::ConcatLabel(label, "generic_instances_"),
  186. generic_instances_);
  187. mem_usage.Collect(MemUsage::ConcatLabel(label, "import_irs_"), import_irs_);
  188. mem_usage.Collect(MemUsage::ConcatLabel(label, "import_ir_insts_"),
  189. import_ir_insts_);
  190. mem_usage.Collect(MemUsage::ConcatLabel(label, "type_blocks_"), type_blocks_);
  191. mem_usage.Collect(MemUsage::ConcatLabel(label, "insts_"), insts_);
  192. mem_usage.Collect(MemUsage::ConcatLabel(label, "name_scopes_"), name_scopes_);
  193. mem_usage.Collect(MemUsage::ConcatLabel(label, "constant_values_"),
  194. constant_values_);
  195. mem_usage.Collect(MemUsage::ConcatLabel(label, "inst_blocks_"), inst_blocks_);
  196. mem_usage.Collect(MemUsage::ConcatLabel(label, "constants_"), constants_);
  197. mem_usage.Collect(MemUsage::ConcatLabel(label, "types_"), types_);
  198. }
  199. // Map an instruction kind representing a type into an integer describing the
  200. // precedence of that type's syntax. Higher numbers correspond to higher
  201. // precedence.
  202. static auto GetTypePrecedence(InstKind kind) -> int {
  203. CARBON_CHECK(kind.is_type() != InstIsType::Never)
  204. << "Only called for kinds which can define a type.";
  205. if (kind == ConstType::Kind) {
  206. return -1;
  207. }
  208. if (kind == PointerType::Kind) {
  209. return -2;
  210. }
  211. return 0;
  212. }
  213. // Implements File::StringifyTypeExpr. Static to prevent accidental use of
  214. // member functions while traversing IRs.
  215. static auto StringifyTypeExprImpl(const SemIR::File& outer_sem_ir,
  216. InstId outer_inst_id) {
  217. std::string str;
  218. llvm::raw_string_ostream out(str);
  219. struct Step {
  220. // The instruction's file.
  221. const File& sem_ir;
  222. // The instruction to print.
  223. InstId inst_id;
  224. // The index into inst_id to print. Not used by all types.
  225. int index = 0;
  226. auto Next() const -> Step {
  227. return {.sem_ir = sem_ir, .inst_id = inst_id, .index = index + 1};
  228. }
  229. };
  230. llvm::SmallVector<Step> steps = {
  231. Step{.sem_ir = outer_sem_ir, .inst_id = outer_inst_id}};
  232. while (!steps.empty()) {
  233. auto step = steps.pop_back_val();
  234. if (!step.inst_id.is_valid()) {
  235. out << "<invalid type>";
  236. continue;
  237. }
  238. // Builtins have designated labels.
  239. if (step.inst_id.is_builtin()) {
  240. out << step.inst_id.builtin_inst_kind().label();
  241. continue;
  242. }
  243. const auto& sem_ir = step.sem_ir;
  244. // Helper for instructions with the current sem_ir.
  245. auto push_inst_id = [&](InstId inst_id) {
  246. steps.push_back({.sem_ir = sem_ir, .inst_id = inst_id});
  247. };
  248. auto untyped_inst = sem_ir.insts().Get(step.inst_id);
  249. CARBON_KIND_SWITCH(untyped_inst) {
  250. case CARBON_KIND(ArrayType inst): {
  251. if (step.index == 0) {
  252. out << "[";
  253. steps.push_back(step.Next());
  254. push_inst_id(sem_ir.types().GetInstId(inst.element_type_id));
  255. } else if (step.index == 1) {
  256. out << "; " << sem_ir.GetArrayBoundValue(inst.bound_id) << "]";
  257. }
  258. break;
  259. }
  260. case CARBON_KIND(AssociatedEntityType inst): {
  261. if (step.index == 0) {
  262. out << "<associated ";
  263. steps.push_back(step.Next());
  264. push_inst_id(sem_ir.types().GetInstId(inst.entity_type_id));
  265. } else {
  266. auto interface_name_id =
  267. sem_ir.interfaces().Get(inst.interface_id).name_id;
  268. out << " in " << sem_ir.names().GetFormatted(interface_name_id)
  269. << ">";
  270. }
  271. break;
  272. }
  273. case BindAlias::Kind:
  274. case BindSymbolicName::Kind:
  275. case ExportDecl::Kind: {
  276. auto name_id =
  277. untyped_inst.As<AnyBindNameOrExportDecl>().entity_name_id;
  278. out << sem_ir.names().GetFormatted(
  279. sem_ir.entity_names().Get(name_id).name_id);
  280. break;
  281. }
  282. case CARBON_KIND(ClassType inst): {
  283. auto class_name_id = sem_ir.classes().Get(inst.class_id).name_id;
  284. out << sem_ir.names().GetFormatted(class_name_id);
  285. break;
  286. }
  287. case CARBON_KIND(ConstType inst): {
  288. if (step.index == 0) {
  289. out << "const ";
  290. // Add parentheses if required.
  291. auto inner_type_inst_id = sem_ir.types().GetInstId(inst.inner_id);
  292. if (GetTypePrecedence(sem_ir.insts().Get(inner_type_inst_id).kind()) <
  293. GetTypePrecedence(SemIR::ConstType::Kind)) {
  294. out << "(";
  295. steps.push_back(step.Next());
  296. }
  297. push_inst_id(inner_type_inst_id);
  298. } else if (step.index == 1) {
  299. out << ")";
  300. }
  301. break;
  302. }
  303. case CARBON_KIND(FacetTypeAccess inst): {
  304. // Print `T as type` as simply `T`.
  305. push_inst_id(inst.facet_id);
  306. break;
  307. }
  308. case CARBON_KIND(FloatType inst): {
  309. // TODO: Is this okay?
  310. if (step.index == 1) {
  311. out << ")";
  312. } else if (auto width_value =
  313. sem_ir.insts().TryGetAs<IntLiteral>(inst.bit_width_id)) {
  314. out << "f";
  315. sem_ir.ints().Get(width_value->int_id).print(out, /*isSigned=*/false);
  316. } else {
  317. out << "Core.Float(";
  318. steps.push_back(step.Next());
  319. push_inst_id(inst.bit_width_id);
  320. }
  321. break;
  322. }
  323. case CARBON_KIND(FunctionType inst): {
  324. auto fn_name_id = sem_ir.functions().Get(inst.function_id).name_id;
  325. out << "<type of " << sem_ir.names().GetFormatted(fn_name_id) << ">";
  326. break;
  327. }
  328. case CARBON_KIND(GenericClassType inst): {
  329. auto class_name_id = sem_ir.classes().Get(inst.class_id).name_id;
  330. out << "<type of " << sem_ir.names().GetFormatted(class_name_id) << ">";
  331. break;
  332. }
  333. case CARBON_KIND(GenericInterfaceType inst): {
  334. auto interface_name_id =
  335. sem_ir.interfaces().Get(inst.interface_id).name_id;
  336. out << "<type of " << sem_ir.names().GetFormatted(interface_name_id)
  337. << ">";
  338. break;
  339. }
  340. case CARBON_KIND(InterfaceType inst): {
  341. auto interface_name_id =
  342. sem_ir.interfaces().Get(inst.interface_id).name_id;
  343. out << sem_ir.names().GetFormatted(interface_name_id);
  344. break;
  345. }
  346. case CARBON_KIND(IntType inst): {
  347. if (step.index == 1) {
  348. out << ")";
  349. } else if (auto width_value =
  350. sem_ir.insts().TryGetAs<IntLiteral>(inst.bit_width_id)) {
  351. out << (inst.int_kind.is_signed() ? "i" : "u");
  352. sem_ir.ints().Get(width_value->int_id).print(out, /*isSigned=*/false);
  353. } else {
  354. out << (inst.int_kind.is_signed() ? "Core.Int(" : "Core.UInt(");
  355. steps.push_back(step.Next());
  356. push_inst_id(inst.bit_width_id);
  357. }
  358. break;
  359. }
  360. case CARBON_KIND(NameRef inst): {
  361. out << sem_ir.names().GetFormatted(inst.name_id);
  362. break;
  363. }
  364. case CARBON_KIND(PointerType inst): {
  365. if (step.index == 0) {
  366. steps.push_back(step.Next());
  367. push_inst_id(sem_ir.types().GetInstId(inst.pointee_id));
  368. } else if (step.index == 1) {
  369. out << "*";
  370. }
  371. break;
  372. }
  373. case CARBON_KIND(StructType inst): {
  374. auto refs = sem_ir.inst_blocks().Get(inst.fields_id);
  375. if (refs.empty()) {
  376. out << "{}";
  377. break;
  378. } else if (step.index == 0) {
  379. out << "{";
  380. } else if (step.index < static_cast<int>(refs.size())) {
  381. out << ", ";
  382. } else {
  383. out << "}";
  384. break;
  385. }
  386. steps.push_back(step.Next());
  387. push_inst_id(refs[step.index]);
  388. break;
  389. }
  390. case CARBON_KIND(StructTypeField inst): {
  391. out << "." << sem_ir.names().GetFormatted(inst.name_id) << ": ";
  392. push_inst_id(sem_ir.types().GetInstId(inst.field_type_id));
  393. break;
  394. }
  395. case CARBON_KIND(TupleType inst): {
  396. auto refs = sem_ir.type_blocks().Get(inst.elements_id);
  397. if (refs.empty()) {
  398. out << "()";
  399. break;
  400. } else if (step.index == 0) {
  401. out << "(";
  402. } else if (step.index < static_cast<int>(refs.size())) {
  403. out << ", ";
  404. } else {
  405. // A tuple of one element has a comma to disambiguate from an
  406. // expression.
  407. if (step.index == 1) {
  408. out << ",";
  409. }
  410. out << ")";
  411. break;
  412. }
  413. steps.push_back(step.Next());
  414. push_inst_id(sem_ir.types().GetInstId(refs[step.index]));
  415. break;
  416. }
  417. case CARBON_KIND(UnboundElementType inst): {
  418. if (step.index == 0) {
  419. out << "<unbound element of class ";
  420. steps.push_back(step.Next());
  421. push_inst_id(sem_ir.types().GetInstId(inst.class_type_id));
  422. } else {
  423. out << ">";
  424. }
  425. break;
  426. }
  427. case AdaptDecl::Kind:
  428. case AddrOf::Kind:
  429. case AddrPattern::Kind:
  430. case ArrayIndex::Kind:
  431. case ArrayInit::Kind:
  432. case AsCompatible::Kind:
  433. case Assign::Kind:
  434. case AssociatedConstantDecl::Kind:
  435. case AssociatedEntity::Kind:
  436. case BaseDecl::Kind:
  437. case BindName::Kind:
  438. case BindValue::Kind:
  439. case BlockArg::Kind:
  440. case BoolLiteral::Kind:
  441. case BoundMethod::Kind:
  442. case Branch::Kind:
  443. case BranchIf::Kind:
  444. case BranchWithArg::Kind:
  445. case BuiltinInst::Kind:
  446. case Call::Kind:
  447. case ClassDecl::Kind:
  448. case ClassElementAccess::Kind:
  449. case ClassInit::Kind:
  450. case Converted::Kind:
  451. case Deref::Kind:
  452. case FieldDecl::Kind:
  453. case FloatLiteral::Kind:
  454. case FunctionDecl::Kind:
  455. case ImplDecl::Kind:
  456. case ImportDecl::Kind:
  457. case ImportRefLoaded::Kind:
  458. case ImportRefUnloaded::Kind:
  459. case InitializeFrom::Kind:
  460. case SpecificConstant::Kind:
  461. case InterfaceDecl::Kind:
  462. case InterfaceWitness::Kind:
  463. case InterfaceWitnessAccess::Kind:
  464. case IntLiteral::Kind:
  465. case Namespace::Kind:
  466. case Param::Kind:
  467. case Return::Kind:
  468. case ReturnExpr::Kind:
  469. case SpliceBlock::Kind:
  470. case StringLiteral::Kind:
  471. case StructAccess::Kind:
  472. case StructLiteral::Kind:
  473. case StructInit::Kind:
  474. case StructValue::Kind:
  475. case Temporary::Kind:
  476. case TemporaryStorage::Kind:
  477. case TupleAccess::Kind:
  478. case TupleIndex::Kind:
  479. case TupleLiteral::Kind:
  480. case TupleInit::Kind:
  481. case TupleValue::Kind:
  482. case UnaryOperatorNot::Kind:
  483. case ValueAsRef::Kind:
  484. case ValueOfInitializer::Kind:
  485. case VarStorage::Kind:
  486. // We don't need to handle stringification for instructions that don't
  487. // show up in errors, but make it clear what's going on so that it's
  488. // clearer when stringification is needed.
  489. out << "<cannot stringify " << step.inst_id << ">";
  490. break;
  491. }
  492. }
  493. return str;
  494. }
  495. auto File::StringifyType(TypeId type_id) const -> std::string {
  496. return StringifyTypeExprImpl(*this, types().GetInstId(type_id));
  497. }
  498. auto File::StringifyType(ConstantId type_const_id) const -> std::string {
  499. return StringifyTypeExprImpl(*this,
  500. constant_values().GetInstId(type_const_id));
  501. }
  502. auto File::StringifyTypeExpr(InstId outer_inst_id) const -> std::string {
  503. return StringifyTypeExprImpl(*this, outer_inst_id);
  504. }
  505. auto GetExprCategory(const File& file, InstId inst_id) -> ExprCategory {
  506. const File* ir = &file;
  507. // The overall expression category if the current instruction is a value
  508. // expression.
  509. ExprCategory value_category = ExprCategory::Value;
  510. while (true) {
  511. auto untyped_inst = ir->insts().Get(inst_id);
  512. CARBON_KIND_SWITCH(untyped_inst) {
  513. case AdaptDecl::Kind:
  514. case Assign::Kind:
  515. case BaseDecl::Kind:
  516. case Branch::Kind:
  517. case BranchIf::Kind:
  518. case BranchWithArg::Kind:
  519. case FieldDecl::Kind:
  520. case FunctionDecl::Kind:
  521. case ImplDecl::Kind:
  522. case Namespace::Kind:
  523. case Return::Kind:
  524. case ReturnExpr::Kind:
  525. case StructTypeField::Kind:
  526. return ExprCategory::NotExpr;
  527. case ImportRefUnloaded::Kind:
  528. case ImportRefLoaded::Kind: {
  529. auto import_ir_inst = ir->import_ir_insts().Get(
  530. untyped_inst.As<SemIR::AnyImportRef>().import_ir_inst_id);
  531. ir = ir->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  532. inst_id = import_ir_inst.inst_id;
  533. continue;
  534. }
  535. case CARBON_KIND(AsCompatible inst): {
  536. inst_id = inst.source_id;
  537. continue;
  538. }
  539. case CARBON_KIND(BindAlias inst): {
  540. inst_id = inst.value_id;
  541. continue;
  542. }
  543. case CARBON_KIND(ExportDecl inst): {
  544. inst_id = inst.value_id;
  545. continue;
  546. }
  547. case CARBON_KIND(NameRef inst): {
  548. inst_id = inst.value_id;
  549. continue;
  550. }
  551. case CARBON_KIND(Converted inst): {
  552. inst_id = inst.result_id;
  553. continue;
  554. }
  555. case CARBON_KIND(SpecificConstant inst): {
  556. inst_id = inst.inst_id;
  557. continue;
  558. }
  559. case AddrOf::Kind:
  560. case AddrPattern::Kind:
  561. case ArrayType::Kind:
  562. case AssociatedConstantDecl::Kind:
  563. case AssociatedEntity::Kind:
  564. case AssociatedEntityType::Kind:
  565. case BindSymbolicName::Kind:
  566. case BindValue::Kind:
  567. case BlockArg::Kind:
  568. case BoolLiteral::Kind:
  569. case BoundMethod::Kind:
  570. case ClassDecl::Kind:
  571. case ClassType::Kind:
  572. case ConstType::Kind:
  573. case FacetTypeAccess::Kind:
  574. case FloatLiteral::Kind:
  575. case FloatType::Kind:
  576. case FunctionType::Kind:
  577. case GenericClassType::Kind:
  578. case GenericInterfaceType::Kind:
  579. case ImportDecl::Kind:
  580. case InterfaceDecl::Kind:
  581. case InterfaceType::Kind:
  582. case InterfaceWitness::Kind:
  583. case InterfaceWitnessAccess::Kind:
  584. case IntLiteral::Kind:
  585. case IntType::Kind:
  586. case Param::Kind:
  587. case PointerType::Kind:
  588. case StringLiteral::Kind:
  589. case StructValue::Kind:
  590. case StructType::Kind:
  591. case TupleValue::Kind:
  592. case TupleType::Kind:
  593. case UnaryOperatorNot::Kind:
  594. case UnboundElementType::Kind:
  595. case ValueOfInitializer::Kind:
  596. return value_category;
  597. case CARBON_KIND(BuiltinInst inst): {
  598. if (inst.builtin_inst_kind == BuiltinInstKind::Error) {
  599. return ExprCategory::Error;
  600. }
  601. return value_category;
  602. }
  603. case CARBON_KIND(BindName inst): {
  604. inst_id = inst.value_id;
  605. continue;
  606. }
  607. case CARBON_KIND(ArrayIndex inst): {
  608. inst_id = inst.array_id;
  609. continue;
  610. }
  611. case CARBON_KIND(ClassElementAccess inst): {
  612. inst_id = inst.base_id;
  613. // A value of class type is a pointer to an object representation.
  614. // Therefore, if the base is a value, the result is an ephemeral
  615. // reference.
  616. value_category = ExprCategory::EphemeralRef;
  617. continue;
  618. }
  619. case CARBON_KIND(StructAccess inst): {
  620. inst_id = inst.struct_id;
  621. continue;
  622. }
  623. case CARBON_KIND(TupleAccess inst): {
  624. inst_id = inst.tuple_id;
  625. continue;
  626. }
  627. case CARBON_KIND(TupleIndex inst): {
  628. inst_id = inst.tuple_id;
  629. continue;
  630. }
  631. case CARBON_KIND(SpliceBlock inst): {
  632. inst_id = inst.result_id;
  633. continue;
  634. }
  635. case StructLiteral::Kind:
  636. case TupleLiteral::Kind:
  637. return ExprCategory::Mixed;
  638. case ArrayInit::Kind:
  639. case Call::Kind:
  640. case InitializeFrom::Kind:
  641. case ClassInit::Kind:
  642. case StructInit::Kind:
  643. case TupleInit::Kind:
  644. return ExprCategory::Initializing;
  645. case Deref::Kind:
  646. case VarStorage::Kind:
  647. return ExprCategory::DurableRef;
  648. case Temporary::Kind:
  649. case TemporaryStorage::Kind:
  650. case ValueAsRef::Kind:
  651. return ExprCategory::EphemeralRef;
  652. }
  653. }
  654. }
  655. auto GetInitRepr(const File& file, TypeId type_id) -> InitRepr {
  656. auto value_rep = GetValueRepr(file, type_id);
  657. switch (value_rep.kind) {
  658. case ValueRepr::None:
  659. return {.kind = InitRepr::None};
  660. case ValueRepr::Copy:
  661. // TODO: Use in-place initialization for types that have non-trivial
  662. // destructive move.
  663. return {.kind = InitRepr::ByCopy};
  664. case ValueRepr::Pointer:
  665. case ValueRepr::Custom:
  666. return {.kind = InitRepr::InPlace};
  667. case ValueRepr::Unknown:
  668. CARBON_FATAL()
  669. << "Attempting to perform initialization of incomplete type "
  670. << file.types().GetAsInst(type_id);
  671. }
  672. }
  673. } // namespace Carbon::SemIR