You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tf_dialect.cpp 11 kB

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