file.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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/node.h"
  12. #include "toolchain/sem_ir/node_kind.h"
  13. namespace Carbon::SemIR {
  14. auto ValueRepresentation::Print(llvm::raw_ostream& out) const -> void {
  15. out << "{kind: ";
  16. switch (kind) {
  17. case Unknown:
  18. out << "unknown";
  19. break;
  20. case None:
  21. out << "none";
  22. break;
  23. case Copy:
  24. out << "copy";
  25. break;
  26. case Pointer:
  27. out << "pointer";
  28. break;
  29. case Custom:
  30. out << "custom";
  31. break;
  32. }
  33. out << ", type: " << type_id << "}";
  34. }
  35. auto TypeInfo::Print(llvm::raw_ostream& out) const -> void {
  36. out << "{node: " << node_id << ", value_rep: " << value_representation << "}";
  37. }
  38. File::File(SharedValueStores& value_stores)
  39. : value_stores_(&value_stores),
  40. filename_("<builtins>"),
  41. // Builtins are always the first IR, even when self-referential.
  42. cross_reference_irs_({this}),
  43. type_blocks_(allocator_),
  44. node_blocks_(allocator_) {
  45. // Default entry for NodeBlockId::Empty.
  46. node_blocks_.AddDefaultValue();
  47. nodes_.Reserve(BuiltinKind::ValidCount);
  48. // Error uses a self-referential type so that it's not accidentally treated as
  49. // a normal type. Every other builtin is a type, including the
  50. // self-referential TypeType.
  51. #define CARBON_SEM_IR_BUILTIN_KIND(Name, ...) \
  52. nodes_.AddInNoBlock(Builtin{BuiltinKind::Name == BuiltinKind::Error \
  53. ? TypeId::Error \
  54. : TypeId::TypeType, \
  55. BuiltinKind::Name});
  56. #include "toolchain/sem_ir/builtin_kind.def"
  57. CARBON_CHECK(nodes_.size() == BuiltinKind::ValidCount)
  58. << "Builtins should produce " << BuiltinKind::ValidCount
  59. << " nodes, actual: " << nodes_.size();
  60. }
  61. File::File(SharedValueStores& value_stores, std::string filename,
  62. const File* builtins)
  63. : value_stores_(&value_stores),
  64. filename_(std::move(filename)),
  65. // Builtins are always the first IR.
  66. cross_reference_irs_({builtins}),
  67. type_blocks_(allocator_),
  68. node_blocks_(allocator_) {
  69. CARBON_CHECK(builtins != nullptr);
  70. CARBON_CHECK(builtins->cross_reference_irs_[0] == builtins)
  71. << "Not called with builtins!";
  72. // Default entry for NodeBlockId::Empty.
  73. node_blocks_.AddDefaultValue();
  74. // Copy builtins over.
  75. nodes_.Reserve(BuiltinKind::ValidCount);
  76. static constexpr auto BuiltinIR = CrossReferenceIRId(0);
  77. for (auto [i, node] : llvm::enumerate(builtins->nodes_.array_ref())) {
  78. // We can reuse builtin type IDs because they're special-cased values.
  79. nodes_.AddInNoBlock(
  80. CrossReference{node.type_id(), BuiltinIR, SemIR::NodeId(i)});
  81. }
  82. }
  83. auto File::Verify() const -> ErrorOr<Success> {
  84. // Invariants don't necessarily hold for invalid IR.
  85. if (has_errors_) {
  86. return Success();
  87. }
  88. // Check that every code block has a terminator sequence that appears at the
  89. // end of the block.
  90. for (const Function& function : functions_.array_ref()) {
  91. for (NodeBlockId block_id : function.body_block_ids) {
  92. TerminatorKind prior_kind = TerminatorKind::NotTerminator;
  93. for (NodeId node_id : node_blocks().Get(block_id)) {
  94. TerminatorKind node_kind =
  95. nodes().Get(node_id).kind().terminator_kind();
  96. if (prior_kind == TerminatorKind::Terminator) {
  97. return Error(llvm::formatv("Node {0} in block {1} follows terminator",
  98. node_id, block_id));
  99. }
  100. if (prior_kind > node_kind) {
  101. return Error(
  102. llvm::formatv("Non-terminator node {0} in block {1} follows "
  103. "terminator sequence",
  104. node_id, block_id));
  105. }
  106. prior_kind = node_kind;
  107. }
  108. if (prior_kind != TerminatorKind::Terminator) {
  109. return Error(llvm::formatv("No terminator in block {0}", block_id));
  110. }
  111. }
  112. }
  113. // TODO: Check that a node only references other nodes that are either global
  114. // or that dominate it.
  115. return Success();
  116. }
  117. auto File::OutputYaml(bool include_builtins) const -> Yaml::OutputMapping {
  118. return Yaml::OutputMapping([this,
  119. include_builtins](Yaml::OutputMapping::Map map) {
  120. map.Add("filename", filename_);
  121. map.Add("sem_ir", Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  122. map.Add("cross_reference_irs_size",
  123. Yaml::OutputScalar(cross_reference_irs_.size()));
  124. map.Add("functions", functions_.OutputYaml());
  125. map.Add("classes", classes_.OutputYaml());
  126. map.Add("types", types_.OutputYaml());
  127. map.Add("type_blocks", type_blocks_.OutputYaml());
  128. map.Add("nodes",
  129. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  130. int start =
  131. include_builtins ? 0 : BuiltinKind::ValidCount;
  132. for (int i : llvm::seq(start, nodes_.size())) {
  133. auto id = NodeId(i);
  134. map.Add(PrintToString(id),
  135. Yaml::OutputScalar(nodes_.Get(id)));
  136. }
  137. }));
  138. map.Add("node_blocks", node_blocks_.OutputYaml());
  139. }));
  140. });
  141. }
  142. // Map a node kind representing a type into an integer describing the
  143. // precedence of that type's syntax. Higher numbers correspond to higher
  144. // precedence.
  145. static auto GetTypePrecedence(NodeKind kind) -> int {
  146. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  147. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  148. switch (kind) {
  149. case ArrayType::Kind:
  150. case Builtin::Kind:
  151. case ClassType::Kind:
  152. case NameReference::Kind:
  153. case StructType::Kind:
  154. case TupleType::Kind:
  155. case UnboundFieldType::Kind:
  156. return 0;
  157. case ConstType::Kind:
  158. return -1;
  159. case PointerType::Kind:
  160. return -2;
  161. case CrossReference::Kind:
  162. // TODO: Once we support stringification of cross-references, we'll need
  163. // to determine the precedence of the target of the cross-reference. For
  164. // now, all cross-references refer to builtin types from the prelude.
  165. return 0;
  166. case AddressOf::Kind:
  167. case ArrayIndex::Kind:
  168. case ArrayInit::Kind:
  169. case Assign::Kind:
  170. case BinaryOperatorAdd::Kind:
  171. case BindName::Kind:
  172. case BindValue::Kind:
  173. case BlockArg::Kind:
  174. case BoolLiteral::Kind:
  175. case Branch::Kind:
  176. case BranchIf::Kind:
  177. case BranchWithArg::Kind:
  178. case Call::Kind:
  179. case ClassDeclaration::Kind:
  180. case ClassFieldAccess::Kind:
  181. case Dereference::Kind:
  182. case Field::Kind:
  183. case FunctionDeclaration::Kind:
  184. case InitializeFrom::Kind:
  185. case IntegerLiteral::Kind:
  186. case Namespace::Kind:
  187. case NoOp::Kind:
  188. case Parameter::Kind:
  189. case RealLiteral::Kind:
  190. case Return::Kind:
  191. case ReturnExpression::Kind:
  192. case SpliceBlock::Kind:
  193. case StringLiteral::Kind:
  194. case StructAccess::Kind:
  195. case StructTypeField::Kind:
  196. case StructLiteral::Kind:
  197. case StructInit::Kind:
  198. case StructValue::Kind:
  199. case Temporary::Kind:
  200. case TemporaryStorage::Kind:
  201. case TupleAccess::Kind:
  202. case TupleIndex::Kind:
  203. case TupleLiteral::Kind:
  204. case TupleInit::Kind:
  205. case TupleValue::Kind:
  206. case UnaryOperatorNot::Kind:
  207. case ValueAsReference::Kind:
  208. case VarStorage::Kind:
  209. CARBON_FATAL() << "GetTypePrecedence for non-type node kind " << kind;
  210. }
  211. }
  212. auto File::StringifyType(TypeId type_id, bool in_type_context) const
  213. -> std::string {
  214. return StringifyTypeExpression(GetTypeAllowBuiltinTypes(type_id),
  215. in_type_context);
  216. }
  217. auto File::StringifyTypeExpression(NodeId outer_node_id,
  218. bool in_type_context) const -> std::string {
  219. std::string str;
  220. llvm::raw_string_ostream out(str);
  221. struct Step {
  222. // The node to print.
  223. NodeId node_id;
  224. // The index into node_id to print. Not used by all types.
  225. int index = 0;
  226. auto Next() const -> Step {
  227. return {.node_id = node_id, .index = index + 1};
  228. }
  229. };
  230. llvm::SmallVector<Step> steps = {{.node_id = outer_node_id}};
  231. while (!steps.empty()) {
  232. auto step = steps.pop_back_val();
  233. if (!step.node_id.is_valid()) {
  234. out << "<invalid type>";
  235. continue;
  236. }
  237. // Builtins have designated labels.
  238. if (step.node_id.index < BuiltinKind::ValidCount) {
  239. out << BuiltinKind::FromInt(step.node_id.index).label();
  240. continue;
  241. }
  242. auto node = nodes().Get(step.node_id);
  243. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  244. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  245. switch (node.kind()) {
  246. case ArrayType::Kind: {
  247. auto array = node.As<ArrayType>();
  248. if (step.index == 0) {
  249. out << "[";
  250. steps.push_back(step.Next());
  251. steps.push_back(
  252. {.node_id = GetTypeAllowBuiltinTypes(array.element_type_id)});
  253. } else if (step.index == 1) {
  254. out << "; " << GetArrayBoundValue(array.bound_id) << "]";
  255. }
  256. break;
  257. }
  258. case ClassType::Kind: {
  259. auto class_name_id =
  260. classes().Get(node.As<ClassType>().class_id).name_id;
  261. out << strings().Get(class_name_id);
  262. break;
  263. }
  264. case ConstType::Kind: {
  265. if (step.index == 0) {
  266. out << "const ";
  267. // Add parentheses if required.
  268. auto inner_type_node_id =
  269. GetTypeAllowBuiltinTypes(node.As<ConstType>().inner_id);
  270. if (GetTypePrecedence(nodes().Get(inner_type_node_id).kind()) <
  271. GetTypePrecedence(node.kind())) {
  272. out << "(";
  273. steps.push_back(step.Next());
  274. }
  275. steps.push_back({.node_id = inner_type_node_id});
  276. } else if (step.index == 1) {
  277. out << ")";
  278. }
  279. break;
  280. }
  281. case NameReference::Kind: {
  282. out << strings().Get(node.As<NameReference>().name_id);
  283. break;
  284. }
  285. case PointerType::Kind: {
  286. if (step.index == 0) {
  287. steps.push_back(step.Next());
  288. steps.push_back({.node_id = GetTypeAllowBuiltinTypes(
  289. node.As<PointerType>().pointee_id)});
  290. } else if (step.index == 1) {
  291. out << "*";
  292. }
  293. break;
  294. }
  295. case StructType::Kind: {
  296. auto refs = node_blocks().Get(node.As<StructType>().fields_id);
  297. if (refs.empty()) {
  298. out << "{}";
  299. break;
  300. } else if (step.index == 0) {
  301. out << "{";
  302. } else if (step.index < static_cast<int>(refs.size())) {
  303. out << ", ";
  304. } else {
  305. out << "}";
  306. break;
  307. }
  308. steps.push_back(step.Next());
  309. steps.push_back({.node_id = refs[step.index]});
  310. break;
  311. }
  312. case StructTypeField::Kind: {
  313. auto field = node.As<StructTypeField>();
  314. out << "." << strings().Get(field.name_id) << ": ";
  315. steps.push_back(
  316. {.node_id = GetTypeAllowBuiltinTypes(field.field_type_id)});
  317. break;
  318. }
  319. case TupleType::Kind: {
  320. auto refs = type_blocks().Get(node.As<TupleType>().elements_id);
  321. if (refs.empty()) {
  322. out << "()";
  323. break;
  324. } else if (step.index == 0) {
  325. out << "(";
  326. } else if (step.index < static_cast<int>(refs.size())) {
  327. out << ", ";
  328. } else {
  329. // A tuple of one element has a comma to disambiguate from an
  330. // expression.
  331. if (step.index == 1) {
  332. out << ",";
  333. }
  334. out << ")";
  335. break;
  336. }
  337. steps.push_back(step.Next());
  338. steps.push_back(
  339. {.node_id = GetTypeAllowBuiltinTypes(refs[step.index])});
  340. break;
  341. }
  342. case UnboundFieldType::Kind: {
  343. if (step.index == 0) {
  344. out << "<unbound field of class ";
  345. steps.push_back(step.Next());
  346. steps.push_back({.node_id = GetTypeAllowBuiltinTypes(
  347. node.As<UnboundFieldType>().class_type_id)});
  348. } else {
  349. out << ">";
  350. }
  351. break;
  352. }
  353. case AddressOf::Kind:
  354. case ArrayIndex::Kind:
  355. case ArrayInit::Kind:
  356. case Assign::Kind:
  357. case BinaryOperatorAdd::Kind:
  358. case BindName::Kind:
  359. case BindValue::Kind:
  360. case BlockArg::Kind:
  361. case BoolLiteral::Kind:
  362. case Branch::Kind:
  363. case BranchIf::Kind:
  364. case BranchWithArg::Kind:
  365. case Builtin::Kind:
  366. case Call::Kind:
  367. case ClassDeclaration::Kind:
  368. case ClassFieldAccess::Kind:
  369. case CrossReference::Kind:
  370. case Dereference::Kind:
  371. case Field::Kind:
  372. case FunctionDeclaration::Kind:
  373. case InitializeFrom::Kind:
  374. case IntegerLiteral::Kind:
  375. case Namespace::Kind:
  376. case NoOp::Kind:
  377. case Parameter::Kind:
  378. case RealLiteral::Kind:
  379. case Return::Kind:
  380. case ReturnExpression::Kind:
  381. case SpliceBlock::Kind:
  382. case StringLiteral::Kind:
  383. case StructAccess::Kind:
  384. case StructLiteral::Kind:
  385. case StructInit::Kind:
  386. case StructValue::Kind:
  387. case Temporary::Kind:
  388. case TemporaryStorage::Kind:
  389. case TupleAccess::Kind:
  390. case TupleIndex::Kind:
  391. case TupleLiteral::Kind:
  392. case TupleInit::Kind:
  393. case TupleValue::Kind:
  394. case UnaryOperatorNot::Kind:
  395. case ValueAsReference::Kind:
  396. case VarStorage::Kind:
  397. // We don't need to handle stringification for nodes that don't show up
  398. // in errors, but make it clear what's going on so that it's clearer
  399. // when stringification is needed.
  400. out << "<cannot stringify " << step.node_id << ">";
  401. break;
  402. }
  403. }
  404. // For `{}` or any tuple type, we've printed a non-type expression, so add a
  405. // conversion to type `type` if it's not implied by the context.
  406. if (!in_type_context) {
  407. auto outer_node = nodes().Get(outer_node_id);
  408. if (outer_node.Is<TupleType>() ||
  409. (outer_node.Is<StructType>() &&
  410. node_blocks().Get(outer_node.As<StructType>().fields_id).empty())) {
  411. out << " as type";
  412. }
  413. }
  414. return str;
  415. }
  416. auto GetExpressionCategory(const File& file, NodeId node_id)
  417. -> ExpressionCategory {
  418. const File* ir = &file;
  419. // The overall expression category if the current node is a value expression.
  420. ExpressionCategory value_category = ExpressionCategory::Value;
  421. while (true) {
  422. auto node = ir->nodes().Get(node_id);
  423. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  424. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  425. switch (node.kind()) {
  426. case Assign::Kind:
  427. case Branch::Kind:
  428. case BranchIf::Kind:
  429. case BranchWithArg::Kind:
  430. case ClassDeclaration::Kind:
  431. case Field::Kind:
  432. case FunctionDeclaration::Kind:
  433. case Namespace::Kind:
  434. case NoOp::Kind:
  435. case Return::Kind:
  436. case ReturnExpression::Kind:
  437. case StructTypeField::Kind:
  438. return ExpressionCategory::NotExpression;
  439. case CrossReference::Kind: {
  440. auto xref = node.As<CrossReference>();
  441. ir = &ir->GetCrossReferenceIR(xref.ir_id);
  442. node_id = xref.node_id;
  443. continue;
  444. }
  445. case NameReference::Kind: {
  446. node_id = node.As<NameReference>().value_id;
  447. continue;
  448. }
  449. case AddressOf::Kind:
  450. case ArrayType::Kind:
  451. case BinaryOperatorAdd::Kind:
  452. case BindValue::Kind:
  453. case BlockArg::Kind:
  454. case BoolLiteral::Kind:
  455. case ClassType::Kind:
  456. case ConstType::Kind:
  457. case IntegerLiteral::Kind:
  458. case Parameter::Kind:
  459. case PointerType::Kind:
  460. case RealLiteral::Kind:
  461. case StringLiteral::Kind:
  462. case StructValue::Kind:
  463. case StructType::Kind:
  464. case TupleValue::Kind:
  465. case TupleType::Kind:
  466. case UnaryOperatorNot::Kind:
  467. case UnboundFieldType::Kind:
  468. return value_category;
  469. case Builtin::Kind: {
  470. if (node.As<Builtin>().builtin_kind == BuiltinKind::Error) {
  471. return ExpressionCategory::Error;
  472. }
  473. return value_category;
  474. }
  475. case BindName::Kind: {
  476. node_id = node.As<BindName>().value_id;
  477. continue;
  478. }
  479. case ArrayIndex::Kind: {
  480. node_id = node.As<ArrayIndex>().array_id;
  481. continue;
  482. }
  483. case ClassFieldAccess::Kind: {
  484. node_id = node.As<ClassFieldAccess>().base_id;
  485. // A value of class type is a pointer to an object representation.
  486. // Therefore, if the base is a value, the result is an ephemeral
  487. // reference.
  488. value_category = ExpressionCategory::EphemeralReference;
  489. continue;
  490. }
  491. case StructAccess::Kind: {
  492. node_id = node.As<StructAccess>().struct_id;
  493. continue;
  494. }
  495. case TupleAccess::Kind: {
  496. node_id = node.As<TupleAccess>().tuple_id;
  497. continue;
  498. }
  499. case TupleIndex::Kind: {
  500. node_id = node.As<TupleIndex>().tuple_id;
  501. continue;
  502. }
  503. case SpliceBlock::Kind: {
  504. node_id = node.As<SpliceBlock>().result_id;
  505. continue;
  506. }
  507. case StructLiteral::Kind:
  508. case TupleLiteral::Kind:
  509. return ExpressionCategory::Mixed;
  510. case ArrayInit::Kind:
  511. case Call::Kind:
  512. case InitializeFrom::Kind:
  513. case StructInit::Kind:
  514. case TupleInit::Kind:
  515. return ExpressionCategory::Initializing;
  516. case Dereference::Kind:
  517. case VarStorage::Kind:
  518. return ExpressionCategory::DurableReference;
  519. case Temporary::Kind:
  520. case TemporaryStorage::Kind:
  521. case ValueAsReference::Kind:
  522. return ExpressionCategory::EphemeralReference;
  523. }
  524. }
  525. }
  526. auto GetInitializingRepresentation(const File& file, TypeId type_id)
  527. -> InitializingRepresentation {
  528. auto value_rep = GetValueRepresentation(file, type_id);
  529. switch (value_rep.kind) {
  530. case ValueRepresentation::None:
  531. return {.kind = InitializingRepresentation::None};
  532. case ValueRepresentation::Copy:
  533. // TODO: Use in-place initialization for types that have non-trivial
  534. // destructive move.
  535. return {.kind = InitializingRepresentation::ByCopy};
  536. case ValueRepresentation::Pointer:
  537. case ValueRepresentation::Custom:
  538. return {.kind = InitializingRepresentation::InPlace};
  539. case ValueRepresentation::Unknown:
  540. CARBON_FATAL()
  541. << "Attempting to perform initialization of incomplete type";
  542. }
  543. }
  544. } // namespace Carbon::SemIR