1 | //===- TypeConversions.cpp - Convert signless types into C/C++ types ------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | |
9 | #include "mlir/Dialect/EmitC/Transforms/TypeConversions.h" |
10 | #include "mlir/Dialect/EmitC/IR/EmitC.h" |
11 | #include "mlir/IR/BuiltinTypes.h" |
12 | #include "mlir/Transforms/DialectConversion.h" |
13 | #include <optional> |
14 | |
15 | using namespace mlir; |
16 | |
17 | namespace { |
18 | |
19 | Value materializeAsUnrealizedCast(OpBuilder &builder, Type resultType, |
20 | ValueRange inputs, Location loc) { |
21 | if (inputs.size() != 1) |
22 | return Value(); |
23 | |
24 | return builder.create<UnrealizedConversionCastOp>(loc, resultType, inputs) |
25 | .getResult(0); |
26 | } |
27 | |
28 | } // namespace |
29 | |
30 | void mlir::populateEmitCSizeTTypeConversions(TypeConverter &converter) { |
31 | converter.addConversion( |
32 | callback: [](IndexType type) { return emitc::SizeTType::get(type.getContext()); }); |
33 | |
34 | converter.addSourceMaterialization(callback&: materializeAsUnrealizedCast); |
35 | converter.addTargetMaterialization(callback&: materializeAsUnrealizedCast); |
36 | } |
37 | |
38 | /// Get an unsigned integer or size data type corresponding to \p ty. |
39 | std::optional<Type> mlir::emitc::getUnsignedTypeFor(Type ty) { |
40 | if (ty.isInteger()) |
41 | return IntegerType::get(ty.getContext(), ty.getIntOrFloatBitWidth(), |
42 | IntegerType::SignednessSemantics::Unsigned); |
43 | if (isa<PtrDiffTType, SignedSizeTType>(ty)) |
44 | return SizeTType::get(ty.getContext()); |
45 | if (isa<SizeTType>(ty)) |
46 | return ty; |
47 | return {}; |
48 | } |
49 | |
50 | /// Get a signed integer or size data type corresponding to \p ty that supports |
51 | /// arithmetic on negative values. |
52 | std::optional<Type> mlir::emitc::getSignedTypeFor(Type ty) { |
53 | if (ty.isInteger()) |
54 | return IntegerType::get(ty.getContext(), ty.getIntOrFloatBitWidth(), |
55 | IntegerType::SignednessSemantics::Signed); |
56 | if (isa<SizeTType, SignedSizeTType>(ty)) |
57 | return PtrDiffTType::get(ty.getContext()); |
58 | if (isa<PtrDiffTType>(ty)) |
59 | return ty; |
60 | return {}; |
61 | } |
62 | |