builtin_function_kind.cpp 19 KB

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