BitcodeReader.h 13 KB

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