Home | History | Annotate | Download | only in BitReader_3_0
      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/ADT/DenseMap.h"
     18 #include "llvm/Bitcode/BitstreamReader.h"
     19 #include "llvm/Bitcode/LLVMBitCodes.h"
     20 #include "llvm/GVMaterializer.h"
     21 #include "llvm/IR/Attributes.h"
     22 #include "llvm/IR/OperandTraits.h"
     23 #include "llvm/IR/Type.h"
     24 #include "llvm/Support/ValueHandle.h"
     25 #include <vector>
     26 
     27 namespace llvm {
     28   class MemoryBuffer;
     29   class LLVMContext;
     30 }
     31 
     32 namespace llvm_3_0 {
     33 
     34 using namespace llvm;
     35 
     36 //===----------------------------------------------------------------------===//
     37 //                          BitcodeReaderValueList Class
     38 //===----------------------------------------------------------------------===//
     39 
     40 class BitcodeReaderValueList {
     41   std::vector<WeakVH> ValuePtrs;
     42 
     43   /// ResolveConstants - As we resolve forward-referenced constants, we add
     44   /// information about them to this vector.  This allows us to resolve them in
     45   /// bulk instead of resolving each reference at a time.  See the code in
     46   /// ResolveConstantForwardRefs for more information about this.
     47   ///
     48   /// The key of this vector is the placeholder constant, the value is the slot
     49   /// number that holds the resolved value.
     50   typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
     51   ResolveConstantsTy ResolveConstants;
     52   LLVMContext &Context;
     53 public:
     54   BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
     55   ~BitcodeReaderValueList() {
     56     assert(ResolveConstants.empty() && "Constants not resolved?");
     57   }
     58 
     59   // vector compatibility methods
     60   unsigned size() const { return ValuePtrs.size(); }
     61   void resize(unsigned N) { ValuePtrs.resize(N); }
     62   void push_back(Value *V) {
     63     ValuePtrs.push_back(V);
     64   }
     65 
     66   void clear() {
     67     assert(ResolveConstants.empty() && "Constants not resolved?");
     68     ValuePtrs.clear();
     69   }
     70 
     71   Value *operator[](unsigned i) const {
     72     assert(i < ValuePtrs.size());
     73     return ValuePtrs[i];
     74   }
     75 
     76   Value *back() const { return ValuePtrs.back(); }
     77     void pop_back() { ValuePtrs.pop_back(); }
     78   bool empty() const { return ValuePtrs.empty(); }
     79   void shrinkTo(unsigned N) {
     80     assert(N <= size() && "Invalid shrinkTo request!");
     81     ValuePtrs.resize(N);
     82   }
     83 
     84   Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
     85   Value *getValueFwdRef(unsigned Idx, Type *Ty);
     86 
     87   void AssignValue(Value *V, unsigned Idx);
     88 
     89   /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
     90   /// resolves any forward references.
     91   void ResolveConstantForwardRefs();
     92 };
     93 
     94 
     95 //===----------------------------------------------------------------------===//
     96 //                          BitcodeReaderMDValueList Class
     97 //===----------------------------------------------------------------------===//
     98 
     99 class BitcodeReaderMDValueList {
    100   std::vector<WeakVH> MDValuePtrs;
    101 
    102   LLVMContext &Context;
    103 public:
    104   BitcodeReaderMDValueList(LLVMContext& C) : Context(C) {}
    105 
    106   // vector compatibility methods
    107   unsigned size() const       { return MDValuePtrs.size(); }
    108   void resize(unsigned N)     { MDValuePtrs.resize(N); }
    109   void push_back(Value *V)    { MDValuePtrs.push_back(V);  }
    110   void clear()                { MDValuePtrs.clear();  }
    111   Value *back() const         { return MDValuePtrs.back(); }
    112   void pop_back()             { MDValuePtrs.pop_back(); }
    113   bool empty() const          { return MDValuePtrs.empty(); }
    114 
    115   Value *operator[](unsigned i) const {
    116     assert(i < MDValuePtrs.size());
    117     return MDValuePtrs[i];
    118   }
    119 
    120   void shrinkTo(unsigned N) {
    121     assert(N <= size() && "Invalid shrinkTo request!");
    122     MDValuePtrs.resize(N);
    123   }
    124 
    125   Value *getValueFwdRef(unsigned Idx);
    126   void AssignValue(Value *V, unsigned Idx);
    127 };
    128 
    129 class BitcodeReader : public GVMaterializer {
    130   LLVMContext &Context;
    131   Module *TheModule;
    132   MemoryBuffer *Buffer;
    133   bool BufferOwned;
    134   OwningPtr<BitstreamReader> StreamFile;
    135   BitstreamCursor Stream;
    136   DataStreamer *LazyStreamer;
    137   uint64_t NextUnreadBit;
    138   bool SeenValueSymbolTable;
    139 
    140   const char *ErrorString;
    141 
    142   std::vector<Type*> TypeList;
    143   BitcodeReaderValueList ValueList;
    144   BitcodeReaderMDValueList MDValueList;
    145   SmallVector<Instruction *, 64> InstructionList;
    146 
    147   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
    148   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
    149 
    150   /// MAttributes - The set of attributes by index.  Index zero in the
    151   /// file is for null, and is thus not represented here.  As such all indices
    152   /// are off by one.
    153   std::vector<AttributeSet> MAttributes;
    154 
    155   /// \brief The set of attribute groups.
    156   std::map<unsigned, AttributeSet> MAttributeGroups;
    157 
    158   /// FunctionBBs - While parsing a function body, this is a list of the basic
    159   /// blocks for the function.
    160   std::vector<BasicBlock*> FunctionBBs;
    161 
    162   // When reading the module header, this list is populated with functions that
    163   // have bodies later in the file.
    164   std::vector<Function*> FunctionsWithBodies;
    165 
    166   // When intrinsic functions are encountered which require upgrading they are
    167   // stored here with their replacement function.
    168   typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
    169   UpgradedIntrinsicMap UpgradedIntrinsics;
    170 
    171   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
    172   DenseMap<unsigned, unsigned> MDKindMap;
    173 
    174   // Several operations happen after the module header has been read, but
    175   // before function bodies are processed. This keeps track of whether
    176   // we've done this yet.
    177   bool SeenFirstFunctionBody;
    178 
    179   /// DeferredFunctionInfo - When function bodies are initially scanned, this
    180   /// map contains info about where to find deferred function body in the
    181   /// stream.
    182   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
    183 
    184   /// BlockAddrFwdRefs - These are blockaddr references to basic blocks.  These
    185   /// are resolved lazily when functions are loaded.
    186   typedef std::pair<unsigned, GlobalVariable*> BlockAddrRefTy;
    187   DenseMap<Function*, std::vector<BlockAddrRefTy> > BlockAddrFwdRefs;
    188 
    189 public:
    190   explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
    191     : Context(C), TheModule(0), Buffer(buffer), BufferOwned(false),
    192       LazyStreamer(0), NextUnreadBit(0), SeenValueSymbolTable(false),
    193       ErrorString(0), ValueList(C), MDValueList(C),
    194       SeenFirstFunctionBody(false) {
    195   }
    196   ~BitcodeReader() {
    197     FreeState();
    198   }
    199 
    200   void FreeState();
    201 
    202   /// setBufferOwned - If this is true, the reader will destroy the MemoryBuffer
    203   /// when the reader is destroyed.
    204   void setBufferOwned(bool Owned) { BufferOwned = Owned; }
    205 
    206   virtual bool isMaterializable(const GlobalValue *GV) const;
    207   virtual bool isDematerializable(const GlobalValue *GV) const;
    208   virtual bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
    209   virtual bool MaterializeModule(Module *M, std::string *ErrInfo = 0);
    210   virtual void Dematerialize(GlobalValue *GV);
    211 
    212   bool Error(const char *Str) {
    213     ErrorString = Str;
    214     return true;
    215   }
    216   const char *getErrorString() const { return ErrorString; }
    217 
    218   /// @brief Main interface to parsing a bitcode buffer.
    219   /// @returns true if an error occurred.
    220   bool ParseBitcodeInto(Module *M);
    221 
    222   /// @brief Cheap mechanism to just extract module triple
    223   /// @returns true if an error occurred.
    224   bool ParseTriple(std::string &Triple);
    225 
    226   static uint64_t decodeSignRotatedValue(uint64_t V);
    227 
    228 private:
    229   Type *getTypeByID(unsigned ID);
    230   Type *getTypeByIDOrNull(unsigned ID);
    231   Value *getFnValueByID(unsigned ID, Type *Ty) {
    232     if (Ty && Ty->isMetadataTy())
    233       return MDValueList.getValueFwdRef(ID);
    234     return ValueList.getValueFwdRef(ID, Ty);
    235   }
    236   BasicBlock *getBasicBlock(unsigned ID) const {
    237     if (ID >= FunctionBBs.size()) return 0; // Invalid ID
    238     return FunctionBBs[ID];
    239   }
    240   AttributeSet getAttributes(unsigned i) const {
    241     if (i-1 < MAttributes.size())
    242       return MAttributes[i-1];
    243     return AttributeSet();
    244   }
    245 
    246   /// getValueTypePair - Read a value/type pair out of the specified record from
    247   /// slot 'Slot'.  Increment Slot past the number of slots used in the record.
    248   /// Return true on failure.
    249   bool getValueTypePair(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
    250                         unsigned InstNum, Value *&ResVal) {
    251     if (Slot == Record.size()) return true;
    252     unsigned ValNo = (unsigned)Record[Slot++];
    253     if (ValNo < InstNum) {
    254       // If this is not a forward reference, just return the value we already
    255       // have.
    256       ResVal = getFnValueByID(ValNo, 0);
    257       return ResVal == 0;
    258     } else if (Slot == Record.size()) {
    259       return true;
    260     }
    261 
    262     unsigned TypeNo = (unsigned)Record[Slot++];
    263     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
    264     return ResVal == 0;
    265   }
    266   bool getValue(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
    267                 Type *Ty, Value *&ResVal) {
    268     if (Slot == Record.size()) return true;
    269     unsigned ValNo = (unsigned)Record[Slot++];
    270     ResVal = getFnValueByID(ValNo, Ty);
    271     return ResVal == 0;
    272   }
    273 
    274 
    275   bool ParseModule(bool Resume);
    276   bool ParseAttributeBlock();
    277   bool ParseTypeTable();
    278   bool ParseOldTypeTable();         // FIXME: Remove in LLVM 3.1
    279   bool ParseTypeTableBody();
    280 
    281   bool ParseOldTypeSymbolTable();   // FIXME: Remove in LLVM 3.1
    282   bool ParseValueSymbolTable();
    283   bool ParseConstants();
    284   bool RememberAndSkipFunctionBody();
    285   bool ParseFunctionBody(Function *F);
    286   bool GlobalCleanup();
    287   bool ResolveGlobalAndAliasInits();
    288   bool ParseMetadata();
    289   bool ParseMetadataAttachment();
    290   bool ParseModuleTriple(std::string &Triple);
    291   bool InitStream();
    292   bool InitStreamFromBuffer();
    293   bool InitLazyStream();
    294 };
    295 
    296 } // End llvm_3_0 namespace
    297 
    298 #endif
    299