BitcodeReader.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. //===- BitcodeReader.h - Internal BitcodeReader impl ------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This header defines the BitcodeReader class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_LIB_BITCODE_READER_BITCODEREADER_H
  14. #define LLVM_LIB_BITCODE_READER_BITCODEREADER_H
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/Bitcode/BitstreamReader.h"
  17. #include "llvm/Bitcode/LLVMBitCodes.h"
  18. #include "llvm/IR/Attributes.h"
  19. #include "llvm/IR/GVMaterializer.h"
  20. #include "llvm/IR/OperandTraits.h"
  21. #include "llvm/IR/Type.h"
  22. #include "llvm/IR/ValueHandle.h"
  23. #include <deque>
  24. #include <system_error>
  25. #include <vector>
  26. namespace llvm {
  27. class Comdat;
  28. class MemoryBuffer;
  29. class LLVMContext;
  30. //===----------------------------------------------------------------------===//
  31. // BitcodeReaderValueList Class
  32. //===----------------------------------------------------------------------===//
  33. class BitcodeReaderValueList {
  34. std::vector<WeakVH> ValuePtrs;
  35. /// ResolveConstants - As we resolve forward-referenced constants, we add
  36. /// information about them to this vector. This allows us to resolve them in
  37. /// bulk instead of resolving each reference at a time. See the code in
  38. /// ResolveConstantForwardRefs for more information about this.
  39. ///
  40. /// The key of this vector is the placeholder constant, the value is the slot
  41. /// number that holds the resolved value.
  42. typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
  43. ResolveConstantsTy ResolveConstants;
  44. LLVMContext &Context;
  45. public:
  46. BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
  47. ~BitcodeReaderValueList() {
  48. assert(ResolveConstants.empty() && "Constants not resolved?");
  49. }
  50. // vector compatibility methods
  51. unsigned size() const { return ValuePtrs.size(); }
  52. void resize(unsigned N) { ValuePtrs.resize(N); }
  53. void push_back(Value *V) {
  54. ValuePtrs.push_back(V);
  55. }
  56. void clear() {
  57. assert(ResolveConstants.empty() && "Constants not resolved?");
  58. ValuePtrs.clear();
  59. }
  60. Value *operator[](unsigned i) const {
  61. assert(i < ValuePtrs.size());
  62. return ValuePtrs[i];
  63. }
  64. Value *back() const { return ValuePtrs.back(); }
  65. void pop_back() { ValuePtrs.pop_back(); }
  66. bool empty() const { return ValuePtrs.empty(); }
  67. void shrinkTo(unsigned N) {
  68. assert(N <= size() && "Invalid shrinkTo request!");
  69. ValuePtrs.resize(N);
  70. }
  71. Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
  72. Value *getValueFwdRef(unsigned Idx, Type *Ty);
  73. void AssignValue(Value *V, unsigned Idx);
  74. /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
  75. /// resolves any forward references.
  76. void ResolveConstantForwardRefs();
  77. };
  78. //===----------------------------------------------------------------------===//
  79. // BitcodeReaderMDValueList Class
  80. //===----------------------------------------------------------------------===//
  81. class BitcodeReaderMDValueList {
  82. std::vector<WeakVH> MDValuePtrs;
  83. LLVMContext &Context;
  84. public:
  85. BitcodeReaderMDValueList(LLVMContext& C) : Context(C) {}
  86. // vector compatibility methods
  87. unsigned size() const { return MDValuePtrs.size(); }
  88. void resize(unsigned N) { MDValuePtrs.resize(N); }
  89. void push_back(Value *V) { MDValuePtrs.push_back(V); }
  90. void clear() { MDValuePtrs.clear(); }
  91. Value *back() const { return MDValuePtrs.back(); }
  92. void pop_back() { MDValuePtrs.pop_back(); }
  93. bool empty() const { return MDValuePtrs.empty(); }
  94. Value *operator[](unsigned i) const {
  95. assert(i < MDValuePtrs.size());
  96. return MDValuePtrs[i];
  97. }
  98. void shrinkTo(unsigned N) {
  99. assert(N <= size() && "Invalid shrinkTo request!");
  100. MDValuePtrs.resize(N);
  101. }
  102. Value *getValueFwdRef(unsigned Idx);
  103. void AssignValue(Value *V, unsigned Idx);
  104. };
  105. class BitcodeReader : public GVMaterializer {
  106. LLVMContext &Context;
  107. Module *TheModule;
  108. std::unique_ptr<MemoryBuffer> Buffer;
  109. std::unique_ptr<BitstreamReader> StreamFile;
  110. BitstreamCursor Stream;
  111. DataStreamer *LazyStreamer;
  112. uint64_t NextUnreadBit;
  113. bool SeenValueSymbolTable;
  114. std::vector<Type*> TypeList;
  115. BitcodeReaderValueList ValueList;
  116. BitcodeReaderMDValueList MDValueList;
  117. std::vector<Comdat *> ComdatList;
  118. SmallVector<Instruction *, 64> InstructionList;
  119. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
  120. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
  121. std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
  122. std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
  123. SmallVector<Instruction*, 64> InstsWithTBAATag;
  124. /// MAttributes - The set of attributes by index. Index zero in the
  125. /// file is for null, and is thus not represented here. As such all indices
  126. /// are off by one.
  127. std::vector<AttributeSet> MAttributes;
  128. /// \brief The set of attribute groups.
  129. std::map<unsigned, AttributeSet> MAttributeGroups;
  130. /// FunctionBBs - While parsing a function body, this is a list of the basic
  131. /// blocks for the function.
  132. std::vector<BasicBlock*> FunctionBBs;
  133. // When reading the module header, this list is populated with functions that
  134. // have bodies later in the file.
  135. std::vector<Function*> FunctionsWithBodies;
  136. // When intrinsic functions are encountered which require upgrading they are
  137. // stored here with their replacement function.
  138. typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
  139. UpgradedIntrinsicMap UpgradedIntrinsics;
  140. // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
  141. DenseMap<unsigned, unsigned> MDKindMap;
  142. // Several operations happen after the module header has been read, but
  143. // before function bodies are processed. This keeps track of whether
  144. // we've done this yet.
  145. bool SeenFirstFunctionBody;
  146. /// DeferredFunctionInfo - When function bodies are initially scanned, this
  147. /// map contains info about where to find deferred function body in the
  148. /// stream.
  149. DenseMap<Function*, uint64_t> DeferredFunctionInfo;
  150. /// These are basic blocks forward-referenced by block addresses. They are
  151. /// inserted lazily into functions when they're loaded. The basic block ID is
  152. /// its index into the vector.
  153. DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
  154. std::deque<Function *> BasicBlockFwdRefQueue;
  155. /// UseRelativeIDs - Indicates that we are using a new encoding for
  156. /// instruction operands where most operands in the current
  157. /// FUNCTION_BLOCK are encoded relative to the instruction number,
  158. /// for a more compact encoding. Some instruction operands are not
  159. /// relative to the instruction ID: basic block numbers, and types.
  160. /// Once the old style function blocks have been phased out, we would
  161. /// not need this flag.
  162. bool UseRelativeIDs;
  163. /// True if all functions will be materialized, negating the need to process
  164. /// (e.g.) blockaddress forward references.
  165. bool WillMaterializeAllForwardRefs;
  166. /// Functions that have block addresses taken. This is usually empty.
  167. SmallPtrSet<const Function *, 4> BlockAddressesTaken;
  168. public:
  169. std::error_code Error(BitcodeError E) { return make_error_code(E); }
  170. explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
  171. : Context(C), TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
  172. NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
  173. MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
  174. WillMaterializeAllForwardRefs(false) {}
  175. explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C)
  176. : Context(C), TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
  177. NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
  178. MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
  179. WillMaterializeAllForwardRefs(false) {}
  180. ~BitcodeReader() { FreeState(); }
  181. std::error_code materializeForwardReferencedFunctions();
  182. void FreeState();
  183. void releaseBuffer();
  184. bool isDematerializable(const GlobalValue *GV) const override;
  185. std::error_code materialize(GlobalValue *GV) override;
  186. std::error_code MaterializeModule(Module *M) override;
  187. std::vector<StructType *> getIdentifiedStructTypes() const override;
  188. void Dematerialize(GlobalValue *GV) override;
  189. /// @brief Main interface to parsing a bitcode buffer.
  190. /// @returns true if an error occurred.
  191. std::error_code ParseBitcodeInto(Module *M);
  192. /// @brief Cheap mechanism to just extract module triple
  193. /// @returns true if an error occurred.
  194. ErrorOr<std::string> parseTriple();
  195. static uint64_t decodeSignRotatedValue(uint64_t V);
  196. private:
  197. std::vector<StructType *> IdentifiedStructTypes;
  198. StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
  199. StructType *createIdentifiedStructType(LLVMContext &Context);
  200. Type *getTypeByID(unsigned ID);
  201. Value *getFnValueByID(unsigned ID, Type *Ty) {
  202. if (Ty && Ty->isMetadataTy())
  203. return MDValueList.getValueFwdRef(ID);
  204. return ValueList.getValueFwdRef(ID, Ty);
  205. }
  206. BasicBlock *getBasicBlock(unsigned ID) const {
  207. if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
  208. return FunctionBBs[ID];
  209. }
  210. AttributeSet getAttributes(unsigned i) const {
  211. if (i-1 < MAttributes.size())
  212. return MAttributes[i-1];
  213. return AttributeSet();
  214. }
  215. /// getValueTypePair - Read a value/type pair out of the specified record from
  216. /// slot 'Slot'. Increment Slot past the number of slots used in the record.
  217. /// Return true on failure.
  218. bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  219. unsigned InstNum, Value *&ResVal) {
  220. if (Slot == Record.size()) return true;
  221. unsigned ValNo = (unsigned)Record[Slot++];
  222. // Adjust the ValNo, if it was encoded relative to the InstNum.
  223. if (UseRelativeIDs)
  224. ValNo = InstNum - ValNo;
  225. if (ValNo < InstNum) {
  226. // If this is not a forward reference, just return the value we already
  227. // have.
  228. ResVal = getFnValueByID(ValNo, nullptr);
  229. return ResVal == nullptr;
  230. } else if (Slot == Record.size()) {
  231. return true;
  232. }
  233. unsigned TypeNo = (unsigned)Record[Slot++];
  234. ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
  235. return ResVal == nullptr;
  236. }
  237. /// popValue - Read a value out of the specified record from slot 'Slot'.
  238. /// Increment Slot past the number of slots used by the value in the record.
  239. /// Return true if there is an error.
  240. bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  241. unsigned InstNum, Type *Ty, Value *&ResVal) {
  242. if (getValue(Record, Slot, InstNum, Ty, ResVal))
  243. return true;
  244. // All values currently take a single record slot.
  245. ++Slot;
  246. return false;
  247. }
  248. /// getValue -- Like popValue, but does not increment the Slot number.
  249. bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  250. unsigned InstNum, Type *Ty, Value *&ResVal) {
  251. ResVal = getValue(Record, Slot, InstNum, Ty);
  252. return ResVal == nullptr;
  253. }
  254. /// getValue -- Version of getValue that returns ResVal directly,
  255. /// or 0 if there is an error.
  256. Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  257. unsigned InstNum, Type *Ty) {
  258. if (Slot == Record.size()) return nullptr;
  259. unsigned ValNo = (unsigned)Record[Slot];
  260. // Adjust the ValNo, if it was encoded relative to the InstNum.
  261. if (UseRelativeIDs)
  262. ValNo = InstNum - ValNo;
  263. return getFnValueByID(ValNo, Ty);
  264. }
  265. /// getValueSigned -- Like getValue, but decodes signed VBRs.
  266. Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  267. unsigned InstNum, Type *Ty) {
  268. if (Slot == Record.size()) return nullptr;
  269. unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
  270. // Adjust the ValNo, if it was encoded relative to the InstNum.
  271. if (UseRelativeIDs)
  272. ValNo = InstNum - ValNo;
  273. return getFnValueByID(ValNo, Ty);
  274. }
  275. std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
  276. std::error_code ParseModule(bool Resume);
  277. std::error_code ParseAttributeBlock();
  278. std::error_code ParseAttributeGroupBlock();
  279. std::error_code ParseTypeTable();
  280. std::error_code ParseTypeTableBody();
  281. std::error_code ParseValueSymbolTable();
  282. std::error_code ParseConstants();
  283. std::error_code RememberAndSkipFunctionBody();
  284. std::error_code ParseFunctionBody(Function *F);
  285. std::error_code GlobalCleanup();
  286. std::error_code ResolveGlobalAndAliasInits();
  287. std::error_code ParseMetadata();
  288. std::error_code ParseMetadataAttachment();
  289. ErrorOr<std::string> parseModuleTriple();
  290. std::error_code ParseUseLists();
  291. std::error_code InitStream();
  292. std::error_code InitStreamFromBuffer();
  293. std::error_code InitLazyStream();
  294. std::error_code FindFunctionInStream(
  295. Function *F,
  296. DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
  297. };
  298. } // End llvm namespace
  299. #endif