xref: /llvm-project/llvm/tools/llvm-split/llvm-split.cpp (revision f3a710cade9381030f3e1e9778c5fc12f8a02fdf)
1 //===-- llvm-split: command line tool for testing module splitter ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This program can be used to test the llvm::SplitModule function.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/StringExtras.h"
14 #include "llvm/Bitcode/BitcodeWriter.h"
15 #include "llvm/IR/LLVMContext.h"
16 #include "llvm/IR/Verifier.h"
17 #include "llvm/IRReader/IRReader.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/SourceMgr.h"
21 #include "llvm/Support/ToolOutputFile.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Transforms/Utils/SplitModule.h"
24 
25 using namespace llvm;
26 
27 static cl::opt<std::string>
28 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
29     cl::init("-"), cl::value_desc("filename"));
30 
31 static cl::opt<std::string>
32 OutputFilename("o", cl::desc("Override output filename"),
33                cl::value_desc("filename"));
34 
35 static cl::opt<unsigned> NumOutputs("j", cl::Prefix, cl::init(2),
36                                     cl::desc("Number of output files"));
37 
38 static cl::opt<bool>
39     PreserveLocals("preserve-locals", cl::Prefix, cl::init(false),
40                    cl::desc("Split without externalizing locals"));
41 
42 int main(int argc, char **argv) {
43   LLVMContext Context;
44   SMDiagnostic Err;
45   cl::ParseCommandLineOptions(argc, argv, "LLVM module splitter\n");
46 
47   std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
48 
49   if (!M) {
50     Err.print(argv[0], errs());
51     return 1;
52   }
53 
54   unsigned I = 0;
55   SplitModule(
56       *M, NumOutputs,
57       [&](std::unique_ptr<Module> MPart) {
58         std::error_code EC;
59         std::unique_ptr<ToolOutputFile> Out(new ToolOutputFile(
60             OutputFilename + utostr(I++), EC, sys::fs::OF_None));
61         if (EC) {
62           errs() << EC.message() << '\n';
63           exit(1);
64         }
65 
66         if (verifyModule(*MPart, &errs())) {
67           errs() << "Broken module!\n";
68           exit(1);
69         }
70 
71         WriteBitcodeToFile(*MPart, Out->os());
72 
73         // Declare success.
74         Out->keep();
75       },
76       PreserveLocals);
77 
78   return 0;
79 }
80