BitcodeReader.h revision 19c874638d9478a5d5028854817a5ee72293bb2b
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/ADT/DenseMap.h"
24#include <vector>
25
26namespace llvm {
27  class MemoryBuffer;
28
29//===----------------------------------------------------------------------===//
30//                          BitcodeReaderValueList Class
31//===----------------------------------------------------------------------===//
32
33class BitcodeReaderValueList : public User {
34  unsigned Capacity;
35
36  /// ResolveConstants - As we resolve forward-referenced constants, we add
37  /// information about them to this vector.  This allows us to resolve them in
38  /// bulk instead of resolving each reference at a time.  See the code in
39  /// ResolveConstantForwardRefs for more information about this.
40  ///
41  /// The key of this vector is the placeholder constant, the value is the slot
42  /// number that holds the resolved value.
43  typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
44  ResolveConstantsTy ResolveConstants;
45public:
46  BitcodeReaderValueList() : User(Type::VoidTy, Value::ArgumentVal, 0, 0)
47                           , Capacity(0) {}
48  ~BitcodeReaderValueList() {
49    assert(ResolveConstants.empty() && "Constants not resolved?");
50  }
51
52  /// Provide fast operand accessors
53  DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
54
55  // vector compatibility methods
56  unsigned size() const { return getNumOperands(); }
57  void resize(unsigned);
58  void push_back(Value *V) {
59    unsigned OldOps(NumOperands), NewOps(NumOperands + 1);
60    resize(NewOps);
61    NumOperands = NewOps;
62    OperandList[OldOps] = V;
63  }
64
65  void clear() {
66    assert(ResolveConstants.empty() && "Constants not resolved?");
67    if (OperandList) dropHungoffUses(OperandList);
68    Capacity = 0;
69  }
70
71  Value *operator[](unsigned i) const { return getOperand(i); }
72
73  Value *back() const { return getOperand(size() - 1); }
74  void pop_back() { setOperand(size() - 1, 0); --NumOperands; }
75  bool empty() const { return NumOperands == 0; }
76  void shrinkTo(unsigned N) {
77    assert(N <= NumOperands && "Invalid shrinkTo request!");
78    while (NumOperands > N)
79      pop_back();
80  }
81  virtual void print(std::ostream&) const {}
82
83  Constant *getConstantFwdRef(unsigned Idx, const Type *Ty);
84  Value *getValueFwdRef(unsigned Idx, const Type *Ty);
85
86  void AssignValue(Value *V, unsigned Idx) {
87    if (Idx == size()) {
88      push_back(V);
89    } else if (Value *OldV = getOperand(Idx)) {
90      // Handle constants and non-constants (e.g. instrs) differently for
91      // efficiency.
92      if (Constant *PHC = dyn_cast<Constant>(OldV)) {
93        ResolveConstants.push_back(std::make_pair(PHC, Idx));
94        setOperand(Idx, V);
95      } else {
96        // If there was a forward reference to this value, replace it.
97        setOperand(Idx, V);
98        OldV->replaceAllUsesWith(V);
99        delete OldV;
100      }
101    } else {
102      initVal(Idx, V);
103    }
104  }
105
106  /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
107  /// resolves any forward references.
108  void ResolveConstantForwardRefs();
109
110private:
111  void initVal(unsigned Idx, Value *V) {
112    if (Idx >= size()) {
113      // Insert a bunch of null values.
114      resize(Idx * 2 + 1);
115    }
116    assert(getOperand(Idx) == 0 && "Cannot init an already init'd Use!");
117    OperandList[Idx] = V;
118  }
119};
120
121template <>
122struct OperandTraits<BitcodeReaderValueList>
123  : HungoffOperandTraits</*16 FIXME*/> {
124};
125
126DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BitcodeReaderValueList, Value)
127
128class BitcodeReader : public ModuleProvider {
129  MemoryBuffer *Buffer;
130  BitstreamReader Stream;
131
132  const char *ErrorString;
133
134  std::vector<PATypeHolder> TypeList;
135  BitcodeReaderValueList ValueList;
136  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
137  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
138
139  /// MAttributes - The set of attributes by index.  Index zero in the
140  /// file is for null, and is thus not represented here.  As such all indices
141  /// are off by one.
142  std::vector<AttrListPtr> MAttributes;
143
144  /// FunctionBBs - While parsing a function body, this is a list of the basic
145  /// blocks for the function.
146  std::vector<BasicBlock*> FunctionBBs;
147
148  // When reading the module header, this list is populated with functions that
149  // have bodies later in the file.
150  std::vector<Function*> FunctionsWithBodies;
151
152  // When intrinsic functions are encountered which require upgrading they are
153  // stored here with their replacement function.
154  typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
155  UpgradedIntrinsicMap UpgradedIntrinsics;
156
157  // After the module header has been read, the FunctionsWithBodies list is
158  // reversed.  This keeps track of whether we've done this yet.
159  bool HasReversedFunctionsWithBodies;
160
161  /// DeferredFunctionInfo - When function bodies are initially scanned, this
162  /// map contains info about where to find deferred function body (in the
163  /// stream) and what linkage the original function had.
164  DenseMap<Function*, std::pair<uint64_t, unsigned> > DeferredFunctionInfo;
165public:
166  explicit BitcodeReader(MemoryBuffer *buffer)
167      : Buffer(buffer), ErrorString(0) {
168    HasReversedFunctionsWithBodies = false;
169  }
170  ~BitcodeReader() {
171    FreeState();
172  }
173
174  void FreeState();
175
176  /// releaseMemoryBuffer - This causes the reader to completely forget about
177  /// the memory buffer it contains, which prevents the buffer from being
178  /// destroyed when it is deleted.
179  void releaseMemoryBuffer() {
180    Buffer = 0;
181  }
182
183  virtual bool materializeFunction(Function *F, std::string *ErrInfo = 0);
184  virtual Module *materializeModule(std::string *ErrInfo = 0);
185  virtual void dematerializeFunction(Function *F);
186  virtual Module *releaseModule(std::string *ErrInfo = 0);
187
188  bool Error(const char *Str) {
189    ErrorString = Str;
190    return true;
191  }
192  const char *getErrorString() const { return ErrorString; }
193
194  /// @brief Main interface to parsing a bitcode buffer.
195  /// @returns true if an error occurred.
196  bool ParseBitcode();
197private:
198  const Type *getTypeByID(unsigned ID, bool isTypeTable = false);
199  Value *getFnValueByID(unsigned ID, const Type *Ty) {
200    return ValueList.getValueFwdRef(ID, Ty);
201  }
202  BasicBlock *getBasicBlock(unsigned ID) const {
203    if (ID >= FunctionBBs.size()) return 0; // Invalid ID
204    return FunctionBBs[ID];
205  }
206  AttrListPtr getAttributes(unsigned i) const {
207    if (i-1 < MAttributes.size())
208      return MAttributes[i-1];
209    return AttrListPtr();
210  }
211
212  /// getValueTypePair - Read a value/type pair out of the specified record from
213  /// slot 'Slot'.  Increment Slot past the number of slots used in the record.
214  /// Return true on failure.
215  bool getValueTypePair(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
216                        unsigned InstNum, Value *&ResVal) {
217    if (Slot == Record.size()) return true;
218    unsigned ValNo = (unsigned)Record[Slot++];
219    if (ValNo < InstNum) {
220      // If this is not a forward reference, just return the value we already
221      // have.
222      ResVal = getFnValueByID(ValNo, 0);
223      return ResVal == 0;
224    } else if (Slot == Record.size()) {
225      return true;
226    }
227
228    unsigned TypeNo = (unsigned)Record[Slot++];
229    ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
230    return ResVal == 0;
231  }
232  bool getValue(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
233                const Type *Ty, Value *&ResVal) {
234    if (Slot == Record.size()) return true;
235    unsigned ValNo = (unsigned)Record[Slot++];
236    ResVal = getFnValueByID(ValNo, Ty);
237    return ResVal == 0;
238  }
239
240
241  bool ParseModule(const std::string &ModuleID);
242  bool ParseAttributeBlock();
243  bool ParseTypeTable();
244  bool ParseTypeSymbolTable();
245  bool ParseValueSymbolTable();
246  bool ParseConstants();
247  bool RememberAndSkipFunctionBody();
248  bool ParseFunctionBody(Function *F);
249  bool ResolveGlobalAndAliasInits();
250};
251
252} // End llvm namespace
253
254#endif
255