handle.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 "llvm/ADT/STLExtras.h"
  5. #include "llvm/ADT/Sequence.h"
  6. #include "toolchain/lower/function_context.h"
  7. #include "toolchain/sem_ir/node.h"
  8. #include "toolchain/sem_ir/node_kind.h"
  9. namespace Carbon::Lower {
  10. auto HandleCrossReference(FunctionContext& /*context*/,
  11. SemIR::NodeId /*node_id*/, SemIR::CrossReference node)
  12. -> void {
  13. CARBON_FATAL() << "TODO: Add support: " << node;
  14. }
  15. auto HandleAddressOf(FunctionContext& context, SemIR::NodeId node_id,
  16. SemIR::AddressOf node) -> void {
  17. context.SetLocal(node_id, context.GetLocal(node.lvalue_id));
  18. }
  19. auto HandleArrayIndex(FunctionContext& context, SemIR::NodeId node_id,
  20. SemIR::ArrayIndex node) -> void {
  21. auto* array_value = context.GetLocal(node.array_id);
  22. auto* llvm_type =
  23. context.GetType(context.semantics_ir().GetNode(node.array_id).type_id());
  24. llvm::Value* indexes[2] = {
  25. llvm::ConstantInt::get(llvm::Type::getInt32Ty(context.llvm_context()), 0),
  26. context.GetLocal(node.index_id)};
  27. context.SetLocal(node_id,
  28. context.builder().CreateInBoundsGEP(llvm_type, array_value,
  29. indexes, "array.index"));
  30. }
  31. auto HandleArrayInit(FunctionContext& context, SemIR::NodeId node_id,
  32. SemIR::ArrayInit node) -> void {
  33. // The result of initialization is the return slot of the initializer.
  34. context.SetLocal(
  35. node_id, context.GetLocal(context.semantics_ir()
  36. .GetNodeBlock(node.inits_and_return_slot_id)
  37. .back()));
  38. }
  39. auto HandleAssign(FunctionContext& context, SemIR::NodeId /*node_id*/,
  40. SemIR::Assign node) -> void {
  41. auto storage_type_id = context.semantics_ir().GetNode(node.lhs_id).type_id();
  42. context.FinishInitialization(storage_type_id, node.lhs_id, node.rhs_id);
  43. }
  44. auto HandleBinaryOperatorAdd(FunctionContext& /*context*/,
  45. SemIR::NodeId /*node_id*/,
  46. SemIR::BinaryOperatorAdd node) -> void {
  47. CARBON_FATAL() << "TODO: Add support: " << node;
  48. }
  49. auto HandleBindName(FunctionContext& context, SemIR::NodeId node_id,
  50. SemIR::BindName node) -> void {
  51. context.SetLocal(node_id, context.GetLocal(node.value_id));
  52. }
  53. auto HandleBlockArg(FunctionContext& context, SemIR::NodeId node_id,
  54. SemIR::BlockArg node) -> void {
  55. context.SetLocal(node_id, context.GetBlockArg(node.block_id, node.type_id));
  56. }
  57. auto HandleBoolLiteral(FunctionContext& context, SemIR::NodeId node_id,
  58. SemIR::BoolLiteral node) -> void {
  59. llvm::Value* v =
  60. llvm::ConstantInt::get(context.builder().getInt1Ty(), node.value.index);
  61. context.SetLocal(node_id, v);
  62. }
  63. auto HandleBranch(FunctionContext& context, SemIR::NodeId /*node_id*/,
  64. SemIR::Branch node) -> void {
  65. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  66. // TODO: Don't do this if it would remove a loop preheader block.
  67. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  68. if (block->empty() && context.TryToReuseBlock(node.target_id, block)) {
  69. // Reuse this block as the branch target.
  70. } else {
  71. context.builder().CreateBr(context.GetBlock(node.target_id));
  72. }
  73. context.builder().ClearInsertionPoint();
  74. }
  75. auto HandleBranchIf(FunctionContext& context, SemIR::NodeId /*node_id*/,
  76. SemIR::BranchIf node) -> void {
  77. llvm::Value* cond = context.GetLocal(node.cond_id);
  78. llvm::BasicBlock* then_block = context.GetBlock(node.target_id);
  79. llvm::BasicBlock* else_block = context.CreateSyntheticBlock();
  80. context.builder().CreateCondBr(cond, then_block, else_block);
  81. context.builder().SetInsertPoint(else_block);
  82. }
  83. auto HandleBranchWithArg(FunctionContext& context, SemIR::NodeId /*node_id*/,
  84. SemIR::BranchWithArg node) -> void {
  85. llvm::Value* arg = context.GetLocal(node.arg_id);
  86. SemIR::TypeId arg_type_id =
  87. context.semantics_ir().GetNode(node.arg_id).type_id();
  88. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  89. // We only do this for a block that we know will only have a single
  90. // predecessor, so that we can correctly populate the predecessors of the
  91. // PHINode.
  92. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  93. llvm::BasicBlock* phi_predecessor = block;
  94. if (block->empty() && context.IsCurrentSyntheticBlock(block) &&
  95. context.TryToReuseBlock(node.target_id, block)) {
  96. // Reuse this block as the branch target.
  97. phi_predecessor = block->getSinglePredecessor();
  98. CARBON_CHECK(phi_predecessor)
  99. << "Synthetic block did not have a single predecessor";
  100. } else {
  101. context.builder().CreateBr(context.GetBlock(node.target_id));
  102. }
  103. context.GetBlockArg(node.target_id, arg_type_id)
  104. ->addIncoming(arg, phi_predecessor);
  105. context.builder().ClearInsertionPoint();
  106. }
  107. auto HandleBuiltin(FunctionContext& /*context*/, SemIR::NodeId /*node_id*/,
  108. SemIR::Builtin node) -> void {
  109. CARBON_FATAL() << "TODO: Add support: " << node;
  110. }
  111. auto HandleCall(FunctionContext& context, SemIR::NodeId node_id,
  112. SemIR::Call node) -> void {
  113. auto* llvm_function = context.GetFunction(node.function_id);
  114. const auto& function = context.semantics_ir().GetFunction(node.function_id);
  115. std::vector<llvm::Value*> args;
  116. llvm::ArrayRef<SemIR::NodeId> arg_ids =
  117. context.semantics_ir().GetNodeBlock(node.args_id);
  118. if (function.return_slot_id.is_valid()) {
  119. args.push_back(context.GetLocal(arg_ids.back()));
  120. arg_ids = arg_ids.drop_back();
  121. }
  122. for (auto arg_id : arg_ids) {
  123. auto arg_type_id = context.semantics_ir().GetNode(arg_id).type_id();
  124. if (SemIR::GetValueRepresentation(context.semantics_ir(), arg_type_id)
  125. .kind != SemIR::ValueRepresentation::None) {
  126. args.push_back(context.GetLocal(arg_id));
  127. }
  128. }
  129. if (llvm_function->getReturnType()->isVoidTy()) {
  130. context.builder().CreateCall(llvm_function, args);
  131. // The value of a function call with a void return type shouldn't used, but
  132. // StubReference needs a value to propagate.
  133. // TODO: Remove this now the StubReferences are gone.
  134. context.SetLocal(node_id,
  135. llvm::PoisonValue::get(context.GetType(node.type_id)));
  136. } else {
  137. context.SetLocal(node_id,
  138. context.builder().CreateCall(llvm_function, args,
  139. llvm_function->getName()));
  140. }
  141. }
  142. auto HandleClassDeclaration(FunctionContext& /*context*/,
  143. SemIR::NodeId /*node_id*/,
  144. SemIR::ClassDeclaration /*node*/) -> void {
  145. // No action to perform.
  146. }
  147. auto HandleDereference(FunctionContext& context, SemIR::NodeId node_id,
  148. SemIR::Dereference node) -> void {
  149. context.SetLocal(node_id, context.GetLocal(node.pointer_id));
  150. }
  151. auto HandleFunctionDeclaration(FunctionContext& /*context*/,
  152. SemIR::NodeId /*node_id*/,
  153. SemIR::FunctionDeclaration node) -> void {
  154. CARBON_FATAL()
  155. << "Should not be encountered. If that changes, we may want to change "
  156. "higher-level logic to skip them rather than calling this. "
  157. << node;
  158. }
  159. auto HandleInitializeFrom(FunctionContext& context, SemIR::NodeId /*node_id*/,
  160. SemIR::InitializeFrom node) -> void {
  161. auto storage_type_id = context.semantics_ir().GetNode(node.dest_id).type_id();
  162. context.FinishInitialization(storage_type_id, node.dest_id, node.src_id);
  163. }
  164. auto HandleIntegerLiteral(FunctionContext& context, SemIR::NodeId node_id,
  165. SemIR::IntegerLiteral node) -> void {
  166. const llvm::APInt& i = context.semantics_ir().GetInteger(node.integer_id);
  167. // TODO: This won't offer correct semantics, but seems close enough for now.
  168. llvm::Value* v =
  169. llvm::ConstantInt::get(context.builder().getInt32Ty(), i.getZExtValue());
  170. context.SetLocal(node_id, v);
  171. }
  172. auto HandleNameReference(FunctionContext& context, SemIR::NodeId node_id,
  173. SemIR::NameReference node) -> void {
  174. auto type_node_id =
  175. context.semantics_ir().GetTypeAllowBuiltinTypes(node.type_id);
  176. if (type_node_id == SemIR::NodeId::BuiltinFunctionType ||
  177. type_node_id == SemIR::NodeId::BuiltinNamespaceType) {
  178. return;
  179. }
  180. // TODO: Handle name references to globals
  181. context.SetLocal(node_id, context.GetLocal(node.value_id));
  182. }
  183. auto HandleNamespace(FunctionContext& /*context*/, SemIR::NodeId /*node_id*/,
  184. SemIR::Namespace node) -> void {
  185. CARBON_FATAL()
  186. << "Should not be encountered. If that changes, we may want to change "
  187. "higher-level logic to skip them rather than calling this. "
  188. << node;
  189. }
  190. auto HandleNoOp(FunctionContext& /*context*/, SemIR::NodeId /*node_id*/,
  191. SemIR::NoOp /*node*/) -> void {
  192. // No action to take.
  193. }
  194. auto HandleParameter(FunctionContext& /*context*/, SemIR::NodeId /*node_id*/,
  195. SemIR::Parameter /*node*/) -> void {
  196. CARBON_FATAL() << "Parameters should be lowered by `BuildFunctionDefinition`";
  197. }
  198. auto HandleRealLiteral(FunctionContext& context, SemIR::NodeId node_id,
  199. SemIR::RealLiteral node) -> void {
  200. const SemIR::Real& real = context.semantics_ir().GetReal(node.real_id);
  201. // TODO: This will probably have overflow issues, and should be fixed.
  202. double val =
  203. real.mantissa.getZExtValue() *
  204. std::pow((real.is_decimal ? 10 : 2), real.exponent.getSExtValue());
  205. llvm::APFloat llvm_val(val);
  206. context.SetLocal(node_id, llvm::ConstantFP::get(
  207. context.builder().getDoubleTy(), llvm_val));
  208. }
  209. auto HandleReturn(FunctionContext& context, SemIR::NodeId /*node_id*/,
  210. SemIR::Return /*node*/) -> void {
  211. context.builder().CreateRetVoid();
  212. }
  213. auto HandleReturnExpression(FunctionContext& context, SemIR::NodeId /*node_id*/,
  214. SemIR::ReturnExpression node) -> void {
  215. switch (SemIR::GetInitializingRepresentation(
  216. context.semantics_ir(),
  217. context.semantics_ir().GetNode(node.expr_id).type_id())
  218. .kind) {
  219. case SemIR::InitializingRepresentation::None:
  220. case SemIR::InitializingRepresentation::InPlace:
  221. // Nothing to return.
  222. context.builder().CreateRetVoid();
  223. return;
  224. case SemIR::InitializingRepresentation::ByCopy:
  225. // The expression produces the value representation for the type.
  226. context.builder().CreateRet(context.GetLocal(node.expr_id));
  227. return;
  228. }
  229. }
  230. auto HandleSpliceBlock(FunctionContext& context, SemIR::NodeId node_id,
  231. SemIR::SpliceBlock node) -> void {
  232. context.LowerBlock(node.block_id);
  233. context.SetLocal(node_id, context.GetLocal(node.result_id));
  234. }
  235. auto HandleStringLiteral(FunctionContext& /*context*/,
  236. SemIR::NodeId /*node_id*/, SemIR::StringLiteral node)
  237. -> void {
  238. CARBON_FATAL() << "TODO: Add support: " << node;
  239. }
  240. // Extracts an element of either a struct or a tuple by index. Depending on the
  241. // expression category of the aggregate input, this will either produce a value
  242. // or a reference.
  243. static auto GetStructOrTupleElement(FunctionContext& context,
  244. SemIR::NodeId aggr_node_id, unsigned idx,
  245. SemIR::TypeId result_type_id,
  246. llvm::Twine name) -> llvm::Value* {
  247. auto aggr_node = context.semantics_ir().GetNode(aggr_node_id);
  248. auto* aggr_value = context.GetLocal(aggr_node_id);
  249. auto aggr_cat =
  250. SemIR::GetExpressionCategory(context.semantics_ir(), aggr_node_id);
  251. if (aggr_cat == SemIR::ExpressionCategory::Value &&
  252. SemIR::GetValueRepresentation(context.semantics_ir(), aggr_node.type_id())
  253. .kind == SemIR::ValueRepresentation::Copy) {
  254. // We are holding the values of the aggregate directly, elementwise.
  255. return context.builder().CreateExtractValue(aggr_value, idx, name);
  256. }
  257. // Either we're accessing an element of a reference and producing a reference,
  258. // or we're accessing an element of a value that is held by pointer and we're
  259. // producing a value.
  260. auto* aggr_type = context.GetType(aggr_node.type_id());
  261. auto* elem_ptr =
  262. context.builder().CreateStructGEP(aggr_type, aggr_value, idx, name);
  263. // If this is a value access, load the element if necessary.
  264. if (aggr_cat == SemIR::ExpressionCategory::Value) {
  265. switch (
  266. SemIR::GetValueRepresentation(context.semantics_ir(), result_type_id)
  267. .kind) {
  268. case SemIR::ValueRepresentation::None:
  269. return llvm::PoisonValue::get(context.GetType(result_type_id));
  270. case SemIR::ValueRepresentation::Copy:
  271. return context.builder().CreateLoad(context.GetType(result_type_id),
  272. elem_ptr, name + ".load");
  273. case SemIR::ValueRepresentation::Pointer:
  274. return elem_ptr;
  275. case SemIR::ValueRepresentation::Custom:
  276. CARBON_FATAL() << "TODO: Add support for custom value representation";
  277. }
  278. }
  279. return elem_ptr;
  280. }
  281. auto HandleStructAccess(FunctionContext& context, SemIR::NodeId node_id,
  282. SemIR::StructAccess node) -> void {
  283. auto struct_type_id =
  284. context.semantics_ir().GetNode(node.struct_id).type_id();
  285. // Get type information for member names.
  286. auto fields = context.semantics_ir().GetNodeBlock(
  287. context.semantics_ir()
  288. .GetNodeAs<SemIR::StructType>(
  289. context.semantics_ir().GetType(struct_type_id))
  290. .fields_id);
  291. auto field = context.semantics_ir().GetNodeAs<SemIR::StructTypeField>(
  292. fields[node.index.index]);
  293. auto member_name = context.semantics_ir().GetString(field.name_id);
  294. context.SetLocal(node_id, GetStructOrTupleElement(context, node.struct_id,
  295. node.index.index,
  296. node.type_id, member_name));
  297. }
  298. auto HandleStructLiteral(FunctionContext& context, SemIR::NodeId node_id,
  299. SemIR::StructLiteral node) -> void {
  300. // A StructLiteral should always be converted to a StructInit or StructValue
  301. // if its value is needed.
  302. context.SetLocal(node_id,
  303. llvm::PoisonValue::get(context.GetType(node.type_id)));
  304. }
  305. // Emits the value representation for a struct or tuple whose elements are the
  306. // contents of `refs_id`.
  307. auto EmitStructOrTupleValueRepresentation(FunctionContext& context,
  308. SemIR::TypeId type_id,
  309. SemIR::NodeBlockId refs_id,
  310. llvm::Twine name) -> llvm::Value* {
  311. auto* llvm_type = context.GetType(type_id);
  312. switch (SemIR::GetValueRepresentation(context.semantics_ir(), type_id).kind) {
  313. case SemIR::ValueRepresentation::None:
  314. // TODO: Add a helper to get a "no value representation" value.
  315. return llvm::PoisonValue::get(llvm_type);
  316. case SemIR::ValueRepresentation::Copy: {
  317. auto refs = context.semantics_ir().GetNodeBlock(refs_id);
  318. CARBON_CHECK(refs.size() == 1)
  319. << "Unexpected size for aggregate with by-copy value representation";
  320. // TODO: Remove the LLVM StructType wrapper in this case, so we don't
  321. // need this `insert_value` wrapping.
  322. return context.builder().CreateInsertValue(
  323. llvm::PoisonValue::get(llvm_type), context.GetLocal(refs[0]), {0});
  324. }
  325. case SemIR::ValueRepresentation::Pointer: {
  326. // Write the object representation to a local alloca so we can produce a
  327. // pointer to it as the value representation.
  328. auto* alloca = context.builder().CreateAlloca(
  329. llvm_type, /*ArraySize=*/nullptr, name);
  330. for (auto [i, ref] :
  331. llvm::enumerate(context.semantics_ir().GetNodeBlock(refs_id))) {
  332. auto* gep = context.builder().CreateStructGEP(llvm_type, alloca, i);
  333. // TODO: We are loading a value representation here and storing an
  334. // object representation!
  335. context.builder().CreateStore(context.GetLocal(ref), gep);
  336. }
  337. return alloca;
  338. }
  339. case SemIR::ValueRepresentation::Custom:
  340. CARBON_FATAL()
  341. << "Aggregate should never have custom value representation";
  342. }
  343. }
  344. auto HandleStructInit(FunctionContext& context, SemIR::NodeId node_id,
  345. SemIR::StructInit node) -> void {
  346. auto* llvm_type = context.GetType(node.type_id);
  347. switch (
  348. SemIR::GetInitializingRepresentation(context.semantics_ir(), node.type_id)
  349. .kind) {
  350. case SemIR::InitializingRepresentation::None:
  351. case SemIR::InitializingRepresentation::InPlace:
  352. // TODO: Add a helper to poison a value slot.
  353. context.SetLocal(node_id, llvm::PoisonValue::get(llvm_type));
  354. break;
  355. case SemIR::InitializingRepresentation::ByCopy: {
  356. context.SetLocal(
  357. node_id, EmitStructOrTupleValueRepresentation(
  358. context, node.type_id, node.elements_id, "struct.init"));
  359. break;
  360. }
  361. }
  362. }
  363. auto HandleStructValue(FunctionContext& context, SemIR::NodeId node_id,
  364. SemIR::StructValue node) -> void {
  365. context.SetLocal(node_id,
  366. EmitStructOrTupleValueRepresentation(
  367. context, node.type_id, node.elements_id, "struct"));
  368. }
  369. auto HandleStructTypeField(FunctionContext& /*context*/,
  370. SemIR::NodeId /*node_id*/,
  371. SemIR::StructTypeField /*node*/) -> void {
  372. // No action to take.
  373. }
  374. auto HandleTupleAccess(FunctionContext& context, SemIR::NodeId node_id,
  375. SemIR::TupleAccess node) -> void {
  376. context.SetLocal(
  377. node_id, GetStructOrTupleElement(context, node.tuple_id, node.index.index,
  378. node.type_id, "tuple.elem"));
  379. }
  380. auto HandleTupleIndex(FunctionContext& context, SemIR::NodeId node_id,
  381. SemIR::TupleIndex node) -> void {
  382. auto index_node =
  383. context.semantics_ir().GetNodeAs<SemIR::IntegerLiteral>(node.index_id);
  384. auto index =
  385. context.semantics_ir().GetInteger(index_node.integer_id).getZExtValue();
  386. context.SetLocal(node_id,
  387. GetStructOrTupleElement(context, node.tuple_id, index,
  388. node.type_id, "tuple.index"));
  389. }
  390. auto HandleTupleLiteral(FunctionContext& context, SemIR::NodeId node_id,
  391. SemIR::TupleLiteral node) -> void {
  392. // A TupleLiteral should always be converted to a TupleInit or TupleValue if
  393. // its value is needed.
  394. context.SetLocal(node_id,
  395. llvm::PoisonValue::get(context.GetType(node.type_id)));
  396. }
  397. auto HandleTupleInit(FunctionContext& context, SemIR::NodeId node_id,
  398. SemIR::TupleInit node) -> void {
  399. auto* llvm_type = context.GetType(node.type_id);
  400. switch (
  401. SemIR::GetInitializingRepresentation(context.semantics_ir(), node.type_id)
  402. .kind) {
  403. case SemIR::InitializingRepresentation::None:
  404. case SemIR::InitializingRepresentation::InPlace:
  405. // TODO: Add a helper to poison a value slot.
  406. context.SetLocal(node_id, llvm::PoisonValue::get(llvm_type));
  407. break;
  408. case SemIR::InitializingRepresentation::ByCopy: {
  409. context.SetLocal(
  410. node_id, EmitStructOrTupleValueRepresentation(
  411. context, node.type_id, node.elements_id, "tuple.init"));
  412. break;
  413. }
  414. }
  415. }
  416. auto HandleTupleValue(FunctionContext& context, SemIR::NodeId node_id,
  417. SemIR::TupleValue node) -> void {
  418. context.SetLocal(
  419. node_id, EmitStructOrTupleValueRepresentation(context, node.type_id,
  420. node.elements_id, "tuple"));
  421. }
  422. auto HandleUnaryOperatorNot(FunctionContext& context, SemIR::NodeId node_id,
  423. SemIR::UnaryOperatorNot node) -> void {
  424. context.SetLocal(
  425. node_id, context.builder().CreateNot(context.GetLocal(node.operand_id)));
  426. }
  427. auto HandleVarStorage(FunctionContext& context, SemIR::NodeId node_id,
  428. SemIR::VarStorage node) -> void {
  429. // TODO: Eventually this name will be optional, and we'll want to provide
  430. // something like `var` as a default. However, that's not possible right now
  431. // so cannot be tested.
  432. auto name = context.semantics_ir().GetString(node.name_id);
  433. auto* alloca = context.builder().CreateAlloca(context.GetType(node.type_id),
  434. /*ArraySize=*/nullptr, name);
  435. context.SetLocal(node_id, alloca);
  436. }
  437. } // namespace Carbon::Lower