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/LTOCodeGenerator.h"
16 
17 #include "UpdateCompilerUsed.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Analysis/Passes.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/Bitcode/ReaderWriter.h"
24 #include "llvm/CodeGen/ParallelCG.h"
25 #include "llvm/CodeGen/RuntimeLibcalls.h"
26 #include "llvm/Config/config.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.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/LTOModule.h"
39 #include "llvm/Linker/Linker.h"
40 #include "llvm/MC/MCAsmInfo.h"
41 #include "llvm/MC/MCContext.h"
42 #include "llvm/MC/SubtargetFeature.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/FileSystem.h"
45 #include "llvm/Support/Host.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/Signals.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/TargetSelect.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Target/TargetLowering.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "llvm/Target/TargetRegisterInfo.h"
55 #include "llvm/Target/TargetSubtargetInfo.h"
56 #include "llvm/Transforms/IPO.h"
57 #include "llvm/Transforms/IPO/Internalize.h"
58 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
59 #include "llvm/Transforms/ObjCARC.h"
60 #include <system_error>
61 using namespace llvm;
62 
63 const char* LTOCodeGenerator::getVersionString() {
64 #ifdef LLVM_VERSION_INFO
65   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
66 #else
67   return PACKAGE_NAME " version " PACKAGE_VERSION;
68 #endif
69 }
70 
71 namespace llvm {
72 cl::opt<bool> LTODiscardValueNames(
73     "lto-discard-value-names",
74     cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
75 #ifdef NDEBUG
76     cl::init(true),
77 #else
78     cl::init(false),
79 #endif
80     cl::Hidden);
81 }
82 
83 LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
84     : Context(Context), MergedModule(new Module("ld-temp.o", Context)),
85       TheLinker(new Linker(*MergedModule)) {
86   Context.setDiscardValueNames(LTODiscardValueNames);
87   Context.ensureDITypeMap();
88   initializeLTOPasses();
89 }
90 
91 LTOCodeGenerator::~LTOCodeGenerator() {}
92 
93 // Initialize LTO passes. Please keep this function in sync with
94 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
95 // passes are initialized.
96 void LTOCodeGenerator::initializeLTOPasses() {
97   PassRegistry &R = *PassRegistry::getPassRegistry();
98 
99   initializeInternalizePassPass(R);
100   initializeIPSCCPPass(R);
101   initializeGlobalOptPass(R);
102   initializeConstantMergePass(R);
103   initializeDAHPass(R);
104   initializeInstructionCombiningPassPass(R);
105   initializeSimpleInlinerPass(R);
106   initializePruneEHPass(R);
107   initializeGlobalDCEPass(R);
108   initializeArgPromotionPass(R);
109   initializeJumpThreadingPass(R);
110   initializeSROALegacyPassPass(R);
111   initializeSROA_DTPass(R);
112   initializeSROA_SSAUpPass(R);
113   initializePostOrderFunctionAttrsLegacyPassPass(R);
114   initializeReversePostOrderFunctionAttrsPass(R);
115   initializeGlobalsAAWrapperPassPass(R);
116   initializeLICMPass(R);
117   initializeMergedLoadStoreMotionPass(R);
118   initializeGVNLegacyPassPass(R);
119   initializeMemCpyOptPass(R);
120   initializeDCEPass(R);
121   initializeCFGSimplifyPassPass(R);
122 }
123 
124 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
125   assert(&Mod->getModule().getContext() == &Context &&
126          "Expected module in same context");
127 
128   bool ret = TheLinker->linkInModule(Mod->takeModule());
129 
130   const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs();
131   for (int i = 0, e = undefs.size(); i != e; ++i)
132     AsmUndefinedRefs[undefs[i]] = 1;
133 
134   return !ret;
135 }
136 
137 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
138   assert(&Mod->getModule().getContext() == &Context &&
139          "Expected module in same context");
140 
141   AsmUndefinedRefs.clear();
142 
143   MergedModule = Mod->takeModule();
144   TheLinker = make_unique<Linker>(*MergedModule);
145 
146   const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
147   for (int I = 0, E = Undefs.size(); I != E; ++I)
148     AsmUndefinedRefs[Undefs[I]] = 1;
149 }
150 
151 void LTOCodeGenerator::setTargetOptions(TargetOptions Options) {
152   this->Options = Options;
153 }
154 
155 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
156   switch (Debug) {
157   case LTO_DEBUG_MODEL_NONE:
158     EmitDwarfDebugInfo = false;
159     return;
160 
161   case LTO_DEBUG_MODEL_DWARF:
162     EmitDwarfDebugInfo = true;
163     return;
164   }
165   llvm_unreachable("Unknown debug format!");
166 }
167 
168 void LTOCodeGenerator::setOptLevel(unsigned Level) {
169   OptLevel = Level;
170   switch (OptLevel) {
171   case 0:
172     CGOptLevel = CodeGenOpt::None;
173     break;
174   case 1:
175     CGOptLevel = CodeGenOpt::Less;
176     break;
177   case 2:
178     CGOptLevel = CodeGenOpt::Default;
179     break;
180   case 3:
181     CGOptLevel = CodeGenOpt::Aggressive;
182     break;
183   }
184 }
185 
186 bool LTOCodeGenerator::writeMergedModules(const char *Path) {
187   if (!determineTarget())
188     return false;
189 
190   // mark which symbols can not be internalized
191   applyScopeRestrictions();
192 
193   // create output file
194   std::error_code EC;
195   tool_output_file Out(Path, EC, sys::fs::F_None);
196   if (EC) {
197     std::string ErrMsg = "could not open bitcode file for writing: ";
198     ErrMsg += Path;
199     emitError(ErrMsg);
200     return false;
201   }
202 
203   // write bitcode to it
204   WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
205   Out.os().close();
206 
207   if (Out.os().has_error()) {
208     std::string ErrMsg = "could not write bitcode file: ";
209     ErrMsg += Path;
210     emitError(ErrMsg);
211     Out.os().clear_error();
212     return false;
213   }
214 
215   Out.keep();
216   return true;
217 }
218 
219 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
220   // make unique temp output file to put generated code
221   SmallString<128> Filename;
222   int FD;
223 
224   const char *Extension =
225       (FileType == TargetMachine::CGFT_AssemblyFile ? "s" : "o");
226 
227   std::error_code EC =
228       sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
229   if (EC) {
230     emitError(EC.message());
231     return false;
232   }
233 
234   // generate object file
235   tool_output_file objFile(Filename.c_str(), FD);
236 
237   bool genResult = compileOptimized(&objFile.os());
238   objFile.os().close();
239   if (objFile.os().has_error()) {
240     objFile.os().clear_error();
241     sys::fs::remove(Twine(Filename));
242     return false;
243   }
244 
245   objFile.keep();
246   if (!genResult) {
247     sys::fs::remove(Twine(Filename));
248     return false;
249   }
250 
251   NativeObjectPath = Filename.c_str();
252   *Name = NativeObjectPath.c_str();
253   return true;
254 }
255 
256 std::unique_ptr<MemoryBuffer>
257 LTOCodeGenerator::compileOptimized() {
258   const char *name;
259   if (!compileOptimizedToFile(&name))
260     return nullptr;
261 
262   // read .o file into memory buffer
263   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
264       MemoryBuffer::getFile(name, -1, false);
265   if (std::error_code EC = BufferOrErr.getError()) {
266     emitError(EC.message());
267     sys::fs::remove(NativeObjectPath);
268     return nullptr;
269   }
270 
271   // remove temp files
272   sys::fs::remove(NativeObjectPath);
273 
274   return std::move(*BufferOrErr);
275 }
276 
277 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableVerify,
278                                        bool DisableInline,
279                                        bool DisableGVNLoadPRE,
280                                        bool DisableVectorization) {
281   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
282                 DisableVectorization))
283     return false;
284 
285   return compileOptimizedToFile(Name);
286 }
287 
288 std::unique_ptr<MemoryBuffer>
289 LTOCodeGenerator::compile(bool DisableVerify, bool DisableInline,
290                           bool DisableGVNLoadPRE, bool DisableVectorization) {
291   if (!optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
292                 DisableVectorization))
293     return nullptr;
294 
295   return compileOptimized();
296 }
297 
298 bool LTOCodeGenerator::determineTarget() {
299   if (TargetMach)
300     return true;
301 
302   TripleStr = MergedModule->getTargetTriple();
303   if (TripleStr.empty()) {
304     TripleStr = sys::getDefaultTargetTriple();
305     MergedModule->setTargetTriple(TripleStr);
306   }
307   llvm::Triple Triple(TripleStr);
308 
309   // create target machine from info for merged modules
310   std::string ErrMsg;
311   MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
312   if (!MArch) {
313     emitError(ErrMsg);
314     return false;
315   }
316 
317   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
318   // the default set of features.
319   SubtargetFeatures Features(MAttr);
320   Features.getDefaultSubtargetFeatures(Triple);
321   FeatureStr = Features.getString();
322   // Set a default CPU for Darwin triples.
323   if (MCpu.empty() && Triple.isOSDarwin()) {
324     if (Triple.getArch() == llvm::Triple::x86_64)
325       MCpu = "core2";
326     else if (Triple.getArch() == llvm::Triple::x86)
327       MCpu = "yonah";
328     else if (Triple.getArch() == llvm::Triple::aarch64)
329       MCpu = "cyclone";
330   }
331 
332   TargetMach = createTargetMachine();
333   return true;
334 }
335 
336 std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
337   return std::unique_ptr<TargetMachine>(
338       MArch->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
339                                  RelocModel, CodeModel::Default, CGOptLevel));
340 }
341 
342 void LTOCodeGenerator::applyScopeRestrictions() {
343   if (ScopeRestrictionsDone || !ShouldInternalize)
344     return;
345 
346   if (ShouldRestoreGlobalsLinkage) {
347     // Record the linkage type of non-local symbols so they can be restored
348     // prior
349     // to module splitting.
350     auto RecordLinkage = [&](const GlobalValue &GV) {
351       if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
352           GV.hasName())
353         ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
354     };
355     for (auto &GV : *MergedModule)
356       RecordLinkage(GV);
357     for (auto &GV : MergedModule->globals())
358       RecordLinkage(GV);
359     for (auto &GV : MergedModule->aliases())
360       RecordLinkage(GV);
361   }
362 
363   // Update the llvm.compiler_used globals to force preserving libcalls and
364   // symbols referenced from asm
365   UpdateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
366 
367   // Declare a callback for the internalize pass that will ask for every
368   // candidate GlobalValue if it can be internalized or not.
369   Mangler Mangler;
370   SmallString<64> MangledName;
371   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
372     // Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
373     // with the linker supplied name, which on Darwin includes a leading
374     // underscore.
375     MangledName.clear();
376     MangledName.reserve(GV.getName().size() + 1);
377     Mangler::getNameWithPrefix(MangledName, GV.getName(),
378                                MergedModule->getDataLayout());
379     return MustPreserveSymbols.count(MangledName);
380   };
381 
382   internalizeModule(*MergedModule, MustPreserveGV);
383 
384   ScopeRestrictionsDone = true;
385 }
386 
387 /// Restore original linkage for symbols that may have been internalized
388 void LTOCodeGenerator::restoreLinkageForExternals() {
389   if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
390     return;
391 
392   assert(ScopeRestrictionsDone &&
393          "Cannot externalize without internalization!");
394 
395   if (ExternalSymbols.empty())
396     return;
397 
398   auto externalize = [this](GlobalValue &GV) {
399     if (!GV.hasLocalLinkage() || !GV.hasName())
400       return;
401 
402     auto I = ExternalSymbols.find(GV.getName());
403     if (I == ExternalSymbols.end())
404       return;
405 
406     GV.setLinkage(I->second);
407   };
408 
409   std::for_each(MergedModule->begin(), MergedModule->end(), externalize);
410   std::for_each(MergedModule->global_begin(), MergedModule->global_end(),
411                 externalize);
412   std::for_each(MergedModule->alias_begin(), MergedModule->alias_end(),
413                 externalize);
414 }
415 
416 /// Optimize merged modules using various IPO passes
417 bool LTOCodeGenerator::optimize(bool DisableVerify, bool DisableInline,
418                                 bool DisableGVNLoadPRE,
419                                 bool DisableVectorization) {
420   if (!this->determineTarget())
421     return false;
422 
423   // We always run the verifier once on the merged module, the `DisableVerify`
424   // parameter only applies to subsequent verify.
425   if (verifyModule(*MergedModule, &dbgs()))
426     report_fatal_error("Broken module found, compilation aborted!");
427 
428   // Mark which symbols can not be internalized
429   this->applyScopeRestrictions();
430 
431   // Instantiate the pass manager to organize the passes.
432   legacy::PassManager passes;
433 
434   // Add an appropriate DataLayout instance for this module...
435   MergedModule->setDataLayout(TargetMach->createDataLayout());
436 
437   passes.add(
438       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
439 
440   Triple TargetTriple(TargetMach->getTargetTriple());
441   PassManagerBuilder PMB;
442   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
443   PMB.LoopVectorize = !DisableVectorization;
444   PMB.SLPVectorize = !DisableVectorization;
445   if (!DisableInline)
446     PMB.Inliner = createFunctionInliningPass();
447   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
448   PMB.OptLevel = OptLevel;
449   PMB.VerifyInput = !DisableVerify;
450   PMB.VerifyOutput = !DisableVerify;
451 
452   PMB.populateLTOPassManager(passes);
453 
454   // Run our queue of passes all at once now, efficiently.
455   passes.run(*MergedModule);
456 
457   return true;
458 }
459 
460 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out) {
461   if (!this->determineTarget())
462     return false;
463 
464   legacy::PassManager preCodeGenPasses;
465 
466   // If the bitcode files contain ARC code and were compiled with optimization,
467   // the ObjCARCContractPass must be run, so do it unconditionally here.
468   preCodeGenPasses.add(createObjCARCContractPass());
469   preCodeGenPasses.run(*MergedModule);
470 
471   // Re-externalize globals that may have been internalized to increase scope
472   // for splitting
473   restoreLinkageForExternals();
474 
475   // Do code generation. We need to preserve the module in case the client calls
476   // writeMergedModules() after compilation, but we only need to allow this at
477   // parallelism level 1. This is achieved by having splitCodeGen return the
478   // original module at parallelism level 1 which we then assign back to
479   // MergedModule.
480   MergedModule = splitCodeGen(std::move(MergedModule), Out, {},
481                               [&]() { return createTargetMachine(); }, FileType,
482                               ShouldRestoreGlobalsLinkage);
483 
484   // If statistics were requested, print them out after codegen.
485   if (llvm::AreStatisticsEnabled())
486     llvm::PrintStatistics();
487 
488   return true;
489 }
490 
491 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
492 /// LTO problems.
493 void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) {
494   for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
495        o = getToken(o.second))
496     CodegenOptions.push_back(o.first);
497 }
498 
499 void LTOCodeGenerator::parseCodeGenDebugOptions() {
500   // if options were requested, set them
501   if (!CodegenOptions.empty()) {
502     // ParseCommandLineOptions() expects argv[0] to be program name.
503     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
504     for (std::string &Arg : CodegenOptions)
505       CodegenArgv.push_back(Arg.c_str());
506     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
507   }
508 }
509 
510 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
511                                          void *Context) {
512   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
513 }
514 
515 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
516   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
517   lto_codegen_diagnostic_severity_t Severity;
518   switch (DI.getSeverity()) {
519   case DS_Error:
520     Severity = LTO_DS_ERROR;
521     break;
522   case DS_Warning:
523     Severity = LTO_DS_WARNING;
524     break;
525   case DS_Remark:
526     Severity = LTO_DS_REMARK;
527     break;
528   case DS_Note:
529     Severity = LTO_DS_NOTE;
530     break;
531   }
532   // Create the string that will be reported to the external diagnostic handler.
533   std::string MsgStorage;
534   raw_string_ostream Stream(MsgStorage);
535   DiagnosticPrinterRawOStream DP(Stream);
536   DI.print(DP);
537   Stream.flush();
538 
539   // If this method has been called it means someone has set up an external
540   // diagnostic handler. Assert on that.
541   assert(DiagHandler && "Invalid diagnostic handler");
542   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
543 }
544 
545 void
546 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
547                                        void *Ctxt) {
548   this->DiagHandler = DiagHandler;
549   this->DiagContext = Ctxt;
550   if (!DiagHandler)
551     return Context.setDiagnosticHandler(nullptr, nullptr);
552   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
553   // diagnostic to the external DiagHandler.
554   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
555                                /* RespectFilters */ true);
556 }
557 
558 namespace {
559 class LTODiagnosticInfo : public DiagnosticInfo {
560   const Twine &Msg;
561 public:
562   LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
563       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
564   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
565 };
566 }
567 
568 void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
569   if (DiagHandler)
570     (*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
571   else
572     Context.diagnose(LTODiagnosticInfo(ErrMsg));
573 }
574