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/Support/system_error.h"
48 #include "llvm/Target/TargetLibraryInfo.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Target/TargetRegisterInfo.h"
52 #include "llvm/Transforms/IPO.h"
53 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 #include "llvm/Transforms/ObjCARC.h"
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 initializeJumpInstrTablesPass(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 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->getLLVVMModule(), &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) {
128 Options.LessPreciseFPMADOption = options.LessPreciseFPMADOption;
129 Options.NoFramePointerElim = options.NoFramePointerElim;
130 Options.AllowFPOpFusion = options.AllowFPOpFusion;
131 Options.UnsafeFPMath = options.UnsafeFPMath;
132 Options.NoInfsFPMath = options.NoInfsFPMath;
133 Options.NoNaNsFPMath = options.NoNaNsFPMath;
134 Options.HonorSignDependentRoundingFPMathOption =
135 options.HonorSignDependentRoundingFPMathOption;
136 Options.UseSoftFloat = options.UseSoftFloat;
137 Options.FloatABIType = options.FloatABIType;
138 Options.NoZerosInBSS = options.NoZerosInBSS;
139 Options.GuaranteedTailCallOpt = options.GuaranteedTailCallOpt;
140 Options.DisableTailCalls = options.DisableTailCalls;
141 Options.StackAlignmentOverride = options.StackAlignmentOverride;
142 Options.TrapFuncName = options.TrapFuncName;
143 Options.PositionIndependentExecutable = options.PositionIndependentExecutable;
144 Options.UseInitArray = options.UseInitArray;
147 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
149 case LTO_DEBUG_MODEL_NONE:
150 EmitDwarfDebugInfo = false;
153 case LTO_DEBUG_MODEL_DWARF:
154 EmitDwarfDebugInfo = true;
157 llvm_unreachable("Unknown debug format!");
160 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
162 case LTO_CODEGEN_PIC_MODEL_STATIC:
163 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
164 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
165 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
169 llvm_unreachable("Unknown PIC model!");
172 bool LTOCodeGenerator::writeMergedModules(const char *path,
173 std::string &errMsg) {
174 if (!determineTarget(errMsg))
177 // mark which symbols can not be internalized
178 applyScopeRestrictions();
180 // create output file
182 tool_output_file Out(path, ErrInfo, sys::fs::F_None);
183 if (!ErrInfo.empty()) {
184 errMsg = "could not open bitcode file for writing: ";
189 // write bitcode to it
190 WriteBitcodeToFile(IRLinker.getModule(), Out.os());
193 if (Out.os().has_error()) {
194 errMsg = "could not write bitcode file: ";
196 Out.os().clear_error();
204 bool LTOCodeGenerator::compile_to_file(const char** name,
207 bool disableGVNLoadPRE,
208 std::string& errMsg) {
209 // make unique temp .o file to put generated object file
210 SmallString<128> Filename;
212 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
214 errMsg = EC.message();
218 // generate object file
219 tool_output_file objFile(Filename.c_str(), FD);
221 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
222 disableGVNLoadPRE, errMsg);
223 objFile.os().close();
224 if (objFile.os().has_error()) {
225 objFile.os().clear_error();
226 sys::fs::remove(Twine(Filename));
232 sys::fs::remove(Twine(Filename));
236 NativeObjectPath = Filename.c_str();
237 *name = NativeObjectPath.c_str();
241 const void* LTOCodeGenerator::compile(size_t* length,
244 bool disableGVNLoadPRE,
245 std::string& errMsg) {
247 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
251 // remove old buffer if compile() called twice
252 delete NativeObjectFile;
254 // read .o file into memory buffer
255 std::unique_ptr<MemoryBuffer> BuffPtr;
256 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
257 errMsg = ec.message();
258 sys::fs::remove(NativeObjectPath);
261 NativeObjectFile = BuffPtr.release();
264 sys::fs::remove(NativeObjectPath);
266 // return buffer, unless error
267 if (!NativeObjectFile)
269 *length = NativeObjectFile->getBufferSize();
270 return NativeObjectFile->getBufferStart();
273 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
277 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
278 if (TripleStr.empty())
279 TripleStr = sys::getDefaultTargetTriple();
280 llvm::Triple Triple(TripleStr);
282 // create target machine from info for merged modules
283 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
287 // The relocation model is actually a static member of TargetMachine and
288 // needs to be set before the TargetMachine is instantiated.
289 Reloc::Model RelocModel = Reloc::Default;
291 case LTO_CODEGEN_PIC_MODEL_STATIC:
292 RelocModel = Reloc::Static;
294 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
295 RelocModel = Reloc::PIC_;
297 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
298 RelocModel = Reloc::DynamicNoPIC;
300 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
301 // RelocModel is already the default, so leave it that way.
305 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
306 // the default set of features.
307 SubtargetFeatures Features(MAttr);
308 Features.getDefaultSubtargetFeatures(Triple);
309 std::string FeatureStr = Features.getString();
310 // Set a default CPU for Darwin triples.
311 if (MCpu.empty() && Triple.isOSDarwin()) {
312 if (Triple.getArch() == llvm::Triple::x86_64)
314 else if (Triple.getArch() == llvm::Triple::x86)
316 else if (Triple.getArch() == llvm::Triple::arm64 ||
317 Triple.getArch() == llvm::Triple::aarch64)
321 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
322 RelocModel, CodeModel::Default,
323 CodeGenOpt::Aggressive);
327 void LTOCodeGenerator::
328 applyRestriction(GlobalValue &GV,
329 const ArrayRef<StringRef> &Libcalls,
330 std::vector<const char*> &MustPreserveList,
331 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
333 // There are no restrictions to apply to declarations.
334 if (GV.isDeclaration())
337 // There is nothing more restrictive than private linkage.
338 if (GV.hasPrivateLinkage())
341 SmallString<64> Buffer;
342 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
344 if (MustPreserveSymbols.count(Buffer))
345 MustPreserveList.push_back(GV.getName().data());
346 if (AsmUndefinedRefs.count(Buffer))
349 // Conservatively append user-supplied runtime library functions to
350 // llvm.compiler.used. These could be internalized and deleted by
351 // optimizations like -globalopt, causing problems when later optimizations
352 // add new library calls (e.g., llvm.memset => memset and printf => puts).
353 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
354 if (isa<Function>(GV) &&
355 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
359 static void findUsedValues(GlobalVariable *LLVMUsed,
360 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
361 if (!LLVMUsed) return;
363 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
364 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
365 if (GlobalValue *GV =
366 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
367 UsedValues.insert(GV);
370 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
371 const TargetLibraryInfo& TLI,
372 const TargetLowering *Lowering)
374 // TargetLibraryInfo has info on C runtime library calls on the current
376 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
378 LibFunc::Func F = static_cast<LibFunc::Func>(I);
380 Libcalls.push_back(TLI.getName(F));
383 // TargetLowering has info on library calls that CodeGen expects to be
384 // available, both from the C runtime and compiler-rt.
386 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
389 = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
390 Libcalls.push_back(Name);
392 array_pod_sort(Libcalls.begin(), Libcalls.end());
393 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
397 void LTOCodeGenerator::applyScopeRestrictions() {
398 if (ScopeRestrictionsDone)
400 Module *mergedModule = IRLinker.getModule();
402 // Start off with a verification pass.
404 passes.add(createVerifierPass());
405 passes.add(createDebugInfoVerifierPass());
407 // mark which symbols can not be internalized
408 Mangler Mangler(TargetMach->getDataLayout());
409 std::vector<const char*> MustPreserveList;
410 SmallPtrSet<GlobalValue*, 8> AsmUsed;
411 std::vector<StringRef> Libcalls;
412 TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
413 accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
415 for (Module::iterator f = mergedModule->begin(),
416 e = mergedModule->end(); f != e; ++f)
417 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
418 for (Module::global_iterator v = mergedModule->global_begin(),
419 e = mergedModule->global_end(); v != e; ++v)
420 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
421 for (Module::alias_iterator a = mergedModule->alias_begin(),
422 e = mergedModule->alias_end(); a != e; ++a)
423 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
425 GlobalVariable *LLVMCompilerUsed =
426 mergedModule->getGlobalVariable("llvm.compiler.used");
427 findUsedValues(LLVMCompilerUsed, AsmUsed);
428 if (LLVMCompilerUsed)
429 LLVMCompilerUsed->eraseFromParent();
431 if (!AsmUsed.empty()) {
432 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
433 std::vector<Constant*> asmUsed2;
434 for (auto *GV : AsmUsed) {
435 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
436 asmUsed2.push_back(c);
439 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
441 new llvm::GlobalVariable(*mergedModule, ATy, false,
442 llvm::GlobalValue::AppendingLinkage,
443 llvm::ConstantArray::get(ATy, asmUsed2),
444 "llvm.compiler.used");
446 LLVMCompilerUsed->setSection("llvm.metadata");
449 passes.add(createInternalizePass(MustPreserveList));
451 // apply scope restrictions
452 passes.run(*mergedModule);
454 ScopeRestrictionsDone = true;
457 /// Optimize merged modules using various IPO passes
458 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
461 bool DisableGVNLoadPRE,
462 std::string &errMsg) {
463 if (!this->determineTarget(errMsg))
466 Module *mergedModule = IRLinker.getModule();
468 // Mark which symbols can not be internalized
469 this->applyScopeRestrictions();
471 // Instantiate the pass manager to organize the passes.
474 // Start off with a verification pass.
475 passes.add(createVerifierPass());
476 passes.add(createDebugInfoVerifierPass());
478 // Add an appropriate DataLayout instance for this module...
479 mergedModule->setDataLayout(TargetMach->getDataLayout());
480 passes.add(new DataLayoutPass(mergedModule));
482 // Add appropriate TargetLibraryInfo for this module.
483 passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
485 TargetMach->addAnalysisPasses(passes);
487 // Enabling internalize here would use its AllButMain variant. It
488 // keeps only main if it exists and does nothing for libraries. Instead
489 // we create the pass ourselves with the symbol list provided by the linker.
491 PassManagerBuilder().populateLTOPassManager(passes,
492 /*Internalize=*/false,
496 // Make sure everything is still good.
497 passes.add(createVerifierPass());
498 passes.add(createDebugInfoVerifierPass());
500 PassManager codeGenPasses;
502 codeGenPasses.add(new DataLayoutPass(mergedModule));
504 formatted_raw_ostream Out(out);
506 // If the bitcode files contain ARC code and were compiled with optimization,
507 // the ObjCARCContractPass must be run, so do it unconditionally here.
508 codeGenPasses.add(createObjCARCContractPass());
510 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
511 TargetMachine::CGFT_ObjectFile)) {
512 errMsg = "target file type not supported";
516 // Run our queue of passes all at once now, efficiently.
517 passes.run(*mergedModule);
519 // Run the code generator, and write assembly file
520 codeGenPasses.run(*mergedModule);
525 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
527 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
528 for (std::pair<StringRef, StringRef> o = getToken(options);
529 !o.first.empty(); o = getToken(o.second)) {
530 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
532 if (CodegenOptions.empty())
533 CodegenOptions.push_back(strdup("libLLVMLTO"));
534 CodegenOptions.push_back(strdup(o.first.str().c_str()));
538 void LTOCodeGenerator::parseCodeGenDebugOptions() {
539 // if options were requested, set them
540 if (!CodegenOptions.empty())
541 cl::ParseCommandLineOptions(CodegenOptions.size(),
542 const_cast<char **>(&CodegenOptions[0]));
545 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
547 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
550 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
551 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
552 lto_codegen_diagnostic_severity_t Severity;
553 switch (DI.getSeverity()) {
555 Severity = LTO_DS_ERROR;
558 Severity = LTO_DS_WARNING;
561 Severity = LTO_DS_REMARK;
564 Severity = LTO_DS_NOTE;
567 // Create the string that will be reported to the external diagnostic handler.
568 std::string MsgStorage;
569 raw_string_ostream Stream(MsgStorage);
570 DiagnosticPrinterRawOStream DP(Stream);
574 // If this method has been called it means someone has set up an external
575 // diagnostic handler. Assert on that.
576 assert(DiagHandler && "Invalid diagnostic handler");
577 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
581 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
583 this->DiagHandler = DiagHandler;
584 this->DiagContext = Ctxt;
586 return Context.setDiagnosticHandler(nullptr, nullptr);
587 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
588 // diagnostic to the external DiagHandler.
589 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this);