builtin_function_kind.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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 "toolchain/sem_ir/builtin_function_kind.h"
  5. #include <utility>
  6. #include "toolchain/sem_ir/file.h"
  7. #include "toolchain/sem_ir/ids.h"
  8. #include "toolchain/sem_ir/typed_insts.h"
  9. namespace Carbon::SemIR {
  10. // A function that validates that a builtin was declared properly.
  11. using ValidateFn = auto(const File& sem_ir, llvm::ArrayRef<TypeId> arg_types,
  12. TypeId return_type) -> bool;
  13. namespace {
  14. // Information about a builtin function.
  15. struct BuiltinInfo {
  16. llvm::StringLiteral name;
  17. ValidateFn* validate;
  18. };
  19. // The maximum number of type parameters any builtin needs.
  20. constexpr int MaxTypeParams = 2;
  21. // State used when validating a builtin signature that persists between
  22. // individual checks.
  23. struct ValidateState {
  24. // The type values of type parameters in the builtin signature. Invalid if
  25. // either no value has been deduced yet or the parameter is not used.
  26. TypeId type_params[MaxTypeParams] = {TypeId::None, TypeId::None};
  27. };
  28. // Constraint that a type is generic type parameter `I` of the builtin,
  29. // satisfying `TypeConstraint`. See ValidateSignature for details.
  30. template <int I, typename TypeConstraint>
  31. struct TypeParam {
  32. static_assert(I >= 0 && I < MaxTypeParams);
  33. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  34. -> bool {
  35. if (state.type_params[I].has_value() && type_id != state.type_params[I]) {
  36. return false;
  37. }
  38. if (!TypeConstraint::Check(sem_ir, state, type_id)) {
  39. return false;
  40. }
  41. state.type_params[I] = type_id;
  42. return true;
  43. }
  44. };
  45. // Constraint that a type is a specific builtin. See ValidateSignature for
  46. // details.
  47. template <const InstId& BuiltinId>
  48. struct BuiltinType {
  49. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  50. TypeId type_id) -> bool {
  51. return sem_ir.types().GetInstId(type_id) == BuiltinId;
  52. }
  53. };
  54. // Constraint that a type is `()`, used as the return type of builtin functions
  55. // with no return value.
  56. struct NoReturn {
  57. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  58. TypeId type_id) -> bool {
  59. auto tuple = sem_ir.types().TryGetAs<SemIR::TupleType>(type_id);
  60. if (!tuple) {
  61. return false;
  62. }
  63. return sem_ir.inst_blocks().Get(tuple->elements_id).empty();
  64. }
  65. };
  66. // Constraint that a type is `bool`.
  67. using Bool = BuiltinType<BoolType::SingletonInstId>;
  68. // Constraint that requires the type to be a sized integer type.
  69. struct AnySizedInt {
  70. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  71. TypeId type_id) -> bool {
  72. return sem_ir.types().Is<IntType>(type_id);
  73. }
  74. };
  75. // Constraint that requires the type to be an integer type.
  76. struct AnyInt {
  77. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  78. -> bool {
  79. return AnySizedInt::Check(sem_ir, state, type_id) ||
  80. BuiltinType<IntLiteralType::SingletonInstId>::Check(sem_ir, state,
  81. type_id);
  82. }
  83. };
  84. // Constraint that requires the type to be a float type.
  85. struct AnyFloat {
  86. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  87. -> bool {
  88. if (BuiltinType<LegacyFloatType::SingletonInstId>::Check(sem_ir, state,
  89. type_id)) {
  90. return true;
  91. }
  92. return sem_ir.types().Is<FloatType>(type_id);
  93. }
  94. };
  95. // Constraint that requires the type to be the type type.
  96. using Type = BuiltinType<TypeType::SingletonInstId>;
  97. // Constraint that requires the type to be a type value, whose type is type
  98. // type. Also accepts symbolic constant value types.
  99. struct AnyType {
  100. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  101. -> bool {
  102. if (BuiltinType<TypeType::SingletonInstId>::Check(sem_ir, state, type_id)) {
  103. return true;
  104. }
  105. return sem_ir.types().GetAsInst(type_id).type_id() ==
  106. TypeType::SingletonTypeId;
  107. }
  108. };
  109. // Checks that the specified type matches the given type constraint.
  110. template <typename TypeConstraint>
  111. auto Check(const File& sem_ir, ValidateState& state, TypeId type_id) -> bool {
  112. while (type_id.has_value()) {
  113. // Allow a type that satisfies the constraint.
  114. if (TypeConstraint::Check(sem_ir, state, type_id)) {
  115. return true;
  116. }
  117. // Also allow a class type that adapts a matching type.
  118. auto class_type = sem_ir.types().TryGetAs<ClassType>(type_id);
  119. if (!class_type) {
  120. break;
  121. }
  122. type_id = sem_ir.classes()
  123. .Get(class_type->class_id)
  124. .GetAdaptedType(sem_ir, class_type->specific_id);
  125. }
  126. return false;
  127. }
  128. } // namespace
  129. // Validates that this builtin has a signature matching the specified signature.
  130. //
  131. // `SignatureFnType` is a C++ function type that describes the signature that is
  132. // expected for this builtin. For example, `auto (AnyInt, AnyInt) -> AnyInt`
  133. // specifies that the builtin takes values of two integer types and returns a
  134. // value of a third integer type. Types used within the signature should provide
  135. // a `Check` function that validates that the Carbon type is expected:
  136. //
  137. // auto Check(const File&, ValidateState&, TypeId) -> bool;
  138. //
  139. // To constrain that the same type is used in multiple places in the signature,
  140. // `TypeParam<I, T>` can be used. For example:
  141. //
  142. // auto (TypeParam<0, AnyInt>, AnyInt) -> TypeParam<0, AnyInt>
  143. //
  144. // describes a builtin that takes two integers, and whose return type matches
  145. // its first parameter type. For convenience, typedefs for `TypeParam<I, T>`
  146. // are used in the descriptions of the builtins.
  147. template <typename SignatureFnType>
  148. static auto ValidateSignature(const File& sem_ir,
  149. llvm::ArrayRef<TypeId> arg_types,
  150. TypeId return_type) -> bool {
  151. using SignatureTraits = llvm::function_traits<SignatureFnType*>;
  152. ValidateState state;
  153. // Must have expected number of arguments.
  154. if (arg_types.size() != SignatureTraits::num_args) {
  155. return false;
  156. }
  157. // Argument types must match.
  158. if (![&]<size_t... Indexes>(std::index_sequence<Indexes...>) {
  159. return ((Check<typename SignatureTraits::template arg_t<Indexes>>(
  160. sem_ir, state, arg_types[Indexes])) &&
  161. ...);
  162. }(std::make_index_sequence<SignatureTraits::num_args>())) {
  163. return false;
  164. }
  165. // Result type must match.
  166. if (!Check<typename SignatureTraits::result_t>(sem_ir, state, return_type)) {
  167. return false;
  168. }
  169. return true;
  170. }
  171. // Descriptions of builtin functions follow. For each builtin, a corresponding
  172. // `BuiltinInfo` constant is declared describing properties of that builtin.
  173. namespace BuiltinFunctionInfo {
  174. // Convenience name used in the builtin type signatures below for a first
  175. // generic type parameter that is constrained to be an integer type.
  176. using IntT = TypeParam<0, AnyInt>;
  177. // Convenience name used in the builtin type signatures below for a second
  178. // generic type parameter that is constrained to be an integer type.
  179. using IntU = TypeParam<1, AnyInt>;
  180. // Convenience name used in the builtin type signatures below for a first
  181. // generic type parameter that is constrained to be a sized integer type.
  182. using SizedIntT = TypeParam<0, AnySizedInt>;
  183. // Convenience name used in the builtin type signatures below for a first
  184. // generic type parameter that is constrained to be an float type.
  185. using FloatT = TypeParam<0, AnyFloat>;
  186. // Not a builtin function.
  187. constexpr BuiltinInfo None = {"", nullptr};
  188. // Prints a single character.
  189. constexpr BuiltinInfo PrintChar = {
  190. "print.char", ValidateSignature<auto(AnySizedInt)->AnySizedInt>};
  191. // Prints an integer.
  192. constexpr BuiltinInfo PrintInt = {
  193. "print.int", ValidateSignature<auto(AnySizedInt)->NoReturn>};
  194. // Reads a single character from stdin.
  195. constexpr BuiltinInfo ReadChar = {"read.char",
  196. ValidateSignature<auto()->AnySizedInt>};
  197. // Returns the `Core.IntLiteral` type.
  198. constexpr BuiltinInfo IntLiteralMakeType = {"int_literal.make_type",
  199. ValidateSignature<auto()->Type>};
  200. // Returns the `iN` type.
  201. // TODO: Should we use a more specific type as the type of the bit width?
  202. constexpr BuiltinInfo IntMakeTypeSigned = {
  203. "int.make_type_signed", ValidateSignature<auto(AnyInt)->Type>};
  204. // Returns the `uN` type.
  205. constexpr BuiltinInfo IntMakeTypeUnsigned = {
  206. "int.make_type_unsigned", ValidateSignature<auto(AnyInt)->Type>};
  207. // Returns float types, such as `f64`. Currently only supports `f64`.
  208. constexpr BuiltinInfo FloatMakeType = {"float.make_type",
  209. ValidateSignature<auto(AnyInt)->Type>};
  210. // Returns the `bool` type.
  211. constexpr BuiltinInfo BoolMakeType = {"bool.make_type",
  212. ValidateSignature<auto()->Type>};
  213. // Converts between integer types, truncating if necessary.
  214. constexpr BuiltinInfo IntConvert = {"int.convert",
  215. ValidateSignature<auto(AnyInt)->AnyInt>};
  216. // Converts between integer types, with a diagnostic if the value doesn't fit.
  217. constexpr BuiltinInfo IntConvertChecked = {
  218. "int.convert_checked", ValidateSignature<auto(AnyInt)->AnyInt>};
  219. // "int.snegate": integer negation.
  220. constexpr BuiltinInfo IntSNegate = {"int.snegate",
  221. ValidateSignature<auto(IntT)->IntT>};
  222. // "int.sadd": integer addition.
  223. constexpr BuiltinInfo IntSAdd = {"int.sadd",
  224. ValidateSignature<auto(IntT, IntT)->IntT>};
  225. // "int.ssub": integer subtraction.
  226. constexpr BuiltinInfo IntSSub = {"int.ssub",
  227. ValidateSignature<auto(IntT, IntT)->IntT>};
  228. // "int.smul": integer multiplication.
  229. constexpr BuiltinInfo IntSMul = {"int.smul",
  230. ValidateSignature<auto(IntT, IntT)->IntT>};
  231. // "int.sdiv": integer division.
  232. constexpr BuiltinInfo IntSDiv = {"int.sdiv",
  233. ValidateSignature<auto(IntT, IntT)->IntT>};
  234. // "int.smod": integer modulo.
  235. constexpr BuiltinInfo IntSMod = {"int.smod",
  236. ValidateSignature<auto(IntT, IntT)->IntT>};
  237. // "int.unegate": unsigned integer negation.
  238. constexpr BuiltinInfo IntUNegate = {
  239. "int.unegate", ValidateSignature<auto(SizedIntT)->SizedIntT>};
  240. // "int.uadd": unsigned integer addition.
  241. constexpr BuiltinInfo IntUAdd = {
  242. "int.uadd", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  243. // "int.usub": unsigned integer subtraction.
  244. constexpr BuiltinInfo IntUSub = {
  245. "int.usub", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  246. // "int.umul": unsigned integer multiplication.
  247. constexpr BuiltinInfo IntUMul = {
  248. "int.umul", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  249. // "int.udiv": unsigned integer division.
  250. constexpr BuiltinInfo IntUDiv = {
  251. "int.udiv", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  252. // "int.mod": integer modulo.
  253. constexpr BuiltinInfo IntUMod = {
  254. "int.umod", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  255. // "int.complement": integer bitwise complement.
  256. constexpr BuiltinInfo IntComplement = {"int.complement",
  257. ValidateSignature<auto(IntT)->IntT>};
  258. // "int.and": integer bitwise and.
  259. constexpr BuiltinInfo IntAnd = {"int.and",
  260. ValidateSignature<auto(IntT, IntT)->IntT>};
  261. // "int.or": integer bitwise or.
  262. constexpr BuiltinInfo IntOr = {"int.or",
  263. ValidateSignature<auto(IntT, IntT)->IntT>};
  264. // "int.xor": integer bitwise xor.
  265. constexpr BuiltinInfo IntXor = {"int.xor",
  266. ValidateSignature<auto(IntT, IntT)->IntT>};
  267. // "int.left_shift": integer left shift.
  268. constexpr BuiltinInfo IntLeftShift = {
  269. "int.left_shift", ValidateSignature<auto(IntT, IntU)->IntT>};
  270. // "int.left_shift": integer right shift.
  271. constexpr BuiltinInfo IntRightShift = {
  272. "int.right_shift", ValidateSignature<auto(IntT, IntU)->IntT>};
  273. // "int.eq": integer equality comparison.
  274. constexpr BuiltinInfo IntEq = {"int.eq",
  275. ValidateSignature<auto(IntT, IntU)->Bool>};
  276. // "int.neq": integer non-equality comparison.
  277. constexpr BuiltinInfo IntNeq = {"int.neq",
  278. ValidateSignature<auto(IntT, IntU)->Bool>};
  279. // "int.less": integer less than comparison.
  280. constexpr BuiltinInfo IntLess = {"int.less",
  281. ValidateSignature<auto(IntT, IntU)->Bool>};
  282. // "int.less_eq": integer less than or equal comparison.
  283. constexpr BuiltinInfo IntLessEq = {"int.less_eq",
  284. ValidateSignature<auto(IntT, IntU)->Bool>};
  285. // "int.greater": integer greater than comparison.
  286. constexpr BuiltinInfo IntGreater = {"int.greater",
  287. ValidateSignature<auto(IntT, IntU)->Bool>};
  288. // "int.greater_eq": integer greater than or equal comparison.
  289. constexpr BuiltinInfo IntGreaterEq = {
  290. "int.greater_eq", ValidateSignature<auto(IntT, IntU)->Bool>};
  291. // "float.negate": float negation.
  292. constexpr BuiltinInfo FloatNegate = {"float.negate",
  293. ValidateSignature<auto(FloatT)->FloatT>};
  294. // "float.add": float addition.
  295. constexpr BuiltinInfo FloatAdd = {
  296. "float.add", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  297. // "float.sub": float subtraction.
  298. constexpr BuiltinInfo FloatSub = {
  299. "float.sub", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  300. // "float.mul": float multiplication.
  301. constexpr BuiltinInfo FloatMul = {
  302. "float.mul", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  303. // "float.div": float division.
  304. constexpr BuiltinInfo FloatDiv = {
  305. "float.div", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  306. // "float.eq": float equality comparison.
  307. constexpr BuiltinInfo FloatEq = {"float.eq",
  308. ValidateSignature<auto(FloatT, FloatT)->Bool>};
  309. // "float.neq": float non-equality comparison.
  310. constexpr BuiltinInfo FloatNeq = {
  311. "float.neq", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  312. // "float.less": float less than comparison.
  313. constexpr BuiltinInfo FloatLess = {
  314. "float.less", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  315. // "float.less_eq": float less than or equal comparison.
  316. constexpr BuiltinInfo FloatLessEq = {
  317. "float.less_eq", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  318. // "float.greater": float greater than comparison.
  319. constexpr BuiltinInfo FloatGreater = {
  320. "float.greater", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  321. // "float.greater_eq": float greater than or equal comparison.
  322. constexpr BuiltinInfo FloatGreaterEq = {
  323. "float.greater_eq", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  324. // "bool.eq": bool equality comparison.
  325. constexpr BuiltinInfo BoolEq = {"bool.eq",
  326. ValidateSignature<auto(Bool, Bool)->Bool>};
  327. // "bool.neq": bool non-equality comparison.
  328. constexpr BuiltinInfo BoolNeq = {"bool.neq",
  329. ValidateSignature<auto(Bool, Bool)->Bool>};
  330. // "type.and": facet type combination.
  331. constexpr BuiltinInfo TypeAnd = {
  332. "type.and", ValidateSignature<auto(AnyType, AnyType)->AnyType>};
  333. } // namespace BuiltinFunctionInfo
  334. CARBON_DEFINE_ENUM_CLASS_NAMES(BuiltinFunctionKind) = {
  335. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  336. BuiltinFunctionInfo::Name.name,
  337. #include "toolchain/sem_ir/builtin_function_kind.def"
  338. };
  339. // Returns the builtin function kind with the given name, or None if the name
  340. // is unknown.
  341. auto BuiltinFunctionKind::ForBuiltinName(llvm::StringRef name)
  342. -> BuiltinFunctionKind {
  343. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  344. if (name == BuiltinFunctionInfo::Name.name) { \
  345. return BuiltinFunctionKind::Name; \
  346. }
  347. #include "toolchain/sem_ir/builtin_function_kind.def"
  348. return BuiltinFunctionKind::None;
  349. }
  350. auto BuiltinFunctionKind::IsValidType(const File& sem_ir,
  351. llvm::ArrayRef<TypeId> arg_types,
  352. TypeId return_type) const -> bool {
  353. static constexpr ValidateFn* ValidateFns[] = {
  354. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  355. BuiltinFunctionInfo::Name.validate,
  356. #include "toolchain/sem_ir/builtin_function_kind.def"
  357. };
  358. return ValidateFns[AsInt()](sem_ir, arg_types, return_type);
  359. }
  360. // Determines whether a builtin call involves an integer literal in its
  361. // arguments or return type. If so, for many builtins we want to treat the call
  362. // as being compile-time-only. This is because `Core.IntLiteral` has an empty
  363. // runtime representation, and a value of that type isn't necessarily a
  364. // compile-time constant, so an arbitrary runtime value of type
  365. // `Core.IntLiteral` may not have a value available for the builtin to use. For
  366. // example, given:
  367. //
  368. // var n: Core.IntLiteral() = 123;
  369. //
  370. // we would be unable to lower a runtime operation such as `(1 as i32) << n`
  371. // because the runtime representation of `n` doesn't track its value at all.
  372. //
  373. // For now, we treat all operations involving `Core.IntLiteral` as being
  374. // compile-time-only.
  375. //
  376. // TODO: We will need to accept things like `some_i32 << 5` eventually. We could
  377. // allow builtin calls at runtime if all the IntLiteral arguments have constant
  378. // values, or add logic to the prelude to promote the `IntLiteral` operand to a
  379. // different type in such cases.
  380. //
  381. // TODO: For now, we also treat builtins *returning* `Core.IntLiteral` as being
  382. // compile-time-only. This is mostly done for simplicity, but should probably be
  383. // revisited.
  384. static auto AnyIntLiteralTypes(const File& sem_ir,
  385. llvm::ArrayRef<InstId> arg_ids,
  386. TypeId return_type_id) -> bool {
  387. if (sem_ir.types().Is<SemIR::IntLiteralType>(return_type_id)) {
  388. return true;
  389. }
  390. for (auto arg_id : arg_ids) {
  391. if (sem_ir.types().Is<SemIR::IntLiteralType>(
  392. sem_ir.insts().Get(arg_id).type_id())) {
  393. return true;
  394. }
  395. }
  396. return false;
  397. }
  398. auto BuiltinFunctionKind::IsCompTimeOnly(const File& sem_ir,
  399. llvm::ArrayRef<InstId> arg_ids,
  400. TypeId return_type_id) const -> bool {
  401. switch (*this) {
  402. case IntConvertChecked:
  403. // Checked integer conversions are compile-time only.
  404. return true;
  405. case IntConvert:
  406. case IntSNegate:
  407. case IntComplement:
  408. case IntSAdd:
  409. case IntSSub:
  410. case IntSMul:
  411. case IntSDiv:
  412. case IntSMod:
  413. case IntAnd:
  414. case IntOr:
  415. case IntXor:
  416. case IntLeftShift:
  417. case IntRightShift:
  418. case IntEq:
  419. case IntNeq:
  420. case IntLess:
  421. case IntLessEq:
  422. case IntGreater:
  423. case IntGreaterEq:
  424. // Integer operations are compile-time-only if they involve integer
  425. // literal types. See AnyIntLiteralTypes comment for explanation.
  426. return AnyIntLiteralTypes(sem_ir, arg_ids, return_type_id);
  427. case TypeAnd:
  428. return true;
  429. default:
  430. // TODO: Should the sized MakeType functions be compile-time only? We
  431. // can't produce diagnostics for bad sizes at runtime.
  432. return false;
  433. }
  434. }
  435. } // namespace Carbon::SemIR