junrushao commented on code in PR #228: URL: https://github.com/apache/tvm-ffi/pull/228#discussion_r2573338636
########## include/tvm/ffi/extra/stl.h: ########## @@ -0,0 +1,649 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/*! + * \file tvm/ffi/extra/stl.h + * \brief STL container support. + * \note This file is an extra extension of TVM FFI, + * which provides support for STL containers in C++ exported functions. + * + * Whenever possible, prefer using tvm/ffi/container/ implementations, + * such as `tvm::ffi::Array` and `tvm::ffi::Tuple`, over STL containers. + * + * Native ffi objects comes with stable data layout and can be directly accessed + * through compiled languages (Rust) and DSLs(via LLVM) with raw pointer access + * for better performance and compatibility. + */ +#ifndef TVM_FFI_EXTRA_STL_H_ +#define TVM_FFI_EXTRA_STL_H_ + +#include <tvm/ffi/base_details.h> +#include <tvm/ffi/c_api.h> +#include <tvm/ffi/container/array.h> +#include <tvm/ffi/container/map.h> +#include <tvm/ffi/error.h> +#include <tvm/ffi/object.h> +#include <tvm/ffi/type_traits.h> + +#include <algorithm> +#include <array> +#include <cstddef> +#include <cstdint> +#include <exception> +#include <functional> +#include <iterator> +#include <map> +#include <optional> +#include <tuple> +#include <type_traits> +#include <utility> +#include <variant> +#include <vector> + +#include "tvm/ffi/function.h" + +namespace tvm { +namespace ffi { +namespace details { + +struct STLTypeMismatch : public std::exception { + const char* what() const noexcept override { return "STL type mismatch"; } +}; + +struct STLTypeTrait : public TypeTraitsBase { + public: + static constexpr bool storage_enabled = false; + + protected: + /// NOTE: we always copy STL types into an Object first, then move the ObjectPtr to Any. + template <typename T> + TVM_FFI_INLINE static void MoveToAnyImpl(ObjectPtr<T>&& src, TVMFFIAny* result) { + TVMFFIObject* obj_ptr = ObjectUnsafe::MoveObjectPtrToTVMFFIObjectPtr(std::move(src)); + result->type_index = obj_ptr->type_index; + result->zero_padding = 0; + TVM_FFI_CLEAR_PTR_PADDING_IN_FFI_ANY(result); + result->v_obj = obj_ptr; + } + + /// NOTE: we always construct STL types from an Object first, then copy from the ObjectPtr in Any. + template <typename T> + TVM_FFI_INLINE static ObjectPtr<T> CopyFromAnyImpl(const TVMFFIAny* src) { + return ObjectUnsafe::ObjectPtrFromUnowned<T>(src->v_obj); + } + + /// NOTE: STL types are not natively movable from Any, so we always make a new copy. + template <typename T> + TVM_FFI_INLINE static T ConstructFromAny(const Any& value) { + using TypeTrait = TypeTraits<T>; + if constexpr (std::is_same_v<T, Any>) { + return value; + } else { + /// NOTE: Not all type support `CheckArgStrict` (e.g. std::string), + /// so we use `TryCast` instead (without any prior check). + auto opt = TypeTrait::TryCastFromAnyView(AnyUnsafe::TVMFFIAnyPtrFromAny(value)); + if (!opt.has_value()) { + throw STLTypeMismatch{}; + } + return std::move(*opt); + } + } +}; + +struct ListTemplate {}; +struct MapTemplate {}; + +} // namespace details + +template <> +struct TypeTraits<details::ListTemplate> : public details::STLTypeTrait { + public: + static constexpr int32_t field_static_type_index = TypeIndex::kTVMFFIArray; + + private: + template <std::size_t... Is, typename Tuple> + TVM_FFI_INLINE static ObjectPtr<ArrayObj> CopyToTupleImpl(std::index_sequence<Is...>, + Tuple&& src) { + auto array = ArrayObj::Empty(static_cast<std::int64_t>(sizeof...(Is))); + auto dst = array->MutableBegin(); + // increase size after each new to ensure exception safety + ((::new (dst++) Any(std::get<Is>(std::forward<Tuple>(src))), array->size_++), ...); Review Comment: 😯 Here's what clangd says: ``` /Users/jshao/Projects/tvm-ffi/include/tvm/ffi/extra/stl.h:125:58: error: 'src' used after it was forwarded [bugprone-use-after-move,-warnings-as-errors] 125 | ((::new (dst++) Any(std::get<Is>(std::forward<Tuple>(src))), array->size_++), ...); | ^ /Users/jshao/Projects/tvm-ffi/include/tvm/ffi/extra/stl.h:125:25: note: forward occurred here 125 | ((::new (dst++) Any(std::get<Is>(std::forward<Tuple>(src))), array->size_++), ...); | ^ ``` Basically, we should not forward `Tuple` multiple times during index unpacking. Very subtle bug @DarkSharpness! -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
