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/GVMaterializer.h"
18 #include "llvm/Attributes.h"
19 #include "llvm/Type.h"
20 #include "llvm/OperandTraits.h"
21 #include "llvm/Bitcode/BitstreamReader.h"
22 #include "llvm/Bitcode/LLVMBitCodes.h"
23 #include "llvm/Support/ValueHandle.h"
24 #include "llvm/ADT/DenseMap.h"
31 //===----------------------------------------------------------------------===//
32 // BitcodeReaderValueList Class
33 //===----------------------------------------------------------------------===//
35 class BitcodeReaderValueList {
36 std::vector<WeakVH> ValuePtrs;
38 /// ResolveConstants - As we resolve forward-referenced constants, we add
39 /// information about them to this vector. This allows us to resolve them in
40 /// bulk instead of resolving each reference at a time. See the code in
41 /// ResolveConstantForwardRefs for more information about this.
43 /// The key of this vector is the placeholder constant, the value is the slot
44 /// number that holds the resolved value.
45 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
46 ResolveConstantsTy ResolveConstants;
49 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
50 ~BitcodeReaderValueList() {
51 assert(ResolveConstants.empty() && "Constants not resolved?");
54 // vector compatibility methods
55 unsigned size() const { return ValuePtrs.size(); }
56 void resize(unsigned N) { ValuePtrs.resize(N); }
57 void push_back(Value *V) {
58 ValuePtrs.push_back(V);
62 assert(ResolveConstants.empty() && "Constants not resolved?");
66 Value *operator[](unsigned i) const {
67 assert(i < ValuePtrs.size());
71 Value *back() const { return ValuePtrs.back(); }
72 void pop_back() { ValuePtrs.pop_back(); }
73 bool empty() const { return ValuePtrs.empty(); }
74 void shrinkTo(unsigned N) {
75 assert(N <= size() && "Invalid shrinkTo request!");
79 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
80 Value *getValueFwdRef(unsigned Idx, Type *Ty);
82 void AssignValue(Value *V, unsigned Idx);
84 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
85 /// resolves any forward references.
86 void ResolveConstantForwardRefs();
90 //===----------------------------------------------------------------------===//
91 // BitcodeReaderMDValueList Class
92 //===----------------------------------------------------------------------===//
94 class BitcodeReaderMDValueList {
95 std::vector<WeakVH> MDValuePtrs;
99 BitcodeReaderMDValueList(LLVMContext& C) : Context(C) {}
101 // vector compatibility methods
102 unsigned size() const { return MDValuePtrs.size(); }
103 void resize(unsigned N) { MDValuePtrs.resize(N); }
104 void push_back(Value *V) { MDValuePtrs.push_back(V); }
105 void clear() { MDValuePtrs.clear(); }
106 Value *back() const { return MDValuePtrs.back(); }
107 void pop_back() { MDValuePtrs.pop_back(); }
108 bool empty() const { return MDValuePtrs.empty(); }
110 Value *operator[](unsigned i) const {
111 assert(i < MDValuePtrs.size());
112 return MDValuePtrs[i];
115 void shrinkTo(unsigned N) {
116 assert(N <= size() && "Invalid shrinkTo request!");
117 MDValuePtrs.resize(N);
120 Value *getValueFwdRef(unsigned Idx);
121 void AssignValue(Value *V, unsigned Idx);
124 class BitcodeReader : public GVMaterializer {
125 LLVMContext &Context;
127 MemoryBuffer *Buffer;
129 OwningPtr<BitstreamReader> StreamFile;
130 BitstreamCursor Stream;
131 DataStreamer *LazyStreamer;
132 uint64_t NextUnreadBit;
133 bool SeenValueSymbolTable;
135 const char *ErrorString;
137 std::vector<Type*> TypeList;
138 BitcodeReaderValueList ValueList;
139 BitcodeReaderMDValueList MDValueList;
140 SmallVector<Instruction *, 64> InstructionList;
141 SmallVector<SmallVector<uint64_t, 64>, 64> UseListRecords;
143 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
144 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
146 /// MAttributes - The set of attributes by index. Index zero in the
147 /// file is for null, and is thus not represented here. As such all indices
149 std::vector<AttrListPtr> MAttributes;
151 /// FunctionBBs - While parsing a function body, this is a list of the basic
152 /// blocks for the function.
153 std::vector<BasicBlock*> FunctionBBs;
155 // When reading the module header, this list is populated with functions that
156 // have bodies later in the file.
157 std::vector<Function*> FunctionsWithBodies;
159 // When intrinsic functions are encountered which require upgrading they are
160 // stored here with their replacement function.
161 typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
162 UpgradedIntrinsicMap UpgradedIntrinsics;
164 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
165 DenseMap<unsigned, unsigned> MDKindMap;
167 // Several operations happen after the module header has been read, but
168 // before function bodies are processed. This keeps track of whether
169 // we've done this yet.
170 bool SeenFirstFunctionBody;
172 /// DeferredFunctionInfo - When function bodies are initially scanned, this
173 /// map contains info about where to find deferred function body in the
175 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
177 /// BlockAddrFwdRefs - These are blockaddr references to basic blocks. These
178 /// are resolved lazily when functions are loaded.
179 typedef std::pair<unsigned, GlobalVariable*> BlockAddrRefTy;
180 DenseMap<Function*, std::vector<BlockAddrRefTy> > BlockAddrFwdRefs;
183 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
184 : Context(C), TheModule(0), Buffer(buffer), BufferOwned(false),
185 LazyStreamer(0), SeenValueSymbolTable(false), ErrorString(0),
186 ValueList(C), MDValueList(C), SeenFirstFunctionBody(false) {
188 explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C)
189 : Context(C), TheModule(0), Buffer(0), BufferOwned(false),
190 LazyStreamer(streamer), SeenValueSymbolTable(false), ErrorString(0),
191 ValueList(C), MDValueList(C), SeenFirstFunctionBody(false) {
197 void materializeForwardReferencedFunctions();
201 /// setBufferOwned - If this is true, the reader will destroy the MemoryBuffer
202 /// when the reader is destroyed.
203 void setBufferOwned(bool Owned) { BufferOwned = Owned; }
205 virtual bool isMaterializable(const GlobalValue *GV) const;
206 virtual bool isDematerializable(const GlobalValue *GV) const;
207 virtual bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
208 virtual bool MaterializeModule(Module *M, std::string *ErrInfo = 0);
209 virtual void Dematerialize(GlobalValue *GV);
211 bool Error(const char *Str) {
215 const char *getErrorString() const { return ErrorString; }
217 /// @brief Main interface to parsing a bitcode buffer.
218 /// @returns true if an error occurred.
219 bool ParseBitcodeInto(Module *M);
221 /// @brief Cheap mechanism to just extract module triple
222 /// @returns true if an error occurred.
223 bool ParseTriple(std::string &Triple);
225 Type *getTypeByID(unsigned ID);
226 Value *getFnValueByID(unsigned ID, Type *Ty) {
227 if (Ty && Ty->isMetadataTy())
228 return MDValueList.getValueFwdRef(ID);
229 return ValueList.getValueFwdRef(ID, Ty);
231 BasicBlock *getBasicBlock(unsigned ID) const {
232 if (ID >= FunctionBBs.size()) return 0; // Invalid ID
233 return FunctionBBs[ID];
235 AttrListPtr getAttributes(unsigned i) const {
236 if (i-1 < MAttributes.size())
237 return MAttributes[i-1];
238 return AttrListPtr();
241 /// getValueTypePair - Read a value/type pair out of the specified record from
242 /// slot 'Slot'. Increment Slot past the number of slots used in the record.
243 /// Return true on failure.
244 bool getValueTypePair(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
245 unsigned InstNum, Value *&ResVal) {
246 if (Slot == Record.size()) return true;
247 unsigned ValNo = (unsigned)Record[Slot++];
248 if (ValNo < InstNum) {
249 // If this is not a forward reference, just return the value we already
251 ResVal = getFnValueByID(ValNo, 0);
253 } else if (Slot == Record.size()) {
257 unsigned TypeNo = (unsigned)Record[Slot++];
258 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
261 bool getValue(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
262 Type *Ty, Value *&ResVal) {
263 if (Slot == Record.size()) return true;
264 unsigned ValNo = (unsigned)Record[Slot++];
265 ResVal = getFnValueByID(ValNo, Ty);
270 bool ParseModule(bool Resume);
271 bool ParseAttributeBlock();
272 bool ParseTypeTable();
273 bool ParseTypeTableBody();
275 bool ParseValueSymbolTable();
276 bool ParseConstants();
277 bool RememberAndSkipFunctionBody();
278 bool ParseFunctionBody(Function *F);
279 bool GlobalCleanup();
280 bool ResolveGlobalAndAliasInits();
281 bool ParseMetadata();
282 bool ParseMetadataAttachment();
283 bool ParseModuleTriple(std::string &Triple);
284 bool ParseUseLists();
286 bool InitStreamFromBuffer();
287 bool InitLazyStream();
288 bool FindFunctionInStream(Function *F,
289 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator);
292 } // End llvm namespace