1 /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 #include "tensorflow/compiler/mlir/lite/quantization/lite/tfl_to_std.h"
16 
17 #include "llvm/Support/Casting.h"
18 #include "mlir/Dialect/Quant/QuantOps.h"  // from @llvm-project
19 #include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h"
20 #include "tensorflow/compiler/mlir/lite/quantization/quantization_utils.h"
21 
22 namespace mlir {
23 namespace TFL {
24 
ConvertTFLQuantOpsToMlirQuantOps(FuncOp func)25 void ConvertTFLQuantOpsToMlirQuantOps(FuncOp func) {
26   OpBuilder b(func);
27   func.walk([&](Operation* op) {
28     b.setInsertionPoint(op);
29     if (auto dq = llvm::dyn_cast<DequantizeOp>(op)) {
30       auto dcast = b.create<quant::DequantizeCastOp>(
31           dq.getLoc(), dq.output().getType(), dq.input());
32       dq.output().replaceAllUsesWith(dcast);
33       dq.erase();
34     } else if (auto q = llvm::dyn_cast<QuantizeOp>(op)) {
35       auto qcast = b.create<quant::QuantizeCastOp>(
36           q.getLoc(), q.output().getType(), q.input());
37       q.output().replaceAllUsesWith(qcast);
38       q.erase();
39     }
40   });
41 }
42 
ConvertMlirQuantOpsToTFLQuantOps(FuncOp func)43 void ConvertMlirQuantOpsToTFLQuantOps(FuncOp func) {
44   OpBuilder b(func);
45   func.walk([&](Operation* op) {
46     b.setInsertionPoint(op);
47     if (auto dq = llvm::dyn_cast<quant::DequantizeCastOp>(op)) {
48       auto dcast = b.create<DequantizeOp>(dq.getLoc(), dq.getResult().getType(),
49                                           dq.arg());
50       dq.getResult().replaceAllUsesWith(dcast);
51       if (auto extra_attr = op->getAttr(mlir::quant::kVolatileOpAttrName)) {
52         dcast->setAttr(mlir::quant::kVolatileOpAttrName, extra_attr);
53       }
54       dq.erase();
55     } else if (auto q = llvm::dyn_cast<quant::QuantizeCastOp>(op)) {
56       auto out_type = q.getResult().getType();
57       auto qcast = b.create<QuantizeOp>(q.getLoc(), out_type, q.arg(),
58                                         TypeAttr::get(out_type));
59       q.getResult().replaceAllUsesWith(qcast);
60       if (auto extra_attr = op->getAttr(mlir::quant::kVolatileOpAttrName)) {
61         qcast->setAttr(mlir::quant::kVolatileOpAttrName, extra_attr);
62       }
63       q.erase();
64     }
65   });
66 }
67 
68 }  // namespace TFL
69 }  // namespace mlir
70