handle_call.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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 <algorithm>
  5. #include <vector>
  6. #include "common/raw_string_ostream.h"
  7. #include "llvm/IR/Type.h"
  8. #include "llvm/IR/Value.h"
  9. #include "toolchain/lower/function_context.h"
  10. #include "toolchain/sem_ir/builtin_function_kind.h"
  11. #include "toolchain/sem_ir/function.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/typed_insts.h"
  14. namespace Carbon::Lower {
  15. // Get the predicate to use for an `icmp` instruction generated for the
  16. // specified builtin.
  17. static auto GetBuiltinICmpPredicate(SemIR::BuiltinFunctionKind builtin_kind,
  18. bool is_signed)
  19. -> llvm::CmpInst::Predicate {
  20. switch (builtin_kind) {
  21. case SemIR::BuiltinFunctionKind::IntEq:
  22. case SemIR::BuiltinFunctionKind::BoolEq:
  23. return llvm::CmpInst::ICMP_EQ;
  24. case SemIR::BuiltinFunctionKind::IntNeq:
  25. case SemIR::BuiltinFunctionKind::BoolNeq:
  26. return llvm::CmpInst::ICMP_NE;
  27. case SemIR::BuiltinFunctionKind::IntLess:
  28. return is_signed ? llvm::CmpInst::ICMP_SLT : llvm::CmpInst::ICMP_ULT;
  29. case SemIR::BuiltinFunctionKind::IntLessEq:
  30. return is_signed ? llvm::CmpInst::ICMP_SLE : llvm::CmpInst::ICMP_ULE;
  31. case SemIR::BuiltinFunctionKind::IntGreater:
  32. return is_signed ? llvm::CmpInst::ICMP_SGT : llvm::CmpInst::ICMP_UGT;
  33. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  34. return is_signed ? llvm::CmpInst::ICMP_SGE : llvm::CmpInst::ICMP_UGE;
  35. default:
  36. CARBON_FATAL("Unexpected builtin kind {0}", builtin_kind);
  37. }
  38. }
  39. // Get the predicate to use for an `fcmp` instruction generated for the
  40. // specified builtin.
  41. static auto GetBuiltinFCmpPredicate(SemIR::BuiltinFunctionKind builtin_kind)
  42. -> llvm::CmpInst::Predicate {
  43. switch (builtin_kind) {
  44. case SemIR::BuiltinFunctionKind::FloatEq:
  45. return llvm::CmpInst::FCMP_OEQ;
  46. case SemIR::BuiltinFunctionKind::FloatNeq:
  47. return llvm::CmpInst::FCMP_ONE;
  48. case SemIR::BuiltinFunctionKind::FloatLess:
  49. return llvm::CmpInst::FCMP_OLT;
  50. case SemIR::BuiltinFunctionKind::FloatLessEq:
  51. return llvm::CmpInst::FCMP_OLE;
  52. case SemIR::BuiltinFunctionKind::FloatGreater:
  53. return llvm::CmpInst::FCMP_OGT;
  54. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  55. return llvm::CmpInst::FCMP_OGE;
  56. default:
  57. CARBON_FATAL("Unexpected builtin kind {0}", builtin_kind);
  58. }
  59. }
  60. // Returns whether the specified instruction has a signed integer type.
  61. static auto IsSignedInt(FunctionContext& context, SemIR::InstId int_id)
  62. -> bool {
  63. auto [file, type_id] = context.GetTypeIdOfInst(int_id);
  64. return file->types().IsSignedInt(type_id);
  65. }
  66. // Creates a zext or sext instruction depending on the signedness of the
  67. // operand.
  68. static auto CreateExt(FunctionContext& context, llvm::Value* value,
  69. llvm::Type* type, bool is_signed,
  70. const llvm::Twine& name = "") -> llvm::Value* {
  71. return is_signed ? context.builder().CreateSExt(value, type, name)
  72. : context.builder().CreateZExt(value, type, name);
  73. }
  74. // Creates a zext, sext, or trunc instruction depending on the signedness of the
  75. // operand.
  76. static auto CreateExtOrTrunc(FunctionContext& context, llvm::Value* value,
  77. llvm::Type* type, bool is_signed,
  78. const llvm::Twine& name = "") -> llvm::Value* {
  79. return is_signed ? context.builder().CreateSExtOrTrunc(value, type, name)
  80. : context.builder().CreateZExtOrTrunc(value, type, name);
  81. }
  82. // Create a integer bit shift for a call to a builtin bit shift function.
  83. static auto CreateIntShift(FunctionContext& context,
  84. llvm::Instruction::BinaryOps bin_op,
  85. llvm::Value* lhs, llvm::Value* rhs) -> llvm::Value* {
  86. // Weirdly, LLVM requires the operands of bit shift operators to be of the
  87. // same type. We can always use the width of the LHS, because if the RHS
  88. // doesn't fit in that then the cast is out of range anyway. Zero-extending is
  89. // always fine because it's an error for the RHS to be negative.
  90. //
  91. // TODO: In a development build we should trap if the RHS is signed and
  92. // negative or greater than or equal to the number of bits in the left-hand
  93. // type.
  94. rhs = context.builder().CreateZExtOrTrunc(rhs, lhs->getType(), "rhs");
  95. return context.builder().CreateBinOp(bin_op, lhs, rhs);
  96. }
  97. // Handles a call to a builtin integer comparison operator.
  98. static auto HandleIntComparison(FunctionContext& context, SemIR::InstId inst_id,
  99. SemIR::BuiltinFunctionKind builtin_kind,
  100. SemIR::InstId lhs_id, SemIR::InstId rhs_id)
  101. -> void {
  102. llvm::Value* lhs = context.GetValue(lhs_id);
  103. llvm::Value* rhs = context.GetValue(rhs_id);
  104. const auto* lhs_type = cast<llvm::IntegerType>(lhs->getType());
  105. const auto* rhs_type = cast<llvm::IntegerType>(rhs->getType());
  106. // We perform a signed comparison if either operand is signed.
  107. bool lhs_signed = IsSignedInt(context, lhs_id);
  108. bool rhs_signed = IsSignedInt(context, rhs_id);
  109. bool cmp_signed = lhs_signed || rhs_signed;
  110. // Compute the width for the comparison. This is the smallest width that
  111. // fits both types, after widening them to include a sign bit if
  112. // necessary.
  113. auto width_for_cmp = [&](const llvm::IntegerType* type, bool is_signed) {
  114. unsigned width = type->getBitWidth();
  115. if (!is_signed && cmp_signed) {
  116. // We're performing a signed comparison but this input is unsigned.
  117. // Widen it by at least one bit to provide a sign bit.
  118. ++width;
  119. }
  120. return width;
  121. };
  122. // TODO: This might be an awkward size, such as 33 or 65 bits, for a
  123. // signed/unsigned comparison. Would it be better to round this up to a
  124. // "nicer" bit width?
  125. unsigned cmp_width = std::max(width_for_cmp(lhs_type, lhs_signed),
  126. width_for_cmp(rhs_type, rhs_signed));
  127. auto* cmp_type = llvm::IntegerType::get(context.llvm_context(), cmp_width);
  128. // Widen the operands as needed.
  129. lhs = CreateExt(context, lhs, cmp_type, lhs_signed, "lhs");
  130. rhs = CreateExt(context, rhs, cmp_type, rhs_signed, "rhs");
  131. context.SetLocal(
  132. inst_id,
  133. context.builder().CreateICmp(
  134. GetBuiltinICmpPredicate(builtin_kind, cmp_signed), lhs, rhs));
  135. }
  136. // Creates a binary operator for a call to a builtin for either that operation
  137. // or the corresponding compound assignment.
  138. static auto CreateBinaryOperatorForBuiltin(
  139. FunctionContext& context, SemIR::InstId inst_id,
  140. SemIR::BuiltinFunctionKind builtin_kind, llvm::Value* lhs, llvm::Value* rhs)
  141. -> llvm::Value* {
  142. // TODO: Consider setting this to true in the performance build mode if the
  143. // result type is a signed integer type.
  144. constexpr bool SignedOverflowIsUB = false;
  145. switch (builtin_kind) {
  146. case SemIR::BuiltinFunctionKind::IntSAdd:
  147. case SemIR::BuiltinFunctionKind::IntSAddAssign: {
  148. return context.builder().CreateAdd(lhs, rhs, "",
  149. /*HasNUW=*/false,
  150. /*HasNSW=*/SignedOverflowIsUB);
  151. }
  152. case SemIR::BuiltinFunctionKind::IntSSub:
  153. case SemIR::BuiltinFunctionKind::IntSSubAssign: {
  154. return context.builder().CreateSub(lhs, rhs, "",
  155. /*HasNUW=*/false,
  156. /*HasNSW=*/SignedOverflowIsUB);
  157. }
  158. case SemIR::BuiltinFunctionKind::IntSMul:
  159. case SemIR::BuiltinFunctionKind::IntSMulAssign: {
  160. return context.builder().CreateMul(lhs, rhs, "",
  161. /*HasNUW=*/false,
  162. /*HasNSW=*/SignedOverflowIsUB);
  163. }
  164. case SemIR::BuiltinFunctionKind::IntSDiv:
  165. case SemIR::BuiltinFunctionKind::IntSDivAssign: {
  166. return context.builder().CreateSDiv(lhs, rhs);
  167. }
  168. case SemIR::BuiltinFunctionKind::IntSMod:
  169. case SemIR::BuiltinFunctionKind::IntSModAssign: {
  170. return context.builder().CreateSRem(lhs, rhs);
  171. }
  172. case SemIR::BuiltinFunctionKind::IntUAdd:
  173. case SemIR::BuiltinFunctionKind::IntUAddAssign: {
  174. return context.builder().CreateAdd(lhs, rhs);
  175. }
  176. case SemIR::BuiltinFunctionKind::IntUSub:
  177. case SemIR::BuiltinFunctionKind::IntUSubAssign: {
  178. return context.builder().CreateSub(lhs, rhs);
  179. }
  180. case SemIR::BuiltinFunctionKind::IntUMul:
  181. case SemIR::BuiltinFunctionKind::IntUMulAssign: {
  182. return context.builder().CreateMul(lhs, rhs);
  183. }
  184. case SemIR::BuiltinFunctionKind::IntUDiv:
  185. case SemIR::BuiltinFunctionKind::IntUDivAssign: {
  186. return context.builder().CreateUDiv(lhs, rhs);
  187. }
  188. case SemIR::BuiltinFunctionKind::IntUMod:
  189. case SemIR::BuiltinFunctionKind::IntUModAssign: {
  190. return context.builder().CreateURem(lhs, rhs);
  191. }
  192. case SemIR::BuiltinFunctionKind::IntAnd:
  193. case SemIR::BuiltinFunctionKind::IntAndAssign: {
  194. return context.builder().CreateAnd(lhs, rhs);
  195. }
  196. case SemIR::BuiltinFunctionKind::IntOr:
  197. case SemIR::BuiltinFunctionKind::IntOrAssign: {
  198. return context.builder().CreateOr(lhs, rhs);
  199. }
  200. case SemIR::BuiltinFunctionKind::IntXor:
  201. case SemIR::BuiltinFunctionKind::IntXorAssign: {
  202. return context.builder().CreateXor(lhs, rhs);
  203. }
  204. case SemIR::BuiltinFunctionKind::IntLeftShift:
  205. case SemIR::BuiltinFunctionKind::IntLeftShiftAssign: {
  206. return CreateIntShift(context, llvm::Instruction::Shl, lhs, rhs);
  207. }
  208. case SemIR::BuiltinFunctionKind::IntRightShift:
  209. case SemIR::BuiltinFunctionKind::IntRightShiftAssign: {
  210. // TODO: Split each of these builtins into separate signed and unsigned
  211. // builtins rather than working out here whether we're performing an
  212. // arithmetic or logical shift.
  213. auto lhs_id = context.sem_ir().inst_blocks().Get(
  214. context.sem_ir().insts().GetAs<SemIR::Call>(inst_id).args_id)[0];
  215. auto [lhs_type_file, lhs_type_id] = context.GetTypeIdOfInst(lhs_id);
  216. return CreateIntShift(context,
  217. lhs_type_file->types().IsSignedInt(lhs_type_id)
  218. ? llvm::Instruction::AShr
  219. : llvm::Instruction::LShr,
  220. lhs, rhs);
  221. }
  222. case SemIR::BuiltinFunctionKind::FloatAdd:
  223. case SemIR::BuiltinFunctionKind::FloatAddAssign: {
  224. return context.builder().CreateFAdd(lhs, rhs);
  225. }
  226. case SemIR::BuiltinFunctionKind::FloatSub:
  227. case SemIR::BuiltinFunctionKind::FloatSubAssign: {
  228. return context.builder().CreateFSub(lhs, rhs);
  229. }
  230. case SemIR::BuiltinFunctionKind::FloatMul:
  231. case SemIR::BuiltinFunctionKind::FloatMulAssign: {
  232. return context.builder().CreateFMul(lhs, rhs);
  233. }
  234. case SemIR::BuiltinFunctionKind::FloatDiv:
  235. case SemIR::BuiltinFunctionKind::FloatDivAssign: {
  236. return context.builder().CreateFDiv(lhs, rhs);
  237. }
  238. default: {
  239. CARBON_FATAL("Unexpected binary operator {0}", builtin_kind);
  240. }
  241. }
  242. }
  243. // Handles a call to a builtin function.
  244. static auto HandleBuiltinCall(FunctionContext& context, SemIR::InstId inst_id,
  245. SemIR::BuiltinFunctionKind builtin_kind,
  246. llvm::ArrayRef<SemIR::InstId> arg_ids) -> void {
  247. // TODO: Consider setting this to true in the performance build mode if the
  248. // result type is a signed integer type.
  249. constexpr bool SignedOverflowIsUB = false;
  250. // TODO: Move the instruction names here into InstNamer.
  251. switch (builtin_kind) {
  252. case SemIR::BuiltinFunctionKind::None:
  253. CARBON_FATAL("No callee in function call.");
  254. case SemIR::BuiltinFunctionKind::NoOp:
  255. return;
  256. case SemIR::BuiltinFunctionKind::PrimitiveCopy:
  257. context.SetLocal(inst_id, context.GetValue(arg_ids[0]));
  258. return;
  259. case SemIR::BuiltinFunctionKind::PrintChar: {
  260. auto* i32_type = llvm::IntegerType::getInt32Ty(context.llvm_context());
  261. llvm::Value* arg_value = context.builder().CreateSExtOrTrunc(
  262. context.GetValue(arg_ids[0]), i32_type);
  263. auto putchar = context.llvm_module().getOrInsertFunction(
  264. "putchar", i32_type, i32_type);
  265. auto* result = context.builder().CreateCall(putchar, {arg_value});
  266. context.SetLocal(inst_id, context.builder().CreateSExtOrTrunc(
  267. result, context.GetTypeOfInst(inst_id)));
  268. return;
  269. }
  270. case SemIR::BuiltinFunctionKind::PrintInt: {
  271. auto* i32_type = llvm::IntegerType::getInt32Ty(context.llvm_context());
  272. auto* ptr_type = llvm::PointerType::get(context.llvm_context(), 0);
  273. auto* printf_type = llvm::FunctionType::get(i32_type, {ptr_type},
  274. /*isVarArg=*/true);
  275. llvm::FunctionCallee printf =
  276. context.llvm_module().getOrInsertFunction("printf", printf_type);
  277. llvm::Value* format_string = context.printf_int_format_string();
  278. llvm::Value* arg_value = context.builder().CreateSExtOrTrunc(
  279. context.GetValue(arg_ids[0]), i32_type);
  280. context.SetLocal(inst_id, context.builder().CreateCall(
  281. printf, {format_string, arg_value}));
  282. return;
  283. }
  284. case SemIR::BuiltinFunctionKind::ReadChar: {
  285. auto* i32_type = llvm::IntegerType::getInt32Ty(context.llvm_context());
  286. auto getchar =
  287. context.llvm_module().getOrInsertFunction("getchar", i32_type);
  288. auto* result = context.builder().CreateCall(getchar, {});
  289. context.SetLocal(inst_id, context.builder().CreateSExtOrTrunc(
  290. result, context.GetTypeOfInst(inst_id)));
  291. return;
  292. }
  293. case SemIR::BuiltinFunctionKind::StringAt: {
  294. auto string_inst_id = arg_ids[0];
  295. auto* string_arg = context.GetValue(string_inst_id);
  296. auto string_type_id = context.GetTypeIdOfInst(string_inst_id);
  297. auto* string_type = context.GetType(string_type_id);
  298. auto* string_value =
  299. context.builder().CreateLoad(string_type, string_arg, "string.load");
  300. auto* string_ptr_field =
  301. context.builder().CreateExtractValue(string_value, {0}, "string.ptr");
  302. auto* index_value = context.GetValue(arg_ids[1]);
  303. auto* char_ptr = context.builder().CreateInBoundsGEP(
  304. llvm::Type::getInt8Ty(context.llvm_context()), string_ptr_field,
  305. index_value, "string.char_ptr");
  306. auto* char_i8 = context.builder().CreateLoad(
  307. llvm::Type::getInt8Ty(context.llvm_context()), char_ptr,
  308. "string.char");
  309. context.SetLocal(inst_id, context.builder().CreateZExt(
  310. char_i8, context.GetTypeOfInst(inst_id),
  311. "string.char.zext"));
  312. return;
  313. }
  314. case SemIR::BuiltinFunctionKind::TypeAnd: {
  315. context.SetLocal(inst_id, context.GetTypeAsValue());
  316. return;
  317. }
  318. case SemIR::BuiltinFunctionKind::BoolMakeType:
  319. case SemIR::BuiltinFunctionKind::CharLiteralMakeType:
  320. case SemIR::BuiltinFunctionKind::FloatLiteralMakeType:
  321. case SemIR::BuiltinFunctionKind::FloatMakeType:
  322. case SemIR::BuiltinFunctionKind::IntLiteralMakeType:
  323. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned:
  324. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned:
  325. case SemIR::BuiltinFunctionKind::MaybeUnformedMakeType:
  326. context.SetLocal(inst_id, context.GetTypeAsValue());
  327. return;
  328. case SemIR::BuiltinFunctionKind::IntConvertChar:
  329. case SemIR::BuiltinFunctionKind::IntConvert: {
  330. context.SetLocal(inst_id,
  331. CreateExtOrTrunc(context, context.GetValue(arg_ids[0]),
  332. context.GetTypeOfInst(inst_id),
  333. IsSignedInt(context, arg_ids[0])));
  334. return;
  335. }
  336. case SemIR::BuiltinFunctionKind::IntSNegate: {
  337. // Lower `-x` as `0 - x`.
  338. auto* operand = context.GetValue(arg_ids[0]);
  339. context.SetLocal(
  340. inst_id,
  341. context.builder().CreateSub(
  342. llvm::ConstantInt::getNullValue(operand->getType()), operand, "",
  343. /*HasNUW=*/false,
  344. /*HasNSW=*/SignedOverflowIsUB));
  345. return;
  346. }
  347. case SemIR::BuiltinFunctionKind::IntUNegate: {
  348. // Lower `-x` as `0 - x`.
  349. auto* operand = context.GetValue(arg_ids[0]);
  350. context.SetLocal(
  351. inst_id,
  352. context.builder().CreateSub(
  353. llvm::ConstantInt::getNullValue(operand->getType()), operand));
  354. return;
  355. }
  356. case SemIR::BuiltinFunctionKind::IntComplement: {
  357. // Lower `^x` as `-1 ^ x`.
  358. auto* operand = context.GetValue(arg_ids[0]);
  359. context.SetLocal(
  360. inst_id,
  361. context.builder().CreateXor(
  362. llvm::ConstantInt::getSigned(operand->getType(), -1), operand));
  363. return;
  364. }
  365. case SemIR::BuiltinFunctionKind::IntSAdd:
  366. case SemIR::BuiltinFunctionKind::IntSSub:
  367. case SemIR::BuiltinFunctionKind::IntSMul:
  368. case SemIR::BuiltinFunctionKind::IntSDiv:
  369. case SemIR::BuiltinFunctionKind::IntSMod:
  370. case SemIR::BuiltinFunctionKind::IntUAdd:
  371. case SemIR::BuiltinFunctionKind::IntUSub:
  372. case SemIR::BuiltinFunctionKind::IntUMul:
  373. case SemIR::BuiltinFunctionKind::IntUDiv:
  374. case SemIR::BuiltinFunctionKind::IntUMod:
  375. case SemIR::BuiltinFunctionKind::IntAnd:
  376. case SemIR::BuiltinFunctionKind::IntOr:
  377. case SemIR::BuiltinFunctionKind::IntXor:
  378. case SemIR::BuiltinFunctionKind::IntLeftShift:
  379. case SemIR::BuiltinFunctionKind::IntRightShift:
  380. case SemIR::BuiltinFunctionKind::FloatAdd:
  381. case SemIR::BuiltinFunctionKind::FloatSub:
  382. case SemIR::BuiltinFunctionKind::FloatMul:
  383. case SemIR::BuiltinFunctionKind::FloatDiv: {
  384. context.SetLocal(inst_id, CreateBinaryOperatorForBuiltin(
  385. context, inst_id, builtin_kind,
  386. context.GetValue(arg_ids[0]),
  387. context.GetValue(arg_ids[1])));
  388. return;
  389. }
  390. case SemIR::BuiltinFunctionKind::IntSAddAssign:
  391. case SemIR::BuiltinFunctionKind::IntSSubAssign:
  392. case SemIR::BuiltinFunctionKind::IntSMulAssign:
  393. case SemIR::BuiltinFunctionKind::IntSDivAssign:
  394. case SemIR::BuiltinFunctionKind::IntSModAssign:
  395. case SemIR::BuiltinFunctionKind::IntUAddAssign:
  396. case SemIR::BuiltinFunctionKind::IntUSubAssign:
  397. case SemIR::BuiltinFunctionKind::IntUMulAssign:
  398. case SemIR::BuiltinFunctionKind::IntUDivAssign:
  399. case SemIR::BuiltinFunctionKind::IntUModAssign:
  400. case SemIR::BuiltinFunctionKind::IntAndAssign:
  401. case SemIR::BuiltinFunctionKind::IntOrAssign:
  402. case SemIR::BuiltinFunctionKind::IntXorAssign:
  403. case SemIR::BuiltinFunctionKind::IntLeftShiftAssign:
  404. case SemIR::BuiltinFunctionKind::IntRightShiftAssign:
  405. case SemIR::BuiltinFunctionKind::FloatAddAssign:
  406. case SemIR::BuiltinFunctionKind::FloatSubAssign:
  407. case SemIR::BuiltinFunctionKind::FloatMulAssign:
  408. case SemIR::BuiltinFunctionKind::FloatDivAssign: {
  409. auto* lhs_ptr = context.GetValue(arg_ids[0]);
  410. auto lhs_type = context.GetTypeIdOfInst(arg_ids[0]);
  411. auto* lhs_value = context.LoadObject(lhs_type, lhs_ptr);
  412. auto* result = CreateBinaryOperatorForBuiltin(
  413. context, inst_id, builtin_kind, lhs_value,
  414. context.GetValue(arg_ids[1]));
  415. context.StoreObject(lhs_type, result, lhs_ptr);
  416. // TODO: Add a helper to get a "no value representation" value.
  417. context.SetLocal(inst_id,
  418. llvm::PoisonValue::get(context.GetTypeOfInst(inst_id)));
  419. return;
  420. }
  421. case SemIR::BuiltinFunctionKind::IntEq:
  422. case SemIR::BuiltinFunctionKind::IntNeq:
  423. case SemIR::BuiltinFunctionKind::IntLess:
  424. case SemIR::BuiltinFunctionKind::IntLessEq:
  425. case SemIR::BuiltinFunctionKind::IntGreater:
  426. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  427. case SemIR::BuiltinFunctionKind::BoolEq:
  428. case SemIR::BuiltinFunctionKind::BoolNeq: {
  429. HandleIntComparison(context, inst_id, builtin_kind, arg_ids[0],
  430. arg_ids[1]);
  431. return;
  432. }
  433. case SemIR::BuiltinFunctionKind::FloatNegate: {
  434. context.SetLocal(
  435. inst_id, context.builder().CreateFNeg(context.GetValue(arg_ids[0])));
  436. return;
  437. }
  438. case SemIR::BuiltinFunctionKind::FloatEq:
  439. case SemIR::BuiltinFunctionKind::FloatNeq:
  440. case SemIR::BuiltinFunctionKind::FloatLess:
  441. case SemIR::BuiltinFunctionKind::FloatLessEq:
  442. case SemIR::BuiltinFunctionKind::FloatGreater:
  443. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  444. context.SetLocal(inst_id, context.builder().CreateFCmp(
  445. GetBuiltinFCmpPredicate(builtin_kind),
  446. context.GetValue(arg_ids[0]),
  447. context.GetValue(arg_ids[1])));
  448. return;
  449. }
  450. case SemIR::BuiltinFunctionKind::CharConvertChecked:
  451. case SemIR::BuiltinFunctionKind::FloatConvertChecked:
  452. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  453. // TODO: Check this statically.
  454. CARBON_CHECK(builtin_kind.IsCompTimeOnly(
  455. context.sem_ir(), arg_ids,
  456. context.sem_ir().insts().Get(inst_id).type_id()));
  457. CARBON_FATAL("Missing constant value for call to comptime-only function");
  458. }
  459. case SemIR::BuiltinFunctionKind::PointerMakeNull: {
  460. context.SetLocal(inst_id,
  461. llvm::ConstantPointerNull::get(
  462. llvm::PointerType::get(context.llvm_context(),
  463. /*AddressSpace=*/0)));
  464. return;
  465. }
  466. case SemIR::BuiltinFunctionKind::PointerIsNull: {
  467. context.SetLocal(inst_id, context.builder().CreateIsNull(
  468. context.GetValue(arg_ids[0])));
  469. return;
  470. }
  471. case SemIR::BuiltinFunctionKind::PointerUnsafeConvert: {
  472. context.SetLocal(inst_id, context.GetValue(arg_ids[0]));
  473. return;
  474. }
  475. }
  476. CARBON_FATAL("Unsupported builtin call.");
  477. }
  478. static auto HandleVirtualCall(FunctionContext& context,
  479. llvm::ArrayRef<llvm::Value*> args,
  480. const SemIR::File* callee_file,
  481. const SemIR::Function& function,
  482. const SemIR::CalleeFunction& callee_function)
  483. -> llvm::CallInst* {
  484. CARBON_CHECK(!args.empty(),
  485. "Virtual functions must have at least one parameter");
  486. auto* ptr_type =
  487. llvm::PointerType::get(context.llvm_context(), /*AddressSpace=*/0);
  488. // The vtable pointer is always at the start of the object in the Carbon
  489. // ABI, so a pointer to the object is a pointer to the vtable pointer - load
  490. // that to get a pointer to the vtable.
  491. // TODO: Handle the case in C++ interop where the vtable pointer isn't at
  492. // the start of the object.
  493. // TODO: Use `context.LoadObject`.
  494. auto* vtable = context.builder().CreateLoad(ptr_type, args.front(), "vtable");
  495. auto* i32_type = llvm::IntegerType::getInt32Ty(context.llvm_context());
  496. auto* pointer_type =
  497. llvm::PointerType::get(context.llvm_context(), /* address space */ 0);
  498. auto function_info =
  499. context.GetFileContext(callee_file)
  500. .GetOrCreateFunctionInfo(callee_function.function_id,
  501. callee_function.resolved_specific_id);
  502. llvm::Value* virtual_fn;
  503. if (function.clang_decl_id.has_value()) {
  504. // Use absolute vtables for clang interop - the itanium vtable contains
  505. // function pointers.
  506. auto* virtual_function_pointer_address = context.builder().CreateGEP(
  507. pointer_type, vtable,
  508. {llvm::ConstantInt::get(
  509. i32_type, static_cast<uint64_t>(function.virtual_index))});
  510. virtual_fn = context.builder().CreateLoad(
  511. pointer_type, virtual_function_pointer_address, "memptr.virtualfn");
  512. } else {
  513. // For Carbon, use Relative VTables as pioneered by Fuchsia:
  514. // https://llvm.org/devmtg/2021-11/slides/2021-RelativeVTablesinC.pdf
  515. // In this case, the vtable contains an offset from the vtable itself to the
  516. // function in question. This avoids the use of link-time relocations in the
  517. // vtable (making object files smaller, improving link time) - at the cost
  518. // of extra instructions to resolve the offset at the call-site.
  519. // This uses the `llvm.load.relative` intrinsic (
  520. // https://llvm.org/docs/LangRef.html#llvm-load-relative-intrinsic ) that
  521. // essentially does the arithmetic in one-shot: ptr + *(ptr + offset)
  522. virtual_fn = context.builder().CreateCall(
  523. llvm::Intrinsic::getOrInsertDeclaration(
  524. &context.llvm_module(), llvm::Intrinsic::load_relative, {i32_type}),
  525. {vtable,
  526. llvm::ConstantInt::get(
  527. i32_type, static_cast<uint64_t>(function.virtual_index) * 4)});
  528. }
  529. return context.builder().CreateCall(function_info->type, virtual_fn, args);
  530. }
  531. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  532. SemIR::Call inst) -> void {
  533. llvm::ArrayRef<SemIR::InstId> arg_ids =
  534. context.sem_ir().inst_blocks().Get(inst.args_id);
  535. // TODO: This duplicates the SpecificId handling in `GetCallee`.
  536. // TODO: Should the `bound_method` be removed when forming the `call`
  537. // instruction? The `self` parameter is transferred into the call argument
  538. // list.
  539. FunctionContext::InstInFile callee = {.file = &context.sem_ir(),
  540. .inst_id = inst.callee_id};
  541. if (auto bound_method = context.sem_ir().insts().TryGetAs<SemIR::BoundMethod>(
  542. callee.inst_id)) {
  543. callee.inst_id = bound_method->function_decl_id;
  544. }
  545. // Map to the callee in the specific. This might be in a different file than
  546. // the one we're currently lowering.
  547. if (context.specific_id().has_value()) {
  548. auto [const_file, const_id] = GetConstantValueInSpecific(
  549. context.specific_sem_ir(), context.specific_id(), context.sem_ir(),
  550. callee.inst_id);
  551. callee.file = const_file;
  552. callee.inst_id = const_file->constant_values().GetInstIdIfValid(const_id);
  553. CARBON_CHECK(callee.inst_id.has_value());
  554. }
  555. auto callee_function =
  556. SemIR::GetCalleeAsFunction(*callee.file, callee.inst_id);
  557. const SemIR::Function& function =
  558. callee.file->functions().Get(callee_function.function_id);
  559. context.AddCallToCurrentFingerprint(callee.file->check_ir_id(),
  560. callee_function.function_id,
  561. callee_function.resolved_specific_id);
  562. if (auto builtin_kind = function.builtin_function_kind();
  563. builtin_kind != SemIR::BuiltinFunctionKind::None) {
  564. HandleBuiltinCall(context, inst_id, builtin_kind, arg_ids);
  565. return;
  566. }
  567. auto& function_info =
  568. context.GetFileContext(callee.file)
  569. .GetOrCreateFunctionInfo(callee_function.function_id,
  570. callee_function.resolved_specific_id);
  571. // Lower args in the LLVM parameter order, rather than the SemIR parameter
  572. // order.
  573. std::vector<llvm::Value*> args;
  574. for (auto param_pattern_id : function_info->lowered_param_pattern_ids) {
  575. auto sem_ir_index = callee.file->insts()
  576. .GetAs<SemIR::AnyParamPattern>(param_pattern_id)
  577. .index.index;
  578. args.push_back(context.GetValue(arg_ids[sem_ir_index]));
  579. }
  580. llvm::CallInst* call;
  581. if (function.virtual_modifier == SemIR::Function::VirtualModifier::None) {
  582. auto* llvm_callee = function_info->llvm_function;
  583. auto describe_call = [&] {
  584. RawStringOstream out;
  585. out << "call ";
  586. llvm_callee->printAsOperand(out);
  587. out << "(";
  588. llvm::ListSeparator sep;
  589. for (auto* arg : args) {
  590. out << sep;
  591. arg->printAsOperand(out);
  592. }
  593. out << ")\n";
  594. llvm_callee->print(out);
  595. return out.TakeStr();
  596. };
  597. CARBON_CHECK(llvm_callee->arg_size() == args.size(),
  598. "Argument count mismatch: {0}", describe_call());
  599. call = context.builder().CreateCall(llvm_callee, args);
  600. } else {
  601. call = HandleVirtualCall(context, args, callee.file, function,
  602. callee_function);
  603. }
  604. context.SetLocal(inst_id, call);
  605. }
  606. } // namespace Carbon::Lower