LLVM  mainline
ReaderWriter.h
Go to the documentation of this file.
00001 //===-- llvm/Bitcode/ReaderWriter.h - Bitcode reader/writers ----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This header defines interfaces to read and write LLVM bitcode files/streams.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_BITCODE_READERWRITER_H
00015 #define LLVM_BITCODE_READERWRITER_H
00016 
00017 #include "llvm/IR/DiagnosticInfo.h"
00018 #include "llvm/Support/ErrorOr.h"
00019 #include "llvm/Support/MemoryBuffer.h"
00020 #include <memory>
00021 #include <string>
00022 
00023 namespace llvm {
00024   class BitstreamWriter;
00025   class DataStreamer;
00026   class LLVMContext;
00027   class Module;
00028   class ModulePass;
00029   class raw_ostream;
00030 
00031   /// Read the header of the specified bitcode buffer and prepare for lazy
00032   /// deserialization of function bodies. If ShouldLazyLoadMetadata is true,
00033   /// lazily load metadata as well. If successful, this moves Buffer. On
00034   /// error, this *does not* move Buffer.
00035   ErrorOr<Module *>
00036   getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
00037                        LLVMContext &Context,
00038                        DiagnosticHandlerFunction DiagnosticHandler = nullptr,
00039                        bool ShouldLazyLoadMetadata = false);
00040 
00041   /// Read the header of the specified stream and prepare for lazy
00042   /// deserialization and streaming of function bodies.
00043   ErrorOr<std::unique_ptr<Module>> getStreamedBitcodeModule(
00044       StringRef Name, DataStreamer *Streamer, LLVMContext &Context,
00045       DiagnosticHandlerFunction DiagnosticHandler = nullptr);
00046 
00047   /// Read the header of the specified bitcode buffer and extract just the
00048   /// triple information. If successful, this returns a string. On error, this
00049   /// returns "".
00050   std::string
00051   getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
00052                          DiagnosticHandlerFunction DiagnosticHandler = nullptr);
00053 
00054   /// Read the specified bitcode file, returning the module.
00055   ErrorOr<Module *>
00056   parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
00057                    DiagnosticHandlerFunction DiagnosticHandler = nullptr);
00058 
00059   /// WriteBitcodeToFile - Write the specified module to the specified
00060   /// raw output stream.  For streams where it matters, the given stream
00061   /// should be in "binary" mode.
00062   void WriteBitcodeToFile(const Module *M, raw_ostream &Out);
00063 
00064 
00065   /// isBitcodeWrapper - Return true if the given bytes are the magic bytes
00066   /// for an LLVM IR bitcode wrapper.
00067   ///
00068   inline bool isBitcodeWrapper(const unsigned char *BufPtr,
00069                                const unsigned char *BufEnd) {
00070     // See if you can find the hidden message in the magic bytes :-).
00071     // (Hint: it's a little-endian encoding.)
00072     return BufPtr != BufEnd &&
00073            BufPtr[0] == 0xDE &&
00074            BufPtr[1] == 0xC0 &&
00075            BufPtr[2] == 0x17 &&
00076            BufPtr[3] == 0x0B;
00077   }
00078 
00079   /// isRawBitcode - Return true if the given bytes are the magic bytes for
00080   /// raw LLVM IR bitcode (without a wrapper).
00081   ///
00082   inline bool isRawBitcode(const unsigned char *BufPtr,
00083                            const unsigned char *BufEnd) {
00084     // These bytes sort of have a hidden message, but it's not in
00085     // little-endian this time, and it's a little redundant.
00086     return BufPtr != BufEnd &&
00087            BufPtr[0] == 'B' &&
00088            BufPtr[1] == 'C' &&
00089            BufPtr[2] == 0xc0 &&
00090            BufPtr[3] == 0xde;
00091   }
00092 
00093   /// isBitcode - Return true if the given bytes are the magic bytes for
00094   /// LLVM IR bitcode, either with or without a wrapper.
00095   ///
00096   inline bool isBitcode(const unsigned char *BufPtr,
00097                         const unsigned char *BufEnd) {
00098     return isBitcodeWrapper(BufPtr, BufEnd) ||
00099            isRawBitcode(BufPtr, BufEnd);
00100   }
00101 
00102   /// SkipBitcodeWrapperHeader - Some systems wrap bc files with a special
00103   /// header for padding or other reasons.  The format of this header is:
00104   ///
00105   /// struct bc_header {
00106   ///   uint32_t Magic;         // 0x0B17C0DE
00107   ///   uint32_t Version;       // Version, currently always 0.
00108   ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
00109   ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
00110   ///   ... potentially other gunk ...
00111   /// };
00112   ///
00113   /// This function is called when we find a file with a matching magic number.
00114   /// In this case, skip down to the subsection of the file that is actually a
00115   /// BC file.
00116   /// If 'VerifyBufferSize' is true, check that the buffer is large enough to
00117   /// contain the whole bitcode file.
00118   inline bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr,
00119                                        const unsigned char *&BufEnd,
00120                                        bool VerifyBufferSize) {
00121     enum {
00122       KnownHeaderSize = 4*4,  // Size of header we read.
00123       OffsetField = 2*4,      // Offset in bytes to Offset field.
00124       SizeField = 3*4         // Offset in bytes to Size field.
00125     };
00126 
00127     // Must contain the header!
00128     if (BufEnd-BufPtr < KnownHeaderSize) return true;
00129 
00130     unsigned Offset = ( BufPtr[OffsetField  ]        |
00131                        (BufPtr[OffsetField+1] << 8)  |
00132                        (BufPtr[OffsetField+2] << 16) |
00133                        (BufPtr[OffsetField+3] << 24));
00134     unsigned Size   = ( BufPtr[SizeField    ]        |
00135                        (BufPtr[SizeField  +1] << 8)  |
00136                        (BufPtr[SizeField  +2] << 16) |
00137                        (BufPtr[SizeField  +3] << 24));
00138 
00139     // Verify that Offset+Size fits in the file.
00140     if (VerifyBufferSize && Offset+Size > unsigned(BufEnd-BufPtr))
00141       return true;
00142     BufPtr += Offset;
00143     BufEnd = BufPtr+Size;
00144     return false;
00145   }
00146 
00147   const std::error_category &BitcodeErrorCategory();
00148   enum class BitcodeError { InvalidBitcodeSignature, CorruptedBitcode };
00149   inline std::error_code make_error_code(BitcodeError E) {
00150     return std::error_code(static_cast<int>(E), BitcodeErrorCategory());
00151   }
00152 
00153   class BitcodeDiagnosticInfo : public DiagnosticInfo {
00154     const Twine &Msg;
00155     std::error_code EC;
00156 
00157   public:
00158     BitcodeDiagnosticInfo(std::error_code EC, DiagnosticSeverity Severity,
00159                           const Twine &Msg);
00160     void print(DiagnosticPrinter &DP) const override;
00161     std::error_code getError() const { return EC; };
00162 
00163     static bool classof(const DiagnosticInfo *DI) {
00164       return DI->getKind() == DK_Bitcode;
00165     }
00166   };
00167 
00168 } // End llvm namespace
00169 
00170 namespace std {
00171 template <> struct is_error_code_enum<llvm::BitcodeError> : std::true_type {};
00172 }
00173 
00174 #endif