• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
14 #ifndef BITCODE_READER_H
15 #define BITCODE_READER_H
16 
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"
25 #include <vector>
26 
27 namespace llvm {
28   class MemoryBuffer;
29   class LLVMContext;
30 
31 //===----------------------------------------------------------------------===//
32 //                          BitcodeReaderValueList Class
33 //===----------------------------------------------------------------------===//
34 
35 class BitcodeReaderValueList {
36   std::vector<WeakVH> ValuePtrs;
37 
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.
42   ///
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;
47   LLVMContext &Context;
48 public:
BitcodeReaderValueList(LLVMContext & C)49   BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
~BitcodeReaderValueList()50   ~BitcodeReaderValueList() {
51     assert(ResolveConstants.empty() && "Constants not resolved?");
52   }
53 
54   // vector compatibility methods
size()55   unsigned size() const { return ValuePtrs.size(); }
resize(unsigned N)56   void resize(unsigned N) { ValuePtrs.resize(N); }
push_back(Value * V)57   void push_back(Value *V) {
58     ValuePtrs.push_back(V);
59   }
60 
clear()61   void clear() {
62     assert(ResolveConstants.empty() && "Constants not resolved?");
63     ValuePtrs.clear();
64   }
65 
66   Value *operator[](unsigned i) const {
67     assert(i < ValuePtrs.size());
68     return ValuePtrs[i];
69   }
70 
back()71   Value *back() const { return ValuePtrs.back(); }
pop_back()72     void pop_back() { ValuePtrs.pop_back(); }
empty()73   bool empty() const { return ValuePtrs.empty(); }
shrinkTo(unsigned N)74   void shrinkTo(unsigned N) {
75     assert(N <= size() && "Invalid shrinkTo request!");
76     ValuePtrs.resize(N);
77   }
78 
79   Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
80   Value *getValueFwdRef(unsigned Idx, Type *Ty);
81 
82   void AssignValue(Value *V, unsigned Idx);
83 
84   /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
85   /// resolves any forward references.
86   void ResolveConstantForwardRefs();
87 };
88 
89 
90 //===----------------------------------------------------------------------===//
91 //                          BitcodeReaderMDValueList Class
92 //===----------------------------------------------------------------------===//
93 
94 class BitcodeReaderMDValueList {
95   std::vector<WeakVH> MDValuePtrs;
96 
97   LLVMContext &Context;
98 public:
BitcodeReaderMDValueList(LLVMContext & C)99   BitcodeReaderMDValueList(LLVMContext& C) : Context(C) {}
100 
101   // vector compatibility methods
size()102   unsigned size() const       { return MDValuePtrs.size(); }
resize(unsigned N)103   void resize(unsigned N)     { MDValuePtrs.resize(N); }
push_back(Value * V)104   void push_back(Value *V)    { MDValuePtrs.push_back(V);  }
clear()105   void clear()                { MDValuePtrs.clear();  }
back()106   Value *back() const         { return MDValuePtrs.back(); }
pop_back()107   void pop_back()             { MDValuePtrs.pop_back(); }
empty()108   bool empty() const          { return MDValuePtrs.empty(); }
109 
110   Value *operator[](unsigned i) const {
111     assert(i < MDValuePtrs.size());
112     return MDValuePtrs[i];
113   }
114 
shrinkTo(unsigned N)115   void shrinkTo(unsigned N) {
116     assert(N <= size() && "Invalid shrinkTo request!");
117     MDValuePtrs.resize(N);
118   }
119 
120   Value *getValueFwdRef(unsigned Idx);
121   void AssignValue(Value *V, unsigned Idx);
122 };
123 
124 class BitcodeReader : public GVMaterializer {
125   LLVMContext &Context;
126   Module *TheModule;
127   MemoryBuffer *Buffer;
128   bool BufferOwned;
129   OwningPtr<BitstreamReader> StreamFile;
130   BitstreamCursor Stream;
131   DataStreamer *LazyStreamer;
132   uint64_t NextUnreadBit;
133   bool SeenValueSymbolTable;
134 
135   const char *ErrorString;
136 
137   std::vector<Type*> TypeList;
138   BitcodeReaderValueList ValueList;
139   BitcodeReaderMDValueList MDValueList;
140   SmallVector<Instruction *, 64> InstructionList;
141   SmallVector<SmallVector<uint64_t, 64>, 64> UseListRecords;
142 
143   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
144   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
145 
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
148   /// are off by one.
149   std::vector<AttrListPtr> MAttributes;
150 
151   /// FunctionBBs - While parsing a function body, this is a list of the basic
152   /// blocks for the function.
153   std::vector<BasicBlock*> FunctionBBs;
154 
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;
158 
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;
163 
164   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
165   DenseMap<unsigned, unsigned> MDKindMap;
166 
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;
171 
172   /// DeferredFunctionInfo - When function bodies are initially scanned, this
173   /// map contains info about where to find deferred function body in the
174   /// stream.
175   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
176 
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;
181 
182 public:
BitcodeReader(MemoryBuffer * buffer,LLVMContext & C)183   explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
184     : Context(C), TheModule(0), Buffer(buffer), BufferOwned(false),
185       LazyStreamer(0), NextUnreadBit(0), SeenValueSymbolTable(false),
186       ErrorString(0), ValueList(C), MDValueList(C),
187       SeenFirstFunctionBody(false) {
188   }
BitcodeReader(DataStreamer * streamer,LLVMContext & C)189   explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C)
190     : Context(C), TheModule(0), Buffer(0), BufferOwned(false),
191       LazyStreamer(streamer), NextUnreadBit(0), SeenValueSymbolTable(false),
192       ErrorString(0), ValueList(C), MDValueList(C),
193       SeenFirstFunctionBody(false) {
194   }
~BitcodeReader()195   ~BitcodeReader() {
196     FreeState();
197   }
198 
199   void materializeForwardReferencedFunctions();
200 
201   void FreeState();
202 
203   /// setBufferOwned - If this is true, the reader will destroy the MemoryBuffer
204   /// when the reader is destroyed.
setBufferOwned(bool Owned)205   void setBufferOwned(bool Owned) { BufferOwned = Owned; }
206 
207   virtual bool isMaterializable(const GlobalValue *GV) const;
208   virtual bool isDematerializable(const GlobalValue *GV) const;
209   virtual bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
210   virtual bool MaterializeModule(Module *M, std::string *ErrInfo = 0);
211   virtual void Dematerialize(GlobalValue *GV);
212 
Error(const char * Str)213   bool Error(const char *Str) {
214     ErrorString = Str;
215     return true;
216   }
getErrorString()217   const char *getErrorString() const { return ErrorString; }
218 
219   /// @brief Main interface to parsing a bitcode buffer.
220   /// @returns true if an error occurred.
221   bool ParseBitcodeInto(Module *M);
222 
223   /// @brief Cheap mechanism to just extract module triple
224   /// @returns true if an error occurred.
225   bool ParseTriple(std::string &Triple);
226 private:
227   Type *getTypeByID(unsigned ID);
getFnValueByID(unsigned ID,Type * Ty)228   Value *getFnValueByID(unsigned ID, Type *Ty) {
229     if (Ty && Ty->isMetadataTy())
230       return MDValueList.getValueFwdRef(ID);
231     return ValueList.getValueFwdRef(ID, Ty);
232   }
getBasicBlock(unsigned ID)233   BasicBlock *getBasicBlock(unsigned ID) const {
234     if (ID >= FunctionBBs.size()) return 0; // Invalid ID
235     return FunctionBBs[ID];
236   }
getAttributes(unsigned i)237   AttrListPtr getAttributes(unsigned i) const {
238     if (i-1 < MAttributes.size())
239       return MAttributes[i-1];
240     return AttrListPtr();
241   }
242 
243   /// getValueTypePair - Read a value/type pair out of the specified record from
244   /// slot 'Slot'.  Increment Slot past the number of slots used in the record.
245   /// Return true on failure.
getValueTypePair(SmallVector<uint64_t,64> & Record,unsigned & Slot,unsigned InstNum,Value * & ResVal)246   bool getValueTypePair(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
247                         unsigned InstNum, Value *&ResVal) {
248     if (Slot == Record.size()) return true;
249     unsigned ValNo = (unsigned)Record[Slot++];
250     if (ValNo < InstNum) {
251       // If this is not a forward reference, just return the value we already
252       // have.
253       ResVal = getFnValueByID(ValNo, 0);
254       return ResVal == 0;
255     } else if (Slot == Record.size()) {
256       return true;
257     }
258 
259     unsigned TypeNo = (unsigned)Record[Slot++];
260     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
261     return ResVal == 0;
262   }
getValue(SmallVector<uint64_t,64> & Record,unsigned & Slot,Type * Ty,Value * & ResVal)263   bool getValue(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
264                 Type *Ty, Value *&ResVal) {
265     if (Slot == Record.size()) return true;
266     unsigned ValNo = (unsigned)Record[Slot++];
267     ResVal = getFnValueByID(ValNo, Ty);
268     return ResVal == 0;
269   }
270 
271 
272   bool ParseModule(bool Resume);
273   bool ParseAttributeBlock();
274   bool ParseTypeTable();
275   bool ParseTypeTableBody();
276 
277   bool ParseValueSymbolTable();
278   bool ParseConstants();
279   bool RememberAndSkipFunctionBody();
280   bool ParseFunctionBody(Function *F);
281   bool GlobalCleanup();
282   bool ResolveGlobalAndAliasInits();
283   bool ParseMetadata();
284   bool ParseMetadataAttachment();
285   bool ParseModuleTriple(std::string &Triple);
286   bool ParseUseLists();
287   bool InitStream();
288   bool InitStreamFromBuffer();
289   bool InitLazyStream();
290   bool FindFunctionInStream(Function *F,
291          DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator);
292 };
293 
294 } // End llvm namespace
295 
296 #endif
297