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/CodeGen/RuntimeLibcalls.h"
22 #include "llvm/Config/config.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/InitializePasses.h"
29 #include "llvm/Linker.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCContext.h"
32 #include "llvm/MC/SubtargetFeature.h"
33 #include "llvm/PassManager.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/Support/Host.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/Signals.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/TargetSelect.h"
42 #include "llvm/Support/ToolOutputFile.h"
43 #include "llvm/Support/system_error.h"
44 #include "llvm/Target/TargetLibraryInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Target/TargetRegisterInfo.h"
48 #include "llvm/Target/Mangler.h"
49 #include "llvm/Transforms/IPO.h"
50 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
51 #include "llvm/Transforms/ObjCARC.h"
54 const char* LTOCodeGenerator::getVersionString() {
55 #ifdef LLVM_VERSION_INFO
56 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
58 return PACKAGE_NAME " version " PACKAGE_VERSION;
62 LTOCodeGenerator::LTOCodeGenerator()
63 : Context(getGlobalContext()), Linker(new Module("ld-temp.o", Context)),
64 TargetMach(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false),
65 CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC), NativeObjectFile(NULL) {
66 initializeLTOPasses();
69 LTOCodeGenerator::~LTOCodeGenerator() {
71 delete NativeObjectFile;
73 NativeObjectFile = NULL;
75 Linker.deleteModule();
77 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
78 E = CodegenOptions.end();
83 // Initialize LTO passes. Please keep this funciton in sync with
84 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
85 // passes are initialized.
87 void LTOCodeGenerator::initializeLTOPasses() {
88 PassRegistry &R = *PassRegistry::getPassRegistry();
90 initializeInternalizePassPass(R);
91 initializeIPSCCPPass(R);
92 initializeGlobalOptPass(R);
93 initializeConstantMergePass(R);
95 initializeInstCombinerPass(R);
96 initializeSimpleInlinerPass(R);
97 initializePruneEHPass(R);
98 initializeGlobalDCEPass(R);
99 initializeArgPromotionPass(R);
100 initializeJumpThreadingPass(R);
101 initializeSROAPass(R);
102 initializeSROA_DTPass(R);
103 initializeSROA_SSAUpPass(R);
104 initializeFunctionAttrsPass(R);
105 initializeGlobalsModRefPass(R);
106 initializeLICMPass(R);
107 initializeGVNPass(R);
108 initializeMemCpyOptPass(R);
109 initializeDCEPass(R);
110 initializeCFGSimplifyPassPass(R);
113 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
114 bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
116 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
117 for (int i = 0, e = undefs.size(); i != e; ++i)
118 AsmUndefinedRefs[undefs[i]] = 1;
123 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
124 Options.LessPreciseFPMADOption = options.LessPreciseFPMADOption;
125 Options.NoFramePointerElim = options.NoFramePointerElim;
126 Options.AllowFPOpFusion = options.AllowFPOpFusion;
127 Options.UnsafeFPMath = options.UnsafeFPMath;
128 Options.NoInfsFPMath = options.NoInfsFPMath;
129 Options.NoNaNsFPMath = options.NoNaNsFPMath;
130 Options.HonorSignDependentRoundingFPMathOption =
131 options.HonorSignDependentRoundingFPMathOption;
132 Options.UseSoftFloat = options.UseSoftFloat;
133 Options.FloatABIType = options.FloatABIType;
134 Options.NoZerosInBSS = options.NoZerosInBSS;
135 Options.GuaranteedTailCallOpt = options.GuaranteedTailCallOpt;
136 Options.DisableTailCalls = options.DisableTailCalls;
137 Options.StackAlignmentOverride = options.StackAlignmentOverride;
138 Options.TrapFuncName = options.TrapFuncName;
139 Options.PositionIndependentExecutable = options.PositionIndependentExecutable;
140 Options.EnableSegmentedStacks = options.EnableSegmentedStacks;
141 Options.UseInitArray = options.UseInitArray;
144 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
146 case LTO_DEBUG_MODEL_NONE:
147 EmitDwarfDebugInfo = false;
150 case LTO_DEBUG_MODEL_DWARF:
151 EmitDwarfDebugInfo = true;
154 llvm_unreachable("Unknown debug format!");
157 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
159 case LTO_CODEGEN_PIC_MODEL_STATIC:
160 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
161 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
165 llvm_unreachable("Unknown PIC model!");
168 bool LTOCodeGenerator::writeMergedModules(const char *path,
169 std::string &errMsg) {
170 if (!determineTarget(errMsg))
173 // mark which symbols can not be internalized
174 applyScopeRestrictions();
176 // create output file
178 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
179 if (!ErrInfo.empty()) {
180 errMsg = "could not open bitcode file for writing: ";
185 // write bitcode to it
186 WriteBitcodeToFile(Linker.getModule(), Out.os());
189 if (Out.os().has_error()) {
190 errMsg = "could not write bitcode file: ";
192 Out.os().clear_error();
200 bool LTOCodeGenerator::compile_to_file(const char** name,
203 bool disableGVNLoadPRE,
204 std::string& errMsg) {
205 // make unique temp .o file to put generated object file
206 SmallString<128> Filename;
208 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
210 errMsg = EC.message();
214 // generate object file
215 tool_output_file objFile(Filename.c_str(), FD);
217 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
218 disableGVNLoadPRE, errMsg);
219 objFile.os().close();
220 if (objFile.os().has_error()) {
221 objFile.os().clear_error();
222 sys::fs::remove(Twine(Filename));
228 sys::fs::remove(Twine(Filename));
232 NativeObjectPath = Filename.c_str();
233 *name = NativeObjectPath.c_str();
237 const void* LTOCodeGenerator::compile(size_t* length,
240 bool disableGVNLoadPRE,
241 std::string& errMsg) {
243 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
247 // remove old buffer if compile() called twice
248 delete NativeObjectFile;
250 // read .o file into memory buffer
251 OwningPtr<MemoryBuffer> BuffPtr;
252 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
253 errMsg = ec.message();
254 sys::fs::remove(NativeObjectPath);
257 NativeObjectFile = BuffPtr.take();
260 sys::fs::remove(NativeObjectPath);
262 // return buffer, unless error
263 if (NativeObjectFile == NULL)
265 *length = NativeObjectFile->getBufferSize();
266 return NativeObjectFile->getBufferStart();
269 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
270 if (TargetMach != NULL)
273 std::string TripleStr = Linker.getModule()->getTargetTriple();
274 if (TripleStr.empty())
275 TripleStr = sys::getDefaultTargetTriple();
276 llvm::Triple Triple(TripleStr);
278 // create target machine from info for merged modules
279 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
283 // The relocation model is actually a static member of TargetMachine and
284 // needs to be set before the TargetMachine is instantiated.
285 Reloc::Model RelocModel = Reloc::Default;
287 case LTO_CODEGEN_PIC_MODEL_STATIC:
288 RelocModel = Reloc::Static;
290 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
291 RelocModel = Reloc::PIC_;
293 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
294 RelocModel = Reloc::DynamicNoPIC;
298 // construct LTOModule, hand over ownership of module and target
299 SubtargetFeatures Features;
300 Features.getDefaultSubtargetFeatures(Triple);
301 std::string FeatureStr = Features.getString();
302 // Set a default CPU for Darwin triples.
303 if (MCpu.empty() && Triple.isOSDarwin()) {
304 if (Triple.getArch() == llvm::Triple::x86_64)
306 else if (Triple.getArch() == llvm::Triple::x86)
310 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
311 RelocModel, CodeModel::Default,
312 CodeGenOpt::Aggressive);
316 void LTOCodeGenerator::
317 applyRestriction(GlobalValue &GV,
318 const ArrayRef<StringRef> &Libcalls,
319 std::vector<const char*> &MustPreserveList,
320 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
322 SmallString<64> Buffer;
323 Mangler.getNameWithPrefix(Buffer, &GV, false);
325 if (GV.isDeclaration())
327 if (MustPreserveSymbols.count(Buffer))
328 MustPreserveList.push_back(GV.getName().data());
329 if (AsmUndefinedRefs.count(Buffer))
332 // Conservatively append user-supplied runtime library functions to
333 // llvm.compiler.used. These could be internalized and deleted by
334 // optimizations like -globalopt, causing problems when later optimizations
335 // add new library calls (e.g., llvm.memset => memset and printf => puts).
336 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
337 if (isa<Function>(GV) &&
338 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
342 static void findUsedValues(GlobalVariable *LLVMUsed,
343 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
344 if (LLVMUsed == 0) return;
346 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
347 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
348 if (GlobalValue *GV =
349 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
350 UsedValues.insert(GV);
353 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
354 const TargetLibraryInfo& TLI,
355 const TargetLowering *Lowering)
357 // TargetLibraryInfo has info on C runtime library calls on the current
359 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
361 LibFunc::Func F = static_cast<LibFunc::Func>(I);
363 Libcalls.push_back(TLI.getName(F));
366 // TargetLowering has info on library calls that CodeGen expects to be
367 // available, both from the C runtime and compiler-rt.
369 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
372 = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
373 Libcalls.push_back(Name);
375 std::sort(Libcalls.begin(), Libcalls.end());
376 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
380 void LTOCodeGenerator::applyScopeRestrictions() {
381 if (ScopeRestrictionsDone)
383 Module *mergedModule = Linker.getModule();
385 // Start off with a verification pass.
387 passes.add(createVerifierPass());
389 // mark which symbols can not be internalized
390 Mangler Mangler(TargetMach);
391 std::vector<const char*> MustPreserveList;
392 SmallPtrSet<GlobalValue*, 8> AsmUsed;
393 std::vector<StringRef> Libcalls;
394 TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
395 accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
397 for (Module::iterator f = mergedModule->begin(),
398 e = mergedModule->end(); f != e; ++f)
399 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
400 for (Module::global_iterator v = mergedModule->global_begin(),
401 e = mergedModule->global_end(); v != e; ++v)
402 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
403 for (Module::alias_iterator a = mergedModule->alias_begin(),
404 e = mergedModule->alias_end(); a != e; ++a)
405 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
407 GlobalVariable *LLVMCompilerUsed =
408 mergedModule->getGlobalVariable("llvm.compiler.used");
409 findUsedValues(LLVMCompilerUsed, AsmUsed);
410 if (LLVMCompilerUsed)
411 LLVMCompilerUsed->eraseFromParent();
413 if (!AsmUsed.empty()) {
414 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
415 std::vector<Constant*> asmUsed2;
416 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
417 e = AsmUsed.end(); i !=e; ++i) {
418 GlobalValue *GV = *i;
419 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
420 asmUsed2.push_back(c);
423 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
425 new llvm::GlobalVariable(*mergedModule, ATy, false,
426 llvm::GlobalValue::AppendingLinkage,
427 llvm::ConstantArray::get(ATy, asmUsed2),
428 "llvm.compiler.used");
430 LLVMCompilerUsed->setSection("llvm.metadata");
433 passes.add(createInternalizePass(MustPreserveList));
435 // apply scope restrictions
436 passes.run(*mergedModule);
438 ScopeRestrictionsDone = true;
441 /// Optimize merged modules using various IPO passes
442 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
445 bool DisableGVNLoadPRE,
446 std::string &errMsg) {
447 if (!this->determineTarget(errMsg))
450 Module *mergedModule = Linker.getModule();
452 // Mark which symbols can not be internalized
453 this->applyScopeRestrictions();
455 // Instantiate the pass manager to organize the passes.
458 // Start off with a verification pass.
459 passes.add(createVerifierPass());
461 // Add an appropriate DataLayout instance for this module...
462 passes.add(new DataLayout(*TargetMach->getDataLayout()));
463 TargetMach->addAnalysisPasses(passes);
465 // Enabling internalize here would use its AllButMain variant. It
466 // keeps only main if it exists and does nothing for libraries. Instead
467 // we create the pass ourselves with the symbol list provided by the linker.
469 PassManagerBuilder().populateLTOPassManager(passes,
470 /*Internalize=*/false,
474 // Make sure everything is still good.
475 passes.add(createVerifierPass());
477 PassManager codeGenPasses;
479 codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
480 TargetMach->addAnalysisPasses(codeGenPasses);
482 formatted_raw_ostream Out(out);
484 // If the bitcode files contain ARC code and were compiled with optimization,
485 // the ObjCARCContractPass must be run, so do it unconditionally here.
486 codeGenPasses.add(createObjCARCContractPass());
488 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
489 TargetMachine::CGFT_ObjectFile)) {
490 errMsg = "target file type not supported";
494 // Run our queue of passes all at once now, efficiently.
495 passes.run(*mergedModule);
497 // Run the code generator, and write assembly file
498 codeGenPasses.run(*mergedModule);
503 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
505 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
506 for (std::pair<StringRef, StringRef> o = getToken(options);
507 !o.first.empty(); o = getToken(o.second)) {
508 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
510 if (CodegenOptions.empty())
511 CodegenOptions.push_back(strdup("libLLVMLTO"));
512 CodegenOptions.push_back(strdup(o.first.str().c_str()));
516 void LTOCodeGenerator::parseCodeGenDebugOptions() {
517 // if options were requested, set them
518 if (!CodegenOptions.empty())
519 cl::ParseCommandLineOptions(CodegenOptions.size(),
520 const_cast<char **>(&CodegenOptions[0]));