1//===- TypeConverter.cpp - Convert builtin to EmitC dialect 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/Conversion/EmitCCommon/TypeConverter.h"
10
11#include "mlir/Dialect/EmitC/IR/EmitC.h"
12#include "mlir/IR/BuiltinTypes.h"
13#include "llvm/ADT/STLExtras.h"
14
15using namespace mlir;
16
17namespace {
18
19static bool isMemRefTypeLegalForEmitC(MemRefType memRefType) {
20 return memRefType.hasStaticShape() && memRefType.getLayout().isIdentity() &&
21 !llvm::is_contained(Range: memRefType.getShape(), Element: 0);
22}
23
24static Value materializeAsUnrealizedCast(OpBuilder &builder, Type resultType,
25 ValueRange inputs, Location loc) {
26 if (inputs.size() != 1)
27 return Value();
28
29 return UnrealizedConversionCastOp::create(builder, location: loc, resultTypes: resultType, operands: inputs)
30 .getResult(i: 0);
31}
32
33} // namespace
34
35EmitCTypeConverter::EmitCTypeConverter(MLIRContext *ctx) {
36 (void)ctx;
37
38 addConversion(callback: [](Type type) -> std::optional<Type> {
39 if (!emitc::isSupportedEmitCType(type))
40 return {};
41 return type;
42 });
43
44 addConversion(callback: [&](MemRefType memRefType) -> std::optional<Type> {
45 if (!isMemRefTypeLegalForEmitC(memRefType))
46 return {};
47
48 Type convertedElementType = convertType(t: memRefType.getElementType());
49 if (!convertedElementType)
50 return {};
51
52 if (memRefType.getRank() == 0)
53 return emitc::PointerType::get(pointee: convertedElementType);
54 return emitc::ArrayType::get(shape: memRefType.getShape(), elementType: convertedElementType);
55 });
56
57 addSourceMaterialization(callback&: materializeAsUnrealizedCast);
58 addTargetMaterialization(callback&: materializeAsUnrealizedCast);
59}
60