Canonicalize header guards into a common format.
[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 LLVM_LIB_BITCODE_READER_BITCODEREADER_H
15 #define LLVM_LIB_BITCODE_READER_BITCODEREADER_H
16
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/Bitcode/BitstreamReader.h"
19 #include "llvm/Bitcode/LLVMBitCodes.h"
20 #include "llvm/IR/Attributes.h"
21 #include "llvm/IR/GVMaterializer.h"
22 #include "llvm/IR/OperandTraits.h"
23 #include "llvm/IR/Type.h"
24 #include "llvm/IR/ValueHandle.h"
25 #include <deque>
26 #include <system_error>
27 #include <vector>
28
29 namespace llvm {
30   class Comdat;
31   class MemoryBuffer;
32   class LLVMContext;
33
34 //===----------------------------------------------------------------------===//
35 //                          BitcodeReaderValueList Class
36 //===----------------------------------------------------------------------===//
37
38 class BitcodeReaderValueList {
39   std::vector<WeakVH> ValuePtrs;
40
41   /// ResolveConstants - As we resolve forward-referenced constants, we add
42   /// information about them to this vector.  This allows us to resolve them in
43   /// bulk instead of resolving each reference at a time.  See the code in
44   /// ResolveConstantForwardRefs for more information about this.
45   ///
46   /// The key of this vector is the placeholder constant, the value is the slot
47   /// number that holds the resolved value.
48   typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
49   ResolveConstantsTy ResolveConstants;
50   LLVMContext &Context;
51 public:
52   BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
53   ~BitcodeReaderValueList() {
54     assert(ResolveConstants.empty() && "Constants not resolved?");
55   }
56
57   // vector compatibility methods
58   unsigned size() const { return ValuePtrs.size(); }
59   void resize(unsigned N) { ValuePtrs.resize(N); }
60   void push_back(Value *V) {
61     ValuePtrs.push_back(V);
62   }
63
64   void clear() {
65     assert(ResolveConstants.empty() && "Constants not resolved?");
66     ValuePtrs.clear();
67   }
68
69   Value *operator[](unsigned i) const {
70     assert(i < ValuePtrs.size());
71     return ValuePtrs[i];
72   }
73
74   Value *back() const { return ValuePtrs.back(); }
75     void pop_back() { ValuePtrs.pop_back(); }
76   bool empty() const { return ValuePtrs.empty(); }
77   void shrinkTo(unsigned N) {
78     assert(N <= size() && "Invalid shrinkTo request!");
79     ValuePtrs.resize(N);
80   }
81
82   Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
83   Value *getValueFwdRef(unsigned Idx, Type *Ty);
84
85   void AssignValue(Value *V, unsigned Idx);
86
87   /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
88   /// resolves any forward references.
89   void ResolveConstantForwardRefs();
90 };
91
92
93 //===----------------------------------------------------------------------===//
94 //                          BitcodeReaderMDValueList Class
95 //===----------------------------------------------------------------------===//
96
97 class BitcodeReaderMDValueList {
98   std::vector<WeakVH> MDValuePtrs;
99
100   LLVMContext &Context;
101 public:
102   BitcodeReaderMDValueList(LLVMContext& C) : Context(C) {}
103
104   // vector compatibility methods
105   unsigned size() const       { return MDValuePtrs.size(); }
106   void resize(unsigned N)     { MDValuePtrs.resize(N); }
107   void push_back(Value *V)    { MDValuePtrs.push_back(V);  }
108   void clear()                { MDValuePtrs.clear();  }
109   Value *back() const         { return MDValuePtrs.back(); }
110   void pop_back()             { MDValuePtrs.pop_back(); }
111   bool empty() const          { return MDValuePtrs.empty(); }
112
113   Value *operator[](unsigned i) const {
114     assert(i < MDValuePtrs.size());
115     return MDValuePtrs[i];
116   }
117
118   void shrinkTo(unsigned N) {
119     assert(N <= size() && "Invalid shrinkTo request!");
120     MDValuePtrs.resize(N);
121   }
122
123   Value *getValueFwdRef(unsigned Idx);
124   void AssignValue(Value *V, unsigned Idx);
125 };
126
127 class BitcodeReader : public GVMaterializer {
128   LLVMContext &Context;
129   Module *TheModule;
130   std::unique_ptr<MemoryBuffer> Buffer;
131   std::unique_ptr<BitstreamReader> StreamFile;
132   BitstreamCursor Stream;
133   DataStreamer *LazyStreamer;
134   uint64_t NextUnreadBit;
135   bool SeenValueSymbolTable;
136
137   std::vector<Type*> TypeList;
138   BitcodeReaderValueList ValueList;
139   BitcodeReaderMDValueList MDValueList;
140   std::vector<Comdat *> ComdatList;
141   SmallVector<Instruction *, 64> InstructionList;
142
143   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
144   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
145   std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
146
147   SmallVector<Instruction*, 64> InstsWithTBAATag;
148
149   /// MAttributes - The set of attributes by index.  Index zero in the
150   /// file is for null, and is thus not represented here.  As such all indices
151   /// are off by one.
152   std::vector<AttributeSet> MAttributes;
153
154   /// \brief The set of attribute groups.
155   std::map<unsigned, AttributeSet> MAttributeGroups;
156
157   /// FunctionBBs - While parsing a function body, this is a list of the basic
158   /// blocks for the function.
159   std::vector<BasicBlock*> FunctionBBs;
160
161   // When reading the module header, this list is populated with functions that
162   // have bodies later in the file.
163   std::vector<Function*> FunctionsWithBodies;
164
165   // When intrinsic functions are encountered which require upgrading they are
166   // stored here with their replacement function.
167   typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
168   UpgradedIntrinsicMap UpgradedIntrinsics;
169
170   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
171   DenseMap<unsigned, unsigned> MDKindMap;
172
173   // Several operations happen after the module header has been read, but
174   // before function bodies are processed. This keeps track of whether
175   // we've done this yet.
176   bool SeenFirstFunctionBody;
177
178   /// DeferredFunctionInfo - When function bodies are initially scanned, this
179   /// map contains info about where to find deferred function body in the
180   /// stream.
181   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
182
183   /// These are basic blocks forward-referenced by block addresses.  They are
184   /// inserted lazily into functions when they're loaded.
185   typedef std::pair<unsigned, BasicBlock *> BasicBlockRefTy;
186   DenseMap<Function *, std::vector<BasicBlockRefTy>> BasicBlockFwdRefs;
187   std::deque<Function *> BasicBlockFwdRefQueue;
188
189   /// UseRelativeIDs - Indicates that we are using a new encoding for
190   /// instruction operands where most operands in the current
191   /// FUNCTION_BLOCK are encoded relative to the instruction number,
192   /// for a more compact encoding.  Some instruction operands are not
193   /// relative to the instruction ID: basic block numbers, and types.
194   /// Once the old style function blocks have been phased out, we would
195   /// not need this flag.
196   bool UseRelativeIDs;
197
198   /// True if all functions will be materialized, negating the need to process
199   /// (e.g.) blockaddress forward references.
200   bool WillMaterializeAllForwardRefs;
201
202   /// Functions that have block addresses taken.  This is usually empty.
203   SmallPtrSet<const Function *, 4> BlockAddressesTaken;
204
205 public:
206   std::error_code Error(BitcodeError E) { return make_error_code(E); }
207
208   explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
209       : Context(C), TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
210         NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
211         MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
212         WillMaterializeAllForwardRefs(false) {}
213   explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C)
214       : Context(C), TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
215         NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
216         MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
217         WillMaterializeAllForwardRefs(false) {}
218   ~BitcodeReader() { FreeState(); }
219
220   std::error_code materializeForwardReferencedFunctions();
221
222   void FreeState();
223
224   void releaseBuffer() override;
225
226   bool isMaterializable(const GlobalValue *GV) const override;
227   bool isDematerializable(const GlobalValue *GV) const override;
228   std::error_code Materialize(GlobalValue *GV) override;
229   std::error_code MaterializeModule(Module *M) override;
230   void Dematerialize(GlobalValue *GV) override;
231
232   /// @brief Main interface to parsing a bitcode buffer.
233   /// @returns true if an error occurred.
234   std::error_code ParseBitcodeInto(Module *M);
235
236   /// @brief Cheap mechanism to just extract module triple
237   /// @returns true if an error occurred.
238   ErrorOr<std::string> parseTriple();
239
240   static uint64_t decodeSignRotatedValue(uint64_t V);
241
242 private:
243   Type *getTypeByID(unsigned ID);
244   Value *getFnValueByID(unsigned ID, Type *Ty) {
245     if (Ty && Ty->isMetadataTy())
246       return MDValueList.getValueFwdRef(ID);
247     return ValueList.getValueFwdRef(ID, Ty);
248   }
249   BasicBlock *getBasicBlock(unsigned ID) const {
250     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
251     return FunctionBBs[ID];
252   }
253   AttributeSet getAttributes(unsigned i) const {
254     if (i-1 < MAttributes.size())
255       return MAttributes[i-1];
256     return AttributeSet();
257   }
258
259   /// getValueTypePair - Read a value/type pair out of the specified record from
260   /// slot 'Slot'.  Increment Slot past the number of slots used in the record.
261   /// Return true on failure.
262   bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
263                         unsigned InstNum, Value *&ResVal) {
264     if (Slot == Record.size()) return true;
265     unsigned ValNo = (unsigned)Record[Slot++];
266     // Adjust the ValNo, if it was encoded relative to the InstNum.
267     if (UseRelativeIDs)
268       ValNo = InstNum - ValNo;
269     if (ValNo < InstNum) {
270       // If this is not a forward reference, just return the value we already
271       // have.
272       ResVal = getFnValueByID(ValNo, nullptr);
273       return ResVal == nullptr;
274     } else if (Slot == Record.size()) {
275       return true;
276     }
277
278     unsigned TypeNo = (unsigned)Record[Slot++];
279     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
280     return ResVal == nullptr;
281   }
282
283   /// popValue - Read a value out of the specified record from slot 'Slot'.
284   /// Increment Slot past the number of slots used by the value in the record.
285   /// Return true if there is an error.
286   bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
287                 unsigned InstNum, Type *Ty, Value *&ResVal) {
288     if (getValue(Record, Slot, InstNum, Ty, ResVal))
289       return true;
290     // All values currently take a single record slot.
291     ++Slot;
292     return false;
293   }
294
295   /// getValue -- Like popValue, but does not increment the Slot number.
296   bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
297                 unsigned InstNum, Type *Ty, Value *&ResVal) {
298     ResVal = getValue(Record, Slot, InstNum, Ty);
299     return ResVal == nullptr;
300   }
301
302   /// getValue -- Version of getValue that returns ResVal directly,
303   /// or 0 if there is an error.
304   Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
305                   unsigned InstNum, Type *Ty) {
306     if (Slot == Record.size()) return nullptr;
307     unsigned ValNo = (unsigned)Record[Slot];
308     // Adjust the ValNo, if it was encoded relative to the InstNum.
309     if (UseRelativeIDs)
310       ValNo = InstNum - ValNo;
311     return getFnValueByID(ValNo, Ty);
312   }
313
314   /// getValueSigned -- Like getValue, but decodes signed VBRs.
315   Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
316                         unsigned InstNum, Type *Ty) {
317     if (Slot == Record.size()) return nullptr;
318     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
319     // Adjust the ValNo, if it was encoded relative to the InstNum.
320     if (UseRelativeIDs)
321       ValNo = InstNum - ValNo;
322     return getFnValueByID(ValNo, Ty);
323   }
324
325   std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
326   std::error_code ParseModule(bool Resume);
327   std::error_code ParseAttributeBlock();
328   std::error_code ParseAttributeGroupBlock();
329   std::error_code ParseTypeTable();
330   std::error_code ParseTypeTableBody();
331
332   std::error_code ParseValueSymbolTable();
333   std::error_code ParseConstants();
334   std::error_code RememberAndSkipFunctionBody();
335   std::error_code ParseFunctionBody(Function *F);
336   std::error_code GlobalCleanup();
337   std::error_code ResolveGlobalAndAliasInits();
338   std::error_code ParseMetadata();
339   std::error_code ParseMetadataAttachment();
340   ErrorOr<std::string> parseModuleTriple();
341   std::error_code ParseUseLists();
342   std::error_code InitStream();
343   std::error_code InitStreamFromBuffer();
344   std::error_code InitLazyStream();
345   std::error_code FindFunctionInStream(
346       Function *F,
347       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
348 };
349
350 } // End llvm namespace
351
352 #endif