1 //===-- llvm-modextract.cpp - LLVM module extractor utility ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This program is for testing features that rely on multi-module bitcode files.
11 // It takes a multi-module bitcode file, extracts one of the modules and writes
12 // it to the output file.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Bitcode/BitcodeReader.h"
17 #include "llvm/Bitcode/BitcodeWriter.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Error.h"
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/ToolOutputFile.h"
26 BinaryExtract("b", cl::desc("Whether to perform binary extraction"));
28 static cl::opt<std::string> OutputFilename("o", cl::Required,
29 cl::desc("Output filename"),
30 cl::value_desc("filename"));
32 static cl::opt<std::string>
33 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
35 static cl::opt<unsigned> ModuleIndex("n", cl::Required,
36 cl::desc("Index of module to extract"),
37 cl::value_desc("index"));
39 int main(int argc, char **argv) {
40 cl::ParseCommandLineOptions(argc, argv, "Module extractor");
42 ExitOnError ExitOnErr("llvm-modextract: error: ");
44 std::unique_ptr<MemoryBuffer> MB =
45 ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(InputFilename)));
46 std::vector<BitcodeModule> Ms = ExitOnErr(getBitcodeModuleList(*MB));
49 if (ModuleIndex >= Ms.size()) {
50 errs() << "llvm-modextract: error: module index out of range; bitcode file "
52 << Ms.size() << " module(s)\n";
57 std::unique_ptr<tool_output_file> Out(
58 new tool_output_file(OutputFilename, EC, sys::fs::F_None));
59 ExitOnErr(errorCodeToError(EC));
62 SmallVector<char, 0> Header;
63 BitcodeWriter Writer(Header);
64 Out->os() << Header << Ms[ModuleIndex].getBuffer();
69 std::unique_ptr<Module> M = ExitOnErr(Ms[ModuleIndex].parseModule(Context));
70 WriteBitcodeToFile(M.get(), Out->os());