Hold the LLVMContext by reference rather than by pointer.
[oota-llvm.git] / lib / Bitcode / Reader / BitcodeReader.h
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/ModuleProvider.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 public:
48   BitcodeReaderValueList() {}
49   ~BitcodeReaderValueList() {
50     assert(ResolveConstants.empty() && "Constants not resolved?");
51   }
52
53   // vector compatibility methods
54   unsigned size() const { return ValuePtrs.size(); }
55   void resize(unsigned N) { ValuePtrs.resize(N); }
56   void push_back(Value *V) {
57     ValuePtrs.push_back(V);
58   }
59   
60   void clear() {
61     assert(ResolveConstants.empty() && "Constants not resolved?");
62     ValuePtrs.clear();
63   }
64   
65   Value *operator[](unsigned i) const {
66     assert(i < ValuePtrs.size());
67     return ValuePtrs[i];
68   }
69   
70   Value *back() const { return ValuePtrs.back(); }
71     void pop_back() { ValuePtrs.pop_back(); }
72   bool empty() const { return ValuePtrs.empty(); }
73   void shrinkTo(unsigned N) {
74     assert(N <= size() && "Invalid shrinkTo request!");
75     ValuePtrs.resize(N);
76   }
77   
78   Constant *getConstantFwdRef(unsigned Idx, const Type *Ty);
79   Value *getValueFwdRef(unsigned Idx, const Type *Ty);
80   
81   void AssignValue(Value *V, unsigned Idx);
82   
83   /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
84   /// resolves any forward references.
85   void ResolveConstantForwardRefs();
86 };
87
88 class BitcodeReader : public ModuleProvider {
89   const LLVMContext& Context;
90   MemoryBuffer *Buffer;
91   BitstreamReader StreamFile;
92   BitstreamCursor Stream;
93   
94   const char *ErrorString;
95   
96   std::vector<PATypeHolder> TypeList;
97   BitcodeReaderValueList ValueList;
98   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
99   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
100   
101   /// MAttributes - The set of attributes by index.  Index zero in the
102   /// file is for null, and is thus not represented here.  As such all indices
103   /// are off by one.
104   std::vector<AttrListPtr> MAttributes;
105   
106   /// FunctionBBs - While parsing a function body, this is a list of the basic
107   /// blocks for the function.
108   std::vector<BasicBlock*> FunctionBBs;
109   
110   // When reading the module header, this list is populated with functions that
111   // have bodies later in the file.
112   std::vector<Function*> FunctionsWithBodies;
113
114   // When intrinsic functions are encountered which require upgrading they are 
115   // stored here with their replacement function.
116   typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
117   UpgradedIntrinsicMap UpgradedIntrinsics;
118   
119   // After the module header has been read, the FunctionsWithBodies list is 
120   // reversed.  This keeps track of whether we've done this yet.
121   bool HasReversedFunctionsWithBodies;
122   
123   /// DeferredFunctionInfo - When function bodies are initially scanned, this
124   /// map contains info about where to find deferred function body (in the
125   /// stream) and what linkage the original function had.
126   DenseMap<Function*, std::pair<uint64_t, unsigned> > DeferredFunctionInfo;
127 public:
128   explicit BitcodeReader(MemoryBuffer *buffer, const LLVMContext& C)
129       : Context(C), Buffer(buffer), ErrorString(0) {
130     HasReversedFunctionsWithBodies = false;
131   }
132   ~BitcodeReader() {
133     FreeState();
134   }
135   
136   void FreeState();
137   
138   /// releaseMemoryBuffer - This causes the reader to completely forget about
139   /// the memory buffer it contains, which prevents the buffer from being
140   /// destroyed when it is deleted.
141   void releaseMemoryBuffer() {
142     Buffer = 0;
143   }
144   
145   virtual bool materializeFunction(Function *F, std::string *ErrInfo = 0);
146   virtual Module *materializeModule(std::string *ErrInfo = 0);
147   virtual void dematerializeFunction(Function *F);
148   virtual Module *releaseModule(std::string *ErrInfo = 0);
149
150   bool Error(const char *Str) {
151     ErrorString = Str;
152     return true;
153   }
154   const char *getErrorString() const { return ErrorString; }
155   
156   /// @brief Main interface to parsing a bitcode buffer.
157   /// @returns true if an error occurred.
158   bool ParseBitcode();
159 private:
160   const Type *getTypeByID(unsigned ID, bool isTypeTable = false);
161   Value *getFnValueByID(unsigned ID, const Type *Ty) {
162     return ValueList.getValueFwdRef(ID, Ty);
163   }
164   BasicBlock *getBasicBlock(unsigned ID) const {
165     if (ID >= FunctionBBs.size()) return 0; // Invalid ID
166     return FunctionBBs[ID];
167   }
168   AttrListPtr getAttributes(unsigned i) const {
169     if (i-1 < MAttributes.size())
170       return MAttributes[i-1];
171     return AttrListPtr();
172   }
173   
174   /// getValueTypePair - Read a value/type pair out of the specified record from
175   /// slot 'Slot'.  Increment Slot past the number of slots used in the record.
176   /// Return true on failure.
177   bool getValueTypePair(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
178                         unsigned InstNum, Value *&ResVal) {
179     if (Slot == Record.size()) return true;
180     unsigned ValNo = (unsigned)Record[Slot++];
181     if (ValNo < InstNum) {
182       // If this is not a forward reference, just return the value we already
183       // have.
184       ResVal = getFnValueByID(ValNo, 0);
185       return ResVal == 0;
186     } else if (Slot == Record.size()) {
187       return true;
188     }
189     
190     unsigned TypeNo = (unsigned)Record[Slot++];
191     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
192     return ResVal == 0;
193   }
194   bool getValue(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
195                 const Type *Ty, Value *&ResVal) {
196     if (Slot == Record.size()) return true;
197     unsigned ValNo = (unsigned)Record[Slot++];
198     ResVal = getFnValueByID(ValNo, Ty);
199     return ResVal == 0;
200   }
201
202   
203   bool ParseModule(const std::string &ModuleID);
204   bool ParseAttributeBlock();
205   bool ParseTypeTable();
206   bool ParseTypeSymbolTable();
207   bool ParseValueSymbolTable();
208   bool ParseConstants();
209   bool RememberAndSkipFunctionBody();
210   bool ParseFunctionBody(Function *F);
211   bool ResolveGlobalAndAliasInits();
212 };
213   
214 } // End llvm namespace
215
216 #endif