file.cpp 20 KB

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