handle_call.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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/IR/Type.h"
  5. #include "llvm/IR/Value.h"
  6. #include "toolchain/lower/function_context.h"
  7. #include "toolchain/sem_ir/builtin_function_kind.h"
  8. #include "toolchain/sem_ir/ids.h"
  9. #include "toolchain/sem_ir/typed_insts.h"
  10. namespace Carbon::Lower {
  11. // Get the predicate to use for an `icmp` instruction generated for the
  12. // specified builtin.
  13. static auto GetBuiltinICmpPredicate(SemIR::BuiltinFunctionKind builtin_kind,
  14. bool is_signed)
  15. -> llvm::CmpInst::Predicate {
  16. switch (builtin_kind) {
  17. case SemIR::BuiltinFunctionKind::IntEq:
  18. case SemIR::BuiltinFunctionKind::BoolEq:
  19. return llvm::CmpInst::ICMP_EQ;
  20. case SemIR::BuiltinFunctionKind::IntNeq:
  21. case SemIR::BuiltinFunctionKind::BoolNeq:
  22. return llvm::CmpInst::ICMP_NE;
  23. case SemIR::BuiltinFunctionKind::IntLess:
  24. return is_signed ? llvm::CmpInst::ICMP_SLT : llvm::CmpInst::ICMP_ULT;
  25. case SemIR::BuiltinFunctionKind::IntLessEq:
  26. return is_signed ? llvm::CmpInst::ICMP_SLE : llvm::CmpInst::ICMP_ULE;
  27. case SemIR::BuiltinFunctionKind::IntGreater:
  28. return is_signed ? llvm::CmpInst::ICMP_SGT : llvm::CmpInst::ICMP_UGT;
  29. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  30. return is_signed ? llvm::CmpInst::ICMP_SGE : llvm::CmpInst::ICMP_UGE;
  31. default:
  32. CARBON_FATAL("Unexpected builtin kind {0}", builtin_kind);
  33. }
  34. }
  35. // Get the predicate to use for an `fcmp` instruction generated for the
  36. // specified builtin.
  37. static auto GetBuiltinFCmpPredicate(SemIR::BuiltinFunctionKind builtin_kind)
  38. -> llvm::CmpInst::Predicate {
  39. switch (builtin_kind) {
  40. case SemIR::BuiltinFunctionKind::FloatEq:
  41. return llvm::CmpInst::FCMP_OEQ;
  42. case SemIR::BuiltinFunctionKind::FloatNeq:
  43. return llvm::CmpInst::FCMP_ONE;
  44. case SemIR::BuiltinFunctionKind::FloatLess:
  45. return llvm::CmpInst::FCMP_OLT;
  46. case SemIR::BuiltinFunctionKind::FloatLessEq:
  47. return llvm::CmpInst::FCMP_OLE;
  48. case SemIR::BuiltinFunctionKind::FloatGreater:
  49. return llvm::CmpInst::FCMP_OGT;
  50. case SemIR::BuiltinFunctionKind::FloatGreaterEq:
  51. return llvm::CmpInst::FCMP_OGE;
  52. default:
  53. CARBON_FATAL("Unexpected builtin kind {0}", builtin_kind);
  54. }
  55. }
  56. // Returns whether the specified instruction has a signed integer type.
  57. static auto IsSignedInt(FunctionContext& context, SemIR::InstId int_id)
  58. -> bool {
  59. return context.sem_ir().types().IsSignedInt(
  60. context.sem_ir().insts().Get(int_id).type_id());
  61. }
  62. // Creates a zext or sext instruction depending on the signedness of the
  63. // operand.
  64. static auto CreateExt(FunctionContext& context, llvm::Value* value,
  65. llvm::Type* type, bool is_signed,
  66. const llvm::Twine& name = "") -> llvm::Value* {
  67. return is_signed ? context.builder().CreateSExt(value, type, name)
  68. : context.builder().CreateZExt(value, type, name);
  69. }
  70. // Creates a zext, sext, or trunc instruction depending on the signedness of the
  71. // operand.
  72. static auto CreateExtOrTrunc(FunctionContext& context, llvm::Value* value,
  73. llvm::Type* type, bool is_signed,
  74. const llvm::Twine& name = "") -> llvm::Value* {
  75. return is_signed ? context.builder().CreateSExtOrTrunc(value, type, name)
  76. : context.builder().CreateZExtOrTrunc(value, type, name);
  77. }
  78. // Handles a call to a builtin integer bit shift operator.
  79. static auto HandleIntShift(FunctionContext& context, SemIR::InstId inst_id,
  80. llvm::Instruction::BinaryOps bin_op,
  81. SemIR::InstId lhs_id, SemIR::InstId rhs_id) -> void {
  82. llvm::Value* lhs = context.GetValue(lhs_id);
  83. llvm::Value* rhs = context.GetValue(rhs_id);
  84. // Weirdly, LLVM requires the operands of bit shift operators to be of the
  85. // same type. We can always use the width of the LHS, because if the RHS
  86. // doesn't fit in that then the cast is out of range anyway. Zero-extending is
  87. // always fine because it's an error for the RHS to be negative.
  88. //
  89. // TODO: In a development build we should trap if the RHS is signed and
  90. // negative or greater than or equal to the number of bits in the left-hand
  91. // type.
  92. rhs = context.builder().CreateZExtOrTrunc(rhs, lhs->getType(), "rhs");
  93. context.SetLocal(inst_id, context.builder().CreateBinOp(bin_op, lhs, rhs));
  94. }
  95. // Handles a call to a builtin integer comparison operator.
  96. static auto HandleIntComparison(FunctionContext& context, SemIR::InstId inst_id,
  97. SemIR::BuiltinFunctionKind builtin_kind,
  98. SemIR::InstId lhs_id, SemIR::InstId rhs_id)
  99. -> void {
  100. llvm::Value* lhs = context.GetValue(lhs_id);
  101. llvm::Value* rhs = context.GetValue(rhs_id);
  102. const auto* lhs_type = cast<llvm::IntegerType>(lhs->getType());
  103. const auto* rhs_type = cast<llvm::IntegerType>(rhs->getType());
  104. // We perform a signed comparison if either operand is signed.
  105. bool lhs_signed = IsSignedInt(context, lhs_id);
  106. bool rhs_signed = IsSignedInt(context, rhs_id);
  107. bool cmp_signed = lhs_signed || rhs_signed;
  108. // Compute the width for the comparison. This is the smallest width that
  109. // fits both types, after widening them to include a sign bit if
  110. // necessary.
  111. auto width_for_cmp = [&](const llvm::IntegerType* type, bool is_signed) {
  112. unsigned width = type->getBitWidth();
  113. if (!is_signed && cmp_signed) {
  114. // We're performing a signed comparison but this input is unsigned.
  115. // Widen it by at least one bit to provide a sign bit.
  116. ++width;
  117. }
  118. return width;
  119. };
  120. // TODO: This might be an awkward size, such as 33 or 65 bits, for a
  121. // signed/unsigned comparison. Would it be better to round this up to a
  122. // "nicer" bit width?
  123. unsigned cmp_width = std::max(width_for_cmp(lhs_type, lhs_signed),
  124. width_for_cmp(rhs_type, rhs_signed));
  125. auto* cmp_type = llvm::IntegerType::get(context.llvm_context(), cmp_width);
  126. // Widen the operands as needed.
  127. lhs = CreateExt(context, lhs, cmp_type, lhs_signed, "lhs");
  128. rhs = CreateExt(context, rhs, cmp_type, rhs_signed, "rhs");
  129. context.SetLocal(
  130. inst_id,
  131. context.builder().CreateICmp(
  132. GetBuiltinICmpPredicate(builtin_kind, cmp_signed), lhs, rhs));
  133. }
  134. // Handles a call to a builtin function.
  135. static auto HandleBuiltinCall(FunctionContext& context, SemIR::InstId inst_id,
  136. SemIR::BuiltinFunctionKind builtin_kind,
  137. llvm::ArrayRef<SemIR::InstId> arg_ids) -> void {
  138. // TODO: Consider setting this to true in the performance build mode if the
  139. // result type is a signed integer type.
  140. constexpr bool SignedOverflowIsUB = false;
  141. // TODO: Move the instruction names here into InstNamer.
  142. switch (builtin_kind) {
  143. case SemIR::BuiltinFunctionKind::None:
  144. CARBON_FATAL("No callee in function call.");
  145. case SemIR::BuiltinFunctionKind::PrintChar: {
  146. auto* i32_type = llvm::IntegerType::getInt32Ty(context.llvm_context());
  147. llvm::Value* arg_value = context.builder().CreateSExtOrTrunc(
  148. context.GetValue(arg_ids[0]), i32_type);
  149. auto putchar = context.llvm_module().getOrInsertFunction(
  150. "putchar", i32_type, i32_type);
  151. auto* result = context.builder().CreateCall(putchar, {arg_value});
  152. context.SetLocal(
  153. inst_id,
  154. context.builder().CreateSExtOrTrunc(
  155. result, context.GetType(
  156. context.sem_ir().insts().Get(inst_id).type_id())));
  157. return;
  158. }
  159. case SemIR::BuiltinFunctionKind::PrintInt: {
  160. auto* i32_type = llvm::IntegerType::getInt32Ty(context.llvm_context());
  161. auto* ptr_type = llvm::PointerType::get(context.llvm_context(), 0);
  162. auto* printf_type = llvm::FunctionType::get(i32_type, {ptr_type},
  163. /*isVarArg=*/true);
  164. llvm::FunctionCallee printf =
  165. context.llvm_module().getOrInsertFunction("printf", printf_type);
  166. llvm::Value* format_string =
  167. context.builder().CreateGlobalString("%d\n", "printf.int.format");
  168. llvm::Value* arg_value = context.builder().CreateSExtOrTrunc(
  169. context.GetValue(arg_ids[0]), i32_type);
  170. context.SetLocal(inst_id, context.builder().CreateCall(
  171. printf, {format_string, arg_value}));
  172. return;
  173. }
  174. case SemIR::BuiltinFunctionKind::ReadChar: {
  175. auto* i32_type = llvm::IntegerType::getInt32Ty(context.llvm_context());
  176. auto getchar =
  177. context.llvm_module().getOrInsertFunction("getchar", i32_type);
  178. auto* result = context.builder().CreateCall(getchar, {});
  179. context.SetLocal(
  180. inst_id,
  181. context.builder().CreateSExtOrTrunc(
  182. result, context.GetType(
  183. context.sem_ir().insts().Get(inst_id).type_id())));
  184. return;
  185. }
  186. case SemIR::BuiltinFunctionKind::TypeAnd: {
  187. context.SetLocal(inst_id, context.GetTypeAsValue());
  188. return;
  189. }
  190. case SemIR::BuiltinFunctionKind::BoolMakeType:
  191. case SemIR::BuiltinFunctionKind::FloatMakeType:
  192. case SemIR::BuiltinFunctionKind::IntLiteralMakeType:
  193. case SemIR::BuiltinFunctionKind::IntMakeTypeSigned:
  194. case SemIR::BuiltinFunctionKind::IntMakeTypeUnsigned:
  195. context.SetLocal(inst_id, context.GetTypeAsValue());
  196. return;
  197. case SemIR::BuiltinFunctionKind::IntConvert: {
  198. context.SetLocal(
  199. inst_id,
  200. CreateExtOrTrunc(
  201. context, context.GetValue(arg_ids[0]),
  202. context.GetType(context.sem_ir().insts().Get(inst_id).type_id()),
  203. IsSignedInt(context, arg_ids[0])));
  204. return;
  205. }
  206. case SemIR::BuiltinFunctionKind::IntSNegate: {
  207. // Lower `-x` as `0 - x`.
  208. auto* operand = context.GetValue(arg_ids[0]);
  209. context.SetLocal(
  210. inst_id,
  211. context.builder().CreateSub(
  212. llvm::ConstantInt::getNullValue(operand->getType()), operand, "",
  213. /*HasNUW=*/false,
  214. /*HasNSW=*/SignedOverflowIsUB));
  215. return;
  216. }
  217. case SemIR::BuiltinFunctionKind::IntUNegate: {
  218. // Lower `-x` as `0 - x`.
  219. auto* operand = context.GetValue(arg_ids[0]);
  220. context.SetLocal(
  221. inst_id,
  222. context.builder().CreateSub(
  223. llvm::ConstantInt::getNullValue(operand->getType()), operand));
  224. return;
  225. }
  226. case SemIR::BuiltinFunctionKind::IntComplement: {
  227. // Lower `^x` as `-1 ^ x`.
  228. auto* operand = context.GetValue(arg_ids[0]);
  229. context.SetLocal(
  230. inst_id,
  231. context.builder().CreateXor(
  232. llvm::ConstantInt::getSigned(operand->getType(), -1), operand));
  233. return;
  234. }
  235. case SemIR::BuiltinFunctionKind::IntSAdd: {
  236. context.SetLocal(
  237. inst_id, context.builder().CreateAdd(context.GetValue(arg_ids[0]),
  238. context.GetValue(arg_ids[1]), "",
  239. /*HasNUW=*/false,
  240. /*HasNSW=*/SignedOverflowIsUB));
  241. return;
  242. }
  243. case SemIR::BuiltinFunctionKind::IntSSub: {
  244. context.SetLocal(
  245. inst_id, context.builder().CreateSub(context.GetValue(arg_ids[0]),
  246. context.GetValue(arg_ids[1]), "",
  247. /*HasNUW=*/false,
  248. /*HasNSW=*/SignedOverflowIsUB));
  249. return;
  250. }
  251. case SemIR::BuiltinFunctionKind::IntSMul: {
  252. context.SetLocal(
  253. inst_id, context.builder().CreateMul(context.GetValue(arg_ids[0]),
  254. context.GetValue(arg_ids[1]), "",
  255. /*HasNUW=*/false,
  256. /*HasNSW=*/SignedOverflowIsUB));
  257. return;
  258. }
  259. case SemIR::BuiltinFunctionKind::IntSDiv: {
  260. context.SetLocal(
  261. inst_id, context.builder().CreateSDiv(context.GetValue(arg_ids[0]),
  262. context.GetValue(arg_ids[1])));
  263. return;
  264. }
  265. case SemIR::BuiltinFunctionKind::IntSMod: {
  266. context.SetLocal(
  267. inst_id, context.builder().CreateSRem(context.GetValue(arg_ids[0]),
  268. context.GetValue(arg_ids[1])));
  269. return;
  270. }
  271. case SemIR::BuiltinFunctionKind::IntUAdd: {
  272. context.SetLocal(
  273. inst_id, context.builder().CreateAdd(context.GetValue(arg_ids[0]),
  274. context.GetValue(arg_ids[1])));
  275. return;
  276. }
  277. case SemIR::BuiltinFunctionKind::IntUSub: {
  278. context.SetLocal(
  279. inst_id, context.builder().CreateSub(context.GetValue(arg_ids[0]),
  280. context.GetValue(arg_ids[1])));
  281. return;
  282. }
  283. case SemIR::BuiltinFunctionKind::IntUMul: {
  284. context.SetLocal(
  285. inst_id, context.builder().CreateMul(context.GetValue(arg_ids[0]),
  286. context.GetValue(arg_ids[1])));
  287. return;
  288. }
  289. case SemIR::BuiltinFunctionKind::IntUDiv: {
  290. context.SetLocal(
  291. inst_id, context.builder().CreateUDiv(context.GetValue(arg_ids[0]),
  292. context.GetValue(arg_ids[1])));
  293. return;
  294. }
  295. case SemIR::BuiltinFunctionKind::IntUMod: {
  296. context.SetLocal(
  297. inst_id, context.builder().CreateURem(context.GetValue(arg_ids[0]),
  298. context.GetValue(arg_ids[1])));
  299. return;
  300. }
  301. case SemIR::BuiltinFunctionKind::IntAnd: {
  302. context.SetLocal(
  303. inst_id, context.builder().CreateAnd(context.GetValue(arg_ids[0]),
  304. context.GetValue(arg_ids[1])));
  305. return;
  306. }
  307. case SemIR::BuiltinFunctionKind::IntOr: {
  308. context.SetLocal(
  309. inst_id, context.builder().CreateOr(context.GetValue(arg_ids[0]),
  310. context.GetValue(arg_ids[1])));
  311. return;
  312. }
  313. case SemIR::BuiltinFunctionKind::IntXor: {
  314. context.SetLocal(
  315. inst_id, context.builder().CreateXor(context.GetValue(arg_ids[0]),
  316. context.GetValue(arg_ids[1])));
  317. return;
  318. }
  319. case SemIR::BuiltinFunctionKind::IntLeftShift: {
  320. HandleIntShift(context, inst_id, llvm::Instruction::Shl, arg_ids[0],
  321. arg_ids[1]);
  322. return;
  323. }
  324. case SemIR::BuiltinFunctionKind::IntRightShift: {
  325. HandleIntShift(context, inst_id,
  326. IsSignedInt(context, inst_id) ? llvm::Instruction::AShr
  327. : llvm::Instruction::LShr,
  328. arg_ids[0], arg_ids[1]);
  329. return;
  330. }
  331. case SemIR::BuiltinFunctionKind::IntEq:
  332. case SemIR::BuiltinFunctionKind::IntNeq:
  333. case SemIR::BuiltinFunctionKind::IntLess:
  334. case SemIR::BuiltinFunctionKind::IntLessEq:
  335. case SemIR::BuiltinFunctionKind::IntGreater:
  336. case SemIR::BuiltinFunctionKind::IntGreaterEq:
  337. case SemIR::BuiltinFunctionKind::BoolEq:
  338. case SemIR::BuiltinFunctionKind::BoolNeq: {
  339. HandleIntComparison(context, inst_id, builtin_kind, arg_ids[0],
  340. arg_ids[1]);
  341. return;
  342. }
  343. case SemIR::BuiltinFunctionKind::FloatNegate: {
  344. context.SetLocal(
  345. inst_id, context.builder().CreateFNeg(context.GetValue(arg_ids[0])));
  346. return;
  347. }
  348. case SemIR::BuiltinFunctionKind::FloatAdd: {
  349. context.SetLocal(
  350. inst_id, context.builder().CreateFAdd(context.GetValue(arg_ids[0]),
  351. context.GetValue(arg_ids[1])));
  352. return;
  353. }
  354. case SemIR::BuiltinFunctionKind::FloatSub: {
  355. context.SetLocal(
  356. inst_id, context.builder().CreateFSub(context.GetValue(arg_ids[0]),
  357. context.GetValue(arg_ids[1])));
  358. return;
  359. }
  360. case SemIR::BuiltinFunctionKind::FloatMul: {
  361. context.SetLocal(
  362. inst_id, context.builder().CreateFMul(context.GetValue(arg_ids[0]),
  363. context.GetValue(arg_ids[1])));
  364. return;
  365. }
  366. case SemIR::BuiltinFunctionKind::FloatDiv: {
  367. context.SetLocal(
  368. inst_id, context.builder().CreateFDiv(context.GetValue(arg_ids[0]),
  369. context.GetValue(arg_ids[1])));
  370. return;
  371. }
  372. case SemIR::BuiltinFunctionKind::FloatEq:
  373. case SemIR::BuiltinFunctionKind::FloatNeq:
  374. case SemIR::BuiltinFunctionKind::FloatLess:
  375. case SemIR::BuiltinFunctionKind::FloatLessEq:
  376. case SemIR::BuiltinFunctionKind::FloatGreater:
  377. case SemIR::BuiltinFunctionKind::FloatGreaterEq: {
  378. context.SetLocal(inst_id, context.builder().CreateFCmp(
  379. GetBuiltinFCmpPredicate(builtin_kind),
  380. context.GetValue(arg_ids[0]),
  381. context.GetValue(arg_ids[1])));
  382. return;
  383. }
  384. case SemIR::BuiltinFunctionKind::IntConvertChecked: {
  385. // TODO: Check this statically.
  386. CARBON_CHECK(builtin_kind.IsCompTimeOnly(
  387. context.sem_ir(), arg_ids,
  388. context.sem_ir().insts().Get(inst_id).type_id()));
  389. CARBON_FATAL("Missing constant value for call to comptime-only function");
  390. }
  391. }
  392. CARBON_FATAL("Unsupported builtin call.");
  393. }
  394. auto HandleInst(FunctionContext& context, SemIR::InstId inst_id,
  395. SemIR::Call inst) -> void {
  396. llvm::ArrayRef<SemIR::InstId> arg_ids =
  397. context.sem_ir().inst_blocks().Get(inst.args_id);
  398. auto callee_function = SemIR::GetCalleeFunction(
  399. context.sem_ir(), inst.callee_id, context.specific_id());
  400. CARBON_CHECK(callee_function.function_id.has_value());
  401. if (auto builtin_kind = context.sem_ir()
  402. .functions()
  403. .Get(callee_function.function_id)
  404. .builtin_function_kind;
  405. builtin_kind != SemIR::BuiltinFunctionKind::None) {
  406. HandleBuiltinCall(context, inst_id, builtin_kind, arg_ids);
  407. return;
  408. }
  409. auto* callee = context.GetOrCreateFunction(
  410. callee_function.function_id, callee_function.resolved_specific_id);
  411. std::vector<llvm::Value*> args;
  412. auto inst_type_id = SemIR::GetTypeOfInstInSpecific(
  413. context.sem_ir(), context.specific_id(), inst_id);
  414. if (SemIR::ReturnTypeInfo::ForType(context.sem_ir(), inst_type_id)
  415. .has_return_slot()) {
  416. args.push_back(context.GetValue(arg_ids.back()));
  417. arg_ids = arg_ids.drop_back();
  418. }
  419. for (auto arg_id : arg_ids) {
  420. auto arg_type_id = context.sem_ir().insts().Get(arg_id).type_id();
  421. if (SemIR::ValueRepr::ForType(context.sem_ir(), arg_type_id).kind !=
  422. SemIR::ValueRepr::None) {
  423. args.push_back(context.GetValue(arg_id));
  424. }
  425. }
  426. context.SetLocal(inst_id, context.builder().CreateCall(callee, args));
  427. }
  428. } // namespace Carbon::Lower