BitcodeConvenience.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Bitcode/BitcodeConvenience.h - Convenience Wrappers -*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file Convenience wrappers for the LLVM bitcode format and bitstream APIs.
  15. ///
  16. /// This allows you to use a sort of DSL to declare and use bitcode
  17. /// abbreviations and records. Example:
  18. ///
  19. /// \code
  20. /// using Metadata = BCRecordLayout<
  21. /// METADATA_ID, // ID
  22. /// BCFixed<16>, // Module format major version
  23. /// BCFixed<16>, // Module format minor version
  24. /// BCBlob // misc. version information
  25. /// >;
  26. /// Metadata metadata(Out);
  27. /// metadata.emit(ScratchRecord, VERSION_MAJOR, VERSION_MINOR, Data);
  28. /// \endcode
  29. ///
  30. /// For details on the bitcode format, see
  31. /// http://llvm.org/docs/BitCodeFormat.html
  32. ///
  33. //===----------------------------------------------------------------------===//
  34. #ifndef LLVM_BITCODE_BITCODECONVENIENCE_H
  35. #define LLVM_BITCODE_BITCODECONVENIENCE_H
  36. #include "llvm/Bitstream/BitCodes.h"
  37. #include "llvm/Bitstream/BitstreamWriter.h"
  38. #include <cstdint>
  39. namespace llvm {
  40. namespace detail {
  41. /// Convenience base for all kinds of bitcode abbreviation fields.
  42. ///
  43. /// This just defines common properties queried by the metaprogramming.
  44. template <bool Compound = false> class BCField {
  45. public:
  46. static const bool IsCompound = Compound;
  47. /// Asserts that the given data is a valid value for this field.
  48. template <typename T> static void assertValid(const T &data) {}
  49. /// Converts a raw numeric representation of this value to its preferred
  50. /// type.
  51. template <typename T> static T convert(T rawValue) { return rawValue; }
  52. };
  53. } // namespace detail
  54. /// Represents a literal operand in a bitcode record.
  55. ///
  56. /// The value of a literal operand is the same for all instances of the record,
  57. /// so it is only emitted in the abbreviation definition.
  58. ///
  59. /// Note that because this uses a compile-time template, you cannot have a
  60. /// literal operand that is fixed at run-time without dropping down to the
  61. /// raw LLVM APIs.
  62. template <uint64_t Value> class BCLiteral : public detail::BCField<> {
  63. public:
  64. static void emitOp(llvm::BitCodeAbbrev &abbrev) {
  65. abbrev.Add(llvm::BitCodeAbbrevOp(Value));
  66. }
  67. template <typename T> static void assertValid(const T &data) {
  68. assert(data == Value && "data value does not match declared literal value");
  69. }
  70. };
  71. /// Represents a fixed-width value in a bitcode record.
  72. ///
  73. /// Note that the LLVM bitcode format only supports unsigned values.
  74. template <unsigned Width> class BCFixed : public detail::BCField<> {
  75. public:
  76. static_assert(Width <= 64, "fixed-width field is too large");
  77. static void emitOp(llvm::BitCodeAbbrev &abbrev) {
  78. abbrev.Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, Width));
  79. }
  80. static void assertValid(const bool &data) {
  81. assert(llvm::isUInt<Width>(data) &&
  82. "data value does not fit in the given bit width");
  83. }
  84. template <typename T> static void assertValid(const T &data) {
  85. assert(data >= 0 && "cannot encode signed integers");
  86. assert(llvm::isUInt<Width>(data) &&
  87. "data value does not fit in the given bit width");
  88. }
  89. };
  90. /// Represents a variable-width value in a bitcode record.
  91. ///
  92. /// The \p Width parameter should include the continuation bit.
  93. ///
  94. /// Note that the LLVM bitcode format only supports unsigned values.
  95. template <unsigned Width> class BCVBR : public detail::BCField<> {
  96. static_assert(Width >= 2, "width does not have room for continuation bit");
  97. public:
  98. static void emitOp(llvm::BitCodeAbbrev &abbrev) {
  99. abbrev.Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, Width));
  100. }
  101. template <typename T> static void assertValid(const T &data) {
  102. assert(data >= 0 && "cannot encode signed integers");
  103. }
  104. };
  105. /// Represents a character encoded in LLVM's Char6 encoding.
  106. ///
  107. /// This format is suitable for encoding decimal numbers (without signs or
  108. /// exponents) and C identifiers (without dollar signs), but not much else.
  109. ///
  110. /// \sa http://llvm.org/docs/BitCodeFormat.html#char6-encoded-value
  111. class BCChar6 : public detail::BCField<> {
  112. public:
  113. static void emitOp(llvm::BitCodeAbbrev &abbrev) {
  114. abbrev.Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Char6));
  115. }
  116. template <typename T> static void assertValid(const T &data) {
  117. assert(llvm::BitCodeAbbrevOp::isChar6(data) && "invalid Char6 data");
  118. }
  119. template <typename T> char convert(T rawValue) {
  120. return static_cast<char>(rawValue);
  121. }
  122. };
  123. /// Represents an untyped blob of bytes.
  124. ///
  125. /// If present, this must be the last field in a record.
  126. class BCBlob : public detail::BCField<true> {
  127. public:
  128. static void emitOp(llvm::BitCodeAbbrev &abbrev) {
  129. abbrev.Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
  130. }
  131. };
  132. /// Represents an array of some other type.
  133. ///
  134. /// If present, this must be the last field in a record.
  135. template <typename ElementTy> class BCArray : public detail::BCField<true> {
  136. static_assert(!ElementTy::IsCompound, "arrays can only contain scalar types");
  137. public:
  138. static void emitOp(llvm::BitCodeAbbrev &abbrev) {
  139. abbrev.Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Array));
  140. ElementTy::emitOp(abbrev);
  141. }
  142. };
  143. namespace detail {
  144. /// Attaches the last field to an abbreviation.
  145. ///
  146. /// This is the base case for \c emitOps.
  147. ///
  148. /// \sa BCRecordLayout::emitAbbrev
  149. template <typename FieldTy> static void emitOps(llvm::BitCodeAbbrev &abbrev) {
  150. FieldTy::emitOp(abbrev);
  151. }
  152. /// Attaches fields to an abbreviation.
  153. ///
  154. /// This is the recursive case for \c emitOps.
  155. ///
  156. /// \sa BCRecordLayout::emitAbbrev
  157. template <typename FieldTy, typename Next, typename... Rest>
  158. static void emitOps(llvm::BitCodeAbbrev &abbrev) {
  159. static_assert(!FieldTy::IsCompound,
  160. "arrays and blobs may not appear in the middle of a record");
  161. FieldTy::emitOp(abbrev);
  162. emitOps<Next, Rest...>(abbrev);
  163. }
  164. /// Helper class for dealing with a scalar element in the middle of a record.
  165. ///
  166. /// \sa BCRecordLayout
  167. template <typename ElementTy, typename... Fields> class BCRecordCoding {
  168. public:
  169. template <typename BufferTy, typename ElementDataTy, typename... DataTy>
  170. static void emit(llvm::BitstreamWriter &Stream, BufferTy &buffer,
  171. unsigned code, ElementDataTy element, DataTy &&...data) {
  172. static_assert(!ElementTy::IsCompound,
  173. "arrays and blobs may not appear in the middle of a record");
  174. ElementTy::assertValid(element);
  175. buffer.push_back(element);
  176. BCRecordCoding<Fields...>::emit(Stream, buffer, code,
  177. std::forward<DataTy>(data)...);
  178. }
  179. template <typename T, typename ElementDataTy, typename... DataTy>
  180. static void read(ArrayRef<T> buffer, ElementDataTy &element,
  181. DataTy &&...data) {
  182. assert(!buffer.empty() && "too few elements in buffer");
  183. element = ElementTy::convert(buffer.front());
  184. BCRecordCoding<Fields...>::read(buffer.slice(1),
  185. std::forward<DataTy>(data)...);
  186. }
  187. template <typename T, typename... DataTy>
  188. static void read(ArrayRef<T> buffer, NoneType, DataTy &&...data) {
  189. assert(!buffer.empty() && "too few elements in buffer");
  190. BCRecordCoding<Fields...>::read(buffer.slice(1),
  191. std::forward<DataTy>(data)...);
  192. }
  193. };
  194. /// Helper class for dealing with a scalar element at the end of a record.
  195. ///
  196. /// This has a separate implementation because up until now we've only been
  197. /// \em building the record (into a data buffer), and now we need to hand it
  198. /// off to the BitstreamWriter to be emitted.
  199. ///
  200. /// \sa BCRecordLayout
  201. template <typename ElementTy> class BCRecordCoding<ElementTy> {
  202. public:
  203. template <typename BufferTy, typename DataTy>
  204. static void emit(llvm::BitstreamWriter &Stream, BufferTy &buffer,
  205. unsigned code, const DataTy &data) {
  206. static_assert(!ElementTy::IsCompound,
  207. "arrays and blobs need special handling");
  208. ElementTy::assertValid(data);
  209. buffer.push_back(data);
  210. Stream.EmitRecordWithAbbrev(code, buffer);
  211. }
  212. template <typename T, typename DataTy>
  213. static void read(ArrayRef<T> buffer, DataTy &data) {
  214. assert(buffer.size() == 1 && "record data does not match layout");
  215. data = ElementTy::convert(buffer.front());
  216. }
  217. template <typename T> static void read(ArrayRef<T> buffer, NoneType) {
  218. assert(buffer.size() == 1 && "record data does not match layout");
  219. (void)buffer;
  220. }
  221. template <typename T> static void read(ArrayRef<T> buffer) = delete;
  222. };
  223. /// Helper class for dealing with an array at the end of a record.
  224. ///
  225. /// \sa BCRecordLayout::emitRecord
  226. template <typename ElementTy> class BCRecordCoding<BCArray<ElementTy>> {
  227. public:
  228. template <typename BufferTy>
  229. static void emit(llvm::BitstreamWriter &Stream, BufferTy &buffer,
  230. unsigned code, StringRef data) {
  231. // TODO: validate array data.
  232. Stream.EmitRecordWithArray(code, buffer, data);
  233. }
  234. template <typename BufferTy, typename ArrayTy>
  235. static void emit(llvm::BitstreamWriter &Stream, BufferTy &buffer,
  236. unsigned code, const ArrayTy &array) {
  237. #ifndef NDEBUG
  238. for (auto &element : array)
  239. ElementTy::assertValid(element);
  240. #endif
  241. buffer.reserve(buffer.size() + std::distance(array.begin(), array.end()));
  242. std::copy(array.begin(), array.end(), std::back_inserter(buffer));
  243. Stream.EmitRecordWithAbbrev(code, buffer);
  244. }
  245. template <typename BufferTy, typename ElementDataTy, typename... DataTy>
  246. static void emit(llvm::BitstreamWriter &Stream, BufferTy &buffer,
  247. unsigned code, ElementDataTy element, DataTy... data) {
  248. std::array<ElementDataTy, 1 + sizeof...(data)> array{{element, data...}};
  249. emit(Stream, buffer, code, array);
  250. }
  251. template <typename BufferTy>
  252. static void emit(llvm::BitstreamWriter &Stream, BufferTy &Buffer,
  253. unsigned code, NoneType) {
  254. Stream.EmitRecordWithAbbrev(code, Buffer);
  255. }
  256. template <typename T>
  257. static void read(ArrayRef<T> Buffer, ArrayRef<T> &rawData) {
  258. rawData = Buffer;
  259. }
  260. template <typename T, typename ArrayTy>
  261. static void read(ArrayRef<T> buffer, ArrayTy &array) {
  262. array.append(llvm::map_iterator(buffer.begin(), T::convert),
  263. llvm::map_iterator(buffer.end(), T::convert));
  264. }
  265. template <typename T> static void read(ArrayRef<T> buffer, NoneType) {
  266. (void)buffer;
  267. }
  268. template <typename T> static void read(ArrayRef<T> buffer) = delete;
  269. };
  270. /// Helper class for dealing with a blob at the end of a record.
  271. ///
  272. /// \sa BCRecordLayout
  273. template <> class BCRecordCoding<BCBlob> {
  274. public:
  275. template <typename BufferTy>
  276. static void emit(llvm::BitstreamWriter &Stream, BufferTy &buffer,
  277. unsigned code, StringRef data) {
  278. Stream.EmitRecordWithBlob(code, buffer, data);
  279. }
  280. template <typename T> static void read(ArrayRef<T> buffer) { (void)buffer; }
  281. /// Blob data is not stored in the buffer if you are using the correct
  282. /// accessor; this method should not be used.
  283. template <typename T, typename DataTy>
  284. static void read(ArrayRef<T> buffer, DataTy &data) = delete;
  285. };
  286. /// A type trait whose \c type field is the last of its template parameters.
  287. template <typename Head, typename... Tail> struct last_type {
  288. using type = typename last_type<Tail...>::type;
  289. };
  290. template <typename Head> struct last_type<Head> { using type = Head; };
  291. /// A type trait whose \c value field is \c true if the last type is BCBlob.
  292. template <typename... Types>
  293. using has_blob = std::is_same<BCBlob, typename last_type<int, Types...>::type>;
  294. /// A type trait whose \c value field is \c true if the given type is a
  295. /// BCArray (of any element kind).
  296. template <typename T> struct is_array {
  297. private:
  298. template <typename E> static bool check(BCArray<E> *);
  299. static int check(...);
  300. public:
  301. typedef bool value_type;
  302. static constexpr bool value = !std::is_same<decltype(check((T *)nullptr)),
  303. decltype(check(false))>::value;
  304. };
  305. /// A type trait whose \c value field is \c true if the last type is a
  306. /// BCArray (of any element kind).
  307. template <typename... Types>
  308. using has_array = is_array<typename last_type<int, Types...>::type>;
  309. } // namespace detail
  310. /// Represents a single bitcode record type.
  311. ///
  312. /// This class template is meant to be instantiated and then given a name,
  313. /// so that from then on that name can be used.
  314. template <typename IDField, typename... Fields> class BCGenericRecordLayout {
  315. llvm::BitstreamWriter &Stream;
  316. public:
  317. /// The abbreviation code used for this record in the current block.
  318. ///
  319. /// Note that this is not the same as the semantic record code, which is the
  320. /// first field of the record.
  321. const unsigned AbbrevCode;
  322. /// Create a layout and register it with the given bitstream writer.
  323. explicit BCGenericRecordLayout(llvm::BitstreamWriter &Stream)
  324. : Stream(Stream), AbbrevCode(emitAbbrev(Stream)) {}
  325. /// Emit a record to the bitstream writer, using the given buffer for scratch
  326. /// space.
  327. ///
  328. /// Note that even fixed arguments must be specified here.
  329. template <typename BufferTy, typename... Data>
  330. void emit(BufferTy &buffer, unsigned id, Data &&...data) const {
  331. emitRecord(Stream, buffer, AbbrevCode, id, std::forward<Data>(data)...);
  332. }
  333. /// Registers this record's layout with the bitstream reader.
  334. ///
  335. /// eturns The abbreviation code for the newly-registered record type.
  336. static unsigned emitAbbrev(llvm::BitstreamWriter &Stream) {
  337. auto Abbrev = std::make_shared<llvm::BitCodeAbbrev>();
  338. detail::emitOps<IDField, Fields...>(*Abbrev);
  339. return Stream.EmitAbbrev(std::move(Abbrev));
  340. }
  341. /// Emit a record identified by \p abbrCode to bitstream reader \p Stream,
  342. /// using \p buffer for scratch space.
  343. ///
  344. /// Note that even fixed arguments must be specified here. Blobs are passed
  345. /// as StringRefs, while arrays can be passed inline, as aggregates, or as
  346. /// pre-encoded StringRef data. Skipped values and empty arrays should use
  347. /// the special Nothing value.
  348. template <typename BufferTy, typename... Data>
  349. static void emitRecord(llvm::BitstreamWriter &Stream, BufferTy &buffer,
  350. unsigned abbrCode, unsigned recordID, Data &&...data) {
  351. static_assert(sizeof...(data) <= sizeof...(Fields) ||
  352. detail::has_array<Fields...>::value,
  353. "Too many record elements");
  354. static_assert(sizeof...(data) >= sizeof...(Fields),
  355. "Too few record elements");
  356. buffer.clear();
  357. detail::BCRecordCoding<IDField, Fields...>::emit(
  358. Stream, buffer, abbrCode, recordID, std::forward<Data>(data)...);
  359. }
  360. /// Extract record data from \p buffer into the given data fields.
  361. ///
  362. /// Note that even fixed arguments must be specified here. Pass \c Nothing
  363. /// if you don't care about a particular parameter. Blob data is not included
  364. /// in the buffer and should be handled separately by the caller.
  365. template <typename ElementTy, typename... Data>
  366. static void readRecord(ArrayRef<ElementTy> buffer, Data &&...data) {
  367. static_assert(sizeof...(data) <= sizeof...(Fields),
  368. "Too many record elements");
  369. static_assert(sizeof...(Fields) <=
  370. sizeof...(data) + detail::has_blob<Fields...>::value,
  371. "Too few record elements");
  372. return detail::BCRecordCoding<Fields...>::read(buffer,
  373. std::forward<Data>(data)...);
  374. }
  375. /// Extract record data from \p buffer into the given data fields.
  376. ///
  377. /// Note that even fixed arguments must be specified here. Pass \c Nothing
  378. /// if you don't care about a particular parameter. Blob data is not included
  379. /// in the buffer and should be handled separately by the caller.
  380. template <typename BufferTy, typename... Data>
  381. static void readRecord(BufferTy &buffer, Data &&...data) {
  382. return readRecord(llvm::makeArrayRef(buffer), std::forward<Data>(data)...);
  383. }
  384. };
  385. /// A record with a fixed record code.
  386. template <unsigned RecordCode, typename... Fields>
  387. class BCRecordLayout
  388. : public BCGenericRecordLayout<BCLiteral<RecordCode>, Fields...> {
  389. using Base = BCGenericRecordLayout<BCLiteral<RecordCode>, Fields...>;
  390. public:
  391. enum : unsigned {
  392. /// The record code associated with this layout.
  393. Code = RecordCode
  394. };
  395. /// Create a layout and register it with the given bitstream writer.
  396. explicit BCRecordLayout(llvm::BitstreamWriter &Stream) : Base(Stream) {}
  397. /// Emit a record to the bitstream writer, using the given buffer for scratch
  398. /// space.
  399. ///
  400. /// Note that even fixed arguments must be specified here.
  401. template <typename BufferTy, typename... Data>
  402. void emit(BufferTy &buffer, Data &&...data) const {
  403. Base::emit(buffer, RecordCode, std::forward<Data>(data)...);
  404. }
  405. /// Emit a record identified by \p abbrCode to bitstream reader \p Stream,
  406. /// using \p buffer for scratch space.
  407. ///
  408. /// Note that even fixed arguments must be specified here. Currently, arrays
  409. /// and blobs can only be passed as StringRefs.
  410. template <typename BufferTy, typename... Data>
  411. static void emitRecord(llvm::BitstreamWriter &Stream, BufferTy &buffer,
  412. unsigned abbrCode, Data &&...data) {
  413. Base::emitRecord(Stream, buffer, abbrCode, RecordCode,
  414. std::forward<Data>(data)...);
  415. }
  416. };
  417. /// RAII object to pair entering and exiting a sub-block.
  418. class BCBlockRAII {
  419. llvm::BitstreamWriter &Stream;
  420. public:
  421. BCBlockRAII(llvm::BitstreamWriter &Stream, unsigned block, unsigned abbrev)
  422. : Stream(Stream) {
  423. Stream.EnterSubblock(block, abbrev);
  424. }
  425. ~BCBlockRAII() { Stream.ExitBlock(); }
  426. };
  427. } // namespace llvm
  428. #endif
  429. #ifdef __GNUC__
  430. #pragma GCC diagnostic pop
  431. #endif