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/ADT/StringExtras.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Bitcode/ReaderWriter.h"
19 #include "llvm/CodeGen/RuntimeLibcalls.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Mangler.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Verifier.h"
28 #include "llvm/InitializePasses.h"
29 #include "llvm/LTO/LTOModule.h"
30 #include "llvm/Linker.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCContext.h"
33 #include "llvm/MC/SubtargetFeature.h"
34 #include "llvm/PassManager.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/Support/Host.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/TargetSelect.h"
43 #include "llvm/Support/ToolOutputFile.h"
44 #include "llvm/Support/system_error.h"
45 #include "llvm/Target/TargetLibraryInfo.h"
46 #include "llvm/Target/TargetLowering.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Target/TargetRegisterInfo.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),
66 InternalizeStrategy(LTO_INTERNALIZE_FULL), NativeObjectFile(NULL) {
67 initializeLTOPasses();
70 LTOCodeGenerator::~LTOCodeGenerator() {
72 delete NativeObjectFile;
74 NativeObjectFile = NULL;
76 Linker.deleteModule();
78 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
79 E = CodegenOptions.end();
84 // Initialize LTO passes. Please keep this funciton in sync with
85 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
86 // 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!");
169 LTOCodeGenerator::setInternalizeStrategy(lto_internalize_strategy Strategy) {
171 case LTO_INTERNALIZE_FULL:
172 case LTO_INTERNALIZE_NONE:
173 case LTO_INTERNALIZE_HIDDEN:
174 InternalizeStrategy = Strategy;
177 llvm_unreachable("Unknown internalize strategy!");
180 bool LTOCodeGenerator::writeMergedModules(const char *path,
181 std::string &errMsg) {
182 if (!determineTarget(errMsg))
185 // mark which symbols can not be internalized
186 applyScopeRestrictions();
188 // create output file
190 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
191 if (!ErrInfo.empty()) {
192 errMsg = "could not open bitcode file for writing: ";
197 // write bitcode to it
198 WriteBitcodeToFile(Linker.getModule(), Out.os());
201 if (Out.os().has_error()) {
202 errMsg = "could not write bitcode file: ";
204 Out.os().clear_error();
212 bool LTOCodeGenerator::compile_to_file(const char** name,
215 bool disableGVNLoadPRE,
216 std::string& errMsg) {
217 // make unique temp .o file to put generated object file
218 SmallString<128> Filename;
220 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
222 errMsg = EC.message();
226 // generate object file
227 tool_output_file objFile(Filename.c_str(), FD);
229 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
230 disableGVNLoadPRE, errMsg);
231 objFile.os().close();
232 if (objFile.os().has_error()) {
233 objFile.os().clear_error();
234 sys::fs::remove(Twine(Filename));
240 sys::fs::remove(Twine(Filename));
244 NativeObjectPath = Filename.c_str();
245 *name = NativeObjectPath.c_str();
249 const void* LTOCodeGenerator::compile(size_t* length,
252 bool disableGVNLoadPRE,
253 std::string& errMsg) {
255 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
259 // remove old buffer if compile() called twice
260 delete NativeObjectFile;
262 // read .o file into memory buffer
263 OwningPtr<MemoryBuffer> BuffPtr;
264 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
265 errMsg = ec.message();
266 sys::fs::remove(NativeObjectPath);
269 NativeObjectFile = BuffPtr.take();
272 sys::fs::remove(NativeObjectPath);
274 // return buffer, unless error
275 if (NativeObjectFile == NULL)
277 *length = NativeObjectFile->getBufferSize();
278 return NativeObjectFile->getBufferStart();
281 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
282 if (TargetMach != NULL)
285 std::string TripleStr = Linker.getModule()->getTargetTriple();
286 if (TripleStr.empty())
287 TripleStr = sys::getDefaultTargetTriple();
288 llvm::Triple Triple(TripleStr);
290 // create target machine from info for merged modules
291 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
295 // The relocation model is actually a static member of TargetMachine and
296 // needs to be set before the TargetMachine is instantiated.
297 Reloc::Model RelocModel = Reloc::Default;
299 case LTO_CODEGEN_PIC_MODEL_STATIC:
300 RelocModel = Reloc::Static;
302 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
303 RelocModel = Reloc::PIC_;
305 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
306 RelocModel = Reloc::DynamicNoPIC;
310 // construct LTOModule, hand over ownership of module and target
311 SubtargetFeatures Features;
312 Features.getDefaultSubtargetFeatures(Triple);
313 std::string FeatureStr = Features.getString();
314 // Set a default CPU for Darwin triples.
315 if (MCpu.empty() && Triple.isOSDarwin()) {
316 if (Triple.getArch() == llvm::Triple::x86_64)
318 else if (Triple.getArch() == llvm::Triple::x86)
322 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
323 RelocModel, CodeModel::Default,
324 CodeGenOpt::Aggressive);
328 void LTOCodeGenerator::
329 applyRestriction(GlobalValue &GV,
330 const ArrayRef<StringRef> &Libcalls,
331 std::vector<const char*> &MustPreserveList,
332 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
334 SmallString<64> Buffer;
335 Mangler.getNameWithPrefix(Buffer, &GV);
337 if (GV.isDeclaration())
339 if (MustPreserveSymbols.count(Buffer))
340 MustPreserveList.push_back(GV.getName().data());
341 if (AsmUndefinedRefs.count(Buffer))
344 // Conservatively append user-supplied runtime library functions to
345 // llvm.compiler.used. These could be internalized and deleted by
346 // optimizations like -globalopt, causing problems when later optimizations
347 // add new library calls (e.g., llvm.memset => memset and printf => puts).
348 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
349 if (isa<Function>(GV) &&
350 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
354 static void findUsedValues(GlobalVariable *LLVMUsed,
355 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
356 if (LLVMUsed == 0) return;
358 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
359 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
360 if (GlobalValue *GV =
361 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
362 UsedValues.insert(GV);
365 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
366 const TargetLibraryInfo& TLI,
367 const TargetLowering *Lowering)
369 // TargetLibraryInfo has info on C runtime library calls on the current
371 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
373 LibFunc::Func F = static_cast<LibFunc::Func>(I);
375 Libcalls.push_back(TLI.getName(F));
378 // TargetLowering has info on library calls that CodeGen expects to be
379 // available, both from the C runtime and compiler-rt.
381 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
384 = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
385 Libcalls.push_back(Name);
387 array_pod_sort(Libcalls.begin(), Libcalls.end());
388 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
392 void LTOCodeGenerator::applyScopeRestrictions() {
393 if (ScopeRestrictionsDone || !shouldInternalize())
395 Module *mergedModule = Linker.getModule();
397 // Start off with a verification pass.
399 passes.add(createVerifierPass());
401 // mark which symbols can not be internalized
402 Mangler Mangler(TargetMach->getDataLayout());
403 std::vector<const char*> MustPreserveList;
404 SmallPtrSet<GlobalValue*, 8> AsmUsed;
405 std::vector<StringRef> Libcalls;
406 TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
407 accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
409 for (Module::iterator f = mergedModule->begin(),
410 e = mergedModule->end(); f != e; ++f)
411 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
412 for (Module::global_iterator v = mergedModule->global_begin(),
413 e = mergedModule->global_end(); v != e; ++v)
414 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
415 for (Module::alias_iterator a = mergedModule->alias_begin(),
416 e = mergedModule->alias_end(); a != e; ++a)
417 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
419 GlobalVariable *LLVMCompilerUsed =
420 mergedModule->getGlobalVariable("llvm.compiler.used");
421 findUsedValues(LLVMCompilerUsed, AsmUsed);
422 if (LLVMCompilerUsed)
423 LLVMCompilerUsed->eraseFromParent();
425 if (!AsmUsed.empty()) {
426 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
427 std::vector<Constant*> asmUsed2;
428 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
429 e = AsmUsed.end(); i !=e; ++i) {
430 GlobalValue *GV = *i;
431 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
432 asmUsed2.push_back(c);
435 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
437 new llvm::GlobalVariable(*mergedModule, ATy, false,
438 llvm::GlobalValue::AppendingLinkage,
439 llvm::ConstantArray::get(ATy, asmUsed2),
440 "llvm.compiler.used");
442 LLVMCompilerUsed->setSection("llvm.metadata");
446 createInternalizePass(MustPreserveList, shouldOnlyInternalizeHidden()));
448 // apply scope restrictions
449 passes.run(*mergedModule);
451 ScopeRestrictionsDone = true;
454 /// Optimize merged modules using various IPO passes
455 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
458 bool DisableGVNLoadPRE,
459 std::string &errMsg) {
460 if (!this->determineTarget(errMsg))
463 Module *mergedModule = Linker.getModule();
465 // Mark which symbols can not be internalized
466 this->applyScopeRestrictions();
468 // Instantiate the pass manager to organize the passes.
471 // Start off with a verification pass.
472 passes.add(createVerifierPass());
474 // Add an appropriate DataLayout instance for this module...
475 passes.add(new DataLayout(*TargetMach->getDataLayout()));
477 // Add appropriate TargetLibraryInfo for this module.
478 passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
480 TargetMach->addAnalysisPasses(passes);
482 // Enabling internalize here would use its AllButMain variant. It
483 // keeps only main if it exists and does nothing for libraries. Instead
484 // we create the pass ourselves with the symbol list provided by the linker.
486 PassManagerBuilder().populateLTOPassManager(passes,
487 /*Internalize=*/false,
491 // Make sure everything is still good.
492 passes.add(createVerifierPass());
494 PassManager codeGenPasses;
496 codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
497 TargetMach->addAnalysisPasses(codeGenPasses);
499 formatted_raw_ostream Out(out);
501 // If the bitcode files contain ARC code and were compiled with optimization,
502 // the ObjCARCContractPass must be run, so do it unconditionally here.
503 codeGenPasses.add(createObjCARCContractPass());
505 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
506 TargetMachine::CGFT_ObjectFile)) {
507 errMsg = "target file type not supported";
511 // Run our queue of passes all at once now, efficiently.
512 passes.run(*mergedModule);
514 // Run the code generator, and write assembly file
515 codeGenPasses.run(*mergedModule);
520 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
522 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
523 for (std::pair<StringRef, StringRef> o = getToken(options);
524 !o.first.empty(); o = getToken(o.second)) {
525 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
527 if (CodegenOptions.empty())
528 CodegenOptions.push_back(strdup("libLLVMLTO"));
529 CodegenOptions.push_back(strdup(o.first.str().c_str()));
533 void LTOCodeGenerator::parseCodeGenDebugOptions() {
534 // if options were requested, set them
535 if (!CodegenOptions.empty())
536 cl::ParseCommandLineOptions(CodegenOptions.size(),
537 const_cast<char **>(&CodegenOptions[0]));