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/DiagnosticInfo.h"
25 #include "llvm/IR/DiagnosticPrinter.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Mangler.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Verifier.h"
30 #include "llvm/InitializePasses.h"
31 #include "llvm/LTO/LTOModule.h"
32 #include "llvm/Linker/Linker.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCContext.h"
35 #include "llvm/MC/SubtargetFeature.h"
36 #include "llvm/PassManager.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/Host.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/Signals.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/ToolOutputFile.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Target/TargetLibraryInfo.h"
48 #include "llvm/Target/TargetLowering.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #include "llvm/Transforms/IPO.h"
52 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
53 #include "llvm/Transforms/ObjCARC.h"
54 #include <system_error>
57 const char* LTOCodeGenerator::getVersionString() {
58 #ifdef LLVM_VERSION_INFO
59 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
61 return PACKAGE_NAME " version " PACKAGE_VERSION;
65 LTOCodeGenerator::LTOCodeGenerator()
66 : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)),
67 TargetMach(nullptr), EmitDwarfDebugInfo(false),
68 ScopeRestrictionsDone(false), CodeModel(LTO_CODEGEN_PIC_MODEL_DEFAULT),
69 NativeObjectFile(nullptr), DiagHandler(nullptr), DiagContext(nullptr) {
70 initializeLTOPasses();
73 LTOCodeGenerator::~LTOCodeGenerator() {
75 delete NativeObjectFile;
77 NativeObjectFile = nullptr;
79 IRLinker.deleteModule();
81 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
82 E = CodegenOptions.end();
87 // Initialize LTO passes. Please keep this funciton in sync with
88 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
89 // passes are initialized.
90 void LTOCodeGenerator::initializeLTOPasses() {
91 PassRegistry &R = *PassRegistry::getPassRegistry();
93 initializeInternalizePassPass(R);
94 initializeIPSCCPPass(R);
95 initializeGlobalOptPass(R);
96 initializeConstantMergePass(R);
98 initializeInstCombinerPass(R);
99 initializeSimpleInlinerPass(R);
100 initializePruneEHPass(R);
101 initializeGlobalDCEPass(R);
102 initializeArgPromotionPass(R);
103 initializeJumpThreadingPass(R);
104 initializeSROAPass(R);
105 initializeSROA_DTPass(R);
106 initializeSROA_SSAUpPass(R);
107 initializeFunctionAttrsPass(R);
108 initializeGlobalsModRefPass(R);
109 initializeLICMPass(R);
110 initializeMergedLoadStoreMotionPass(R);
111 initializeGVNPass(R);
112 initializeMemCpyOptPass(R);
113 initializeDCEPass(R);
114 initializeCFGSimplifyPassPass(R);
117 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
118 bool ret = IRLinker.linkInModule(&mod->getModule(), &errMsg);
120 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
121 for (int i = 0, e = undefs.size(); i != e; ++i)
122 AsmUndefinedRefs[undefs[i]] = 1;
127 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
131 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
133 case LTO_DEBUG_MODEL_NONE:
134 EmitDwarfDebugInfo = false;
137 case LTO_DEBUG_MODEL_DWARF:
138 EmitDwarfDebugInfo = true;
141 llvm_unreachable("Unknown debug format!");
144 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
146 case LTO_CODEGEN_PIC_MODEL_STATIC:
147 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
148 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
149 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
153 llvm_unreachable("Unknown PIC model!");
156 bool LTOCodeGenerator::writeMergedModules(const char *path,
157 std::string &errMsg) {
158 if (!determineTarget(errMsg))
161 // mark which symbols can not be internalized
162 applyScopeRestrictions();
164 // create output file
166 tool_output_file Out(path, ErrInfo, sys::fs::F_None);
167 if (!ErrInfo.empty()) {
168 errMsg = "could not open bitcode file for writing: ";
173 // write bitcode to it
174 WriteBitcodeToFile(IRLinker.getModule(), Out.os());
177 if (Out.os().has_error()) {
178 errMsg = "could not write bitcode file: ";
180 Out.os().clear_error();
188 bool LTOCodeGenerator::compile_to_file(const char** name,
191 bool disableGVNLoadPRE,
192 std::string& errMsg) {
193 // make unique temp .o file to put generated object file
194 SmallString<128> Filename;
197 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
199 errMsg = EC.message();
203 // generate object file
204 tool_output_file objFile(Filename.c_str(), FD);
206 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
207 disableGVNLoadPRE, errMsg);
208 objFile.os().close();
209 if (objFile.os().has_error()) {
210 objFile.os().clear_error();
211 sys::fs::remove(Twine(Filename));
217 sys::fs::remove(Twine(Filename));
221 NativeObjectPath = Filename.c_str();
222 *name = NativeObjectPath.c_str();
226 const void* LTOCodeGenerator::compile(size_t* length,
229 bool disableGVNLoadPRE,
230 std::string& errMsg) {
232 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
236 // remove old buffer if compile() called twice
237 delete NativeObjectFile;
239 // read .o file into memory buffer
240 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
241 MemoryBuffer::getFile(name, -1, false);
242 if (std::error_code EC = BufferOrErr.getError()) {
243 errMsg = EC.message();
244 sys::fs::remove(NativeObjectPath);
247 NativeObjectFile = BufferOrErr.get().release();
250 sys::fs::remove(NativeObjectPath);
252 // return buffer, unless error
253 if (!NativeObjectFile)
255 *length = NativeObjectFile->getBufferSize();
256 return NativeObjectFile->getBufferStart();
259 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
263 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
264 if (TripleStr.empty())
265 TripleStr = sys::getDefaultTargetTriple();
266 llvm::Triple Triple(TripleStr);
268 // create target machine from info for merged modules
269 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
273 // The relocation model is actually a static member of TargetMachine and
274 // needs to be set before the TargetMachine is instantiated.
275 Reloc::Model RelocModel = Reloc::Default;
277 case LTO_CODEGEN_PIC_MODEL_STATIC:
278 RelocModel = Reloc::Static;
280 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
281 RelocModel = Reloc::PIC_;
283 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
284 RelocModel = Reloc::DynamicNoPIC;
286 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
287 // RelocModel is already the default, so leave it that way.
291 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
292 // the default set of features.
293 SubtargetFeatures Features(MAttr);
294 Features.getDefaultSubtargetFeatures(Triple);
295 std::string FeatureStr = Features.getString();
296 // Set a default CPU for Darwin triples.
297 if (MCpu.empty() && Triple.isOSDarwin()) {
298 if (Triple.getArch() == llvm::Triple::x86_64)
300 else if (Triple.getArch() == llvm::Triple::x86)
302 else if (Triple.getArch() == llvm::Triple::arm64 ||
303 Triple.getArch() == llvm::Triple::aarch64)
307 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
308 RelocModel, CodeModel::Default,
309 CodeGenOpt::Aggressive);
313 void LTOCodeGenerator::
314 applyRestriction(GlobalValue &GV,
315 const ArrayRef<StringRef> &Libcalls,
316 std::vector<const char*> &MustPreserveList,
317 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
319 // There are no restrictions to apply to declarations.
320 if (GV.isDeclaration())
323 // There is nothing more restrictive than private linkage.
324 if (GV.hasPrivateLinkage())
327 SmallString<64> Buffer;
328 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
330 if (MustPreserveSymbols.count(Buffer))
331 MustPreserveList.push_back(GV.getName().data());
332 if (AsmUndefinedRefs.count(Buffer))
335 // Conservatively append user-supplied runtime library functions to
336 // llvm.compiler.used. These could be internalized and deleted by
337 // optimizations like -globalopt, causing problems when later optimizations
338 // add new library calls (e.g., llvm.memset => memset and printf => puts).
339 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
340 if (isa<Function>(GV) &&
341 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
345 static void findUsedValues(GlobalVariable *LLVMUsed,
346 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
347 if (!LLVMUsed) return;
349 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
350 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
351 if (GlobalValue *GV =
352 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
353 UsedValues.insert(GV);
356 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
357 const TargetLibraryInfo& TLI,
358 const TargetLowering *Lowering)
360 // TargetLibraryInfo has info on C runtime library calls on the current
362 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
364 LibFunc::Func F = static_cast<LibFunc::Func>(I);
366 Libcalls.push_back(TLI.getName(F));
369 // TargetLowering has info on library calls that CodeGen expects to be
370 // available, both from the C runtime and compiler-rt.
372 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
375 = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
376 Libcalls.push_back(Name);
378 array_pod_sort(Libcalls.begin(), Libcalls.end());
379 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
383 void LTOCodeGenerator::applyScopeRestrictions() {
384 if (ScopeRestrictionsDone)
386 Module *mergedModule = IRLinker.getModule();
388 // Start off with a verification pass.
390 passes.add(createVerifierPass());
391 passes.add(createDebugInfoVerifierPass());
393 // mark which symbols can not be internalized
394 Mangler Mangler(TargetMach->getDataLayout());
395 std::vector<const char*> MustPreserveList;
396 SmallPtrSet<GlobalValue*, 8> AsmUsed;
397 std::vector<StringRef> Libcalls;
398 TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
399 accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
401 for (Module::iterator f = mergedModule->begin(),
402 e = mergedModule->end(); f != e; ++f)
403 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
404 for (Module::global_iterator v = mergedModule->global_begin(),
405 e = mergedModule->global_end(); v != e; ++v)
406 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
407 for (Module::alias_iterator a = mergedModule->alias_begin(),
408 e = mergedModule->alias_end(); a != e; ++a)
409 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
411 GlobalVariable *LLVMCompilerUsed =
412 mergedModule->getGlobalVariable("llvm.compiler.used");
413 findUsedValues(LLVMCompilerUsed, AsmUsed);
414 if (LLVMCompilerUsed)
415 LLVMCompilerUsed->eraseFromParent();
417 if (!AsmUsed.empty()) {
418 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
419 std::vector<Constant*> asmUsed2;
420 for (auto *GV : AsmUsed) {
421 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
422 asmUsed2.push_back(c);
425 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
427 new llvm::GlobalVariable(*mergedModule, ATy, false,
428 llvm::GlobalValue::AppendingLinkage,
429 llvm::ConstantArray::get(ATy, asmUsed2),
430 "llvm.compiler.used");
432 LLVMCompilerUsed->setSection("llvm.metadata");
435 passes.add(createInternalizePass(MustPreserveList));
437 // apply scope restrictions
438 passes.run(*mergedModule);
440 ScopeRestrictionsDone = true;
443 /// Optimize merged modules using various IPO passes
444 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
447 bool DisableGVNLoadPRE,
448 std::string &errMsg) {
449 if (!this->determineTarget(errMsg))
452 Module *mergedModule = IRLinker.getModule();
454 // Mark which symbols can not be internalized
455 this->applyScopeRestrictions();
457 // Instantiate the pass manager to organize the passes.
460 // Start off with a verification pass.
461 passes.add(createVerifierPass());
462 passes.add(createDebugInfoVerifierPass());
464 // Add an appropriate DataLayout instance for this module...
465 mergedModule->setDataLayout(TargetMach->getDataLayout());
466 passes.add(new DataLayoutPass(mergedModule));
468 // Add appropriate TargetLibraryInfo for this module.
469 passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
471 TargetMach->addAnalysisPasses(passes);
473 // Enabling internalize here would use its AllButMain variant. It
474 // keeps only main if it exists and does nothing for libraries. Instead
475 // we create the pass ourselves with the symbol list provided by the linker.
477 PassManagerBuilder().populateLTOPassManager(passes,
478 /*Internalize=*/false,
482 // Make sure everything is still good.
483 passes.add(createVerifierPass());
484 passes.add(createDebugInfoVerifierPass());
486 PassManager codeGenPasses;
488 codeGenPasses.add(new DataLayoutPass(mergedModule));
490 formatted_raw_ostream Out(out);
492 // If the bitcode files contain ARC code and were compiled with optimization,
493 // the ObjCARCContractPass must be run, so do it unconditionally here.
494 codeGenPasses.add(createObjCARCContractPass());
496 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
497 TargetMachine::CGFT_ObjectFile)) {
498 errMsg = "target file type not supported";
502 // Run our queue of passes all at once now, efficiently.
503 passes.run(*mergedModule);
505 // Run the code generator, and write assembly file
506 codeGenPasses.run(*mergedModule);
511 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
513 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
514 for (std::pair<StringRef, StringRef> o = getToken(options);
515 !o.first.empty(); o = getToken(o.second)) {
516 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
518 if (CodegenOptions.empty())
519 CodegenOptions.push_back(strdup("libLLVMLTO"));
520 CodegenOptions.push_back(strdup(o.first.str().c_str()));
524 void LTOCodeGenerator::parseCodeGenDebugOptions() {
525 // if options were requested, set them
526 if (!CodegenOptions.empty())
527 cl::ParseCommandLineOptions(CodegenOptions.size(),
528 const_cast<char **>(&CodegenOptions[0]));
531 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
533 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
536 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
537 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
538 lto_codegen_diagnostic_severity_t Severity;
539 switch (DI.getSeverity()) {
541 Severity = LTO_DS_ERROR;
544 Severity = LTO_DS_WARNING;
547 Severity = LTO_DS_REMARK;
550 Severity = LTO_DS_NOTE;
553 // Create the string that will be reported to the external diagnostic handler.
554 std::string MsgStorage;
555 raw_string_ostream Stream(MsgStorage);
556 DiagnosticPrinterRawOStream DP(Stream);
560 // If this method has been called it means someone has set up an external
561 // diagnostic handler. Assert on that.
562 assert(DiagHandler && "Invalid diagnostic handler");
563 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
567 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
569 this->DiagHandler = DiagHandler;
570 this->DiagContext = Ctxt;
572 return Context.setDiagnosticHandler(nullptr, nullptr);
573 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
574 // diagnostic to the external DiagHandler.
575 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this);