handle.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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/APFloat.h"
  5. #include "llvm/ADT/APInt.h"
  6. #include "llvm/ADT/ArrayRef.h"
  7. #include "llvm/IR/BasicBlock.h"
  8. #include "llvm/IR/Constants.h"
  9. #include "llvm/IR/Type.h"
  10. #include "llvm/IR/Value.h"
  11. #include "llvm/Support/Casting.h"
  12. #include "toolchain/lower/function_context.h"
  13. #include "toolchain/sem_ir/builtin_function_kind.h"
  14. #include "toolchain/sem_ir/function.h"
  15. #include "toolchain/sem_ir/inst.h"
  16. #include "toolchain/sem_ir/typed_insts.h"
  17. namespace Carbon::Lower {
  18. template <typename InstT>
  19. static auto FatalErrorIfEncountered(InstT inst) -> void {
  20. CARBON_FATAL()
  21. << "Encountered an instruction that isn't expected to lower. It's "
  22. "possible that logic needs to be changed in order to stop "
  23. "showing this instruction in lowered contexts. Instruction: "
  24. << inst;
  25. }
  26. auto HandleAddrOf(FunctionContext& context, SemIR::InstId inst_id,
  27. SemIR::AddrOf inst) -> void {
  28. context.SetLocal(inst_id, context.GetValue(inst.lvalue_id));
  29. }
  30. auto HandleAddrPattern(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  31. SemIR::AddrPattern /*inst*/) -> void {
  32. CARBON_FATAL() << "`addr` should be lowered by `BuildFunctionDefinition`";
  33. }
  34. auto HandleArrayIndex(FunctionContext& context, SemIR::InstId inst_id,
  35. SemIR::ArrayIndex inst) -> void {
  36. auto* array_value = context.GetValue(inst.array_id);
  37. auto* llvm_type =
  38. context.GetType(context.sem_ir().insts().Get(inst.array_id).type_id());
  39. llvm::Value* indexes[2] = {
  40. llvm::ConstantInt::get(llvm::Type::getInt32Ty(context.llvm_context()), 0),
  41. context.GetValue(inst.index_id)};
  42. context.SetLocal(inst_id,
  43. context.builder().CreateInBoundsGEP(llvm_type, array_value,
  44. indexes, "array.index"));
  45. }
  46. auto HandleArrayInit(FunctionContext& context, SemIR::InstId inst_id,
  47. SemIR::ArrayInit inst) -> void {
  48. // The result of initialization is the return slot of the initializer.
  49. context.SetLocal(inst_id, context.GetValue(inst.dest_id));
  50. }
  51. auto HandleAssign(FunctionContext& context, SemIR::InstId /*inst_id*/,
  52. SemIR::Assign inst) -> void {
  53. auto storage_type_id = context.sem_ir().insts().Get(inst.lhs_id).type_id();
  54. context.FinishInit(storage_type_id, inst.lhs_id, inst.rhs_id);
  55. }
  56. auto HandleAssociatedConstantDecl(FunctionContext& /*context*/,
  57. SemIR::InstId /*inst_id*/,
  58. SemIR::AssociatedConstantDecl inst) -> void {
  59. FatalErrorIfEncountered(inst);
  60. }
  61. auto HandleAssociatedEntity(FunctionContext& /*context*/,
  62. SemIR::InstId /*inst_id*/,
  63. SemIR::AssociatedEntity inst) -> void {
  64. FatalErrorIfEncountered(inst);
  65. }
  66. auto HandleBindAlias(FunctionContext& context, SemIR::InstId inst_id,
  67. SemIR::BindAlias inst) -> void {
  68. auto type_inst_id = context.sem_ir().types().GetInstId(inst.type_id);
  69. if (type_inst_id == SemIR::InstId::BuiltinNamespaceType) {
  70. return;
  71. }
  72. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  73. }
  74. auto HandleBindName(FunctionContext& context, SemIR::InstId inst_id,
  75. SemIR::BindName inst) -> void {
  76. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  77. }
  78. auto HandleBindSymbolicName(FunctionContext& context, SemIR::InstId inst_id,
  79. SemIR::BindSymbolicName inst) -> void {
  80. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  81. }
  82. auto HandleBlockArg(FunctionContext& context, SemIR::InstId inst_id,
  83. SemIR::BlockArg inst) -> void {
  84. context.SetLocal(inst_id, context.GetBlockArg(inst.block_id, inst.type_id));
  85. }
  86. auto HandleBoolLiteral(FunctionContext& context, SemIR::InstId inst_id,
  87. SemIR::BoolLiteral inst) -> void {
  88. llvm::Value* v =
  89. llvm::ConstantInt::get(context.builder().getInt1Ty(), inst.value.index);
  90. context.SetLocal(inst_id, v);
  91. }
  92. auto HandleBoundMethod(FunctionContext& context, SemIR::InstId inst_id,
  93. SemIR::BoundMethod inst) -> void {
  94. // Propagate just the function; the object is separately provided to the
  95. // enclosing call as an implicit argument.
  96. context.SetLocal(inst_id, context.GetValue(inst.function_id));
  97. }
  98. auto HandleBranch(FunctionContext& context, SemIR::InstId /*inst_id*/,
  99. SemIR::Branch inst) -> void {
  100. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  101. // TODO: Don't do this if it would remove a loop preheader block.
  102. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  103. if (block->empty() && context.TryToReuseBlock(inst.target_id, block)) {
  104. // Reuse this block as the branch target.
  105. } else {
  106. context.builder().CreateBr(context.GetBlock(inst.target_id));
  107. }
  108. context.builder().ClearInsertionPoint();
  109. }
  110. auto HandleBranchIf(FunctionContext& context, SemIR::InstId /*inst_id*/,
  111. SemIR::BranchIf inst) -> void {
  112. llvm::Value* cond = context.GetValue(inst.cond_id);
  113. llvm::BasicBlock* then_block = context.GetBlock(inst.target_id);
  114. llvm::BasicBlock* else_block = context.MakeSyntheticBlock();
  115. context.builder().CreateCondBr(cond, then_block, else_block);
  116. context.builder().SetInsertPoint(else_block);
  117. }
  118. auto HandleBranchWithArg(FunctionContext& context, SemIR::InstId /*inst_id*/,
  119. SemIR::BranchWithArg inst) -> void {
  120. llvm::Value* arg = context.GetValue(inst.arg_id);
  121. SemIR::TypeId arg_type_id =
  122. context.sem_ir().insts().Get(inst.arg_id).type_id();
  123. // Opportunistically avoid creating a BasicBlock that contains just a branch.
  124. // We only do this for a block that we know will only have a single
  125. // predecessor, so that we can correctly populate the predecessors of the
  126. // PHINode.
  127. llvm::BasicBlock* block = context.builder().GetInsertBlock();
  128. llvm::BasicBlock* phi_predecessor = block;
  129. if (block->empty() && context.IsCurrentSyntheticBlock(block) &&
  130. context.TryToReuseBlock(inst.target_id, block)) {
  131. // Reuse this block as the branch target.
  132. phi_predecessor = block->getSinglePredecessor();
  133. CARBON_CHECK(phi_predecessor)
  134. << "Synthetic block did not have a single predecessor";
  135. } else {
  136. context.builder().CreateBr(context.GetBlock(inst.target_id));
  137. }
  138. context.GetBlockArg(inst.target_id, arg_type_id)
  139. ->addIncoming(arg, phi_predecessor);
  140. context.builder().ClearInsertionPoint();
  141. }
  142. auto HandleBuiltin(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  143. SemIR::Builtin inst) -> void {
  144. CARBON_FATAL() << "TODO: Add support: " << inst;
  145. }
  146. // Handles a call to a builtin function.
  147. static auto HandleBuiltinCall(FunctionContext& context, SemIR::InstId inst_id,
  148. SemIR::BuiltinFunctionKind builtin_kind,
  149. llvm::ArrayRef<SemIR::InstId> arg_ids) -> void {
  150. // TODO: Consider setting this to true in the performance build mode if the
  151. // result type is a signed integer type.
  152. constexpr bool SignedOverflowIsUB = false;
  153. switch (builtin_kind) {
  154. case SemIR::BuiltinFunctionKind::None:
  155. CARBON_FATAL() << "No callee in function call.";
  156. case SemIR::BuiltinFunctionKind::IntNegate: {
  157. // Lower `-x` as `0 - x`.
  158. auto* operand = context.GetValue(arg_ids[0]);
  159. context.SetLocal(inst_id,
  160. context.builder().CreateSub(
  161. llvm::ConstantInt::getNullValue(operand->getType()),
  162. operand, "neg",
  163. /*HasNUW=*/false,
  164. /*HasNSW=*/SignedOverflowIsUB));
  165. return;
  166. }
  167. case SemIR::BuiltinFunctionKind::IntAdd: {
  168. context.SetLocal(inst_id, context.builder().CreateAdd(
  169. context.GetValue(arg_ids[0]),
  170. context.GetValue(arg_ids[1]), "add",
  171. /*HasNUW=*/false,
  172. /*HasNSW=*/SignedOverflowIsUB));
  173. return;
  174. }
  175. case SemIR::BuiltinFunctionKind::IntSub: {
  176. context.SetLocal(inst_id, context.builder().CreateSub(
  177. context.GetValue(arg_ids[0]),
  178. context.GetValue(arg_ids[1]), "sub",
  179. /*HasNUW=*/false,
  180. /*HasNSW=*/SignedOverflowIsUB));
  181. return;
  182. }
  183. case SemIR::BuiltinFunctionKind::IntMul: {
  184. context.SetLocal(inst_id, context.builder().CreateMul(
  185. context.GetValue(arg_ids[0]),
  186. context.GetValue(arg_ids[1]), "mul",
  187. /*HasNUW=*/false,
  188. /*HasNSW=*/SignedOverflowIsUB));
  189. return;
  190. }
  191. case SemIR::BuiltinFunctionKind::IntDiv: {
  192. context.SetLocal(inst_id, context.builder().CreateSDiv(
  193. context.GetValue(arg_ids[0]),
  194. context.GetValue(arg_ids[1]), "div"));
  195. return;
  196. }
  197. case SemIR::BuiltinFunctionKind::IntMod: {
  198. context.SetLocal(inst_id, context.builder().CreateSRem(
  199. context.GetValue(arg_ids[0]),
  200. context.GetValue(arg_ids[1]), "rem"));
  201. return;
  202. }
  203. case SemIR::BuiltinFunctionKind::IntEq: {
  204. context.SetLocal(inst_id, context.builder().CreateICmpEQ(
  205. context.GetValue(arg_ids[0]),
  206. context.GetValue(arg_ids[1]), "eq"));
  207. return;
  208. }
  209. case SemIR::BuiltinFunctionKind::IntNeq: {
  210. context.SetLocal(inst_id, context.builder().CreateICmpNE(
  211. context.GetValue(arg_ids[0]),
  212. context.GetValue(arg_ids[1]), "neq"));
  213. return;
  214. }
  215. }
  216. CARBON_FATAL() << "Unsupported builtin call.";
  217. }
  218. auto HandleCall(FunctionContext& context, SemIR::InstId inst_id,
  219. SemIR::Call inst) -> void {
  220. llvm::ArrayRef<SemIR::InstId> arg_ids =
  221. context.sem_ir().inst_blocks().Get(inst.args_id);
  222. auto* callee_value = context.GetValue(inst.callee_id);
  223. // A null callee pointer value indicates this isn't a real function.
  224. if (!callee_value) {
  225. auto builtin_kind =
  226. SemIR::BuiltinFunctionKind::ForCallee(context.sem_ir(), inst.callee_id);
  227. HandleBuiltinCall(context, inst_id, builtin_kind, arg_ids);
  228. return;
  229. }
  230. auto* callee = llvm::cast<llvm::Function>(callee_value);
  231. std::vector<llvm::Value*> args;
  232. if (SemIR::GetInitRepr(context.sem_ir(), inst.type_id).has_return_slot()) {
  233. args.push_back(context.GetValue(arg_ids.back()));
  234. arg_ids = arg_ids.drop_back();
  235. }
  236. for (auto arg_id : arg_ids) {
  237. auto arg_type_id = context.sem_ir().insts().Get(arg_id).type_id();
  238. if (SemIR::GetValueRepr(context.sem_ir(), arg_type_id).kind !=
  239. SemIR::ValueRepr::None) {
  240. args.push_back(context.GetValue(arg_id));
  241. }
  242. }
  243. auto* call = context.builder().CreateCall(callee, args);
  244. context.SetLocal(inst_id, call);
  245. // Name the call's result the same as the callee.
  246. // TODO: Is this a helpful name?
  247. if (!call->getType()->isVoidTy()) {
  248. call->setName(callee->getName());
  249. }
  250. }
  251. auto HandleConverted(FunctionContext& context, SemIR::InstId inst_id,
  252. SemIR::Converted inst) -> void {
  253. context.SetLocal(inst_id, context.GetValue(inst.result_id));
  254. }
  255. auto HandleDeref(FunctionContext& context, SemIR::InstId inst_id,
  256. SemIR::Deref inst) -> void {
  257. context.SetLocal(inst_id, context.GetValue(inst.pointer_id));
  258. }
  259. auto HandleFunctionDecl(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  260. SemIR::FunctionDecl inst) -> void {
  261. FatalErrorIfEncountered(inst);
  262. }
  263. auto HandleImplDecl(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  264. SemIR::ImplDecl inst) -> void {
  265. FatalErrorIfEncountered(inst);
  266. }
  267. auto HandleImportRefUnused(FunctionContext& /*context*/,
  268. SemIR::InstId /*inst_id*/,
  269. SemIR::ImportRefUnused inst) -> void {
  270. FatalErrorIfEncountered(inst);
  271. }
  272. auto HandleImportRefUsed(FunctionContext& /*context*/,
  273. SemIR::InstId /*inst_id*/, SemIR::ImportRefUsed inst)
  274. -> void {
  275. FatalErrorIfEncountered(inst);
  276. }
  277. auto HandleInitializeFrom(FunctionContext& context, SemIR::InstId /*inst_id*/,
  278. SemIR::InitializeFrom inst) -> void {
  279. auto storage_type_id = context.sem_ir().insts().Get(inst.dest_id).type_id();
  280. context.FinishInit(storage_type_id, inst.dest_id, inst.src_id);
  281. }
  282. auto HandleInterfaceDecl(FunctionContext& /*context*/,
  283. SemIR::InstId /*inst_id*/, SemIR::InterfaceDecl inst)
  284. -> void {
  285. FatalErrorIfEncountered(inst);
  286. }
  287. auto HandleInterfaceWitness(FunctionContext& /*context*/,
  288. SemIR::InstId /*inst_id*/,
  289. SemIR::InterfaceWitness inst) -> void {
  290. FatalErrorIfEncountered(inst);
  291. }
  292. auto HandleInterfaceWitnessAccess(FunctionContext& context,
  293. SemIR::InstId inst_id,
  294. SemIR::InterfaceWitnessAccess inst) -> void {
  295. // TODO: Add general constant lowering.
  296. auto const_id = context.sem_ir().constant_values().Get(inst_id);
  297. CARBON_CHECK(const_id.is_constant())
  298. << "Lowering non-constant witness access " << inst;
  299. context.SetLocal(inst_id, context.GetValue(const_id.inst_id()));
  300. }
  301. auto HandleIntLiteral(FunctionContext& context, SemIR::InstId inst_id,
  302. SemIR::IntLiteral inst) -> void {
  303. const llvm::APInt& i = context.sem_ir().ints().Get(inst.int_id);
  304. // TODO: This won't offer correct semantics, but seems close enough for now.
  305. llvm::Value* v =
  306. llvm::ConstantInt::get(context.builder().getInt32Ty(), i.getZExtValue());
  307. context.SetLocal(inst_id, v);
  308. }
  309. auto HandleNameRef(FunctionContext& context, SemIR::InstId inst_id,
  310. SemIR::NameRef inst) -> void {
  311. auto type_inst_id = context.sem_ir().types().GetInstId(inst.type_id);
  312. if (type_inst_id == SemIR::InstId::BuiltinNamespaceType) {
  313. return;
  314. }
  315. context.SetLocal(inst_id, context.GetValue(inst.value_id));
  316. }
  317. auto HandleNamespace(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  318. SemIR::Namespace inst) -> void {
  319. FatalErrorIfEncountered(inst);
  320. }
  321. auto HandleParam(FunctionContext& /*context*/, SemIR::InstId /*inst_id*/,
  322. SemIR::Param /*inst*/) -> void {
  323. CARBON_FATAL() << "Parameters should be lowered by `BuildFunctionDefinition`";
  324. }
  325. auto HandleRealLiteral(FunctionContext& context, SemIR::InstId inst_id,
  326. SemIR::RealLiteral inst) -> void {
  327. const Real& real = context.sem_ir().reals().Get(inst.real_id);
  328. // TODO: This will probably have overflow issues, and should be fixed.
  329. double val =
  330. real.mantissa.getZExtValue() *
  331. std::pow((real.is_decimal ? 10 : 2), real.exponent.getSExtValue());
  332. llvm::APFloat llvm_val(val);
  333. context.SetLocal(inst_id, llvm::ConstantFP::get(
  334. context.builder().getDoubleTy(), llvm_val));
  335. }
  336. auto HandleReturn(FunctionContext& context, SemIR::InstId /*inst_id*/,
  337. SemIR::Return /*inst*/) -> void {
  338. context.builder().CreateRetVoid();
  339. }
  340. auto HandleReturnExpr(FunctionContext& context, SemIR::InstId /*inst_id*/,
  341. SemIR::ReturnExpr inst) -> void {
  342. switch (
  343. SemIR::GetInitRepr(context.sem_ir(),
  344. context.sem_ir().insts().Get(inst.expr_id).type_id())
  345. .kind) {
  346. case SemIR::InitRepr::None:
  347. case SemIR::InitRepr::InPlace:
  348. // Nothing to return.
  349. context.builder().CreateRetVoid();
  350. return;
  351. case SemIR::InitRepr::ByCopy:
  352. // The expression produces the value representation for the type.
  353. context.builder().CreateRet(context.GetValue(inst.expr_id));
  354. return;
  355. }
  356. }
  357. auto HandleSpliceBlock(FunctionContext& context, SemIR::InstId inst_id,
  358. SemIR::SpliceBlock inst) -> void {
  359. context.LowerBlock(inst.block_id);
  360. context.SetLocal(inst_id, context.GetValue(inst.result_id));
  361. }
  362. auto HandleStringLiteral(FunctionContext& /*context*/,
  363. SemIR::InstId /*inst_id*/, SemIR::StringLiteral inst)
  364. -> void {
  365. CARBON_FATAL() << "TODO: Add support: " << inst;
  366. }
  367. auto HandleUnaryOperatorNot(FunctionContext& context, SemIR::InstId inst_id,
  368. SemIR::UnaryOperatorNot inst) -> void {
  369. context.SetLocal(
  370. inst_id, context.builder().CreateNot(context.GetValue(inst.operand_id)));
  371. }
  372. auto HandleVarStorage(FunctionContext& context, SemIR::InstId inst_id,
  373. SemIR::VarStorage inst) -> void {
  374. // TODO: Eventually this name will be optional, and we'll want to provide
  375. // something like `var` as a default. However, that's not possible right now
  376. // so cannot be tested.
  377. auto name = context.sem_ir().names().GetIRBaseName(inst.name_id);
  378. auto* alloca = context.builder().CreateAlloca(context.GetType(inst.type_id),
  379. /*ArraySize=*/nullptr, name);
  380. context.SetLocal(inst_id, alloca);
  381. }
  382. } // namespace Carbon::Lower