/
TfheRustBoolEmitter.cpp
360 lines (314 loc) · 12.7 KB
/
TfheRustBoolEmitter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
#include "include/Target/TfheRustBool/TfheRustBoolEmitter.h"
#include <functional>
#include <string>
#include <string_view>
#include "include/Analysis/SelectVariableNames/SelectVariableNames.h"
#include "include/Dialect/TfheRustBool/IR/TfheRustBoolDialect.h"
#include "include/Dialect/TfheRustBool/IR/TfheRustBoolOps.h"
#include "include/Dialect/TfheRustBool/IR/TfheRustBoolTypes.h"
#include "lib/Target/TfheRustBool/TfheRustBoolTemplates.h"
#include "lib/Target/Utils.h"
#include "llvm/include/llvm/ADT/TypeSwitch.h" // from @llvm-project
#include "llvm/include/llvm/Support/FormatVariadic.h" // from @llvm-project
#include "llvm/include/llvm/Support/raw_ostream.h" // from @llvm-project
#include "mlir/include/mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project
#include "mlir/include/mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project
#include "mlir/include/mlir/Dialect/Tensor/IR/Tensor.h" // from @llvm-project
#include "mlir/include/mlir/IR/BuiltinAttributes.h" // from @llvm-project
#include "mlir/include/mlir/IR/BuiltinOps.h" // from @llvm-project
#include "mlir/include/mlir/IR/BuiltinTypeInterfaces.h" // from @llvm-project
#include "mlir/include/mlir/IR/BuiltinTypes.h" // from @llvm-project
#include "mlir/include/mlir/IR/DialectRegistry.h" // from @llvm-project
#include "mlir/include/mlir/IR/Types.h" // from @llvm-project
#include "mlir/include/mlir/IR/Value.h" // from @llvm-project
#include "mlir/include/mlir/IR/ValueRange.h" // from @llvm-project
#include "mlir/include/mlir/IR/Visitors.h" // from @llvm-project
#include "mlir/include/mlir/Support/LLVM.h" // from @llvm-project
#include "mlir/include/mlir/Support/LogicalResult.h" // from @llvm-project
#include "mlir/include/mlir/Tools/mlir-translate/Translation.h" // from @llvm-project
namespace mlir {
namespace heir {
namespace tfhe_rust_bool {
void registerToTfheRustBoolTranslation() {
TranslateFromMLIRRegistration reg(
"emit-tfhe-rust-bool",
"translate the bool tfhe_rs dialect to Rust code for boolean tfhe-rs",
[](Operation *op, llvm::raw_ostream &output) {
return translateToTfheRustBool(op, output);
},
[](DialectRegistry ®istry) {
registry.insert<func::FuncDialect, tfhe_rust_bool::TfheRustBoolDialect,
arith::ArithDialect, tensor::TensorDialect>();
});
}
LogicalResult translateToTfheRustBool(Operation *op, llvm::raw_ostream &os) {
SelectVariableNames variableNames(op);
TfheRustBoolEmitter emitter(os, &variableNames);
LogicalResult result = emitter.translate(*op);
return result;
}
LogicalResult TfheRustBoolEmitter::translate(Operation &op) {
LogicalResult status =
llvm::TypeSwitch<Operation &, LogicalResult>(op)
// Builtin ops
.Case<ModuleOp>([&](auto op) { return printOperation(op); })
// Func ops
.Case<func::FuncOp, func::ReturnOp>(
[&](auto op) { return printOperation(op); })
// Arith ops
.Case<arith::ConstantOp>([&](auto op) { return printOperation(op); })
// TfheRustBool ops
.Case<AndOp, NandOp, OrOp, NorOp, XorOp, XnorOp>(
[&](auto op) { return printOperation(op); })
// Tensor ops
.Case<tensor::ExtractOp, tensor::FromElementsOp>(
[&](auto op) { return printOperation(op); })
.Default([&](Operation &) {
return op.emitOpError("unable to find printer for op");
});
if (failed(status)) {
op.emitOpError(llvm::formatv("Failed to translate op {0}", op.getName()));
return failure();
}
return success();
}
LogicalResult TfheRustBoolEmitter::printOperation(ModuleOp moduleOp) {
os << kModulePrelude << "\n";
for (Operation &op : moduleOp) {
if (failed(translate(op))) {
return failure();
}
}
return success();
}
LogicalResult TfheRustBoolEmitter::printOperation(func::FuncOp funcOp) {
os << "pub fn " << funcOp.getName() << "(\n";
os.indent();
for (Value arg : funcOp.getArguments()) {
auto argName = variableNames->getNameForValue(arg);
os << argName << ": &";
if (failed(emitType(arg.getType()))) {
return funcOp.emitOpError()
<< "Failed to emit tfhe-rs bool type " << arg.getType();
}
os << ",\n";
}
os.unindent();
os << ") -> ";
if (funcOp.getNumResults() == 1) {
Type result = funcOp.getResultTypes()[0];
if (failed(emitType(result))) {
return funcOp.emitOpError()
<< "Failed to emit tfhe-rs bool type " << result;
}
} else {
auto result = commaSeparatedTypes(
funcOp.getResultTypes(), [&](Type type) -> FailureOr<std::string> {
auto result = convertType(type);
if (failed(result)) {
return funcOp.emitOpError()
<< "Failed to emit tfhe-rs bool type " << type;
}
return result;
});
os << "(" << result.value() << ")";
}
os << " {\n";
os.indent();
for (Block &block : funcOp.getBlocks()) {
for (Operation &op : block.getOperations()) {
if (failed(translate(op))) {
return failure();
}
}
}
os.unindent();
os << "}\n";
return success();
}
LogicalResult TfheRustBoolEmitter::printOperation(func::ReturnOp op) {
std::function<std::string(Value)> valueOrClonedValue = [&](Value value) {
auto suffix = "";
if (isa<BlockArgument>(value)) {
suffix = ".clone()";
}
if (isa<tensor::FromElementsOp>(value.getDefiningOp())) {
suffix = ".into_iter().cloned().collect()";
}
return variableNames->getNameForValue(value) + suffix;
};
if (op.getNumOperands() == 1) {
os << valueOrClonedValue(op.getOperands()[0]) << "\n";
return success();
}
os << "(" << commaSeparatedValues(op.getOperands(), valueOrClonedValue)
<< ")\n";
return success();
}
void TfheRustBoolEmitter::emitAssignPrefix(Value result) {
os << "let " << variableNames->getNameForValue(result) << " = ";
}
void TfheRustBoolEmitter::emitReferenceConversion(Value value) {
auto tensorType = dyn_cast<TensorType>(value.getType());
if (isa<EncryptedBoolType>(tensorType.getElementType())) {
auto varName = variableNames->getNameForValue(value);
os << "let " << varName << "_ref = " << varName << ".clone();\n";
os << "let " << varName << "_ref: Vec<&Ciphertext> = " << varName
<< ".iter().collect();\n";
}
}
LogicalResult TfheRustBoolEmitter::printSksMethod(
::mlir::Value result, ::mlir::Value sks, ::mlir::ValueRange nonSksOperands,
std::string_view op, SmallVector<std::string> operandTypes) {
if (isa<TensorType>(nonSksOperands[0].getType())) {
auto *opParent = nonSksOperands[0].getDefiningOp();
if (!opParent) {
for (auto nonSksOperand : nonSksOperands) {
emitReferenceConversion(nonSksOperand);
}
}
emitAssignPrefix(result);
os << variableNames->getNameForValue(sks) << "." << op << "_packed(";
os << commaSeparatedValues(
{nonSksOperands[0], nonSksOperands[1]}, [&](Value value) {
auto *prefix = "&";
auto suffix = "";
// First check if a DefiningOp exists
// if not: comes from function definition
mlir::Operation *opParent = value.getDefiningOp();
if (opParent) {
if (!isa<tensor::FromElementsOp>(value.getDefiningOp()) &
!isa<tensor::ExtractOp>(opParent))
prefix = "";
} else {
prefix = "&";
suffix = "_ref";
}
return prefix + variableNames->getNameForValue(value) + suffix;
});
os << ");\n";
return success();
} else {
emitAssignPrefix(result);
auto operandTypesIt = operandTypes.begin();
os << variableNames->getNameForValue(sks) << "." << op << "(";
os << commaSeparatedValues(nonSksOperands, [&](Value value) {
auto *prefix = value.getType().hasTrait<PassByReference>() ? "&" : "";
// First check if a DefiningOp exists
// if not: comes from function definition
mlir::Operation *op = value.getDefiningOp();
if (op) {
prefix = isa<tensor::ExtractOp>(op) ? "" : prefix;
} else {
prefix = "";
}
return prefix + variableNames->getNameForValue(value) +
(!operandTypes.empty() ? " as " + *operandTypesIt++ : "");
});
os << ");\n";
return success();
}
}
LogicalResult TfheRustBoolEmitter::printOperation(CreateTrivialOp op) {
return printSksMethod(op.getResult(), op.getServerKey(), {op.getValue()},
"create_trivial", {"bool"});
}
LogicalResult TfheRustBoolEmitter::printOperation(arith::ConstantOp op) {
auto valueAttr = op.getValue();
if (isa<IntegerType>(op.getType()) &&
op.getType().getIntOrFloatBitWidth() == 1) {
os << "let " << variableNames->getNameForValue(op.getResult())
<< " : bool = ";
os << (cast<IntegerAttr>(valueAttr).getValue().isZero() ? "false" : "true")
<< ";\n";
return success();
}
emitAssignPrefix(op.getResult());
if (auto intAttr = dyn_cast<IntegerAttr>(valueAttr)) {
os << intAttr.getValue() << ";\n";
} else {
return op.emitError() << "Unknown constant type " << valueAttr.getType();
}
return success();
}
// Produces a &Ciphertext
LogicalResult TfheRustBoolEmitter::printOperation(tensor::ExtractOp op) {
// We assume here that the indices are SSA values (not integer attributes).
emitAssignPrefix(op.getResult());
os << "&" << variableNames->getNameForValue(op.getTensor()) << "["
<< commaSeparatedValues(
op.getIndices(),
[&](Value value) { return variableNames->getNameForValue(value); })
<< "];\n";
return success();
}
// Need to produce a Vec<&Ciphertext>
LogicalResult TfheRustBoolEmitter::printOperation(tensor::FromElementsOp op) {
emitAssignPrefix(op.getResult());
os << "vec![" << commaSeparatedValues(op.getOperands(), [&](Value value) {
// Check if block argument, if so, clone.
auto cloneStr = isa<BlockArgument>(value) ? ".clone()" : "";
// Get the name of defining operation its dialect
auto tfhe_op =
value.getDefiningOp()->getDialect()->getNamespace() == "tfhe_rust_bool";
auto prefix = tfhe_op ? "&" : "";
return std::string(prefix) + variableNames->getNameForValue(value) +
cloneStr;
}) << "];\n";
return success();
}
LogicalResult TfheRustBoolEmitter::printOperation(AndOp op) {
return printSksMethod(op.getResult(), op.getServerKey(),
{op.getLhs(), op.getRhs()}, "and");
}
LogicalResult TfheRustBoolEmitter::printOperation(NandOp op) {
return printSksMethod(op.getResult(), op.getServerKey(),
{op.getLhs(), op.getRhs()}, "nand");
}
LogicalResult TfheRustBoolEmitter::printOperation(OrOp op) {
return printSksMethod(op.getResult(), op.getServerKey(),
{op.getLhs(), op.getRhs()}, "or");
}
LogicalResult TfheRustBoolEmitter::printOperation(NorOp op) {
return printSksMethod(op.getResult(), op.getServerKey(),
{op.getLhs(), op.getRhs()}, "nor");
}
LogicalResult TfheRustBoolEmitter::printOperation(XorOp op) {
return printSksMethod(op.getResult(), op.getServerKey(),
{op.getLhs(), op.getRhs()}, "xor");
}
LogicalResult TfheRustBoolEmitter::printOperation(XnorOp op) {
return printSksMethod(op.getResult(), op.getServerKey(),
{op.getLhs(), op.getRhs()}, "xnor");
}
FailureOr<std::string> TfheRustBoolEmitter::convertType(Type type) {
// Note: these are probably not the right type names to use exactly, and they
// will need to chance to the right values once we try to compile it against
// a specific API version.
if (auto shapedType = dyn_cast<ShapedType>(type)) {
// A lambda in a type switch statement can't return multiple types.
// FIXME: why can't both types be FailureOr<std::string>?
auto elementTy = convertType(shapedType.getElementType());
if (failed(elementTy)) return failure();
return std::string(std::string("Vec<") + elementTy.value() + ">");
}
return llvm::TypeSwitch<Type &, FailureOr<std::string>>(type)
.Case<EncryptedBoolType>(
[&](auto type) { return std::string("Ciphertext"); })
.Case<ServerKeyType>([&](auto type) { return std::string("ServerKey"); })
.Default([&](Type &) { return failure(); });
}
LogicalResult TfheRustBoolEmitter::emitType(Type type) {
auto result = convertType(type);
if (failed(result)) {
return failure();
}
os << result;
return success();
}
TfheRustBoolEmitter::TfheRustBoolEmitter(raw_ostream &os,
SelectVariableNames *variableNames)
: os(os), variableNames(variableNames) {}
} // namespace tfhe_rust_bool
} // namespace heir
} // namespace mlir