handle_call.cpp 30 KB

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