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/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/TargetTransformInfo.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/DiagnosticInfo.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Mangler.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/LTO/LTOModule.h"
35 #include "llvm/Linker/Linker.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/ToolOutputFile.h"
47 #include "llvm/Support/raw_ostream.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()),
68 MergedModule(new Module("ld-temp.o", Context)),
69 IRLinker(MergedModule.get()) {
70 initializeLTOPasses();
73 LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
74 : OwnedContext(std::move(Context)), Context(*OwnedContext),
75 MergedModule(new Module("ld-temp.o", *OwnedContext)),
76 IRLinker(MergedModule.get()) {
77 initializeLTOPasses();
80 LTOCodeGenerator::~LTOCodeGenerator() {}
82 // Initialize LTO passes. Please keep this funciton in sync with
83 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
84 // passes are initialized.
85 void LTOCodeGenerator::initializeLTOPasses() {
86 PassRegistry &R = *PassRegistry::getPassRegistry();
88 initializeInternalizePassPass(R);
89 initializeIPSCCPPass(R);
90 initializeGlobalOptPass(R);
91 initializeConstantMergePass(R);
93 initializeInstructionCombiningPassPass(R);
94 initializeSimpleInlinerPass(R);
95 initializePruneEHPass(R);
96 initializeGlobalDCEPass(R);
97 initializeArgPromotionPass(R);
98 initializeJumpThreadingPass(R);
99 initializeSROAPass(R);
100 initializeSROA_DTPass(R);
101 initializeSROA_SSAUpPass(R);
102 initializeFunctionAttrsPass(R);
103 initializeGlobalsModRefPass(R);
104 initializeLICMPass(R);
105 initializeMergedLoadStoreMotionPass(R);
106 initializeGVNPass(R);
107 initializeMemCpyOptPass(R);
108 initializeDCEPass(R);
109 initializeCFGSimplifyPassPass(R);
112 bool LTOCodeGenerator::addModule(LTOModule *mod) {
113 assert(&mod->getModule().getContext() == &Context &&
114 "Expected module in same context");
116 bool ret = IRLinker.linkInModule(&mod->getModule());
118 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
119 for (int i = 0, e = undefs.size(); i != e; ++i)
120 AsmUndefinedRefs[undefs[i]] = 1;
125 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
126 assert(&Mod->getModule().getContext() == &Context &&
127 "Expected module in same context");
129 AsmUndefinedRefs.clear();
131 MergedModule = Mod->takeModule();
132 IRLinker.setModule(MergedModule.get());
134 const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
135 for (int I = 0, E = Undefs.size(); I != E; ++I)
136 AsmUndefinedRefs[Undefs[I]] = 1;
139 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
143 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
145 case LTO_DEBUG_MODEL_NONE:
146 EmitDwarfDebugInfo = false;
149 case LTO_DEBUG_MODEL_DWARF:
150 EmitDwarfDebugInfo = true;
153 llvm_unreachable("Unknown debug format!");
156 void LTOCodeGenerator::setOptLevel(unsigned level) {
160 CGOptLevel = CodeGenOpt::None;
163 CGOptLevel = CodeGenOpt::Less;
166 CGOptLevel = CodeGenOpt::Default;
169 CGOptLevel = CodeGenOpt::Aggressive;
174 bool LTOCodeGenerator::writeMergedModules(const char *path,
175 std::string &errMsg) {
176 if (!determineTarget(errMsg))
179 // mark which symbols can not be internalized
180 applyScopeRestrictions();
182 // create output file
184 tool_output_file Out(path, EC, sys::fs::F_None);
186 errMsg = "could not open bitcode file for writing: ";
191 // write bitcode to it
192 WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
195 if (Out.os().has_error()) {
196 errMsg = "could not write bitcode file: ";
198 Out.os().clear_error();
206 bool LTOCodeGenerator::compileOptimizedToFile(const char **name,
207 std::string &errMsg) {
208 // make unique temp .o file to put generated object file
209 SmallString<128> Filename;
212 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 = compileOptimized(objFile.os(), errMsg);
222 objFile.os().close();
223 if (objFile.os().has_error()) {
224 objFile.os().clear_error();
225 sys::fs::remove(Twine(Filename));
231 sys::fs::remove(Twine(Filename));
235 NativeObjectPath = Filename.c_str();
236 *name = NativeObjectPath.c_str();
240 std::unique_ptr<MemoryBuffer>
241 LTOCodeGenerator::compileOptimized(std::string &errMsg) {
243 if (!compileOptimizedToFile(&name, errMsg))
246 // read .o file into memory buffer
247 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
248 MemoryBuffer::getFile(name, -1, false);
249 if (std::error_code EC = BufferOrErr.getError()) {
250 errMsg = EC.message();
251 sys::fs::remove(NativeObjectPath);
256 sys::fs::remove(NativeObjectPath);
258 return std::move(*BufferOrErr);
262 bool LTOCodeGenerator::compile_to_file(const char **name,
264 bool disableGVNLoadPRE,
265 bool disableVectorization,
266 std::string &errMsg) {
267 if (!optimize(disableInline, disableGVNLoadPRE,
268 disableVectorization, errMsg))
271 return compileOptimizedToFile(name, errMsg);
274 std::unique_ptr<MemoryBuffer>
275 LTOCodeGenerator::compile(bool disableInline, bool disableGVNLoadPRE,
276 bool disableVectorization, std::string &errMsg) {
277 if (!optimize(disableInline, disableGVNLoadPRE,
278 disableVectorization, errMsg))
281 return compileOptimized(errMsg);
284 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
288 std::string TripleStr = MergedModule->getTargetTriple();
289 if (TripleStr.empty()) {
290 TripleStr = sys::getDefaultTargetTriple();
291 MergedModule->setTargetTriple(TripleStr);
293 llvm::Triple Triple(TripleStr);
295 // create target machine from info for merged modules
296 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
300 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
301 // the default set of features.
302 SubtargetFeatures Features(MAttr);
303 Features.getDefaultSubtargetFeatures(Triple);
304 FeatureStr = Features.getString();
305 // Set a default CPU for Darwin triples.
306 if (MCpu.empty() && Triple.isOSDarwin()) {
307 if (Triple.getArch() == llvm::Triple::x86_64)
309 else if (Triple.getArch() == llvm::Triple::x86)
311 else if (Triple.getArch() == llvm::Triple::aarch64)
315 TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
317 CodeModel::Default, CGOptLevel));
321 void LTOCodeGenerator::
322 applyRestriction(GlobalValue &GV,
323 ArrayRef<StringRef> Libcalls,
324 std::vector<const char*> &MustPreserveList,
325 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
327 // There are no restrictions to apply to declarations.
328 if (GV.isDeclaration())
331 // There is nothing more restrictive than private linkage.
332 if (GV.hasPrivateLinkage())
335 SmallString<64> Buffer;
336 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
338 if (MustPreserveSymbols.count(Buffer))
339 MustPreserveList.push_back(GV.getName().data());
340 if (AsmUndefinedRefs.count(Buffer))
343 // Conservatively append user-supplied runtime library functions to
344 // llvm.compiler.used. These could be internalized and deleted by
345 // optimizations like -globalopt, causing problems when later optimizations
346 // add new library calls (e.g., llvm.memset => memset and printf => puts).
347 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
348 if (isa<Function>(GV) &&
349 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
353 static void findUsedValues(GlobalVariable *LLVMUsed,
354 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
355 if (!LLVMUsed) return;
357 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
358 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
359 if (GlobalValue *GV =
360 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
361 UsedValues.insert(GV);
364 // Collect names of runtime library functions. User-defined functions with the
365 // same names are added to llvm.compiler.used to prevent them from being
366 // deleted by optimizations.
367 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
368 const TargetLibraryInfo& TLI,
370 const TargetMachine &TM) {
371 // TargetLibraryInfo has info on C runtime library calls on the current
373 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
375 LibFunc::Func F = static_cast<LibFunc::Func>(I);
377 Libcalls.push_back(TLI.getName(F));
380 SmallPtrSet<const TargetLowering *, 1> TLSet;
382 for (const Function &F : Mod) {
383 const TargetLowering *Lowering =
384 TM.getSubtargetImpl(F)->getTargetLowering();
386 if (Lowering && TLSet.insert(Lowering).second)
387 // TargetLowering has info on library calls that CodeGen expects to be
388 // available, both from the C runtime and compiler-rt.
389 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
391 if (const char *Name =
392 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
393 Libcalls.push_back(Name);
396 array_pod_sort(Libcalls.begin(), Libcalls.end());
397 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
401 void LTOCodeGenerator::applyScopeRestrictions() {
402 if (ScopeRestrictionsDone || !ShouldInternalize)
405 // Start off with a verification pass.
406 legacy::PassManager passes;
407 passes.add(createVerifierPass());
409 // mark which symbols can not be internalized
411 std::vector<const char*> MustPreserveList;
412 SmallPtrSet<GlobalValue*, 8> AsmUsed;
413 std::vector<StringRef> Libcalls;
414 TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
415 TargetLibraryInfo TLI(TLII);
417 accumulateAndSortLibcalls(Libcalls, TLI, *MergedModule, *TargetMach);
419 for (Function &f : *MergedModule)
420 applyRestriction(f, Libcalls, MustPreserveList, AsmUsed, Mangler);
421 for (GlobalVariable &v : MergedModule->globals())
422 applyRestriction(v, Libcalls, MustPreserveList, AsmUsed, Mangler);
423 for (GlobalAlias &a : MergedModule->aliases())
424 applyRestriction(a, Libcalls, MustPreserveList, AsmUsed, Mangler);
426 GlobalVariable *LLVMCompilerUsed =
427 MergedModule->getGlobalVariable("llvm.compiler.used");
428 findUsedValues(LLVMCompilerUsed, AsmUsed);
429 if (LLVMCompilerUsed)
430 LLVMCompilerUsed->eraseFromParent();
432 if (!AsmUsed.empty()) {
433 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
434 std::vector<Constant*> asmUsed2;
435 for (auto *GV : AsmUsed) {
436 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
437 asmUsed2.push_back(c);
440 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
442 new llvm::GlobalVariable(*MergedModule, ATy, false,
443 llvm::GlobalValue::AppendingLinkage,
444 llvm::ConstantArray::get(ATy, asmUsed2),
445 "llvm.compiler.used");
447 LLVMCompilerUsed->setSection("llvm.metadata");
450 passes.add(createInternalizePass(MustPreserveList));
452 // apply scope restrictions
453 passes.run(*MergedModule);
455 ScopeRestrictionsDone = true;
458 /// Optimize merged modules using various IPO passes
459 bool LTOCodeGenerator::optimize(bool DisableInline,
460 bool DisableGVNLoadPRE,
461 bool DisableVectorization,
462 std::string &errMsg) {
463 if (!this->determineTarget(errMsg))
466 // Mark which symbols can not be internalized
467 this->applyScopeRestrictions();
469 // Instantiate the pass manager to organize the passes.
470 legacy::PassManager passes;
472 // Add an appropriate DataLayout instance for this module...
473 MergedModule->setDataLayout(TargetMach->createDataLayout());
476 createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
478 Triple TargetTriple(TargetMach->getTargetTriple());
479 PassManagerBuilder PMB;
480 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
481 PMB.LoopVectorize = !DisableVectorization;
482 PMB.SLPVectorize = !DisableVectorization;
484 PMB.Inliner = createFunctionInliningPass();
485 PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
486 PMB.OptLevel = OptLevel;
487 PMB.VerifyInput = true;
488 PMB.VerifyOutput = true;
490 PMB.populateLTOPassManager(passes);
492 // Run our queue of passes all at once now, efficiently.
493 passes.run(*MergedModule);
498 bool LTOCodeGenerator::compileOptimized(raw_pwrite_stream &out,
499 std::string &errMsg) {
500 if (!this->determineTarget(errMsg))
503 legacy::PassManager codeGenPasses;
505 // If the bitcode files contain ARC code and were compiled with optimization,
506 // the ObjCARCContractPass must be run, so do it unconditionally here.
507 codeGenPasses.add(createObjCARCContractPass());
509 if (TargetMach->addPassesToEmitFile(codeGenPasses, out,
510 TargetMachine::CGFT_ObjectFile)) {
511 errMsg = "target file type not supported";
515 // Run the code generator, and write object file
516 codeGenPasses.run(*MergedModule);
521 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
523 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
524 for (std::pair<StringRef, StringRef> o = getToken(options);
525 !o.first.empty(); o = getToken(o.second))
526 CodegenOptions.push_back(o.first);
529 void LTOCodeGenerator::parseCodeGenDebugOptions() {
530 // if options were requested, set them
531 if (!CodegenOptions.empty()) {
532 // ParseCommandLineOptions() expects argv[0] to be program name.
533 std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
534 for (std::string &Arg : CodegenOptions)
535 CodegenArgv.push_back(Arg.c_str());
536 cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
540 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
542 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
545 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
546 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
547 lto_codegen_diagnostic_severity_t Severity;
548 switch (DI.getSeverity()) {
550 Severity = LTO_DS_ERROR;
553 Severity = LTO_DS_WARNING;
556 Severity = LTO_DS_REMARK;
559 Severity = LTO_DS_NOTE;
562 // Create the string that will be reported to the external diagnostic handler.
563 std::string MsgStorage;
564 raw_string_ostream Stream(MsgStorage);
565 DiagnosticPrinterRawOStream DP(Stream);
569 // If this method has been called it means someone has set up an external
570 // diagnostic handler. Assert on that.
571 assert(DiagHandler && "Invalid diagnostic handler");
572 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
576 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
578 this->DiagHandler = DiagHandler;
579 this->DiagContext = Ctxt;
581 return Context.setDiagnosticHandler(nullptr, nullptr);
582 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
583 // diagnostic to the external DiagHandler.
584 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
585 /* RespectFilters */ true);