1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
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 file implements the Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/LTO/LTOCodeGenerator.h"
16 #include "llvm/LTO/LTOModule.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Analysis/Passes.h"
19 #include "llvm/Analysis/Verifier.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/Config/config.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/InitializePasses.h"
28 #include "llvm/Linker.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/SubtargetFeature.h"
32 #include "llvm/PassManager.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/FormattedStream.h"
36 #include "llvm/Support/Host.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/Signals.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/ToolOutputFile.h"
42 #include "llvm/Support/system_error.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/Target/Mangler.h"
45 #include "llvm/Transforms/IPO.h"
46 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
47 #include "llvm/Transforms/ObjCARC.h"
51 DisableOpt("disable-opt", cl::init(false),
52 cl::desc("Do not run any optimization passes"));
55 DisableInline("disable-inlining", cl::init(false),
56 cl::desc("Do not run the inliner pass"));
59 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
60 cl::desc("Do not run the GVN load PRE pass"));
62 const char* LTOCodeGenerator::getVersionString() {
63 #ifdef LLVM_VERSION_INFO
64 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
66 return PACKAGE_NAME " version " PACKAGE_VERSION;
70 LTOCodeGenerator::LTOCodeGenerator()
71 : Context(getGlobalContext()), Linker(new Module("ld-temp.o", Context)),
72 TargetMach(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false),
73 CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC), NativeObjectFile(NULL) {
74 initializeLTOPasses();
77 LTOCodeGenerator::~LTOCodeGenerator() {
79 delete NativeObjectFile;
80 delete Linker.getModule();
82 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
83 E = CodegenOptions.end();
88 // Initialize LTO passes. Please keep this funciton in sync with
89 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
90 // passes are initialized.
92 void LTOCodeGenerator::initializeLTOPasses() {
93 PassRegistry &R = *PassRegistry::getPassRegistry();
95 initializeInternalizePassPass(R);
96 initializeIPSCCPPass(R);
97 initializeGlobalOptPass(R);
98 initializeConstantMergePass(R);
100 initializeInstCombinerPass(R);
101 initializeSimpleInlinerPass(R);
102 initializePruneEHPass(R);
103 initializeGlobalDCEPass(R);
104 initializeArgPromotionPass(R);
105 initializeJumpThreadingPass(R);
106 initializeSROAPass(R);
107 initializeSROA_DTPass(R);
108 initializeSROA_SSAUpPass(R);
109 initializeFunctionAttrsPass(R);
110 initializeGlobalsModRefPass(R);
111 initializeLICMPass(R);
112 initializeGVNPass(R);
113 initializeMemCpyOptPass(R);
114 initializeDCEPass(R);
115 initializeCFGSimplifyPassPass(R);
118 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
119 bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
121 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
122 for (int i = 0, e = undefs.size(); i != e; ++i)
123 AsmUndefinedRefs[undefs[i]] = 1;
128 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
130 case LTO_DEBUG_MODEL_NONE:
131 EmitDwarfDebugInfo = false;
134 case LTO_DEBUG_MODEL_DWARF:
135 EmitDwarfDebugInfo = true;
138 llvm_unreachable("Unknown debug format!");
141 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
143 case LTO_CODEGEN_PIC_MODEL_STATIC:
144 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
145 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
149 llvm_unreachable("Unknown PIC model!");
152 bool LTOCodeGenerator::writeMergedModules(const char *path,
153 std::string &errMsg) {
154 if (!determineTarget(errMsg))
157 // mark which symbols can not be internalized
158 applyScopeRestrictions();
160 // create output file
162 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
163 if (!ErrInfo.empty()) {
164 errMsg = "could not open bitcode file for writing: ";
169 // write bitcode to it
170 WriteBitcodeToFile(Linker.getModule(), Out.os());
173 if (Out.os().has_error()) {
174 errMsg = "could not write bitcode file: ";
176 Out.os().clear_error();
184 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
185 // make unique temp .o file to put generated object file
186 SmallString<128> Filename;
188 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
190 errMsg = EC.message();
194 // generate object file
195 tool_output_file objFile(Filename.c_str(), FD);
197 bool genResult = generateObjectFile(objFile.os(), errMsg);
198 objFile.os().close();
199 if (objFile.os().has_error()) {
200 objFile.os().clear_error();
201 sys::fs::remove(Twine(Filename));
207 sys::fs::remove(Twine(Filename));
211 NativeObjectPath = Filename.c_str();
212 *name = NativeObjectPath.c_str();
216 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
218 if (!compile_to_file(&name, errMsg))
221 // remove old buffer if compile() called twice
222 delete NativeObjectFile;
224 // read .o file into memory buffer
225 OwningPtr<MemoryBuffer> BuffPtr;
226 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
227 errMsg = ec.message();
228 sys::fs::remove(NativeObjectPath);
231 NativeObjectFile = BuffPtr.take();
234 sys::fs::remove(NativeObjectPath);
236 // return buffer, unless error
237 if (NativeObjectFile == NULL)
239 *length = NativeObjectFile->getBufferSize();
240 return NativeObjectFile->getBufferStart();
243 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
244 if (TargetMach != NULL)
247 // if options were requested, set them
248 if (!CodegenOptions.empty())
249 cl::ParseCommandLineOptions(CodegenOptions.size(),
250 const_cast<char **>(&CodegenOptions[0]));
252 std::string TripleStr = Linker.getModule()->getTargetTriple();
253 if (TripleStr.empty())
254 TripleStr = sys::getDefaultTargetTriple();
255 llvm::Triple Triple(TripleStr);
257 // create target machine from info for merged modules
258 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
262 // The relocation model is actually a static member of TargetMachine and
263 // needs to be set before the TargetMachine is instantiated.
264 Reloc::Model RelocModel = Reloc::Default;
266 case LTO_CODEGEN_PIC_MODEL_STATIC:
267 RelocModel = Reloc::Static;
269 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
270 RelocModel = Reloc::PIC_;
272 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
273 RelocModel = Reloc::DynamicNoPIC;
277 // construct LTOModule, hand over ownership of module and target
278 SubtargetFeatures Features;
279 Features.getDefaultSubtargetFeatures(Triple);
280 std::string FeatureStr = Features.getString();
281 // Set a default CPU for Darwin triples.
282 if (MCpu.empty() && Triple.isOSDarwin()) {
283 if (Triple.getArch() == llvm::Triple::x86_64)
285 else if (Triple.getArch() == llvm::Triple::x86)
288 TargetOptions Options;
289 LTOModule::getTargetOptions(Options);
290 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
291 RelocModel, CodeModel::Default,
292 CodeGenOpt::Aggressive);
296 void LTOCodeGenerator::
297 applyRestriction(GlobalValue &GV,
298 std::vector<const char*> &MustPreserveList,
299 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
301 SmallString<64> Buffer;
302 Mangler.getNameWithPrefix(Buffer, &GV, false);
304 if (GV.isDeclaration())
306 if (MustPreserveSymbols.count(Buffer))
307 MustPreserveList.push_back(GV.getName().data());
308 if (AsmUndefinedRefs.count(Buffer))
312 static void findUsedValues(GlobalVariable *LLVMUsed,
313 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
314 if (LLVMUsed == 0) return;
316 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
317 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
318 if (GlobalValue *GV =
319 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
320 UsedValues.insert(GV);
323 void LTOCodeGenerator::applyScopeRestrictions() {
324 if (ScopeRestrictionsDone)
326 Module *mergedModule = Linker.getModule();
328 // Start off with a verification pass.
330 passes.add(createVerifierPass());
332 // mark which symbols can not be internalized
333 MCContext MContext(TargetMach->getMCAsmInfo(), TargetMach->getRegisterInfo(),
335 Mangler Mangler(MContext, TargetMach);
336 std::vector<const char*> MustPreserveList;
337 SmallPtrSet<GlobalValue*, 8> AsmUsed;
339 for (Module::iterator f = mergedModule->begin(),
340 e = mergedModule->end(); f != e; ++f)
341 applyRestriction(*f, MustPreserveList, AsmUsed, Mangler);
342 for (Module::global_iterator v = mergedModule->global_begin(),
343 e = mergedModule->global_end(); v != e; ++v)
344 applyRestriction(*v, MustPreserveList, AsmUsed, Mangler);
345 for (Module::alias_iterator a = mergedModule->alias_begin(),
346 e = mergedModule->alias_end(); a != e; ++a)
347 applyRestriction(*a, MustPreserveList, AsmUsed, Mangler);
349 GlobalVariable *LLVMCompilerUsed =
350 mergedModule->getGlobalVariable("llvm.compiler.used");
351 findUsedValues(LLVMCompilerUsed, AsmUsed);
352 if (LLVMCompilerUsed)
353 LLVMCompilerUsed->eraseFromParent();
355 if (!AsmUsed.empty()) {
356 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
357 std::vector<Constant*> asmUsed2;
358 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
359 e = AsmUsed.end(); i !=e; ++i) {
360 GlobalValue *GV = *i;
361 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
362 asmUsed2.push_back(c);
365 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
367 new llvm::GlobalVariable(*mergedModule, ATy, false,
368 llvm::GlobalValue::AppendingLinkage,
369 llvm::ConstantArray::get(ATy, asmUsed2),
370 "llvm.compiler.used");
372 LLVMCompilerUsed->setSection("llvm.metadata");
375 passes.add(createInternalizePass(MustPreserveList));
377 // apply scope restrictions
378 passes.run(*mergedModule);
380 ScopeRestrictionsDone = true;
383 /// Optimize merged modules using various IPO passes
384 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
385 std::string &errMsg) {
386 if (!this->determineTarget(errMsg))
389 Module *mergedModule = Linker.getModule();
391 // Mark which symbols can not be internalized
392 this->applyScopeRestrictions();
394 // Instantiate the pass manager to organize the passes.
397 // Start off with a verification pass.
398 passes.add(createVerifierPass());
400 // Add an appropriate DataLayout instance for this module...
401 passes.add(new DataLayout(*TargetMach->getDataLayout()));
402 TargetMach->addAnalysisPasses(passes);
404 // Enabling internalize here would use its AllButMain variant. It
405 // keeps only main if it exists and does nothing for libraries. Instead
406 // we create the pass ourselves with the symbol list provided by the linker.
408 PassManagerBuilder().populateLTOPassManager(passes,
409 /*Internalize=*/false,
413 // Make sure everything is still good.
414 passes.add(createVerifierPass());
416 PassManager codeGenPasses;
418 codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
419 TargetMach->addAnalysisPasses(codeGenPasses);
421 formatted_raw_ostream Out(out);
423 // If the bitcode files contain ARC code and were compiled with optimization,
424 // the ObjCARCContractPass must be run, so do it unconditionally here.
425 codeGenPasses.add(createObjCARCContractPass());
427 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
428 TargetMachine::CGFT_ObjectFile)) {
429 errMsg = "target file type not supported";
433 // Run our queue of passes all at once now, efficiently.
434 passes.run(*mergedModule);
436 // Run the code generator, and write assembly file
437 codeGenPasses.run(*mergedModule);
442 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
444 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
445 for (std::pair<StringRef, StringRef> o = getToken(options);
446 !o.first.empty(); o = getToken(o.second)) {
447 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
449 if (CodegenOptions.empty())
450 CodegenOptions.push_back(strdup("libLLVMLTO"));
451 CodegenOptions.push_back(strdup(o.first.str().c_str()));