• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- Wrap.h - C API Utilities ---------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains common definitions for wrapping opaque C++ pointers into
10 // C structures for the purpose of C API. This file should not be included from
11 // C++ code other than C API implementation nor from C code.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef MLIR_CAPI_WRAP_H
16 #define MLIR_CAPI_WRAP_H
17 
18 #include "mlir-c/IR.h"
19 #include "mlir/Support/LLVM.h"
20 
21 //===----------------------------------------------------------------------===//
22 // Definitions of methods for non-owning structures used in C API.
23 //===----------------------------------------------------------------------===//
24 
25 #define DEFINE_C_API_PTR_METHODS(name, cpptype)                                \
26   static inline name wrap(cpptype *cpp) { return name{cpp}; }                  \
27   static inline cpptype *unwrap(name c) {                                      \
28     return static_cast<cpptype *>(c.ptr);                                      \
29   }
30 
31 #define DEFINE_C_API_METHODS(name, cpptype)                                    \
32   static inline name wrap(cpptype cpp) {                                       \
33     return name{cpp.getAsOpaquePointer()};                                     \
34   }                                                                            \
35   static inline cpptype unwrap(name c) {                                       \
36     return cpptype::getFromOpaquePointer(c.ptr);                               \
37   }
38 
39 template <typename CppTy, typename CTy>
unwrapList(size_t size,CTy * first,llvm::SmallVectorImpl<CppTy> & storage)40 static llvm::ArrayRef<CppTy> unwrapList(size_t size, CTy *first,
41                                         llvm::SmallVectorImpl<CppTy> &storage) {
42   static_assert(
43       std::is_same<decltype(unwrap(std::declval<CTy>())), CppTy>::value,
44       "incompatible C and C++ types");
45 
46   if (size == 0)
47     return llvm::None;
48 
49   assert(storage.empty() && "expected to populate storage");
50   storage.reserve(size);
51   for (size_t i = 0; i < size; ++i)
52     storage.push_back(unwrap(*(first + i)));
53   return storage;
54 }
55 
56 #endif // MLIR_CAPI_WRAP_H
57