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 LLVM_LIB_BITCODE_READER_BITCODEREADER_H
15 #define LLVM_LIB_BITCODE_READER_BITCODEREADER_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"
26 #include <system_error>
34 //===----------------------------------------------------------------------===//
35 // BitcodeReaderValueList Class
36 //===----------------------------------------------------------------------===//
38 class BitcodeReaderValueList {
39 std::vector<WeakVH> ValuePtrs;
41 /// ResolveConstants - As we resolve forward-referenced constants, we add
42 /// information about them to this vector. This allows us to resolve them in
43 /// bulk instead of resolving each reference at a time. See the code in
44 /// ResolveConstantForwardRefs for more information about this.
46 /// The key of this vector is the placeholder constant, the value is the slot
47 /// number that holds the resolved value.
48 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
49 ResolveConstantsTy ResolveConstants;
52 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
53 ~BitcodeReaderValueList() {
54 assert(ResolveConstants.empty() && "Constants not resolved?");
57 // vector compatibility methods
58 unsigned size() const { return ValuePtrs.size(); }
59 void resize(unsigned N) { ValuePtrs.resize(N); }
60 void push_back(Value *V) {
61 ValuePtrs.push_back(V);
65 assert(ResolveConstants.empty() && "Constants not resolved?");
69 Value *operator[](unsigned i) const {
70 assert(i < ValuePtrs.size());
74 Value *back() const { return ValuePtrs.back(); }
75 void pop_back() { ValuePtrs.pop_back(); }
76 bool empty() const { return ValuePtrs.empty(); }
77 void shrinkTo(unsigned N) {
78 assert(N <= size() && "Invalid shrinkTo request!");
82 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
83 Value *getValueFwdRef(unsigned Idx, Type *Ty);
85 void AssignValue(Value *V, unsigned Idx);
87 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
88 /// resolves any forward references.
89 void ResolveConstantForwardRefs();
93 //===----------------------------------------------------------------------===//
94 // BitcodeReaderMDValueList Class
95 //===----------------------------------------------------------------------===//
97 class BitcodeReaderMDValueList {
98 std::vector<WeakVH> MDValuePtrs;
100 LLVMContext &Context;
102 BitcodeReaderMDValueList(LLVMContext& C) : Context(C) {}
104 // vector compatibility methods
105 unsigned size() const { return MDValuePtrs.size(); }
106 void resize(unsigned N) { MDValuePtrs.resize(N); }
107 void push_back(Value *V) { MDValuePtrs.push_back(V); }
108 void clear() { MDValuePtrs.clear(); }
109 Value *back() const { return MDValuePtrs.back(); }
110 void pop_back() { MDValuePtrs.pop_back(); }
111 bool empty() const { return MDValuePtrs.empty(); }
113 Value *operator[](unsigned i) const {
114 assert(i < MDValuePtrs.size());
115 return MDValuePtrs[i];
118 void shrinkTo(unsigned N) {
119 assert(N <= size() && "Invalid shrinkTo request!");
120 MDValuePtrs.resize(N);
123 Value *getValueFwdRef(unsigned Idx);
124 void AssignValue(Value *V, unsigned Idx);
127 class BitcodeReader : public GVMaterializer {
128 LLVMContext &Context;
130 std::unique_ptr<MemoryBuffer> Buffer;
131 std::unique_ptr<BitstreamReader> StreamFile;
132 BitstreamCursor Stream;
133 DataStreamer *LazyStreamer;
134 uint64_t NextUnreadBit;
135 bool SeenValueSymbolTable;
137 std::vector<Type*> TypeList;
138 BitcodeReaderValueList ValueList;
139 BitcodeReaderMDValueList MDValueList;
140 std::vector<Comdat *> ComdatList;
141 SmallVector<Instruction *, 64> InstructionList;
143 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
144 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
145 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
147 SmallVector<Instruction*, 64> InstsWithTBAATag;
149 /// MAttributes - The set of attributes by index. Index zero in the
150 /// file is for null, and is thus not represented here. As such all indices
152 std::vector<AttributeSet> MAttributes;
154 /// \brief The set of attribute groups.
155 std::map<unsigned, AttributeSet> MAttributeGroups;
157 /// FunctionBBs - While parsing a function body, this is a list of the basic
158 /// blocks for the function.
159 std::vector<BasicBlock*> FunctionBBs;
161 // When reading the module header, this list is populated with functions that
162 // have bodies later in the file.
163 std::vector<Function*> FunctionsWithBodies;
165 // When intrinsic functions are encountered which require upgrading they are
166 // stored here with their replacement function.
167 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
168 UpgradedIntrinsicMap UpgradedIntrinsics;
170 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
171 DenseMap<unsigned, unsigned> MDKindMap;
173 // Several operations happen after the module header has been read, but
174 // before function bodies are processed. This keeps track of whether
175 // we've done this yet.
176 bool SeenFirstFunctionBody;
178 /// DeferredFunctionInfo - When function bodies are initially scanned, this
179 /// map contains info about where to find deferred function body in the
181 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
183 /// These are basic blocks forward-referenced by block addresses. They are
184 /// inserted lazily into functions when they're loaded. The basic block ID is
185 /// its index into the vector.
186 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
187 std::deque<Function *> BasicBlockFwdRefQueue;
189 /// UseRelativeIDs - Indicates that we are using a new encoding for
190 /// instruction operands where most operands in the current
191 /// FUNCTION_BLOCK are encoded relative to the instruction number,
192 /// for a more compact encoding. Some instruction operands are not
193 /// relative to the instruction ID: basic block numbers, and types.
194 /// Once the old style function blocks have been phased out, we would
195 /// not need this flag.
198 /// True if all functions will be materialized, negating the need to process
199 /// (e.g.) blockaddress forward references.
200 bool WillMaterializeAllForwardRefs;
202 /// Functions that have block addresses taken. This is usually empty.
203 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
206 std::error_code Error(BitcodeError E) { return make_error_code(E); }
208 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
209 : Context(C), TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
210 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
211 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
212 WillMaterializeAllForwardRefs(false) {}
213 explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C)
214 : Context(C), TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
215 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
216 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
217 WillMaterializeAllForwardRefs(false) {}
218 ~BitcodeReader() { FreeState(); }
220 std::error_code materializeForwardReferencedFunctions();
224 void releaseBuffer();
226 bool isMaterializable(const GlobalValue *GV) const override;
227 bool isDematerializable(const GlobalValue *GV) const override;
228 std::error_code Materialize(GlobalValue *GV) override;
229 std::error_code MaterializeModule(Module *M) override;
230 void Dematerialize(GlobalValue *GV) override;
232 /// @brief Main interface to parsing a bitcode buffer.
233 /// @returns true if an error occurred.
234 std::error_code ParseBitcodeInto(Module *M);
236 /// @brief Cheap mechanism to just extract module triple
237 /// @returns true if an error occurred.
238 ErrorOr<std::string> parseTriple();
240 static uint64_t decodeSignRotatedValue(uint64_t V);
243 Type *getTypeByID(unsigned ID);
244 Value *getFnValueByID(unsigned ID, Type *Ty) {
245 if (Ty && Ty->isMetadataTy())
246 return MDValueList.getValueFwdRef(ID);
247 return ValueList.getValueFwdRef(ID, Ty);
249 BasicBlock *getBasicBlock(unsigned ID) const {
250 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
251 return FunctionBBs[ID];
253 AttributeSet getAttributes(unsigned i) const {
254 if (i-1 < MAttributes.size())
255 return MAttributes[i-1];
256 return AttributeSet();
259 /// getValueTypePair - Read a value/type pair out of the specified record from
260 /// slot 'Slot'. Increment Slot past the number of slots used in the record.
261 /// Return true on failure.
262 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
263 unsigned InstNum, Value *&ResVal) {
264 if (Slot == Record.size()) return true;
265 unsigned ValNo = (unsigned)Record[Slot++];
266 // Adjust the ValNo, if it was encoded relative to the InstNum.
268 ValNo = InstNum - ValNo;
269 if (ValNo < InstNum) {
270 // If this is not a forward reference, just return the value we already
272 ResVal = getFnValueByID(ValNo, nullptr);
273 return ResVal == nullptr;
274 } else if (Slot == Record.size()) {
278 unsigned TypeNo = (unsigned)Record[Slot++];
279 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
280 return ResVal == nullptr;
283 /// popValue - Read a value out of the specified record from slot 'Slot'.
284 /// Increment Slot past the number of slots used by the value in the record.
285 /// Return true if there is an error.
286 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
287 unsigned InstNum, Type *Ty, Value *&ResVal) {
288 if (getValue(Record, Slot, InstNum, Ty, ResVal))
290 // All values currently take a single record slot.
295 /// getValue -- Like popValue, but does not increment the Slot number.
296 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
297 unsigned InstNum, Type *Ty, Value *&ResVal) {
298 ResVal = getValue(Record, Slot, InstNum, Ty);
299 return ResVal == nullptr;
302 /// getValue -- Version of getValue that returns ResVal directly,
303 /// or 0 if there is an error.
304 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
305 unsigned InstNum, Type *Ty) {
306 if (Slot == Record.size()) return nullptr;
307 unsigned ValNo = (unsigned)Record[Slot];
308 // Adjust the ValNo, if it was encoded relative to the InstNum.
310 ValNo = InstNum - ValNo;
311 return getFnValueByID(ValNo, Ty);
314 /// getValueSigned -- Like getValue, but decodes signed VBRs.
315 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
316 unsigned InstNum, Type *Ty) {
317 if (Slot == Record.size()) return nullptr;
318 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
319 // Adjust the ValNo, if it was encoded relative to the InstNum.
321 ValNo = InstNum - ValNo;
322 return getFnValueByID(ValNo, Ty);
325 std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
326 std::error_code ParseModule(bool Resume);
327 std::error_code ParseAttributeBlock();
328 std::error_code ParseAttributeGroupBlock();
329 std::error_code ParseTypeTable();
330 std::error_code ParseTypeTableBody();
332 std::error_code ParseValueSymbolTable();
333 std::error_code ParseConstants();
334 std::error_code RememberAndSkipFunctionBody();
335 std::error_code ParseFunctionBody(Function *F);
336 std::error_code GlobalCleanup();
337 std::error_code ResolveGlobalAndAliasInits();
338 std::error_code ParseMetadata();
339 std::error_code ParseMetadataAttachment();
340 ErrorOr<std::string> parseModuleTriple();
341 std::error_code ParseUseLists();
342 std::error_code InitStream();
343 std::error_code InitStreamFromBuffer();
344 std::error_code InitLazyStream();
345 std::error_code FindFunctionInStream(
347 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
350 } // End llvm namespace