ValueEnumerator.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. //===- Bitcode/Writer/ValueEnumerator.h - Number values ---------*- 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 class gives values and types Unique ID's.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_LIB_BITCODE_WRITER_VALUEENUMERATOR_H
  13. #define LLVM_LIB_BITCODE_WRITER_VALUEENUMERATOR_H
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/UniqueVector.h"
  17. #include "llvm/IR/Attributes.h"
  18. #include "llvm/IR/UseListOrder.h"
  19. #include <cassert>
  20. #include <cstdint>
  21. #include <utility>
  22. #include <vector>
  23. namespace llvm {
  24. class BasicBlock;
  25. class Comdat;
  26. class DIArgList;
  27. class Function;
  28. class Instruction;
  29. class LocalAsMetadata;
  30. class MDNode;
  31. class Metadata;
  32. class Module;
  33. class NamedMDNode;
  34. class raw_ostream;
  35. class Type;
  36. class Value;
  37. class ValueSymbolTable;
  38. class ValueEnumerator {
  39. public:
  40. using TypeList = std::vector<Type *>;
  41. // For each value, we remember its Value* and occurrence frequency.
  42. using ValueList = std::vector<std::pair<const Value *, unsigned>>;
  43. /// Attribute groups as encoded in bitcode are almost AttributeSets, but they
  44. /// include the AttributeList index, so we have to track that in our map.
  45. using IndexAndAttrSet = std::pair<unsigned, AttributeSet>;
  46. UseListOrderStack UseListOrders;
  47. private:
  48. using TypeMapType = DenseMap<Type *, unsigned>;
  49. TypeMapType TypeMap;
  50. TypeList Types;
  51. using ValueMapType = DenseMap<const Value *, unsigned>;
  52. ValueMapType ValueMap;
  53. ValueList Values;
  54. using ComdatSetType = UniqueVector<const Comdat *>;
  55. ComdatSetType Comdats;
  56. std::vector<const Metadata *> MDs;
  57. std::vector<const Metadata *> FunctionMDs;
  58. /// Index of information about a piece of metadata.
  59. struct MDIndex {
  60. unsigned F = 0; ///< The ID of the function for this metadata, if any.
  61. unsigned ID = 0; ///< The implicit ID of this metadata in bitcode.
  62. MDIndex() = default;
  63. explicit MDIndex(unsigned F) : F(F) {}
  64. /// Check if this has a function tag, and it's different from NewF.
  65. bool hasDifferentFunction(unsigned NewF) const { return F && F != NewF; }
  66. /// Fetch the MD this references out of the given metadata array.
  67. const Metadata *get(ArrayRef<const Metadata *> MDs) const {
  68. assert(ID && "Expected non-zero ID");
  69. assert(ID <= MDs.size() && "Expected valid ID");
  70. return MDs[ID - 1];
  71. }
  72. };
  73. using MetadataMapType = DenseMap<const Metadata *, MDIndex>;
  74. MetadataMapType MetadataMap;
  75. /// Range of metadata IDs, as a half-open range.
  76. struct MDRange {
  77. unsigned First = 0;
  78. unsigned Last = 0;
  79. /// Number of strings in the prefix of the metadata range.
  80. unsigned NumStrings = 0;
  81. MDRange() = default;
  82. explicit MDRange(unsigned First) : First(First) {}
  83. };
  84. SmallDenseMap<unsigned, MDRange, 1> FunctionMDInfo;
  85. bool ShouldPreserveUseListOrder;
  86. using AttributeGroupMapType = DenseMap<IndexAndAttrSet, unsigned>;
  87. AttributeGroupMapType AttributeGroupMap;
  88. std::vector<IndexAndAttrSet> AttributeGroups;
  89. using AttributeListMapType = DenseMap<AttributeList, unsigned>;
  90. AttributeListMapType AttributeListMap;
  91. std::vector<AttributeList> AttributeLists;
  92. /// GlobalBasicBlockIDs - This map memoizes the basic block ID's referenced by
  93. /// the "getGlobalBasicBlockID" method.
  94. mutable DenseMap<const BasicBlock*, unsigned> GlobalBasicBlockIDs;
  95. using InstructionMapType = DenseMap<const Instruction *, unsigned>;
  96. InstructionMapType InstructionMap;
  97. unsigned InstructionCount;
  98. /// BasicBlocks - This contains all the basic blocks for the currently
  99. /// incorporated function. Their reverse mapping is stored in ValueMap.
  100. std::vector<const BasicBlock*> BasicBlocks;
  101. /// When a function is incorporated, this is the size of the Values list
  102. /// before incorporation.
  103. unsigned NumModuleValues;
  104. /// When a function is incorporated, this is the size of the Metadatas list
  105. /// before incorporation.
  106. unsigned NumModuleMDs = 0;
  107. unsigned NumMDStrings = 0;
  108. unsigned FirstFuncConstantID;
  109. unsigned FirstInstID;
  110. public:
  111. ValueEnumerator(const Module &M, bool ShouldPreserveUseListOrder);
  112. ValueEnumerator(const ValueEnumerator &) = delete;
  113. ValueEnumerator &operator=(const ValueEnumerator &) = delete;
  114. void dump() const;
  115. void print(raw_ostream &OS, const ValueMapType &Map, const char *Name) const;
  116. void print(raw_ostream &OS, const MetadataMapType &Map,
  117. const char *Name) const;
  118. unsigned getValueID(const Value *V) const;
  119. unsigned getMetadataID(const Metadata *MD) const {
  120. auto ID = getMetadataOrNullID(MD);
  121. assert(ID != 0 && "Metadata not in slotcalculator!");
  122. return ID - 1;
  123. }
  124. unsigned getMetadataOrNullID(const Metadata *MD) const {
  125. return MetadataMap.lookup(MD).ID;
  126. }
  127. unsigned numMDs() const { return MDs.size(); }
  128. bool shouldPreserveUseListOrder() const { return ShouldPreserveUseListOrder; }
  129. unsigned getTypeID(Type *T) const {
  130. TypeMapType::const_iterator I = TypeMap.find(T);
  131. assert(I != TypeMap.end() && "Type not in ValueEnumerator!");
  132. return I->second-1;
  133. }
  134. unsigned getInstructionID(const Instruction *I) const;
  135. void setInstructionID(const Instruction *I);
  136. unsigned getAttributeListID(AttributeList PAL) const {
  137. if (PAL.isEmpty()) return 0; // Null maps to zero.
  138. AttributeListMapType::const_iterator I = AttributeListMap.find(PAL);
  139. assert(I != AttributeListMap.end() && "Attribute not in ValueEnumerator!");
  140. return I->second;
  141. }
  142. unsigned getAttributeGroupID(IndexAndAttrSet Group) const {
  143. if (!Group.second.hasAttributes())
  144. return 0; // Null maps to zero.
  145. AttributeGroupMapType::const_iterator I = AttributeGroupMap.find(Group);
  146. assert(I != AttributeGroupMap.end() && "Attribute not in ValueEnumerator!");
  147. return I->second;
  148. }
  149. /// getFunctionConstantRange - Return the range of values that corresponds to
  150. /// function-local constants.
  151. void getFunctionConstantRange(unsigned &Start, unsigned &End) const {
  152. Start = FirstFuncConstantID;
  153. End = FirstInstID;
  154. }
  155. const ValueList &getValues() const { return Values; }
  156. /// Check whether the current block has any metadata to emit.
  157. bool hasMDs() const { return NumModuleMDs < MDs.size(); }
  158. /// Get the MDString metadata for this block.
  159. ArrayRef<const Metadata *> getMDStrings() const {
  160. return ArrayRef(MDs).slice(NumModuleMDs, NumMDStrings);
  161. }
  162. /// Get the non-MDString metadata for this block.
  163. ArrayRef<const Metadata *> getNonMDStrings() const {
  164. return ArrayRef(MDs).slice(NumModuleMDs).slice(NumMDStrings);
  165. }
  166. const TypeList &getTypes() const { return Types; }
  167. const std::vector<const BasicBlock*> &getBasicBlocks() const {
  168. return BasicBlocks;
  169. }
  170. const std::vector<AttributeList> &getAttributeLists() const { return AttributeLists; }
  171. const std::vector<IndexAndAttrSet> &getAttributeGroups() const {
  172. return AttributeGroups;
  173. }
  174. const ComdatSetType &getComdats() const { return Comdats; }
  175. unsigned getComdatID(const Comdat *C) const;
  176. /// getGlobalBasicBlockID - This returns the function-specific ID for the
  177. /// specified basic block. This is relatively expensive information, so it
  178. /// should only be used by rare constructs such as address-of-label.
  179. unsigned getGlobalBasicBlockID(const BasicBlock *BB) const;
  180. /// incorporateFunction/purgeFunction - If you'd like to deal with a function,
  181. /// use these two methods to get its data into the ValueEnumerator!
  182. void incorporateFunction(const Function &F);
  183. void purgeFunction();
  184. uint64_t computeBitsRequiredForTypeIndicies() const;
  185. private:
  186. void OptimizeConstants(unsigned CstStart, unsigned CstEnd);
  187. /// Reorder the reachable metadata.
  188. ///
  189. /// This is not just an optimization, but is mandatory for emitting MDString
  190. /// correctly.
  191. void organizeMetadata();
  192. /// Drop the function tag from the transitive operands of the given node.
  193. void dropFunctionFromMetadata(MetadataMapType::value_type &FirstMD);
  194. /// Incorporate the function metadata.
  195. ///
  196. /// This should be called before enumerating LocalAsMetadata for the
  197. /// function.
  198. void incorporateFunctionMetadata(const Function &F);
  199. /// Enumerate a single instance of metadata with the given function tag.
  200. ///
  201. /// If \c MD has already been enumerated, check that \c F matches its
  202. /// function tag. If not, call \a dropFunctionFromMetadata().
  203. ///
  204. /// Otherwise, mark \c MD as visited. Assign it an ID, or just return it if
  205. /// it's an \a MDNode.
  206. const MDNode *enumerateMetadataImpl(unsigned F, const Metadata *MD);
  207. unsigned getMetadataFunctionID(const Function *F) const;
  208. /// Enumerate reachable metadata in (almost) post-order.
  209. ///
  210. /// Enumerate all the metadata reachable from MD. We want to minimize the
  211. /// cost of reading bitcode records, and so the primary consideration is that
  212. /// operands of uniqued nodes are resolved before the nodes are read. This
  213. /// avoids re-uniquing them on the context and factors away RAUW support.
  214. ///
  215. /// This algorithm guarantees that subgraphs of uniqued nodes are in
  216. /// post-order. Distinct subgraphs reachable only from a single uniqued node
  217. /// will be in post-order.
  218. ///
  219. /// \note The relative order of a distinct and uniqued node is irrelevant.
  220. /// \a organizeMetadata() will later partition distinct nodes ahead of
  221. /// uniqued ones.
  222. ///{
  223. void EnumerateMetadata(const Function *F, const Metadata *MD);
  224. void EnumerateMetadata(unsigned F, const Metadata *MD);
  225. ///}
  226. void EnumerateFunctionLocalMetadata(const Function &F,
  227. const LocalAsMetadata *Local);
  228. void EnumerateFunctionLocalMetadata(unsigned F, const LocalAsMetadata *Local);
  229. void EnumerateFunctionLocalListMetadata(const Function &F,
  230. const DIArgList *ArgList);
  231. void EnumerateFunctionLocalListMetadata(unsigned F, const DIArgList *Arglist);
  232. void EnumerateNamedMDNode(const NamedMDNode *NMD);
  233. void EnumerateValue(const Value *V);
  234. void EnumerateType(Type *T);
  235. void EnumerateOperandType(const Value *V);
  236. void EnumerateAttributes(AttributeList PAL);
  237. void EnumerateValueSymbolTable(const ValueSymbolTable &ST);
  238. void EnumerateNamedMetadata(const Module &M);
  239. };
  240. } // end namespace llvm
  241. #endif // LLVM_LIB_BITCODE_WRITER_VALUEENUMERATOR_H