file.cpp 22 KB

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