1 //===- llvm-cat.cpp - LLVM module concatenation 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 list of input modules and uses them to create a multi-module
14 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/Bitcode/BitcodeReader.h"
18 #include "llvm/Bitcode/BitcodeWriter.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IRReader/IRReader.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Error.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/raw_ostream.h"
31 #include <system_error>
37 BinaryCat("b", cl::desc("Whether to perform binary concatenation"));
39 static cl::opt
<std::string
> OutputFilename("o", cl::Required
,
40 cl::desc("Output filename"),
41 cl::value_desc("filename"));
43 static cl::list
<std::string
> InputFilenames(cl::Positional
, cl::ZeroOrMore
,
44 cl::desc("<input files>"));
46 int main(int argc
, char **argv
) {
47 cl::ParseCommandLineOptions(argc
, argv
, "Module concatenation");
49 ExitOnError
ExitOnErr("llvm-cat: ");
52 SmallVector
<char, 0> Buffer
;
53 BitcodeWriter
Writer(Buffer
);
55 for (const auto &InputFilename
: InputFilenames
) {
56 std::unique_ptr
<MemoryBuffer
> MB
= ExitOnErr(
57 errorOrToExpected(MemoryBuffer::getFileOrSTDIN(InputFilename
)));
58 std::vector
<BitcodeModule
> Mods
= ExitOnErr(getBitcodeModuleList(*MB
));
59 for (auto &BitcodeMod
: Mods
) {
60 Buffer
.insert(Buffer
.end(), BitcodeMod
.getBuffer().begin(),
61 BitcodeMod
.getBuffer().end());
62 Writer
.copyStrtab(BitcodeMod
.getStrtab());
66 // The string table does not own strings added to it, some of which are
67 // owned by the modules; keep them alive until we write the string table.
68 std::vector
<std::unique_ptr
<Module
>> OwnedMods
;
69 for (const auto &InputFilename
: InputFilenames
) {
71 std::unique_ptr
<Module
> M
= parseIRFile(InputFilename
, Err
, Context
);
73 Err
.print(argv
[0], errs());
76 Writer
.writeModule(*M
);
77 OwnedMods
.push_back(std::move(M
));
83 raw_fd_ostream
OS(OutputFilename
, EC
, sys::fs::OpenFlags::F_None
);
85 errs() << argv
[0] << ": cannot open " << OutputFilename
<< " for writing: "
90 OS
.write(Buffer
.data(), Buffer
.size());