| 1 | // Tencent is pleased to support the open source community by making ncnn available. |
| 2 | // |
| 3 | // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. |
| 4 | // |
| 5 | // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except |
| 6 | // in compliance with the License. You may obtain a copy of the License at |
| 7 | // |
| 8 | // https://opensource.org/licenses/BSD-3-Clause |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software distributed |
| 11 | // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR |
| 12 | // CONDITIONS OF ANY KIND, either express or implied. See the License for the |
| 13 | // specific language governing permissions and limitations under the License. |
| 14 | |
| 15 | #include "tf_dialect.h" |
| 16 | |
| 17 | #include <mlir/Dialect/Traits.h> |
| 18 | #include <mlir/IR/Attributes.h> |
| 19 | #include <mlir/IR/Builders.h> |
| 20 | #include <mlir/IR/Dialect.h> |
| 21 | #include <mlir/IR/DialectImplementation.h> |
| 22 | #include <mlir/IR/Location.h> |
| 23 | #include <mlir/IR/Matchers.h> |
| 24 | #include <mlir/IR/MLIRContext.h> |
| 25 | #include <mlir/IR/OpDefinition.h> |
| 26 | #include <mlir/IR/OpImplementation.h> |
| 27 | #include <mlir/IR/Operation.h> |
| 28 | #include <mlir/IR/OperationSupport.h> |
| 29 | #include <mlir/IR/PatternMatch.h> |
| 30 | #include <mlir/IR/TypeUtilities.h> |
| 31 | #include <mlir/IR/Types.h> |
| 32 | #include <mlir/IR/Value.h> |
| 33 | #include <mlir/IR/Verifier.h> |
| 34 | #include <mlir/Interfaces/CallInterfaces.h> |
| 35 | #include <mlir/Interfaces/DerivedAttributeOpInterface.h> |
| 36 | #include <mlir/Interfaces/InferTypeOpInterface.h> |
| 37 | #include <mlir/Interfaces/LoopLikeInterface.h> |
| 38 | #include <mlir/Interfaces/SideEffectInterfaces.h> |
| 39 | #include <mlir/Parser.h> |
| 40 | #include <mlir/Support/LogicalResult.h> |
| 41 | #include <mlir/Transforms/InliningUtils.h> |
| 42 | |
| 43 | #include "tf_attributes.h" |
| 44 | #include "tf_side_effects.h" |
| 45 | #include "tf_traits.h" |
| 46 | |
| 47 | namespace mlir { |
| 48 | |
| 49 | static LogicalResult Verify(...) |
| 50 | { |
| 51 | return success(); |
| 52 | } |
| 53 | static LogicalResult VerifyPartitionedCall(...) |
| 54 | { |
| 55 | return success(); |
| 56 | } |
| 57 | static LogicalResult VerifyStridedSliceBase(...) |
| 58 | { |
| 59 | return success(); |
| 60 | } |
| 61 | static LogicalResult VerifyUnsortedSegmentReduction(...) |
| 62 | { |
| 63 | return success(); |
| 64 | } |
| 65 | |
| 66 | namespace TF { |
| 67 | |
| 68 | TensorFlowDialect::TensorFlowDialect(MLIRContext* context) |
| 69 | : Dialect(/*name=*/"tf", context, TypeID::get<TensorFlowDialect>()) |
| 70 | { |
| 71 | addOperations< |
| 72 | #define GET_OP_LIST |
| 73 | #include "tf_all_ops.cc.inc" |
| 74 | >(); |
| 75 | addTypes< |
| 76 | #define HANDLE_TF_TYPE(tftype, enumerant, name) tftype##Type, |
| 77 | #define HANDLE_LAST_TF_TYPE(tftype, enumerant, name) tftype##Type |
| 78 | #include "tf_types.def" |
| 79 | >(); |
| 80 | // addInterfaces<TFInlinerInterface, TFDecodeAttributesInterface, |
| 81 | // TFConstantFoldInterface>(); |
| 82 | addAttributes<ShapeAttr, FuncAttr>(); |
| 83 | |
| 84 | // Support unknown operations because not all TensorFlow operations are |
| 85 | // registered. |
| 86 | allowUnknownOperations(); |
| 87 | |
| 88 | // for (const auto &hook : *TensorFlowDialect::additional_operation_hooks_) { |
| 89 | // hook(*this); |
| 90 | // } |
| 91 | } |
| 92 | |
| 93 | namespace { |
| 94 | |
| 95 | ShapeAttr ParseShapeAttr(MLIRContext* context, StringRef spec, Location loc) |
| 96 | { |
| 97 | auto emit_error = [&, spec]() { |
| 98 | emitError(loc, "invalid TensorFlow shape attribute: ") << spec; |
| 99 | return nullptr; |
| 100 | }; |
| 101 | |
| 102 | if (!spec.consume_front("shape<")) return emit_error(); |
| 103 | |
| 104 | if (spec.consume_front("*>")) |
| 105 | return mlir::TF::ShapeAttr::get(context, llvm::None); |
| 106 | |
| 107 | SmallVector<int64_t, 4> shape; |
| 108 | while (!spec.consume_front(">")) |
| 109 | { |
| 110 | int64_t dim; |
| 111 | |
| 112 | if (spec.consume_front("?")) |
| 113 | dim = -1; |
| 114 | else if (spec.consumeInteger(10, dim) || dim < 0) |
| 115 | return emit_error(); |
| 116 | |
| 117 | spec.consume_front("x"); |
| 118 | |
| 119 | shape.push_back(dim); |
| 120 | } |
| 121 | |
| 122 | return mlir::TF::ShapeAttr::get(context, llvm::makeArrayRef(shape)); |
| 123 | } |
| 124 | |
| 125 | // Parses a #tf.func attribute of the following format: |
| 126 | // |
| 127 | // #tf.func<@symbol, {attr = "value"}> |
| 128 | // |
| 129 | // where the first element is a SymbolRefAttr and the second element is a |
| 130 | // DictionaryAttr. |
| 131 | FuncAttr ParseFuncAttr(MLIRContext* context, StringRef spec, Location loc) |
| 132 | { |
| 133 | auto emit_error = [&, spec]() { |
| 134 | emitError(loc, "invalid TensorFlow func attribute: ") << spec; |
| 135 | return nullptr; |
| 136 | }; |
| 137 | |
| 138 | if (!spec.consume_front("func<")) return emit_error(); |
| 139 | |
| 140 | size_t func_name_num_read = 0; |
| 141 | Attribute func_name_attr = mlir::parseAttribute(spec, context, func_name_num_read); |
| 142 | if (!func_name_attr || !func_name_attr.isa<SymbolRefAttr>()) |
| 143 | return emit_error(); |
| 144 | spec = spec.drop_front(func_name_num_read); |
| 145 | |
| 146 | if (!spec.consume_front(", ")) return emit_error(); |
| 147 | |
| 148 | size_t func_attrs_num_read = 0; |
| 149 | Attribute func_attrs_attr = mlir::parseAttribute(spec, context, func_attrs_num_read); |
| 150 | if (!func_attrs_attr || !func_attrs_attr.isa<DictionaryAttr>()) |
| 151 | return emit_error(); |
| 152 | spec = spec.drop_front(func_attrs_num_read); |
| 153 | |
| 154 | if (!spec.consume_front(">")) return emit_error(); |
| 155 | |
| 156 | return mlir::TF::FuncAttr::get(context, func_name_attr.cast<SymbolRefAttr>(), |
| 157 | func_attrs_attr.cast<DictionaryAttr>()); |
| 158 | } |
| 159 | |
| 160 | } // namespace |
| 161 | |
| 162 | Attribute TensorFlowDialect::parseAttribute(DialectAsmParser& parser, |
| 163 | Type type) const |
| 164 | { |
| 165 | auto spec = parser.getFullSymbolSpec(); |
| 166 | Location loc = parser.getEncodedSourceLoc(parser.getNameLoc()); |
| 167 | |
| 168 | if (spec.startswith("shape")) return ParseShapeAttr(getContext(), spec, loc); |
| 169 | |
| 170 | if (spec.startswith("func")) return ParseFuncAttr(getContext(), spec, loc); |
| 171 | |
| 172 | return (emitError(loc, "unknown TensorFlow attribute: " + spec), nullptr); |
| 173 | } |
| 174 | |
| 175 | // Parses a type registered to this dialect. |
| 176 | Type TensorFlowDialect::parseType(DialectAsmParser& parser) const |
| 177 | { |
| 178 | StringRef data; |
| 179 | if (parser.parseKeyword(&data)) return Type(); |
| 180 | |
| 181 | #define HANDLE_TF_TYPE(tftype, enumerant, name) \ |
| 182 | if (data == name) return tftype##Type::get(getContext()); |
| 183 | // Custom TensorFlow types are handled separately at the end as they do partial |
| 184 | // match. |
| 185 | #define HANDLE_CUSTOM_TF_TYPE(tftype, enumerant, name) |
| 186 | // NOLINTNEXTLINE |
| 187 | #include "tf_types.def" |
| 188 | |
| 189 | llvm::SMLoc loc = parser.getNameLoc(); |
| 190 | if (data.startswith("resource")) |
| 191 | { |
| 192 | Type ret = ParseResourceType(parser); |
| 193 | if (!ret) parser.emitError(loc, "invalid resource type"); |
| 194 | return ret; |
| 195 | } |
| 196 | if (data.startswith("variant")) |
| 197 | { |
| 198 | Type ret = ParseVariantType(parser); |
| 199 | if (!ret) parser.emitError(loc, "invalid variant type"); |
| 200 | return ret; |
| 201 | } |
| 202 | return (parser.emitError(loc, "unknown TensorFlow type: " + data), nullptr); |
| 203 | } |
| 204 | |
| 205 | namespace { |
| 206 | template<typename TypeWithSubtype> |
| 207 | Type ParseTypeWithSubtype(MLIRContext* context, DialectAsmParser& parser) |
| 208 | { |
| 209 | // Default type without inferred subtypes. |
| 210 | if (failed(parser.parseOptionalLess())) return TypeWithSubtype::get(context); |
| 211 | |
| 212 | // Most types with subtypes have only one subtype. |
| 213 | SmallVector<TensorType, 1> subtypes; |
| 214 | do |
| 215 | { |
| 216 | TensorType tensor_ty; |
| 217 | if (parser.parseType(tensor_ty)) return Type(); |
| 218 | |
| 219 | // Each of the subtypes should be a valid TensorFlow type. |
| 220 | // TODO(jpienaar): Remove duplication. |
| 221 | if (!IsValidTFTensorType(tensor_ty)) |
| 222 | { |
| 223 | parser.emitError(parser.getNameLoc()) << "invalid subtype: " << tensor_ty; |
| 224 | return Type(); |
| 225 | } |
| 226 | subtypes.push_back(tensor_ty); |
| 227 | } while (succeeded(parser.parseOptionalComma())); |
| 228 | |
| 229 | if (parser.parseGreater()) return Type(); |
| 230 | |
| 231 | return TypeWithSubtype::get(subtypes, context); |
| 232 | } |
| 233 | } // anonymous namespace |
| 234 | |
| 235 | Type TensorFlowDialect::ParseResourceType(DialectAsmParser& parser) const |
| 236 | { |
| 237 | return ParseTypeWithSubtype<ResourceType>(getContext(), parser); |
| 238 | } |
| 239 | |
| 240 | Type TensorFlowDialect::ParseVariantType(DialectAsmParser& parser) const |
| 241 | { |
| 242 | return ParseTypeWithSubtype<VariantType>(getContext(), parser); |
| 243 | } |
| 244 | |
| 245 | Operation* TensorFlowDialect::materializeConstant(OpBuilder& builder, |
| 246 | Attribute value, Type type, |
| 247 | Location loc) |
| 248 | { |
| 249 | return builder.create<ConstOp>(loc, type, value); |
| 250 | } |
| 251 | |
| 252 | // Builds a constant op with the specified attribute `value`. The result |
| 253 | // op's type is deduced from `value`; if `value` is of scalar type, |
| 254 | // wraps it up with a tensor type of empty shape. |
| 255 | // TODO(jpienaar): This one differs from the autogenerated one as it takes an |
| 256 | // attribute but always creates an ElementsAttr internally. |
| 257 | void ConstOp::build(OpBuilder& builder, OperationState& result, |
| 258 | Attribute value) |
| 259 | { |
| 260 | ShapedType type; |
| 261 | if (auto elem_attr = value.dyn_cast<ElementsAttr>()) |
| 262 | { |
| 263 | return ConstOp::build(builder, result, elem_attr); |
| 264 | } |
| 265 | else if (value.isa<BoolAttr, FloatAttr, IntegerAttr>()) |
| 266 | { |
| 267 | // All TensorFlow types must be tensor types. In the build() method, |
| 268 | // we want to provide more flexibility by allowing attributes of scalar |
| 269 | // types. But we need to wrap it up with ElementsAttr to construct |
| 270 | // valid TensorFlow constants. |
| 271 | type = RankedTensorType::get(/*shape=*/ {}, value.getType()); |
| 272 | return ConstOp::build(builder, result, DenseElementsAttr::get(type, value)); |
| 273 | } |
| 274 | // TODO(jpienaar): support other TensorFlow specific types. |
| 275 | llvm_unreachable("unsupported attribute type for building tf.Const"); |
| 276 | } |
| 277 | |
| 278 | void ConstOp::build(OpBuilder& builder, OperationState& result, Type type, |
| 279 | Attribute value) |
| 280 | { |
| 281 | // Handle the case where the type and value are already tensors. |
| 282 | if (type.isa<TensorType>() && value.isa<ElementsAttr>()) |
| 283 | { |
| 284 | result.addTypes(type); |
| 285 | result.addAttribute("value", value); |
| 286 | return; |
| 287 | } |
| 288 | |
| 289 | // Otherwise, default to the attribute builder. |
| 290 | ConstOp::build(builder, result, value); |
| 291 | assert(type == result.types[0] && "type mismatch in construction"); |
| 292 | } |
| 293 | |
| 294 | Region& WhileRegionOp::getLoopBody() |
| 295 | { |
| 296 | return body(); |
| 297 | } |
| 298 | |
| 299 | bool WhileRegionOp::isDefinedOutsideOfLoop(Value value) |
| 300 | { |
| 301 | // If the Op defining the value exists and the defining op is outside the |
| 302 | // scope of this WhileRegion, then we can infer that its defined outside. |
| 303 | // The defining Op is outside the scope of this WhileRegion if this |
| 304 | // WhileRegionOp is not an ancestor of the defining op in the parent chain. |
| 305 | Operation* def_op = value.getDefiningOp(); |
| 306 | return def_op && !getOperation()->isAncestor(def_op); |
| 307 | } |
| 308 | |
| 309 | LogicalResult WhileRegionOp::moveOutOfLoop( |
| 310 | llvm::ArrayRef<mlir::Operation*> ops) |
| 311 | { |
| 312 | // Move the hoisted value to just before the while. |
| 313 | Operation* while_op = this->getOperation(); |
| 314 | for (auto op : ops) op->moveBefore(while_op); |
| 315 | return success(); |
| 316 | } |
| 317 | |
| 318 | } // namespace TF |
| 319 | |
| 320 | } // namespace mlir |
| 321 | |
| 322 | #define GET_OP_CLASSES |
| 323 | #include "tf_all_ops.cc.inc" |