1 #include "llvm/Bitcode/ReaderWriter.h"
2 #include "llvm/IR/Function.h"
3 #include "llvm/IR/GlobalVariable.h"
4 #include "llvm/IR/LLVMContext.h"
5 #include "llvm/IR/Module.h"
6 #include "llvm/Support/CommandLine.h"
7 #include "llvm/Support/ManagedStatic.h"
8 #include "llvm/Support/MemoryBuffer.h"
9 #include "llvm/Support/FileSystem.h"
10 #include "llvm/Support/raw_ostream.h"
11 #include "llvm/Support/ErrorOr.h"
12 #include "llvm/Support/ToolOutputFile.h"
13 #include "llvm/Config/llvm-config.h"
14 
15 #include <system_error>
16 
17 using namespace llvm;
18 
19 static cl::opt<std::string>
20 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
21 
22 static cl::opt<std::string>
23 OutputFilename("o", cl::desc("Output filename"),
24                cl::value_desc("filename"));
25 
26 int main(int argc, char **argv) {
27   LLVMContext &Context = getGlobalContext();
28   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
29 
30   cl::ParseCommandLineOptions(argc, argv, "libclc builtin preparation tool\n");
31 
32   std::string ErrorMessage;
33   std::auto_ptr<Module> M;
34 
35   {
36     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
37       MemoryBuffer::getFile(InputFilename);
38     std::unique_ptr<MemoryBuffer> &BufferPtr = BufferOrErr.get();
39     if (std::error_code  ec = BufferOrErr.getError())
40       ErrorMessage = ec.message();
41     else {
42       ErrorOr<Module *> ModuleOrErr =
43 	parseBitcodeFile(BufferPtr.get()->getMemBufferRef(), Context);
44       if (std::error_code ec = ModuleOrErr.getError())
45         ErrorMessage = ec.message();
46       M.reset(ModuleOrErr.get());
47     }
48   }
49 
50   if (M.get() == 0) {
51     errs() << argv[0] << ": ";
52     if (ErrorMessage.size())
53       errs() << ErrorMessage << "\n";
54     else
55       errs() << "bitcode didn't read correctly.\n";
56     return 1;
57   }
58 
59   // Set linkage of every external definition to linkonce_odr.
60   for (Module::iterator i = M->begin(), e = M->end(); i != e; ++i) {
61     if (!i->isDeclaration() && i->getLinkage() == GlobalValue::ExternalLinkage)
62       i->setLinkage(GlobalValue::LinkOnceODRLinkage);
63   }
64 
65   for (Module::global_iterator i = M->global_begin(), e = M->global_end();
66        i != e; ++i) {
67     if (!i->isDeclaration() && i->getLinkage() == GlobalValue::ExternalLinkage)
68       i->setLinkage(GlobalValue::LinkOnceODRLinkage);
69   }
70 
71   if (OutputFilename.empty()) {
72     errs() << "no output file\n";
73     return 1;
74   }
75 
76   std::error_code EC;
77   std::unique_ptr<tool_output_file> Out
78   (new tool_output_file(OutputFilename, EC, sys::fs::F_None));
79   if (EC) {
80     errs() << EC.message() << '\n';
81     exit(1);
82   }
83 
84   WriteBitcodeToFile(M.get(), Out->os());
85 
86   // Declare success.
87   Out->keep();
88   return 0;
89 }
90 
91