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/Target/TargetSubtargetInfo.h"
52 #include "llvm/Transforms/IPO.h"
53 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 #include "llvm/Transforms/ObjCARC.h"
55 #include <system_error>
58 const char* LTOCodeGenerator::getVersionString() {
59 #ifdef LLVM_VERSION_INFO
60 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
62 return PACKAGE_NAME " version " PACKAGE_VERSION;
66 LTOCodeGenerator::LTOCodeGenerator()
67 : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)),
68 TargetMach(nullptr), EmitDwarfDebugInfo(false),
69 ScopeRestrictionsDone(false), CodeModel(LTO_CODEGEN_PIC_MODEL_DEFAULT),
70 NativeObjectFile(nullptr), DiagHandler(nullptr), DiagContext(nullptr) {
71 initializeLTOPasses();
74 LTOCodeGenerator::~LTOCodeGenerator() {
76 delete NativeObjectFile;
78 NativeObjectFile = nullptr;
80 IRLinker.deleteModule();
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.
91 void LTOCodeGenerator::initializeLTOPasses() {
92 PassRegistry &R = *PassRegistry::getPassRegistry();
94 initializeInternalizePassPass(R);
95 initializeIPSCCPPass(R);
96 initializeGlobalOptPass(R);
97 initializeConstantMergePass(R);
99 initializeInstCombinerPass(R);
100 initializeSimpleInlinerPass(R);
101 initializePruneEHPass(R);
102 initializeGlobalDCEPass(R);
103 initializeArgPromotionPass(R);
104 initializeJumpThreadingPass(R);
105 initializeSROAPass(R);
106 initializeSROA_DTPass(R);
107 initializeSROA_SSAUpPass(R);
108 initializeFunctionAttrsPass(R);
109 initializeGlobalsModRefPass(R);
110 initializeLICMPass(R);
111 initializeMergedLoadStoreMotionPass(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 = IRLinker.linkInModule(&mod->getModule(), &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::setTargetOptions(TargetOptions options) {
132 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
134 case LTO_DEBUG_MODEL_NONE:
135 EmitDwarfDebugInfo = false;
138 case LTO_DEBUG_MODEL_DWARF:
139 EmitDwarfDebugInfo = true;
142 llvm_unreachable("Unknown debug format!");
145 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
147 case LTO_CODEGEN_PIC_MODEL_STATIC:
148 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
149 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
150 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
154 llvm_unreachable("Unknown PIC model!");
157 bool LTOCodeGenerator::writeMergedModules(const char *path,
158 std::string &errMsg) {
159 if (!determineTarget(errMsg))
162 // mark which symbols can not be internalized
163 applyScopeRestrictions();
165 // create output file
167 tool_output_file Out(path, ErrInfo, sys::fs::F_None);
168 if (!ErrInfo.empty()) {
169 errMsg = "could not open bitcode file for writing: ";
174 // write bitcode to it
175 WriteBitcodeToFile(IRLinker.getModule(), Out.os());
178 if (Out.os().has_error()) {
179 errMsg = "could not write bitcode file: ";
181 Out.os().clear_error();
189 bool LTOCodeGenerator::compile_to_file(const char** name,
192 bool disableGVNLoadPRE,
193 std::string& errMsg) {
194 // make unique temp .o file to put generated object file
195 SmallString<128> Filename;
198 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
200 errMsg = EC.message();
204 // generate object file
205 tool_output_file objFile(Filename.c_str(), FD);
207 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
208 disableGVNLoadPRE, errMsg);
209 objFile.os().close();
210 if (objFile.os().has_error()) {
211 objFile.os().clear_error();
212 sys::fs::remove(Twine(Filename));
218 sys::fs::remove(Twine(Filename));
222 NativeObjectPath = Filename.c_str();
223 *name = NativeObjectPath.c_str();
227 const void* LTOCodeGenerator::compile(size_t* length,
230 bool disableGVNLoadPRE,
231 std::string& errMsg) {
233 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
237 // remove old buffer if compile() called twice
238 delete NativeObjectFile;
240 // read .o file into memory buffer
241 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
242 MemoryBuffer::getFile(name, -1, false);
243 if (std::error_code EC = BufferOrErr.getError()) {
244 errMsg = EC.message();
245 sys::fs::remove(NativeObjectPath);
248 NativeObjectFile = BufferOrErr.get().release();
251 sys::fs::remove(NativeObjectPath);
253 // return buffer, unless error
254 if (!NativeObjectFile)
256 *length = NativeObjectFile->getBufferSize();
257 return NativeObjectFile->getBufferStart();
260 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
264 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
265 if (TripleStr.empty())
266 TripleStr = sys::getDefaultTargetTriple();
267 llvm::Triple Triple(TripleStr);
269 // create target machine from info for merged modules
270 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
274 // The relocation model is actually a static member of TargetMachine and
275 // needs to be set before the TargetMachine is instantiated.
276 Reloc::Model RelocModel = Reloc::Default;
278 case LTO_CODEGEN_PIC_MODEL_STATIC:
279 RelocModel = Reloc::Static;
281 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
282 RelocModel = Reloc::PIC_;
284 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
285 RelocModel = Reloc::DynamicNoPIC;
287 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
288 // RelocModel is already the default, so leave it that way.
292 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
293 // the default set of features.
294 SubtargetFeatures Features(MAttr);
295 Features.getDefaultSubtargetFeatures(Triple);
296 std::string FeatureStr = Features.getString();
297 // Set a default CPU for Darwin triples.
298 if (MCpu.empty() && Triple.isOSDarwin()) {
299 if (Triple.getArch() == llvm::Triple::x86_64)
301 else if (Triple.getArch() == llvm::Triple::x86)
303 else if (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->getSubtargetImpl()->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(
400 Libcalls, TLI, TargetMach->getSubtargetImpl()->getTargetLowering());
402 for (Module::iterator f = mergedModule->begin(),
403 e = mergedModule->end(); f != e; ++f)
404 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
405 for (Module::global_iterator v = mergedModule->global_begin(),
406 e = mergedModule->global_end(); v != e; ++v)
407 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
408 for (Module::alias_iterator a = mergedModule->alias_begin(),
409 e = mergedModule->alias_end(); a != e; ++a)
410 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
412 GlobalVariable *LLVMCompilerUsed =
413 mergedModule->getGlobalVariable("llvm.compiler.used");
414 findUsedValues(LLVMCompilerUsed, AsmUsed);
415 if (LLVMCompilerUsed)
416 LLVMCompilerUsed->eraseFromParent();
418 if (!AsmUsed.empty()) {
419 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
420 std::vector<Constant*> asmUsed2;
421 for (auto *GV : AsmUsed) {
422 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
423 asmUsed2.push_back(c);
426 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
428 new llvm::GlobalVariable(*mergedModule, ATy, false,
429 llvm::GlobalValue::AppendingLinkage,
430 llvm::ConstantArray::get(ATy, asmUsed2),
431 "llvm.compiler.used");
433 LLVMCompilerUsed->setSection("llvm.metadata");
436 passes.add(createInternalizePass(MustPreserveList));
438 // apply scope restrictions
439 passes.run(*mergedModule);
441 ScopeRestrictionsDone = true;
444 /// Optimize merged modules using various IPO passes
445 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
448 bool DisableGVNLoadPRE,
449 std::string &errMsg) {
450 if (!this->determineTarget(errMsg))
453 Module *mergedModule = IRLinker.getModule();
455 // Mark which symbols can not be internalized
456 this->applyScopeRestrictions();
458 // Instantiate the pass manager to organize the passes.
461 // Start off with a verification pass.
462 passes.add(createVerifierPass());
463 passes.add(createDebugInfoVerifierPass());
465 // Add an appropriate DataLayout instance for this module...
466 mergedModule->setDataLayout(TargetMach->getSubtargetImpl()->getDataLayout());
467 passes.add(new DataLayoutPass(mergedModule));
469 // Add appropriate TargetLibraryInfo for this module.
470 passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
472 TargetMach->addAnalysisPasses(passes);
474 // Enabling internalize here would use its AllButMain variant. It
475 // keeps only main if it exists and does nothing for libraries. Instead
476 // we create the pass ourselves with the symbol list provided by the linker.
478 PassManagerBuilder().populateLTOPassManager(passes, !DisableInline,
481 // Make sure everything is still good.
482 passes.add(createVerifierPass());
483 passes.add(createDebugInfoVerifierPass());
485 PassManager codeGenPasses;
487 codeGenPasses.add(new DataLayoutPass(mergedModule));
489 formatted_raw_ostream Out(out);
491 // If the bitcode files contain ARC code and were compiled with optimization,
492 // the ObjCARCContractPass must be run, so do it unconditionally here.
493 codeGenPasses.add(createObjCARCContractPass());
495 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
496 TargetMachine::CGFT_ObjectFile)) {
497 errMsg = "target file type not supported";
501 // Run our queue of passes all at once now, efficiently.
502 passes.run(*mergedModule);
504 // Run the code generator, and write assembly file
505 codeGenPasses.run(*mergedModule);
510 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
512 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
513 for (std::pair<StringRef, StringRef> o = getToken(options);
514 !o.first.empty(); o = getToken(o.second)) {
515 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
517 if (CodegenOptions.empty())
518 CodegenOptions.push_back(strdup("libLLVMLTO"));
519 CodegenOptions.push_back(strdup(o.first.str().c_str()));
523 void LTOCodeGenerator::parseCodeGenDebugOptions() {
524 // if options were requested, set them
525 if (!CodegenOptions.empty())
526 cl::ParseCommandLineOptions(CodegenOptions.size(),
527 const_cast<char **>(&CodegenOptions[0]));
530 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
532 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
535 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
536 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
537 lto_codegen_diagnostic_severity_t Severity;
538 switch (DI.getSeverity()) {
540 Severity = LTO_DS_ERROR;
543 Severity = LTO_DS_WARNING;
546 Severity = LTO_DS_REMARK;
549 Severity = LTO_DS_NOTE;
552 // Create the string that will be reported to the external diagnostic handler.
553 std::string MsgStorage;
554 raw_string_ostream Stream(MsgStorage);
555 DiagnosticPrinterRawOStream DP(Stream);
559 // If this method has been called it means someone has set up an external
560 // diagnostic handler. Assert on that.
561 assert(DiagHandler && "Invalid diagnostic handler");
562 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
566 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
568 this->DiagHandler = DiagHandler;
569 this->DiagContext = Ctxt;
571 return Context.setDiagnosticHandler(nullptr, nullptr);
572 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
573 // diagnostic to the external DiagHandler.
574 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this);