1f785676fSDimitry Andric //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2f785676fSDimitry Andric //
3f785676fSDimitry Andric //                     The LLVM Compiler Infrastructure
4f785676fSDimitry Andric //
5f785676fSDimitry Andric // This file is distributed under the University of Illinois Open Source
6f785676fSDimitry Andric // License. See LICENSE.TXT for details.
7f785676fSDimitry Andric //
8f785676fSDimitry Andric //===----------------------------------------------------------------------===//
9f785676fSDimitry Andric //
10f785676fSDimitry Andric // This file implements the Link Time Optimization library. This library is
11f785676fSDimitry Andric // intended to be used by linker to optimize code at link time.
12f785676fSDimitry Andric //
13f785676fSDimitry Andric //===----------------------------------------------------------------------===//
14f785676fSDimitry Andric 
15f785676fSDimitry Andric #include "llvm/LTO/LTOCodeGenerator.h"
16f785676fSDimitry Andric #include "llvm/ADT/StringExtras.h"
17f785676fSDimitry Andric #include "llvm/Analysis/Passes.h"
18ff0cc061SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
19ff0cc061SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
20f785676fSDimitry Andric #include "llvm/Bitcode/ReaderWriter.h"
217d523365SDimitry Andric #include "llvm/CodeGen/ParallelCG.h"
22f785676fSDimitry Andric #include "llvm/CodeGen/RuntimeLibcalls.h"
23f785676fSDimitry Andric #include "llvm/Config/config.h"
24f785676fSDimitry Andric #include "llvm/IR/Constants.h"
25f785676fSDimitry Andric #include "llvm/IR/DataLayout.h"
26f785676fSDimitry Andric #include "llvm/IR/DerivedTypes.h"
2791bc56edSDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
2891bc56edSDimitry Andric #include "llvm/IR/DiagnosticPrinter.h"
29f785676fSDimitry Andric #include "llvm/IR/LLVMContext.h"
30ff0cc061SDimitry Andric #include "llvm/IR/LegacyPassManager.h"
3191bc56edSDimitry Andric #include "llvm/IR/Mangler.h"
32f785676fSDimitry Andric #include "llvm/IR/Module.h"
3391bc56edSDimitry Andric #include "llvm/IR/Verifier.h"
34f785676fSDimitry Andric #include "llvm/InitializePasses.h"
3591bc56edSDimitry Andric #include "llvm/LTO/LTOModule.h"
3691bc56edSDimitry Andric #include "llvm/Linker/Linker.h"
37f785676fSDimitry Andric #include "llvm/MC/MCAsmInfo.h"
38f785676fSDimitry Andric #include "llvm/MC/MCContext.h"
39f785676fSDimitry Andric #include "llvm/MC/SubtargetFeature.h"
40f785676fSDimitry Andric #include "llvm/Support/CommandLine.h"
41f785676fSDimitry Andric #include "llvm/Support/FileSystem.h"
42f785676fSDimitry Andric #include "llvm/Support/Host.h"
43f785676fSDimitry Andric #include "llvm/Support/MemoryBuffer.h"
44f785676fSDimitry Andric #include "llvm/Support/Signals.h"
45f785676fSDimitry Andric #include "llvm/Support/TargetRegistry.h"
46f785676fSDimitry Andric #include "llvm/Support/TargetSelect.h"
47f785676fSDimitry Andric #include "llvm/Support/ToolOutputFile.h"
4891bc56edSDimitry Andric #include "llvm/Support/raw_ostream.h"
49f785676fSDimitry Andric #include "llvm/Target/TargetLowering.h"
50f785676fSDimitry Andric #include "llvm/Target/TargetOptions.h"
51f785676fSDimitry Andric #include "llvm/Target/TargetRegisterInfo.h"
5239d628a0SDimitry Andric #include "llvm/Target/TargetSubtargetInfo.h"
53f785676fSDimitry Andric #include "llvm/Transforms/IPO.h"
54f785676fSDimitry Andric #include "llvm/Transforms/IPO/PassManagerBuilder.h"
55f785676fSDimitry Andric #include "llvm/Transforms/ObjCARC.h"
5691bc56edSDimitry Andric #include <system_error>
57f785676fSDimitry Andric using namespace llvm;
58f785676fSDimitry Andric 
59f785676fSDimitry Andric const char* LTOCodeGenerator::getVersionString() {
60f785676fSDimitry Andric #ifdef LLVM_VERSION_INFO
61f785676fSDimitry Andric   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
62f785676fSDimitry Andric #else
63f785676fSDimitry Andric   return PACKAGE_NAME " version " PACKAGE_VERSION;
64f785676fSDimitry Andric #endif
65f785676fSDimitry Andric }
66f785676fSDimitry Andric 
677d523365SDimitry Andric LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
687d523365SDimitry Andric     : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
697d523365SDimitry Andric       TheLinker(new Linker(*MergedModule)) {
70ff0cc061SDimitry Andric   initializeLTOPasses();
7139d628a0SDimitry Andric }
7239d628a0SDimitry Andric 
737d523365SDimitry Andric LTOCodeGenerator::~LTOCodeGenerator() {}
74f785676fSDimitry Andric 
757d523365SDimitry Andric // Initialize LTO passes. Please keep this function in sync with
76f785676fSDimitry Andric // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
77f785676fSDimitry Andric // passes are initialized.
78f785676fSDimitry Andric void LTOCodeGenerator::initializeLTOPasses() {
79f785676fSDimitry Andric   PassRegistry &R = *PassRegistry::getPassRegistry();
80f785676fSDimitry Andric 
81f785676fSDimitry Andric   initializeInternalizePassPass(R);
82f785676fSDimitry Andric   initializeIPSCCPPass(R);
83f785676fSDimitry Andric   initializeGlobalOptPass(R);
84f785676fSDimitry Andric   initializeConstantMergePass(R);
85f785676fSDimitry Andric   initializeDAHPass(R);
86ff0cc061SDimitry Andric   initializeInstructionCombiningPassPass(R);
87f785676fSDimitry Andric   initializeSimpleInlinerPass(R);
88f785676fSDimitry Andric   initializePruneEHPass(R);
89f785676fSDimitry Andric   initializeGlobalDCEPass(R);
90f785676fSDimitry Andric   initializeArgPromotionPass(R);
91f785676fSDimitry Andric   initializeJumpThreadingPass(R);
927d523365SDimitry Andric   initializeSROALegacyPassPass(R);
93f785676fSDimitry Andric   initializeSROA_DTPass(R);
94f785676fSDimitry Andric   initializeSROA_SSAUpPass(R);
95f785676fSDimitry Andric   initializeFunctionAttrsPass(R);
967d523365SDimitry Andric   initializeGlobalsAAWrapperPassPass(R);
97f785676fSDimitry Andric   initializeLICMPass(R);
9891bc56edSDimitry Andric   initializeMergedLoadStoreMotionPass(R);
99f785676fSDimitry Andric   initializeGVNPass(R);
100f785676fSDimitry Andric   initializeMemCpyOptPass(R);
101f785676fSDimitry Andric   initializeDCEPass(R);
102f785676fSDimitry Andric   initializeCFGSimplifyPassPass(R);
103f785676fSDimitry Andric }
104f785676fSDimitry Andric 
1057d523365SDimitry Andric bool LTOCodeGenerator::addModule(LTOModule *Mod) {
1067d523365SDimitry Andric   assert(&Mod->getModule().getContext() == &Context &&
10739d628a0SDimitry Andric          "Expected module in same context");
10839d628a0SDimitry Andric 
1097d523365SDimitry Andric   bool ret = TheLinker->linkInModule(Mod->takeModule());
110f785676fSDimitry Andric 
1117d523365SDimitry Andric   const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs();
112f785676fSDimitry Andric   for (int i = 0, e = undefs.size(); i != e; ++i)
113f785676fSDimitry Andric     AsmUndefinedRefs[undefs[i]] = 1;
114f785676fSDimitry Andric 
115f785676fSDimitry Andric   return !ret;
116f785676fSDimitry Andric }
117f785676fSDimitry Andric 
1187d523365SDimitry Andric void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
119ff0cc061SDimitry Andric   assert(&Mod->getModule().getContext() == &Context &&
120ff0cc061SDimitry Andric          "Expected module in same context");
121ff0cc061SDimitry Andric 
122ff0cc061SDimitry Andric   AsmUndefinedRefs.clear();
123ff0cc061SDimitry Andric 
1247d523365SDimitry Andric   MergedModule = Mod->takeModule();
1257d523365SDimitry Andric   TheLinker = make_unique<Linker>(*MergedModule);
126ff0cc061SDimitry Andric 
127ff0cc061SDimitry Andric   const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
128ff0cc061SDimitry Andric   for (int I = 0, E = Undefs.size(); I != E; ++I)
129ff0cc061SDimitry Andric     AsmUndefinedRefs[Undefs[I]] = 1;
130ff0cc061SDimitry Andric }
131ff0cc061SDimitry Andric 
1327d523365SDimitry Andric void LTOCodeGenerator::setTargetOptions(TargetOptions Options) {
1337d523365SDimitry Andric   this->Options = Options;
134f785676fSDimitry Andric }
135f785676fSDimitry Andric 
1367d523365SDimitry Andric void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
1377d523365SDimitry Andric   switch (Debug) {
138f785676fSDimitry Andric   case LTO_DEBUG_MODEL_NONE:
139f785676fSDimitry Andric     EmitDwarfDebugInfo = false;
140f785676fSDimitry Andric     return;
141f785676fSDimitry Andric 
142f785676fSDimitry Andric   case LTO_DEBUG_MODEL_DWARF:
143f785676fSDimitry Andric     EmitDwarfDebugInfo = true;
144f785676fSDimitry Andric     return;
145f785676fSDimitry Andric   }
146f785676fSDimitry Andric   llvm_unreachable("Unknown debug format!");
147f785676fSDimitry Andric }
148f785676fSDimitry Andric 
1497d523365SDimitry Andric void LTOCodeGenerator::setOptLevel(unsigned Level) {
1507d523365SDimitry Andric   OptLevel = Level;
151ff0cc061SDimitry Andric   switch (OptLevel) {
152ff0cc061SDimitry Andric   case 0:
153ff0cc061SDimitry Andric     CGOptLevel = CodeGenOpt::None;
154ff0cc061SDimitry Andric     break;
155ff0cc061SDimitry Andric   case 1:
156ff0cc061SDimitry Andric     CGOptLevel = CodeGenOpt::Less;
157ff0cc061SDimitry Andric     break;
158ff0cc061SDimitry Andric   case 2:
159ff0cc061SDimitry Andric     CGOptLevel = CodeGenOpt::Default;
160ff0cc061SDimitry Andric     break;
161ff0cc061SDimitry Andric   case 3:
162ff0cc061SDimitry Andric     CGOptLevel = CodeGenOpt::Aggressive;
163ff0cc061SDimitry Andric     break;
164ff0cc061SDimitry Andric   }
1657d523365SDimitry Andric }
166ff0cc061SDimitry Andric 
1677d523365SDimitry Andric bool LTOCodeGenerator::writeMergedModules(const char *Path) {
1687d523365SDimitry Andric   if (!determineTarget())
1697d523365SDimitry Andric     return false;
1707d523365SDimitry Andric 
1717d523365SDimitry Andric   // mark which symbols can not be internalized
1727d523365SDimitry Andric   applyScopeRestrictions();
1737d523365SDimitry Andric 
1747d523365SDimitry Andric   // create output file
1757d523365SDimitry Andric   std::error_code EC;
1767d523365SDimitry Andric   tool_output_file Out(Path, EC, sys::fs::F_None);
1777d523365SDimitry Andric   if (EC) {
1787d523365SDimitry Andric     std::string ErrMsg = "could not open bitcode file for writing: ";
1797d523365SDimitry Andric     ErrMsg += Path;
1807d523365SDimitry Andric     emitError(ErrMsg);
1817d523365SDimitry Andric     return false;
1827d523365SDimitry Andric   }
1837d523365SDimitry Andric 
1847d523365SDimitry Andric   // write bitcode to it
1857d523365SDimitry Andric   WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
1867d523365SDimitry Andric   Out.os().close();
1877d523365SDimitry Andric 
1887d523365SDimitry Andric   if (Out.os().has_error()) {
1897d523365SDimitry Andric     std::string ErrMsg = "could not write bitcode file: ";
1907d523365SDimitry Andric     ErrMsg += Path;
1917d523365SDimitry Andric     emitError(ErrMsg);
1927d523365SDimitry Andric     Out.os().clear_error();
1937d523365SDimitry Andric     return false;
1947d523365SDimitry Andric   }
1957d523365SDimitry Andric 
1967d523365SDimitry Andric   Out.keep();
1977d523365SDimitry Andric   return true;
1987d523365SDimitry Andric }
1997d523365SDimitry Andric 
2007d523365SDimitry Andric bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
2017d523365SDimitry Andric   // make unique temp output file to put generated code
2027d523365SDimitry Andric   SmallString<128> Filename;
2037d523365SDimitry Andric   int FD;
2047d523365SDimitry Andric 
2057d523365SDimitry Andric   const char *Extension =
2067d523365SDimitry Andric       (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
2077d523365SDimitry Andric 
2087d523365SDimitry Andric   std::error_code EC =
2097d523365SDimitry Andric       sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
2107d523365SDimitry Andric   if (EC) {
2117d523365SDimitry Andric     emitError(EC.message());
2127d523365SDimitry Andric     return false;
2137d523365SDimitry Andric   }
2147d523365SDimitry Andric 
2157d523365SDimitry Andric   // generate object file
2167d523365SDimitry Andric   tool_output_file objFile(Filename.c_str(), FD);
2177d523365SDimitry Andric 
2187d523365SDimitry Andric   bool genResult = compileOptimized(&objFile.os());
2197d523365SDimitry Andric   objFile.os().close();
2207d523365SDimitry Andric   if (objFile.os().has_error()) {
2217d523365SDimitry Andric     objFile.os().clear_error();
2227d523365SDimitry Andric     sys::fs::remove(Twine(Filename));
2237d523365SDimitry Andric     return false;
2247d523365SDimitry Andric   }
2257d523365SDimitry Andric 
2267d523365SDimitry Andric   objFile.keep();
2277d523365SDimitry Andric   if (!genResult) {
2287d523365SDimitry Andric     sys::fs::remove(Twine(Filename));
2297d523365SDimitry Andric     return false;
2307d523365SDimitry Andric   }
2317d523365SDimitry Andric 
2327d523365SDimitry Andric   NativeObjectPath = Filename.c_str();
2337d523365SDimitry Andric   *Name = NativeObjectPath.c_str();
2347d523365SDimitry Andric   return true;
2357d523365SDimitry Andric }
2367d523365SDimitry Andric 
2377d523365SDimitry Andric std::unique_ptr<MemoryBuffer>
2387d523365SDimitry Andric LTOCodeGenerator::compileOptimized() {
2397d523365SDimitry Andric   const char *name;
2407d523365SDimitry Andric   if (!compileOptimizedToFile(&name))
2417d523365SDimitry Andric     return nullptr;
2427d523365SDimitry Andric 
2437d523365SDimitry Andric   // read .o file into memory buffer
2447d523365SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
2457d523365SDimitry Andric       MemoryBuffer::getFile(name, -1, false);
2467d523365SDimitry Andric   if (std::error_code EC = BufferOrErr.getError()) {
2477d523365SDimitry Andric     emitError(EC.message());
2487d523365SDimitry Andric     sys::fs::remove(NativeObjectPath);
2497d523365SDimitry Andric     return nullptr;
2507d523365SDimitry Andric   }
2517d523365SDimitry Andric 
2527d523365SDimitry Andric   // remove temp files
2537d523365SDimitry Andric   sys::fs::remove(NativeObjectPath);
2547d523365SDimitry Andric 
2557d523365SDimitry Andric   return std::move(*BufferOrErr);
2567d523365SDimitry Andric }
2577d523365SDimitry Andric 
2587d523365SDimitry Andric bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
2597d523365SDimitry Andric                                        bool DisableInline,
2607d523365SDimitry Andric                                        bool DisableGVNLoadPRE,
2617d523365SDimitry Andric                                        bool DisableVectorization) {
2627d523365SDimitry Andric   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
2637d523365SDimitry Andric                 DisableVectorization))
2647d523365SDimitry Andric     return false;
2657d523365SDimitry Andric 
2667d523365SDimitry Andric   return compileOptimizedToFile(Name);
2677d523365SDimitry Andric }
2687d523365SDimitry Andric 
2697d523365SDimitry Andric std::unique_ptr<MemoryBuffer>
2707d523365SDimitry Andric LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
2717d523365SDimitry Andric                           bool DisableGVNLoadPRE, bool DisableVectorization) {
2727d523365SDimitry Andric   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
2737d523365SDimitry Andric                 DisableVectorization))
2747d523365SDimitry Andric     return nullptr;
2757d523365SDimitry Andric 
2767d523365SDimitry Andric   return compileOptimized();
2777d523365SDimitry Andric }
2787d523365SDimitry Andric 
2797d523365SDimitry Andric bool LTOCodeGenerator::determineTarget() {
2807d523365SDimitry Andric   if (TargetMach)
2817d523365SDimitry Andric     return true;
2827d523365SDimitry Andric 
2837d523365SDimitry Andric   std::string TripleStr = MergedModule->getTargetTriple();
2847d523365SDimitry Andric   if (TripleStr.empty()) {
2857d523365SDimitry Andric     TripleStr = sys::getDefaultTargetTriple();
2867d523365SDimitry Andric     MergedModule->setTargetTriple(TripleStr);
2877d523365SDimitry Andric   }
2887d523365SDimitry Andric   llvm::Triple Triple(TripleStr);
2897d523365SDimitry Andric 
2907d523365SDimitry Andric   // create target machine from info for merged modules
2917d523365SDimitry Andric   std::string ErrMsg;
2927d523365SDimitry Andric   const Target *march = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
2937d523365SDimitry Andric   if (!march) {
2947d523365SDimitry Andric     emitError(ErrMsg);
2957d523365SDimitry Andric     return false;
2967d523365SDimitry Andric   }
2977d523365SDimitry Andric 
2987d523365SDimitry Andric   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
2997d523365SDimitry Andric   // the default set of features.
3007d523365SDimitry Andric   SubtargetFeatures Features(MAttr);
3017d523365SDimitry Andric   Features.getDefaultSubtargetFeatures(Triple);
3027d523365SDimitry Andric   FeatureStr = Features.getString();
3037d523365SDimitry Andric   // Set a default CPU for Darwin triples.
3047d523365SDimitry Andric   if (MCpu.empty() && Triple.isOSDarwin()) {
3057d523365SDimitry Andric     if (Triple.getArch() == llvm::Triple::x86_64)
3067d523365SDimitry Andric       MCpu = "core2";
3077d523365SDimitry Andric     else if (Triple.getArch() == llvm::Triple::x86)
3087d523365SDimitry Andric       MCpu = "yonah";
3097d523365SDimitry Andric     else if (Triple.getArch() == llvm::Triple::aarch64)
3107d523365SDimitry Andric       MCpu = "cyclone";
3117d523365SDimitry Andric   }
3127d523365SDimitry Andric 
3137d523365SDimitry Andric   TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
3147d523365SDimitry Andric                                               Options, RelocModel,
3157d523365SDimitry Andric                                               CodeModel::Default, CGOptLevel));
316f785676fSDimitry Andric   return true;
317f785676fSDimitry Andric }
318f785676fSDimitry Andric 
319f785676fSDimitry Andric void LTOCodeGenerator::
320f785676fSDimitry Andric applyRestriction(GlobalValue &GV,
32139d628a0SDimitry Andric                  ArrayRef<StringRef> Libcalls,
322f785676fSDimitry Andric                  std::vector<const char*> &MustPreserveList,
32339d628a0SDimitry Andric                  SmallPtrSetImpl<GlobalValue*> &AsmUsed,
324f785676fSDimitry Andric                  Mangler &Mangler) {
32591bc56edSDimitry Andric   // There are no restrictions to apply to declarations.
326f785676fSDimitry Andric   if (GV.isDeclaration())
327f785676fSDimitry Andric     return;
32891bc56edSDimitry Andric 
32991bc56edSDimitry Andric   // There is nothing more restrictive than private linkage.
33091bc56edSDimitry Andric   if (GV.hasPrivateLinkage())
33191bc56edSDimitry Andric     return;
33291bc56edSDimitry Andric 
33391bc56edSDimitry Andric   SmallString<64> Buffer;
33491bc56edSDimitry Andric   TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
33591bc56edSDimitry Andric 
336f785676fSDimitry Andric   if (MustPreserveSymbols.count(Buffer))
337f785676fSDimitry Andric     MustPreserveList.push_back(GV.getName().data());
338f785676fSDimitry Andric   if (AsmUndefinedRefs.count(Buffer))
339f785676fSDimitry Andric     AsmUsed.insert(&GV);
340f785676fSDimitry Andric 
341f785676fSDimitry Andric   // Conservatively append user-supplied runtime library functions to
342f785676fSDimitry Andric   // llvm.compiler.used.  These could be internalized and deleted by
343f785676fSDimitry Andric   // optimizations like -globalopt, causing problems when later optimizations
344f785676fSDimitry Andric   // add new library calls (e.g., llvm.memset => memset and printf => puts).
345f785676fSDimitry Andric   // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
346f785676fSDimitry Andric   if (isa<Function>(GV) &&
347f785676fSDimitry Andric       std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
348f785676fSDimitry Andric     AsmUsed.insert(&GV);
349f785676fSDimitry Andric }
350f785676fSDimitry Andric 
351f785676fSDimitry Andric static void findUsedValues(GlobalVariable *LLVMUsed,
35239d628a0SDimitry Andric                            SmallPtrSetImpl<GlobalValue*> &UsedValues) {
35391bc56edSDimitry Andric   if (!LLVMUsed) return;
354f785676fSDimitry Andric 
355f785676fSDimitry Andric   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
356f785676fSDimitry Andric   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
357f785676fSDimitry Andric     if (GlobalValue *GV =
358f785676fSDimitry Andric         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
359f785676fSDimitry Andric       UsedValues.insert(GV);
360f785676fSDimitry Andric }
361f785676fSDimitry Andric 
362ff0cc061SDimitry Andric // Collect names of runtime library functions. User-defined functions with the
363ff0cc061SDimitry Andric // same names are added to llvm.compiler.used to prevent them from being
364ff0cc061SDimitry Andric // deleted by optimizations.
365f785676fSDimitry Andric static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
366f785676fSDimitry Andric                                       const TargetLibraryInfo& TLI,
367ff0cc061SDimitry Andric                                       const Module &Mod,
368ff0cc061SDimitry Andric                                       const TargetMachine &TM) {
369f785676fSDimitry Andric   // TargetLibraryInfo has info on C runtime library calls on the current
370f785676fSDimitry Andric   // target.
371f785676fSDimitry Andric   for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
372f785676fSDimitry Andric        I != E; ++I) {
373f785676fSDimitry Andric     LibFunc::Func F = static_cast<LibFunc::Func>(I);
374f785676fSDimitry Andric     if (TLI.has(F))
375f785676fSDimitry Andric       Libcalls.push_back(TLI.getName(F));
376f785676fSDimitry Andric   }
377f785676fSDimitry Andric 
378ff0cc061SDimitry Andric   SmallPtrSet<const TargetLowering *, 1> TLSet;
379ff0cc061SDimitry Andric 
380ff0cc061SDimitry Andric   for (const Function &F : Mod) {
381ff0cc061SDimitry Andric     const TargetLowering *Lowering =
382ff0cc061SDimitry Andric         TM.getSubtargetImpl(F)->getTargetLowering();
383ff0cc061SDimitry Andric 
384ff0cc061SDimitry Andric     if (Lowering && TLSet.insert(Lowering).second)
385f785676fSDimitry Andric       // TargetLowering has info on library calls that CodeGen expects to be
386f785676fSDimitry Andric       // available, both from the C runtime and compiler-rt.
387f785676fSDimitry Andric       for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
388f785676fSDimitry Andric            I != E; ++I)
389ff0cc061SDimitry Andric         if (const char *Name =
390ff0cc061SDimitry Andric                 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
391f785676fSDimitry Andric           Libcalls.push_back(Name);
392ff0cc061SDimitry Andric   }
393f785676fSDimitry Andric 
394f785676fSDimitry Andric   array_pod_sort(Libcalls.begin(), Libcalls.end());
395f785676fSDimitry Andric   Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
396f785676fSDimitry Andric                  Libcalls.end());
397f785676fSDimitry Andric }
398f785676fSDimitry Andric 
399f785676fSDimitry Andric void LTOCodeGenerator::applyScopeRestrictions() {
400ff0cc061SDimitry Andric   if (ScopeRestrictionsDone || !ShouldInternalize)
401f785676fSDimitry Andric     return;
402f785676fSDimitry Andric 
403f785676fSDimitry Andric   // Start off with a verification pass.
404ff0cc061SDimitry Andric   legacy::PassManager passes;
405f785676fSDimitry Andric   passes.add(createVerifierPass());
406f785676fSDimitry Andric 
407f785676fSDimitry Andric   // mark which symbols can not be internalized
4083dac3a9bSDimitry Andric   Mangler Mangler;
409f785676fSDimitry Andric   std::vector<const char*> MustPreserveList;
410f785676fSDimitry Andric   SmallPtrSet<GlobalValue*, 8> AsmUsed;
411f785676fSDimitry Andric   std::vector<StringRef> Libcalls;
412ff0cc061SDimitry Andric   TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
413ff0cc061SDimitry Andric   TargetLibraryInfo TLI(TLII);
414ff0cc061SDimitry Andric 
4157d523365SDimitry Andric   accumulateAndSortLibcalls(Libcalls, TLI, *MergedModule, *TargetMach);
416f785676fSDimitry Andric 
4177d523365SDimitry Andric   for (Function &f : *MergedModule)
4187d523365SDimitry Andric     applyRestriction(f, Libcalls, MustPreserveList, AsmUsed, Mangler);
4197d523365SDimitry Andric   for (GlobalVariable &v : MergedModule->globals())
4207d523365SDimitry Andric     applyRestriction(v, Libcalls, MustPreserveList, AsmUsed, Mangler);
4217d523365SDimitry Andric   for (GlobalAlias &a : MergedModule->aliases())
4227d523365SDimitry Andric     applyRestriction(a, Libcalls, MustPreserveList, AsmUsed, Mangler);
423f785676fSDimitry Andric 
424f785676fSDimitry Andric   GlobalVariable *LLVMCompilerUsed =
4257d523365SDimitry Andric     MergedModule->getGlobalVariable("llvm.compiler.used");
426f785676fSDimitry Andric   findUsedValues(LLVMCompilerUsed, AsmUsed);
427f785676fSDimitry Andric   if (LLVMCompilerUsed)
428f785676fSDimitry Andric     LLVMCompilerUsed->eraseFromParent();
429f785676fSDimitry Andric 
430f785676fSDimitry Andric   if (!AsmUsed.empty()) {
431f785676fSDimitry Andric     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
432f785676fSDimitry Andric     std::vector<Constant*> asmUsed2;
43391bc56edSDimitry Andric     for (auto *GV : AsmUsed) {
434f785676fSDimitry Andric       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
435f785676fSDimitry Andric       asmUsed2.push_back(c);
436f785676fSDimitry Andric     }
437f785676fSDimitry Andric 
438f785676fSDimitry Andric     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
439f785676fSDimitry Andric     LLVMCompilerUsed =
4407d523365SDimitry Andric       new llvm::GlobalVariable(*MergedModule, ATy, false,
441f785676fSDimitry Andric                                llvm::GlobalValue::AppendingLinkage,
442f785676fSDimitry Andric                                llvm::ConstantArray::get(ATy, asmUsed2),
443f785676fSDimitry Andric                                "llvm.compiler.used");
444f785676fSDimitry Andric 
445f785676fSDimitry Andric     LLVMCompilerUsed->setSection("llvm.metadata");
446f785676fSDimitry Andric   }
447f785676fSDimitry Andric 
448f785676fSDimitry Andric   passes.add(createInternalizePass(MustPreserveList));
449f785676fSDimitry Andric 
450f785676fSDimitry Andric   // apply scope restrictions
4517d523365SDimitry Andric   passes.run(*MergedModule);
452f785676fSDimitry Andric 
453f785676fSDimitry Andric   ScopeRestrictionsDone = true;
454f785676fSDimitry Andric }
455f785676fSDimitry Andric 
456f785676fSDimitry Andric /// Optimize merged modules using various IPO passes
4577d523365SDimitry Andric bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
458f785676fSDimitry Andric                                 bool DisableGVNLoadPRE,
4597d523365SDimitry Andric                                 bool DisableVectorization) {
4607d523365SDimitry Andric   if (!this->determineTarget())
461f785676fSDimitry Andric     return false;
462f785676fSDimitry Andric 
463f785676fSDimitry Andric   // Mark which symbols can not be internalized
464f785676fSDimitry Andric   this->applyScopeRestrictions();
465f785676fSDimitry Andric 
466f785676fSDimitry Andric   // Instantiate the pass manager to organize the passes.
467ff0cc061SDimitry Andric   legacy::PassManager passes;
468f785676fSDimitry Andric 
469f785676fSDimitry Andric   // Add an appropriate DataLayout instance for this module...
4707d523365SDimitry Andric   MergedModule->setDataLayout(TargetMach->createDataLayout());
471ff0cc061SDimitry Andric 
472ff0cc061SDimitry Andric   passes.add(
473ff0cc061SDimitry Andric       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
47491bc56edSDimitry Andric 
47539d628a0SDimitry Andric   Triple TargetTriple(TargetMach->getTargetTriple());
47639d628a0SDimitry Andric   PassManagerBuilder PMB;
47739d628a0SDimitry Andric   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
47839d628a0SDimitry Andric   PMB.LoopVectorize = !DisableVectorization;
47939d628a0SDimitry Andric   PMB.SLPVectorize = !DisableVectorization;
48039d628a0SDimitry Andric   if (!DisableInline)
48139d628a0SDimitry Andric     PMB.Inliner = createFunctionInliningPass();
482ff0cc061SDimitry Andric   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
483ff0cc061SDimitry Andric   PMB.OptLevel = OptLevel;
4847d523365SDimitry Andric   PMB.VerifyInput = !DisableVerify;
4857d523365SDimitry Andric   PMB.VerifyOutput = !DisableVerify;
48691bc56edSDimitry Andric 
487ff0cc061SDimitry Andric   PMB.populateLTOPassManager(passes);
488f785676fSDimitry Andric 
489ff0cc061SDimitry Andric   // Run our queue of passes all at once now, efficiently.
4907d523365SDimitry Andric   passes.run(*MergedModule);
491f785676fSDimitry Andric 
492ff0cc061SDimitry Andric   return true;
493ff0cc061SDimitry Andric }
494f785676fSDimitry Andric 
4957d523365SDimitry Andric bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
4967d523365SDimitry Andric   if (!this->determineTarget())
497ff0cc061SDimitry Andric     return false;
498ff0cc061SDimitry Andric 
4997d523365SDimitry Andric   legacy::PassManager preCodeGenPasses;
500f785676fSDimitry Andric 
501f785676fSDimitry Andric   // If the bitcode files contain ARC code and were compiled with optimization,
502f785676fSDimitry Andric   // the ObjCARCContractPass must be run, so do it unconditionally here.
5037d523365SDimitry Andric   preCodeGenPasses.add(createObjCARCContractPass());
5047d523365SDimitry Andric   preCodeGenPasses.run(*MergedModule);
505f785676fSDimitry Andric 
5067d523365SDimitry Andric   // Do code generation. We need to preserve the module in case the client calls
5077d523365SDimitry Andric   // writeMergedModules() after compilation, but we only need to allow this at
5087d523365SDimitry Andric   // parallelism level 1. This is achieved by having splitCodeGen return the
5097d523365SDimitry Andric   // original module at parallelism level 1 which we then assign back to
5107d523365SDimitry Andric   // MergedModule.
5117d523365SDimitry Andric   MergedModule =
5127d523365SDimitry Andric       splitCodeGen(std::move(MergedModule), Out, MCpu, FeatureStr, Options,
5137d523365SDimitry Andric                    RelocModel, CodeModel::Default, CGOptLevel, FileType);
514f785676fSDimitry Andric 
515f785676fSDimitry Andric   return true;
516f785676fSDimitry Andric }
517f785676fSDimitry Andric 
518f785676fSDimitry Andric /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
519f785676fSDimitry Andric /// LTO problems.
5207d523365SDimitry Andric void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) {
5217d523365SDimitry Andric   for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
5227d523365SDimitry Andric        o = getToken(o.second))
5237d523365SDimitry Andric     CodegenOptions.push_back(o.first);
524f785676fSDimitry Andric }
525f785676fSDimitry Andric 
526f785676fSDimitry Andric void LTOCodeGenerator::parseCodeGenDebugOptions() {
527f785676fSDimitry Andric   // if options were requested, set them
5287d523365SDimitry Andric   if (!CodegenOptions.empty()) {
5297d523365SDimitry Andric     // ParseCommandLineOptions() expects argv[0] to be program name.
5307d523365SDimitry Andric     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
5317d523365SDimitry Andric     for (std::string &Arg : CodegenOptions)
5327d523365SDimitry Andric       CodegenArgv.push_back(Arg.c_str());
5337d523365SDimitry Andric     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
5347d523365SDimitry Andric   }
535f785676fSDimitry Andric }
53691bc56edSDimitry Andric 
53791bc56edSDimitry Andric void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
53891bc56edSDimitry Andric                                          void *Context) {
53991bc56edSDimitry Andric   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
54091bc56edSDimitry Andric }
54191bc56edSDimitry Andric 
54291bc56edSDimitry Andric void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
54391bc56edSDimitry Andric   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
54491bc56edSDimitry Andric   lto_codegen_diagnostic_severity_t Severity;
54591bc56edSDimitry Andric   switch (DI.getSeverity()) {
54691bc56edSDimitry Andric   case DS_Error:
54791bc56edSDimitry Andric     Severity = LTO_DS_ERROR;
54891bc56edSDimitry Andric     break;
54991bc56edSDimitry Andric   case DS_Warning:
55091bc56edSDimitry Andric     Severity = LTO_DS_WARNING;
55191bc56edSDimitry Andric     break;
55291bc56edSDimitry Andric   case DS_Remark:
55391bc56edSDimitry Andric     Severity = LTO_DS_REMARK;
55491bc56edSDimitry Andric     break;
55591bc56edSDimitry Andric   case DS_Note:
55691bc56edSDimitry Andric     Severity = LTO_DS_NOTE;
55791bc56edSDimitry Andric     break;
55891bc56edSDimitry Andric   }
55991bc56edSDimitry Andric   // Create the string that will be reported to the external diagnostic handler.
56091bc56edSDimitry Andric   std::string MsgStorage;
56191bc56edSDimitry Andric   raw_string_ostream Stream(MsgStorage);
56291bc56edSDimitry Andric   DiagnosticPrinterRawOStream DP(Stream);
56391bc56edSDimitry Andric   DI.print(DP);
56491bc56edSDimitry Andric   Stream.flush();
56591bc56edSDimitry Andric 
56691bc56edSDimitry Andric   // If this method has been called it means someone has set up an external
56791bc56edSDimitry Andric   // diagnostic handler. Assert on that.
56891bc56edSDimitry Andric   assert(DiagHandler && "Invalid diagnostic handler");
56991bc56edSDimitry Andric   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
57091bc56edSDimitry Andric }
57191bc56edSDimitry Andric 
57291bc56edSDimitry Andric void
57391bc56edSDimitry Andric LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
57491bc56edSDimitry Andric                                        void *Ctxt) {
57591bc56edSDimitry Andric   this->DiagHandler = DiagHandler;
57691bc56edSDimitry Andric   this->DiagContext = Ctxt;
57791bc56edSDimitry Andric   if (!DiagHandler)
57891bc56edSDimitry Andric     return Context.setDiagnosticHandler(nullptr, nullptr);
57991bc56edSDimitry Andric   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
58091bc56edSDimitry Andric   // diagnostic to the external DiagHandler.
58139d628a0SDimitry Andric   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
58239d628a0SDimitry Andric                                /* RespectFilters */ true);
58391bc56edSDimitry Andric }
5847d523365SDimitry Andric 
5857d523365SDimitry Andric namespace {
5867d523365SDimitry Andric class LTODiagnosticInfo : public DiagnosticInfo {
5877d523365SDimitry Andric   const Twine &Msg;
5887d523365SDimitry Andric public:
5897d523365SDimitry Andric   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
5907d523365SDimitry Andric       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
5917d523365SDimitry Andric   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
5927d523365SDimitry Andric };
5937d523365SDimitry Andric }
5947d523365SDimitry Andric 
5957d523365SDimitry Andric void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
5967d523365SDimitry Andric   if (DiagHandler)
5977d523365SDimitry Andric     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
5987d523365SDimitry Andric   else
5997d523365SDimitry Andric     Context.diagnose(LTODiagnosticInfo(ErrMsg));
6007d523365SDimitry Andric }
601