1 //===- BitcodeReader.h - Internal BitcodeReader impl ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This header defines the BitcodeReader class.
12 //===----------------------------------------------------------------------===//
14 #ifndef BITCODE_READER_H
15 #define BITCODE_READER_H
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/Bitcode/BitstreamReader.h"
19 #include "llvm/Bitcode/LLVMBitCodes.h"
20 #include "llvm/IR/Attributes.h"
21 #include "llvm/IR/GVMaterializer.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Type.h"
24 #include "llvm/IR/ValueHandle.h"
25 #include <system_error>
33 //===----------------------------------------------------------------------===//
34 // BitcodeReaderValueList Class
35 //===----------------------------------------------------------------------===//
37 class BitcodeReaderValueList {
38 std::vector<WeakVH> ValuePtrs;
40 /// ResolveConstants - As we resolve forward-referenced constants, we add
41 /// information about them to this vector. This allows us to resolve them in
42 /// bulk instead of resolving each reference at a time. See the code in
43 /// ResolveConstantForwardRefs for more information about this.
45 /// The key of this vector is the placeholder constant, the value is the slot
46 /// number that holds the resolved value.
47 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
48 ResolveConstantsTy ResolveConstants;
51 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
52 ~BitcodeReaderValueList() {
53 assert(ResolveConstants.empty() && "Constants not resolved?");
56 // vector compatibility methods
57 unsigned size() const { return ValuePtrs.size(); }
58 void resize(unsigned N) { ValuePtrs.resize(N); }
59 void push_back(Value *V) {
60 ValuePtrs.push_back(V);
64 assert(ResolveConstants.empty() && "Constants not resolved?");
68 Value *operator[](unsigned i) const {
69 assert(i < ValuePtrs.size());
73 Value *back() const { return ValuePtrs.back(); }
74 void pop_back() { ValuePtrs.pop_back(); }
75 bool empty() const { return ValuePtrs.empty(); }
76 void shrinkTo(unsigned N) {
77 assert(N <= size() && "Invalid shrinkTo request!");
81 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
82 Value *getValueFwdRef(unsigned Idx, Type *Ty);
84 void AssignValue(Value *V, unsigned Idx);
86 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
87 /// resolves any forward references.
88 void ResolveConstantForwardRefs();
92 //===----------------------------------------------------------------------===//
93 // BitcodeReaderMDValueList Class
94 //===----------------------------------------------------------------------===//
96 class BitcodeReaderMDValueList {
97 std::vector<WeakVH> MDValuePtrs;
101 BitcodeReaderMDValueList(LLVMContext& C) : Context(C) {}
103 // vector compatibility methods
104 unsigned size() const { return MDValuePtrs.size(); }
105 void resize(unsigned N) { MDValuePtrs.resize(N); }
106 void push_back(Value *V) { MDValuePtrs.push_back(V); }
107 void clear() { MDValuePtrs.clear(); }
108 Value *back() const { return MDValuePtrs.back(); }
109 void pop_back() { MDValuePtrs.pop_back(); }
110 bool empty() const { return MDValuePtrs.empty(); }
112 Value *operator[](unsigned i) const {
113 assert(i < MDValuePtrs.size());
114 return MDValuePtrs[i];
117 void shrinkTo(unsigned N) {
118 assert(N <= size() && "Invalid shrinkTo request!");
119 MDValuePtrs.resize(N);
122 Value *getValueFwdRef(unsigned Idx);
123 void AssignValue(Value *V, unsigned Idx);
126 class BitcodeReader : public GVMaterializer {
127 LLVMContext &Context;
129 std::unique_ptr<MemoryBuffer> Buffer;
130 std::unique_ptr<BitstreamReader> StreamFile;
131 BitstreamCursor Stream;
132 DataStreamer *LazyStreamer;
133 uint64_t NextUnreadBit;
134 bool SeenValueSymbolTable;
136 std::vector<Type*> TypeList;
137 BitcodeReaderValueList ValueList;
138 BitcodeReaderMDValueList MDValueList;
139 std::vector<Comdat *> ComdatList;
140 SmallVector<Instruction *, 64> InstructionList;
142 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
143 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
144 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
146 SmallVector<Instruction*, 64> InstsWithTBAATag;
148 /// MAttributes - The set of attributes by index. Index zero in the
149 /// file is for null, and is thus not represented here. As such all indices
151 std::vector<AttributeSet> MAttributes;
153 /// \brief The set of attribute groups.
154 std::map<unsigned, AttributeSet> MAttributeGroups;
156 /// FunctionBBs - While parsing a function body, this is a list of the basic
157 /// blocks for the function.
158 std::vector<BasicBlock*> FunctionBBs;
160 // When reading the module header, this list is populated with functions that
161 // have bodies later in the file.
162 std::vector<Function*> FunctionsWithBodies;
164 // When intrinsic functions are encountered which require upgrading they are
165 // stored here with their replacement function.
166 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
167 UpgradedIntrinsicMap UpgradedIntrinsics;
169 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
170 DenseMap<unsigned, unsigned> MDKindMap;
172 // Several operations happen after the module header has been read, but
173 // before function bodies are processed. This keeps track of whether
174 // we've done this yet.
175 bool SeenFirstFunctionBody;
177 /// DeferredFunctionInfo - When function bodies are initially scanned, this
178 /// map contains info about where to find deferred function body in the
180 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
182 /// BlockAddrFwdRefs - These are blockaddr references to basic blocks. These
183 /// are resolved lazily when functions are loaded.
184 typedef std::pair<unsigned, GlobalVariable*> BlockAddrRefTy;
185 DenseMap<Function*, std::vector<BlockAddrRefTy> > BlockAddrFwdRefs;
187 /// UseRelativeIDs - Indicates that we are using a new encoding for
188 /// instruction operands where most operands in the current
189 /// FUNCTION_BLOCK are encoded relative to the instruction number,
190 /// for a more compact encoding. Some instruction operands are not
191 /// relative to the instruction ID: basic block numbers, and types.
192 /// Once the old style function blocks have been phased out, we would
193 /// not need this flag.
196 /// True if all functions will be materialized, negating the need to process
197 /// (e.g.) blockaddress forward references.
198 bool WillMaterializeAllForwardRefs;
200 /// Functions that have block addresses taken. This is usually empty.
201 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
204 std::error_code Error(BitcodeError E) { return make_error_code(E); }
206 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
207 : Context(C), TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
208 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
209 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
210 WillMaterializeAllForwardRefs(false) {}
211 explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C)
212 : Context(C), TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
213 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
214 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
215 WillMaterializeAllForwardRefs(false) {}
216 ~BitcodeReader() { FreeState(); }
218 std::error_code materializeForwardReferencedFunctions();
222 void releaseBuffer() override;
224 bool isMaterializable(const GlobalValue *GV) const override;
225 bool isDematerializable(const GlobalValue *GV) const override;
226 std::error_code Materialize(GlobalValue *GV) override;
227 std::error_code MaterializeModule(Module *M) override;
228 void Dematerialize(GlobalValue *GV) override;
230 /// @brief Main interface to parsing a bitcode buffer.
231 /// @returns true if an error occurred.
232 std::error_code ParseBitcodeInto(Module *M);
234 /// @brief Cheap mechanism to just extract module triple
235 /// @returns true if an error occurred.
236 ErrorOr<std::string> parseTriple();
238 static uint64_t decodeSignRotatedValue(uint64_t V);
241 Type *getTypeByID(unsigned ID);
242 Value *getFnValueByID(unsigned ID, Type *Ty) {
243 if (Ty && Ty->isMetadataTy())
244 return MDValueList.getValueFwdRef(ID);
245 return ValueList.getValueFwdRef(ID, Ty);
247 BasicBlock *getBasicBlock(unsigned ID) const {
248 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
249 return FunctionBBs[ID];
251 AttributeSet getAttributes(unsigned i) const {
252 if (i-1 < MAttributes.size())
253 return MAttributes[i-1];
254 return AttributeSet();
257 /// getValueTypePair - Read a value/type pair out of the specified record from
258 /// slot 'Slot'. Increment Slot past the number of slots used in the record.
259 /// Return true on failure.
260 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
261 unsigned InstNum, Value *&ResVal) {
262 if (Slot == Record.size()) return true;
263 unsigned ValNo = (unsigned)Record[Slot++];
264 // Adjust the ValNo, if it was encoded relative to the InstNum.
266 ValNo = InstNum - ValNo;
267 if (ValNo < InstNum) {
268 // If this is not a forward reference, just return the value we already
270 ResVal = getFnValueByID(ValNo, nullptr);
271 return ResVal == nullptr;
272 } else if (Slot == Record.size()) {
276 unsigned TypeNo = (unsigned)Record[Slot++];
277 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
278 return ResVal == nullptr;
281 /// popValue - Read a value out of the specified record from slot 'Slot'.
282 /// Increment Slot past the number of slots used by the value in the record.
283 /// Return true if there is an error.
284 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
285 unsigned InstNum, Type *Ty, Value *&ResVal) {
286 if (getValue(Record, Slot, InstNum, Ty, ResVal))
288 // All values currently take a single record slot.
293 /// getValue -- Like popValue, but does not increment the Slot number.
294 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
295 unsigned InstNum, Type *Ty, Value *&ResVal) {
296 ResVal = getValue(Record, Slot, InstNum, Ty);
297 return ResVal == nullptr;
300 /// getValue -- Version of getValue that returns ResVal directly,
301 /// or 0 if there is an error.
302 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
303 unsigned InstNum, Type *Ty) {
304 if (Slot == Record.size()) return nullptr;
305 unsigned ValNo = (unsigned)Record[Slot];
306 // Adjust the ValNo, if it was encoded relative to the InstNum.
308 ValNo = InstNum - ValNo;
309 return getFnValueByID(ValNo, Ty);
312 /// getValueSigned -- Like getValue, but decodes signed VBRs.
313 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
314 unsigned InstNum, Type *Ty) {
315 if (Slot == Record.size()) return nullptr;
316 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
317 // Adjust the ValNo, if it was encoded relative to the InstNum.
319 ValNo = InstNum - ValNo;
320 return getFnValueByID(ValNo, Ty);
323 std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
324 std::error_code ParseModule(bool Resume);
325 std::error_code ParseAttributeBlock();
326 std::error_code ParseAttributeGroupBlock();
327 std::error_code ParseTypeTable();
328 std::error_code ParseTypeTableBody();
330 std::error_code ParseValueSymbolTable();
331 std::error_code ParseConstants();
332 std::error_code RememberAndSkipFunctionBody();
333 std::error_code ParseFunctionBody(Function *F);
334 std::error_code GlobalCleanup();
335 std::error_code ResolveGlobalAndAliasInits();
336 std::error_code ParseMetadata();
337 std::error_code ParseMetadataAttachment();
338 ErrorOr<std::string> parseModuleTriple();
339 std::error_code ParseUseLists();
340 std::error_code InitStream();
341 std::error_code InitStreamFromBuffer();
342 std::error_code InitLazyStream();
343 std::error_code FindFunctionInStream(
345 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
348 } // End llvm namespace