LCOV - code coverage report
Current view: top level - lib/LTO - LTOCodeGenerator.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 273 358 76.3 %
Date: 2017-09-14 15:23:50 Functions: 32 40 80.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      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.
      12             : //
      13             : //===----------------------------------------------------------------------===//
      14             : 
      15             : #include "llvm/LTO/legacy/LTOCodeGenerator.h"
      16             : 
      17             : #include "llvm/ADT/Statistic.h"
      18             : #include "llvm/ADT/StringExtras.h"
      19             : #include "llvm/Analysis/Passes.h"
      20             : #include "llvm/Analysis/TargetLibraryInfo.h"
      21             : #include "llvm/Analysis/TargetTransformInfo.h"
      22             : #include "llvm/Bitcode/BitcodeWriter.h"
      23             : #include "llvm/CodeGen/ParallelCG.h"
      24             : #include "llvm/CodeGen/RuntimeLibcalls.h"
      25             : #include "llvm/Config/config.h"
      26             : #include "llvm/IR/Constants.h"
      27             : #include "llvm/IR/DataLayout.h"
      28             : #include "llvm/IR/DebugInfo.h"
      29             : #include "llvm/IR/DerivedTypes.h"
      30             : #include "llvm/IR/DiagnosticInfo.h"
      31             : #include "llvm/IR/DiagnosticPrinter.h"
      32             : #include "llvm/IR/LLVMContext.h"
      33             : #include "llvm/IR/LegacyPassManager.h"
      34             : #include "llvm/IR/Mangler.h"
      35             : #include "llvm/IR/Module.h"
      36             : #include "llvm/IR/Verifier.h"
      37             : #include "llvm/InitializePasses.h"
      38             : #include "llvm/LTO/LTO.h"
      39             : #include "llvm/LTO/legacy/LTOModule.h"
      40             : #include "llvm/LTO/legacy/UpdateCompilerUsed.h"
      41             : #include "llvm/Linker/Linker.h"
      42             : #include "llvm/MC/MCAsmInfo.h"
      43             : #include "llvm/MC/MCContext.h"
      44             : #include "llvm/MC/SubtargetFeature.h"
      45             : #include "llvm/Support/CommandLine.h"
      46             : #include "llvm/Support/FileSystem.h"
      47             : #include "llvm/Support/Host.h"
      48             : #include "llvm/Support/MemoryBuffer.h"
      49             : #include "llvm/Support/Signals.h"
      50             : #include "llvm/Support/TargetRegistry.h"
      51             : #include "llvm/Support/TargetSelect.h"
      52             : #include "llvm/Support/ToolOutputFile.h"
      53             : #include "llvm/Support/YAMLTraits.h"
      54             : #include "llvm/Support/raw_ostream.h"
      55             : #include "llvm/Target/TargetLowering.h"
      56             : #include "llvm/Target/TargetOptions.h"
      57             : #include "llvm/Target/TargetRegisterInfo.h"
      58             : #include "llvm/Target/TargetSubtargetInfo.h"
      59             : #include "llvm/Transforms/IPO.h"
      60             : #include "llvm/Transforms/IPO/Internalize.h"
      61             : #include "llvm/Transforms/IPO/PassManagerBuilder.h"
      62             : #include "llvm/Transforms/ObjCARC.h"
      63             : #include "llvm/Transforms/Utils/ModuleUtils.h"
      64             : #include <system_error>
      65             : using namespace llvm;
      66             : 
      67           0 : const char* LTOCodeGenerator::getVersionString() {
      68             : #ifdef LLVM_VERSION_INFO
      69             :   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
      70             : #else
      71           0 :   return PACKAGE_NAME " version " PACKAGE_VERSION;
      72             : #endif
      73             : }
      74             : 
      75             : namespace llvm {
      76       72306 : cl::opt<bool> LTODiscardValueNames(
      77             :     "lto-discard-value-names",
      78      216918 :     cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
      79             : #ifdef NDEBUG
      80      216918 :     cl::init(true),
      81             : #else
      82             :     cl::init(false),
      83             : #endif
      84      216918 :     cl::Hidden);
      85             : 
      86       72306 : cl::opt<bool> LTOStripInvalidDebugInfo(
      87             :     "lto-strip-invalid-debug-info",
      88      216918 :     cl::desc("Strip invalid debug info metadata during LTO instead of aborting."),
      89             : #ifdef NDEBUG
      90      216918 :     cl::init(true),
      91             : #else
      92             :     cl::init(false),
      93             : #endif
      94      216918 :     cl::Hidden);
      95             : 
      96             : cl::opt<std::string>
      97       72306 :     LTORemarksFilename("lto-pass-remarks-output",
      98      216918 :                        cl::desc("Output filename for pass remarks"),
      99      289224 :                        cl::value_desc("filename"));
     100             : 
     101       72306 : cl::opt<bool> LTOPassRemarksWithHotness(
     102             :     "lto-pass-remarks-with-hotness",
     103      216918 :     cl::desc("With PGO, include profile count in optimization remarks"),
     104      216918 :     cl::Hidden);
     105             : }
     106             : 
     107          44 : LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
     108          44 :     : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
     109         748 :       TheLinker(new Linker(*MergedModule)) {
     110          44 :   Context.setDiscardValueNames(LTODiscardValueNames);
     111          44 :   Context.enableDebugTypeODRUniquing();
     112          44 :   initializeLTOPasses();
     113          44 : }
     114             : 
     115         468 : LTOCodeGenerator::~LTOCodeGenerator() {}
     116             : 
     117             : // Initialize LTO passes. Please keep this function in sync with
     118             : // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
     119             : // passes are initialized.
     120          44 : void LTOCodeGenerator::initializeLTOPasses() {
     121          44 :   PassRegistry &R = *PassRegistry::getPassRegistry();
     122             : 
     123          44 :   initializeInternalizeLegacyPassPass(R);
     124          44 :   initializeIPSCCPLegacyPassPass(R);
     125          44 :   initializeGlobalOptLegacyPassPass(R);
     126          44 :   initializeConstantMergeLegacyPassPass(R);
     127          44 :   initializeDAHPass(R);
     128          44 :   initializeInstructionCombiningPassPass(R);
     129          44 :   initializeSimpleInlinerPass(R);
     130          44 :   initializePruneEHPass(R);
     131          44 :   initializeGlobalDCELegacyPassPass(R);
     132          44 :   initializeArgPromotionPass(R);
     133          44 :   initializeJumpThreadingPass(R);
     134          44 :   initializeSROALegacyPassPass(R);
     135          44 :   initializePostOrderFunctionAttrsLegacyPassPass(R);
     136          44 :   initializeReversePostOrderFunctionAttrsLegacyPassPass(R);
     137          44 :   initializeGlobalsAAWrapperPassPass(R);
     138          44 :   initializeLegacyLICMPassPass(R);
     139          44 :   initializeMergedLoadStoreMotionLegacyPassPass(R);
     140          44 :   initializeGVNLegacyPassPass(R);
     141          44 :   initializeMemCpyOptLegacyPassPass(R);
     142          44 :   initializeDCELegacyPassPass(R);
     143          44 :   initializeCFGSimplifyPassPass(R);
     144          44 :   initializeLateCFGSimplifyPassPass(R);
     145          44 : }
     146             : 
     147          46 : void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
     148          46 :   const std::vector<StringRef> &undefs = Mod->getAsmUndefinedRefs();
     149          96 :   for (int i = 0, e = undefs.size(); i != e; ++i)
     150          12 :     AsmUndefinedRefs[undefs[i]] = 1;
     151          46 : }
     152             : 
     153          45 : bool LTOCodeGenerator::addModule(LTOModule *Mod) {
     154             :   assert(&Mod->getModule().getContext() == &Context &&
     155             :          "Expected module in same context");
     156             : 
     157         225 :   bool ret = TheLinker->linkInModule(Mod->takeModule());
     158          45 :   setAsmUndefinedRefs(Mod);
     159             : 
     160             :   // We've just changed the input, so let's make sure we verify it.
     161          45 :   HasVerifiedInput = false;
     162             : 
     163          45 :   return !ret;
     164             : }
     165             : 
     166           1 : void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
     167             :   assert(&Mod->getModule().getContext() == &Context &&
     168             :          "Expected module in same context");
     169             : 
     170           1 :   AsmUndefinedRefs.clear();
     171             : 
     172           2 :   MergedModule = Mod->takeModule();
     173           3 :   TheLinker = make_unique<Linker>(*MergedModule);
     174           1 :   setAsmUndefinedRefs(&*Mod);
     175             : 
     176             :   // We've just changed the input, so let's make sure we verify it.
     177           1 :   HasVerifiedInput = false;
     178           1 : }
     179             : 
     180          44 : void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
     181          44 :   this->Options = Options;
     182          44 : }
     183             : 
     184          44 : void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
     185          44 :   switch (Debug) {
     186           0 :   case LTO_DEBUG_MODEL_NONE:
     187           0 :     EmitDwarfDebugInfo = false;
     188           0 :     return;
     189             : 
     190          44 :   case LTO_DEBUG_MODEL_DWARF:
     191          44 :     EmitDwarfDebugInfo = true;
     192          44 :     return;
     193             :   }
     194           0 :   llvm_unreachable("Unknown debug format!");
     195             : }
     196             : 
     197          41 : void LTOCodeGenerator::setOptLevel(unsigned Level) {
     198          41 :   OptLevel = Level;
     199          41 :   switch (OptLevel) {
     200           2 :   case 0:
     201           2 :     CGOptLevel = CodeGenOpt::None;
     202           2 :     return;
     203           0 :   case 1:
     204           0 :     CGOptLevel = CodeGenOpt::Less;
     205           0 :     return;
     206          39 :   case 2:
     207          39 :     CGOptLevel = CodeGenOpt::Default;
     208          39 :     return;
     209           0 :   case 3:
     210           0 :     CGOptLevel = CodeGenOpt::Aggressive;
     211           0 :     return;
     212             :   }
     213           0 :   llvm_unreachable("Unknown optimization level!");
     214             : }
     215             : 
     216           2 : bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
     217           2 :   if (!determineTarget())
     218             :     return false;
     219             : 
     220             :   // We always run the verifier once on the merged module.
     221           2 :   verifyMergedModuleOnce();
     222             : 
     223             :   // mark which symbols can not be internalized
     224           2 :   applyScopeRestrictions();
     225             : 
     226             :   // create output file
     227           2 :   std::error_code EC;
     228           2 :   tool_output_file Out(Path, EC, sys::fs::F_None);
     229           2 :   if (EC) {
     230           0 :     std::string ErrMsg = "could not open bitcode file for writing: ";
     231           0 :     ErrMsg += Path;
     232           0 :     emitError(ErrMsg);
     233           0 :     return false;
     234             :   }
     235             : 
     236             :   // write bitcode to it
     237           4 :   WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
     238           2 :   Out.os().close();
     239             : 
     240           2 :   if (Out.os().has_error()) {
     241           0 :     std::string ErrMsg = "could not write bitcode file: ";
     242           0 :     ErrMsg += Path;
     243           0 :     emitError(ErrMsg);
     244           0 :     Out.os().clear_error();
     245           0 :     return false;
     246             :   }
     247             : 
     248           2 :   Out.keep();
     249           2 :   return true;
     250             : }
     251             : 
     252           1 : bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
     253             :   // make unique temp output file to put generated code
     254           2 :   SmallString<128> Filename;
     255             :   int FD;
     256             : 
     257             :   StringRef Extension
     258           2 :       (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
     259             : 
     260             :   std::error_code EC =
     261           1 :       sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
     262           1 :   if (EC) {
     263           0 :     emitError(EC.message());
     264           0 :     return false;
     265             :   }
     266             : 
     267             :   // generate object file
     268           2 :   tool_output_file objFile(Filename, FD);
     269             : 
     270           2 :   bool genResult = compileOptimized(&objFile.os());
     271           1 :   objFile.os().close();
     272           1 :   if (objFile.os().has_error()) {
     273           0 :     emitError((Twine("could not write object file: ") + Filename).str());
     274           0 :     objFile.os().clear_error();
     275           0 :     sys::fs::remove(Twine(Filename));
     276           0 :     return false;
     277             :   }
     278             : 
     279           1 :   objFile.keep();
     280           1 :   if (!genResult) {
     281           0 :     sys::fs::remove(Twine(Filename));
     282           0 :     return false;
     283             :   }
     284             : 
     285           2 :   NativeObjectPath = Filename.c_str();
     286           2 :   *Name = NativeObjectPath.c_str();
     287           1 :   return true;
     288             : }
     289             : 
     290             : std::unique_ptr<MemoryBuffer>
     291           0 : LTOCodeGenerator::compileOptimized() {
     292             :   const char *name;
     293           0 :   if (!compileOptimizedToFile(&name))
     294             :     return nullptr;
     295             : 
     296             :   // read .o file into memory buffer
     297             :   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
     298           0 :       MemoryBuffer::getFile(name, -1, false);
     299           0 :   if (std::error_code EC = BufferOrErr.getError()) {
     300           0 :     emitError(EC.message());
     301           0 :     sys::fs::remove(NativeObjectPath);
     302           0 :     return nullptr;
     303             :   }
     304             : 
     305             :   // remove temp files
     306           0 :   sys::fs::remove(NativeObjectPath);
     307             : 
     308           0 :   return std::move(*BufferOrErr);
     309             : }
     310             : 
     311           1 : bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
     312             :                                        bool DisableInline,
     313             :                                        bool DisableGVNLoadPRE,
     314             :                                        bool DisableVectorization) {
     315           1 :   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
     316             :                 DisableVectorization))
     317             :     return false;
     318             : 
     319           1 :   return compileOptimizedToFile(Name);
     320             : }
     321             : 
     322             : std::unique_ptr<MemoryBuffer>
     323           0 : LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
     324             :                           bool DisableGVNLoadPRE, bool DisableVectorization) {
     325           0 :   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
     326             :                 DisableVectorization))
     327             :     return nullptr;
     328             : 
     329           0 :   return compileOptimized();
     330             : }
     331             : 
     332          83 : bool LTOCodeGenerator::determineTarget() {
     333         166 :   if (TargetMach)
     334             :     return true;
     335             : 
     336         164 :   TripleStr = MergedModule->getTargetTriple();
     337          82 :   if (TripleStr.empty()) {
     338           8 :     TripleStr = sys::getDefaultTargetTriple();
     339          12 :     MergedModule->setTargetTriple(TripleStr);
     340             :   }
     341          82 :   llvm::Triple Triple(TripleStr);
     342             : 
     343             :   // create target machine from info for merged modules
     344          82 :   std::string ErrMsg;
     345          41 :   MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
     346          41 :   if (!MArch) {
     347           0 :     emitError(ErrMsg);
     348           0 :     return false;
     349             :   }
     350             : 
     351             :   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
     352             :   // the default set of features.
     353          82 :   SubtargetFeatures Features(MAttr);
     354          41 :   Features.getDefaultSubtargetFeatures(Triple);
     355          82 :   FeatureStr = Features.getString();
     356             :   // Set a default CPU for Darwin triples.
     357          82 :   if (MCpu.empty() && Triple.isOSDarwin()) {
     358          17 :     if (Triple.getArch() == llvm::Triple::x86_64)
     359          17 :       MCpu = "core2";
     360           0 :     else if (Triple.getArch() == llvm::Triple::x86)
     361           0 :       MCpu = "yonah";
     362           0 :     else if (Triple.getArch() == llvm::Triple::aarch64)
     363           0 :       MCpu = "cyclone";
     364             :   }
     365             : 
     366         123 :   TargetMach = createTargetMachine();
     367          41 :   return true;
     368             : }
     369             : 
     370          82 : std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
     371          82 :   return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
     372         738 :       TripleStr, MCpu, FeatureStr, Options, RelocModel, None, CGOptLevel));
     373             : }
     374             : 
     375             : // If a linkonce global is present in the MustPreserveSymbols, we need to make
     376             : // sure we honor this. To force the compiler to not drop it, we add it to the
     377             : // "llvm.compiler.used" global.
     378          40 : void LTOCodeGenerator::preserveDiscardableGVs(
     379             :     Module &TheModule,
     380             :     llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
     381          42 :   std::vector<GlobalValue *> Used;
     382         116 :   auto mayPreserveGlobal = [&](GlobalValue &GV) {
     383          36 :     if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
     384          36 :         !mustPreserveGV(GV))
     385             :       return;
     386           5 :     if (GV.hasAvailableExternallyLinkage())
     387           0 :       return emitWarning(
     388           0 :           (Twine("Linker asked to preserve available_externally global: '") +
     389           0 :            GV.getName() + "'").str());
     390           5 :     if (GV.hasInternalLinkage())
     391           0 :       return emitWarning((Twine("Linker asked to preserve internal global: '") +
     392           0 :                    GV.getName() + "'").str());
     393          10 :     Used.push_back(&GV);
     394          40 :   };
     395         213 :   for (auto &GV : TheModule)
     396          93 :     mayPreserveGlobal(GV);
     397          63 :   for (auto &GV : TheModule.globals())
     398          23 :     mayPreserveGlobal(GV);
     399          40 :   for (auto &GV : TheModule.aliases())
     400           0 :     mayPreserveGlobal(GV);
     401             : 
     402          40 :   if (Used.empty())
     403          38 :     return;
     404             : 
     405           2 :   appendToCompilerUsed(TheModule, Used);
     406             : }
     407             : 
     408          42 : void LTOCodeGenerator::applyScopeRestrictions() {
     409          42 :   if (ScopeRestrictionsDone)
     410           2 :     return;
     411             : 
     412             :   // Declare a callback for the internalize pass that will ask for every
     413             :   // candidate GlobalValue if it can be internalized or not.
     414          80 :   Mangler Mang;
     415          80 :   SmallString<64> MangledName;
     416         109 :   auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
     417             :     // Unnamed globals can't be mangled, but they can't be preserved either.
     418         218 :     if (!GV.hasName())
     419             :       return false;
     420             : 
     421             :     // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
     422             :     // with the linker supplied name, which on Darwin includes a leading
     423             :     // underscore.
     424         432 :     MangledName.clear();
     425         324 :     MangledName.reserve(GV.getName().size() + 1);
     426         216 :     Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
     427         324 :     return MustPreserveSymbols.count(MangledName);
     428          40 :   };
     429             : 
     430             :   // Preserve linkonce value on linker request
     431         120 :   preserveDiscardableGVs(*MergedModule, mustPreserveGV);
     432             : 
     433          40 :   if (!ShouldInternalize)
     434           0 :     return;
     435             : 
     436          40 :   if (ShouldRestoreGlobalsLinkage) {
     437             :     // Record the linkage type of non-local symbols so they can be restored
     438             :     // prior
     439             :     // to module splitting.
     440           3 :     auto RecordLinkage = [&](const GlobalValue &GV) {
     441           9 :       if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
     442           6 :           GV.hasName())
     443           9 :         ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
     444           4 :     };
     445           7 :     for (auto &GV : *MergedModule)
     446           3 :       RecordLinkage(GV);
     447           3 :     for (auto &GV : MergedModule->globals())
     448           0 :       RecordLinkage(GV);
     449           3 :     for (auto &GV : MergedModule->aliases())
     450           0 :       RecordLinkage(GV);
     451             :   }
     452             : 
     453             :   // Update the llvm.compiler_used globals to force preserving libcalls and
     454             :   // symbols referenced from asm
     455         120 :   updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
     456             : 
     457         120 :   internalizeModule(*MergedModule, mustPreserveGV);
     458             : 
     459          40 :   ScopeRestrictionsDone = true;
     460             : }
     461             : 
     462             : /// Restore original linkage for symbols that may have been internalized
     463          40 : void LTOCodeGenerator::restoreLinkageForExternals() {
     464          40 :   if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
     465             :     return;
     466             : 
     467             :   assert(ScopeRestrictionsDone &&
     468             :          "Cannot externalize without internalization!");
     469             : 
     470           1 :   if (ExternalSymbols.empty())
     471             :     return;
     472             : 
     473           5 :   auto externalize = [this](GlobalValue &GV) {
     474           2 :     if (!GV.hasLocalLinkage() || !GV.hasName())
     475             :       return;
     476             : 
     477           1 :     auto I = ExternalSymbols.find(GV.getName());
     478           2 :     if (I == ExternalSymbols.end())
     479             :       return;
     480             : 
     481           2 :     GV.setLinkage(I->second);
     482           1 :   };
     483             : 
     484           6 :   std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
     485           1 :   std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
     486           5 :                 externalize);
     487             :   std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
     488           5 :                 externalize);
     489             : }
     490             : 
     491          83 : void LTOCodeGenerator::verifyMergedModuleOnce() {
     492             :   // Only run on the first call.
     493          83 :   if (HasVerifiedInput)
     494          42 :     return;
     495          41 :   HasVerifiedInput = true;
     496             : 
     497          41 :   bool BrokenDebugInfo = false;
     498          82 :   if (verifyModule(*MergedModule, &dbgs(),
     499          41 :                    LTOStripInvalidDebugInfo ? &BrokenDebugInfo : nullptr))
     500           1 :     report_fatal_error("Broken module found, compilation aborted!");
     501          40 :   if (BrokenDebugInfo) {
     502           6 :     emitWarning("Invalid debug info found, debug info will be stripped");
     503           4 :     StripDebugInfo(*MergedModule);
     504             :   }
     505             : }
     506             : 
     507          39 : void LTOCodeGenerator::finishOptimizationRemarks() {
     508          78 :   if (DiagnosticOutputFile) {
     509           4 :     DiagnosticOutputFile->keep();
     510             :     // FIXME: LTOCodeGenerator dtor is not invoked on Darwin
     511           4 :     DiagnosticOutputFile->os().flush();
     512             :   }
     513          39 : }
     514             : 
     515             : /// Optimize merged modules using various IPO passes
     516          41 : bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
     517             :                                 bool DisableGVNLoadPRE,
     518             :                                 bool DisableVectorization) {
     519          41 :   if (!this->determineTarget())
     520             :     return false;
     521             : 
     522             :   auto DiagFileOrErr = lto::setupOptimizationRemarks(
     523         122 :       Context, LTORemarksFilename, LTOPassRemarksWithHotness);
     524          41 :   if (!DiagFileOrErr) {
     525           0 :     errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
     526           0 :     report_fatal_error("Can't get an output file for the remarks");
     527             :   }
     528          82 :   DiagnosticOutputFile = std::move(*DiagFileOrErr);
     529             : 
     530             :   // We always run the verifier once on the merged module, the `DisableVerify`
     531             :   // parameter only applies to subsequent verify.
     532          41 :   verifyMergedModuleOnce();
     533             : 
     534             :   // Mark which symbols can not be internalized
     535          40 :   this->applyScopeRestrictions();
     536             : 
     537             :   // Instantiate the pass manager to organize the passes.
     538          80 :   legacy::PassManager passes;
     539             : 
     540             :   // Add an appropriate DataLayout instance for this module...
     541         160 :   MergedModule->setDataLayout(TargetMach->createDataLayout());
     542             : 
     543          40 :   passes.add(
     544         120 :       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
     545             : 
     546         160 :   Triple TargetTriple(TargetMach->getTargetTriple());
     547          80 :   PassManagerBuilder PMB;
     548          40 :   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
     549          40 :   PMB.LoopVectorize = !DisableVectorization;
     550          40 :   PMB.SLPVectorize = !DisableVectorization;
     551          40 :   if (!DisableInline)
     552          40 :     PMB.Inliner = createFunctionInliningPass();
     553          40 :   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
     554          40 :   if (Freestanding)
     555           1 :     PMB.LibraryInfo->disableAllFunctions();
     556          40 :   PMB.OptLevel = OptLevel;
     557          40 :   PMB.VerifyInput = !DisableVerify;
     558          40 :   PMB.VerifyOutput = !DisableVerify;
     559             : 
     560          40 :   PMB.populateLTOPassManager(passes);
     561             : 
     562             :   // Run our queue of passes all at once now, efficiently.
     563          80 :   passes.run(*MergedModule);
     564             : 
     565             :   return true;
     566             : }
     567             : 
     568          40 : bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
     569          40 :   if (!this->determineTarget())
     570             :     return false;
     571             : 
     572             :   // We always run the verifier once on the merged module.  If it has already
     573             :   // been called in optimize(), this call will return early.
     574          40 :   verifyMergedModuleOnce();
     575             : 
     576          79 :   legacy::PassManager preCodeGenPasses;
     577             : 
     578             :   // If the bitcode files contain ARC code and were compiled with optimization,
     579             :   // the ObjCARCContractPass must be run, so do it unconditionally here.
     580          40 :   preCodeGenPasses.add(createObjCARCContractPass());
     581          80 :   preCodeGenPasses.run(*MergedModule);
     582             : 
     583             :   // Re-externalize globals that may have been internalized to increase scope
     584             :   // for splitting
     585          40 :   restoreLinkageForExternals();
     586             : 
     587             :   // Do code generation. We need to preserve the module in case the client calls
     588             :   // writeMergedModules() after compilation, but we only need to allow this at
     589             :   // parallelism level 1. This is achieved by having splitCodeGen return the
     590             :   // original module at parallelism level 1 which we then assign back to
     591             :   // MergedModule.
     592         199 :   MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
     593          41 :                               [&]() { return createTargetMachine(); }, FileType,
     594          80 :                               ShouldRestoreGlobalsLinkage);
     595             : 
     596             :   // If statistics were requested, print them out after codegen.
     597          39 :   if (llvm::AreStatisticsEnabled())
     598           0 :     llvm::PrintStatistics();
     599          39 :   reportAndResetTimings();
     600             : 
     601          39 :   finishOptimizationRemarks();
     602             : 
     603             :   return true;
     604             : }
     605             : 
     606             : /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
     607             : /// LTO problems.
     608           0 : void LTOCodeGenerator::setCodeGenDebugOptions(StringRef Options) {
     609           0 :   for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
     610           0 :        o = getToken(o.second))
     611           0 :     CodegenOptions.push_back(o.first);
     612           0 : }
     613             : 
     614           0 : void LTOCodeGenerator::parseCodeGenDebugOptions() {
     615             :   // if options were requested, set them
     616           0 :   if (!CodegenOptions.empty()) {
     617             :     // ParseCommandLineOptions() expects argv[0] to be program name.
     618           0 :     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
     619           0 :     for (std::string &Arg : CodegenOptions)
     620           0 :       CodegenArgv.push_back(Arg.c_str());
     621           0 :     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
     622             :   }
     623           0 : }
     624             : 
     625           3 : void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
     626             :                                          void *Context) {
     627           3 :   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
     628           3 : }
     629             : 
     630           3 : void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
     631             :   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
     632             :   lto_codegen_diagnostic_severity_t Severity;
     633           3 :   switch (DI.getSeverity()) {
     634           1 :   case DS_Error:
     635           1 :     Severity = LTO_DS_ERROR;
     636           1 :     break;
     637           0 :   case DS_Warning:
     638           0 :     Severity = LTO_DS_WARNING;
     639           0 :     break;
     640           2 :   case DS_Remark:
     641           2 :     Severity = LTO_DS_REMARK;
     642           2 :     break;
     643           0 :   case DS_Note:
     644           0 :     Severity = LTO_DS_NOTE;
     645           0 :     break;
     646             :   }
     647             :   // Create the string that will be reported to the external diagnostic handler.
     648           6 :   std::string MsgStorage;
     649           6 :   raw_string_ostream Stream(MsgStorage);
     650           6 :   DiagnosticPrinterRawOStream DP(Stream);
     651           3 :   DI.print(DP);
     652           3 :   Stream.flush();
     653             : 
     654             :   // If this method has been called it means someone has set up an external
     655             :   // diagnostic handler. Assert on that.
     656             :   assert(DiagHandler && "Invalid diagnostic handler");
     657           6 :   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
     658           3 : }
     659             : 
     660             : void
     661           3 : LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
     662             :                                        void *Ctxt) {
     663           3 :   this->DiagHandler = DiagHandler;
     664           3 :   this->DiagContext = Ctxt;
     665           3 :   if (!DiagHandler)
     666           0 :     return Context.setDiagnosticHandler(nullptr, nullptr);
     667             :   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
     668             :   // diagnostic to the external DiagHandler.
     669           3 :   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
     670             :                                /* RespectFilters */ true);
     671             : }
     672             : 
     673             : namespace {
     674           2 : class LTODiagnosticInfo : public DiagnosticInfo {
     675             :   const Twine &Msg;
     676             : public:
     677             :   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
     678           4 :       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
     679           2 :   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
     680             : };
     681             : }
     682             : 
     683           0 : void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
     684           0 :   if (DiagHandler)
     685           0 :     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
     686             :   else
     687           0 :     Context.diagnose(LTODiagnosticInfo(ErrMsg));
     688           0 : }
     689             : 
     690           2 : void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
     691           2 :   if (DiagHandler)
     692           0 :     (*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
     693             :   else
     694           8 :     Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
     695      216920 : }

Generated by: LCOV version 1.13