Clang format a few prior patches (NFC)
[oota-llvm.git] / include / llvm / Bitcode / ReaderWriter.h
1 //===-- llvm/Bitcode/ReaderWriter.h - Bitcode reader/writers ----*- 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 interfaces to read and write LLVM bitcode files/streams.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_BITCODE_READERWRITER_H
15 #define LLVM_BITCODE_READERWRITER_H
16
17 #include "llvm/IR/DiagnosticInfo.h"
18 #include "llvm/IR/FunctionInfo.h"
19 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/ErrorOr.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include <memory>
23 #include <string>
24
25 namespace llvm {
26   class BitstreamWriter;
27   class DataStreamer;
28   class LLVMContext;
29   class Module;
30   class ModulePass;
31   class raw_ostream;
32
33   /// Read the header of the specified bitcode buffer and prepare for lazy
34   /// deserialization of function bodies. If ShouldLazyLoadMetadata is true,
35   /// lazily load metadata as well. If successful, this moves Buffer. On
36   /// error, this *does not* move Buffer.
37   ErrorOr<std::unique_ptr<Module>>
38   getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
39                        LLVMContext &Context,
40                        DiagnosticHandlerFunction DiagnosticHandler = nullptr,
41                        bool ShouldLazyLoadMetadata = false);
42
43   /// Read the header of the specified stream and prepare for lazy
44   /// deserialization and streaming of function bodies.
45   ErrorOr<std::unique_ptr<Module>> getStreamedBitcodeModule(
46       StringRef Name, std::unique_ptr<DataStreamer> Streamer,
47       LLVMContext &Context,
48       DiagnosticHandlerFunction DiagnosticHandler = nullptr);
49
50   /// Read the header of the specified bitcode buffer and extract just the
51   /// triple information. If successful, this returns a string. On error, this
52   /// returns "".
53   std::string
54   getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
55                          DiagnosticHandlerFunction DiagnosticHandler = nullptr);
56
57   /// Read the specified bitcode file, returning the module.
58   ErrorOr<std::unique_ptr<Module>>
59   parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
60                    DiagnosticHandlerFunction DiagnosticHandler = nullptr);
61
62   /// Check if the given bitcode buffer contains a function summary block.
63   bool hasFunctionSummary(MemoryBufferRef Buffer, LLVMContext &Context,
64                           DiagnosticHandlerFunction DiagnosticHandler);
65
66   /// Parse the specified bitcode buffer, returning the function info index.
67   /// If IsLazy is true, parse the entire function summary into
68   /// the index. Otherwise skip the function summary section, and only create
69   /// an index object with a map from function name to function summary offset.
70   /// The index is used to perform lazy function summary reading later.
71   ErrorOr<std::unique_ptr<FunctionInfoIndex>>
72   getFunctionInfoIndex(MemoryBufferRef Buffer, LLVMContext &Context,
73                        DiagnosticHandlerFunction DiagnosticHandler,
74                        bool IsLazy = false);
75
76   /// This method supports lazy reading of function summary data from the
77   /// combined index during function importing. When reading the combined index
78   /// file, getFunctionInfoIndex is first invoked with IsLazy=true.
79   /// Then this method is called for each function considered for importing,
80   /// to parse the summary information for the given function name into
81   /// the index.
82   std::error_code
83   readFunctionSummary(MemoryBufferRef Buffer, LLVMContext &Context,
84                       DiagnosticHandlerFunction DiagnosticHandler,
85                       StringRef FunctionName,
86                       std::unique_ptr<FunctionInfoIndex> Index);
87
88   /// \brief Write the specified module to the specified raw output stream.
89   ///
90   /// For streams where it matters, the given stream should be in "binary"
91   /// mode.
92   ///
93   /// If \c ShouldPreserveUseListOrder, encode the use-list order for each \a
94   /// Value in \c M.  These will be reconstructed exactly when \a M is
95   /// deserialized.
96   ///
97   /// If \c EmitFunctionSummary, emit the function summary index (currently
98   /// for use in ThinLTO optimization).
99   void WriteBitcodeToFile(const Module *M, raw_ostream &Out,
100                           bool ShouldPreserveUseListOrder = false,
101                           bool EmitFunctionSummary = false);
102
103   /// Write the specified function summary index to the given raw output stream,
104   /// where it will be written in a new bitcode block. This is used when
105   /// writing the combined index file for ThinLTO.
106   void WriteFunctionSummaryToFile(const FunctionInfoIndex &Index,
107                                   raw_ostream &Out);
108
109   /// isBitcodeWrapper - Return true if the given bytes are the magic bytes
110   /// for an LLVM IR bitcode wrapper.
111   ///
112   inline bool isBitcodeWrapper(const unsigned char *BufPtr,
113                                const unsigned char *BufEnd) {
114     // See if you can find the hidden message in the magic bytes :-).
115     // (Hint: it's a little-endian encoding.)
116     return BufPtr != BufEnd &&
117            BufPtr[0] == 0xDE &&
118            BufPtr[1] == 0xC0 &&
119            BufPtr[2] == 0x17 &&
120            BufPtr[3] == 0x0B;
121   }
122
123   /// isRawBitcode - Return true if the given bytes are the magic bytes for
124   /// raw LLVM IR bitcode (without a wrapper).
125   ///
126   inline bool isRawBitcode(const unsigned char *BufPtr,
127                            const unsigned char *BufEnd) {
128     // These bytes sort of have a hidden message, but it's not in
129     // little-endian this time, and it's a little redundant.
130     return BufPtr != BufEnd &&
131            BufPtr[0] == 'B' &&
132            BufPtr[1] == 'C' &&
133            BufPtr[2] == 0xc0 &&
134            BufPtr[3] == 0xde;
135   }
136
137   /// isBitcode - Return true if the given bytes are the magic bytes for
138   /// LLVM IR bitcode, either with or without a wrapper.
139   ///
140   inline bool isBitcode(const unsigned char *BufPtr,
141                         const unsigned char *BufEnd) {
142     return isBitcodeWrapper(BufPtr, BufEnd) ||
143            isRawBitcode(BufPtr, BufEnd);
144   }
145
146   /// SkipBitcodeWrapperHeader - Some systems wrap bc files with a special
147   /// header for padding or other reasons.  The format of this header is:
148   ///
149   /// struct bc_header {
150   ///   uint32_t Magic;         // 0x0B17C0DE
151   ///   uint32_t Version;       // Version, currently always 0.
152   ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
153   ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
154   ///   ... potentially other gunk ...
155   /// };
156   ///
157   /// This function is called when we find a file with a matching magic number.
158   /// In this case, skip down to the subsection of the file that is actually a
159   /// BC file.
160   /// If 'VerifyBufferSize' is true, check that the buffer is large enough to
161   /// contain the whole bitcode file.
162   inline bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr,
163                                        const unsigned char *&BufEnd,
164                                        bool VerifyBufferSize) {
165     enum {
166       KnownHeaderSize = 4*4,  // Size of header we read.
167       OffsetField = 2*4,      // Offset in bytes to Offset field.
168       SizeField = 3*4         // Offset in bytes to Size field.
169     };
170
171     // Must contain the header!
172     if (BufEnd-BufPtr < KnownHeaderSize) return true;
173
174     unsigned Offset = support::endian::read32le(&BufPtr[OffsetField]);
175     unsigned Size = support::endian::read32le(&BufPtr[SizeField]);
176
177     // Verify that Offset+Size fits in the file.
178     if (VerifyBufferSize && Offset+Size > unsigned(BufEnd-BufPtr))
179       return true;
180     BufPtr += Offset;
181     BufEnd = BufPtr+Size;
182     return false;
183   }
184
185   const std::error_category &BitcodeErrorCategory();
186   enum class BitcodeError { InvalidBitcodeSignature = 1, CorruptedBitcode };
187   inline std::error_code make_error_code(BitcodeError E) {
188     return std::error_code(static_cast<int>(E), BitcodeErrorCategory());
189   }
190
191   class BitcodeDiagnosticInfo : public DiagnosticInfo {
192     const Twine &Msg;
193     std::error_code EC;
194
195   public:
196     BitcodeDiagnosticInfo(std::error_code EC, DiagnosticSeverity Severity,
197                           const Twine &Msg);
198     void print(DiagnosticPrinter &DP) const override;
199     std::error_code getError() const { return EC; }
200
201     static bool classof(const DiagnosticInfo *DI) {
202       return DI->getKind() == DK_Bitcode;
203     }
204   };
205
206 } // End llvm namespace
207
208 namespace std {
209 template <> struct is_error_code_enum<llvm::BitcodeError> : std::true_type {};
210 }
211
212 #endif