3f6b444b05612d979f8cbcbee5d5a0604d944160
[oota-llvm.git] / lib / LTO / LTOCodeGenerator.cpp
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 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/CodeGen/ParallelCG.h"
22 #include "llvm/CodeGen/RuntimeLibcalls.h"
23 #include "llvm/Config/config.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/DiagnosticInfo.h"
28 #include "llvm/IR/DiagnosticPrinter.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/LegacyPassManager.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Verifier.h"
34 #include "llvm/InitializePasses.h"
35 #include "llvm/LTO/LTOModule.h"
36 #include "llvm/Linker/Linker.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/SubtargetFeature.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/ToolOutputFile.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Target/TargetRegisterInfo.h"
52 #include "llvm/Target/TargetSubtargetInfo.h"
53 #include "llvm/Transforms/IPO.h"
54 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
55 #include "llvm/Transforms/ObjCARC.h"
56 #include <system_error>
57 using namespace llvm;
58
59 const char* LTOCodeGenerator::getVersionString() {
60 #ifdef LLVM_VERSION_INFO
61   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
62 #else
63   return PACKAGE_NAME " version " PACKAGE_VERSION;
64 #endif
65 }
66
67 LTOCodeGenerator::LTOCodeGenerator()
68     : Context(getGlobalContext()),
69       MergedModule(new Module("ld-temp.o", Context)),
70       IRLinker(MergedModule.get()) {
71   initializeLTOPasses();
72 }
73
74 LTOCodeGenerator::LTOCodeGenerator(std::unique_ptr<LLVMContext> Context)
75     : OwnedContext(std::move(Context)), Context(*OwnedContext),
76       MergedModule(new Module("ld-temp.o", *OwnedContext)),
77       IRLinker(MergedModule.get()) {
78   initializeLTOPasses();
79 }
80
81 LTOCodeGenerator::~LTOCodeGenerator() {}
82
83 // Initialize LTO passes. Please keep this function in sync with
84 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
85 // passes are initialized.
86 void LTOCodeGenerator::initializeLTOPasses() {
87   PassRegistry &R = *PassRegistry::getPassRegistry();
88
89   initializeInternalizePassPass(R);
90   initializeIPSCCPPass(R);
91   initializeGlobalOptPass(R);
92   initializeConstantMergePass(R);
93   initializeDAHPass(R);
94   initializeInstructionCombiningPassPass(R);
95   initializeSimpleInlinerPass(R);
96   initializePruneEHPass(R);
97   initializeGlobalDCEPass(R);
98   initializeArgPromotionPass(R);
99   initializeJumpThreadingPass(R);
100   initializeSROAPass(R);
101   initializeSROA_DTPass(R);
102   initializeSROA_SSAUpPass(R);
103   initializeFunctionAttrsPass(R);
104   initializeGlobalsModRefPass(R);
105   initializeLICMPass(R);
106   initializeMergedLoadStoreMotionPass(R);
107   initializeGVNPass(R);
108   initializeMemCpyOptPass(R);
109   initializeDCEPass(R);
110   initializeCFGSimplifyPassPass(R);
111 }
112
113 bool LTOCodeGenerator::addModule(LTOModule *Mod) {
114   assert(&Mod->getModule().getContext() == &Context &&
115          "Expected module in same context");
116
117   bool ret = IRLinker.linkInModule(&Mod->getModule());
118
119   const std::vector<const char *> &undefs = Mod->getAsmUndefinedRefs();
120   for (int i = 0, e = undefs.size(); i != e; ++i)
121     AsmUndefinedRefs[undefs[i]] = 1;
122
123   return !ret;
124 }
125
126 void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
127   assert(&Mod->getModule().getContext() == &Context &&
128          "Expected module in same context");
129
130   AsmUndefinedRefs.clear();
131
132   MergedModule = Mod->takeModule();
133   IRLinker.setModule(MergedModule.get());
134
135   const std::vector<const char*> &Undefs = Mod->getAsmUndefinedRefs();
136   for (int I = 0, E = Undefs.size(); I != E; ++I)
137     AsmUndefinedRefs[Undefs[I]] = 1;
138 }
139
140 void LTOCodeGenerator::setTargetOptions(TargetOptions Options) {
141   this->Options = Options;
142 }
143
144 void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
145   switch (Debug) {
146   case LTO_DEBUG_MODEL_NONE:
147     EmitDwarfDebugInfo = false;
148     return;
149
150   case LTO_DEBUG_MODEL_DWARF:
151     EmitDwarfDebugInfo = true;
152     return;
153   }
154   llvm_unreachable("Unknown debug format!");
155 }
156
157 void LTOCodeGenerator::setOptLevel(unsigned Level) {
158   OptLevel = Level;
159   switch (OptLevel) {
160   case 0:
161     CGOptLevel = CodeGenOpt::None;
162     break;
163   case 1:
164     CGOptLevel = CodeGenOpt::Less;
165     break;
166   case 2:
167     CGOptLevel = CodeGenOpt::Default;
168     break;
169   case 3:
170     CGOptLevel = CodeGenOpt::Aggressive;
171     break;
172   }
173 }
174
175 bool LTOCodeGenerator::writeMergedModules(const char *Path,
176                                           std::string &ErrMsg) {
177   if (!determineTarget(ErrMsg))
178     return false;
179
180   // mark which symbols can not be internalized
181   applyScopeRestrictions();
182
183   // create output file
184   std::error_code EC;
185   tool_output_file Out(Path, EC, sys::fs::F_None);
186   if (EC) {
187     ErrMsg = "could not open bitcode file for writing: ";
188     ErrMsg += Path;
189     return false;
190   }
191
192   // write bitcode to it
193   WriteBitcodeToFile(MergedModule.get(), Out.os(), ShouldEmbedUselists);
194   Out.os().close();
195
196   if (Out.os().has_error()) {
197     ErrMsg = "could not write bitcode file: ";
198     ErrMsg += Path;
199     Out.os().clear_error();
200     return false;
201   }
202
203   Out.keep();
204   return true;
205 }
206
207 bool LTOCodeGenerator::compileOptimizedToFile(const char **Name,
208                                               std::string &ErrMsg) {
209   // make unique temp .o file to put generated object file
210   SmallString<128> Filename;
211   int FD;
212   std::error_code EC =
213       sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
214   if (EC) {
215     ErrMsg = EC.message();
216     return false;
217   }
218
219   // generate object file
220   tool_output_file objFile(Filename.c_str(), FD);
221
222   bool genResult = compileOptimized(&objFile.os(), ErrMsg);
223   objFile.os().close();
224   if (objFile.os().has_error()) {
225     objFile.os().clear_error();
226     sys::fs::remove(Twine(Filename));
227     return false;
228   }
229
230   objFile.keep();
231   if (!genResult) {
232     sys::fs::remove(Twine(Filename));
233     return false;
234   }
235
236   NativeObjectPath = Filename.c_str();
237   *Name = NativeObjectPath.c_str();
238   return true;
239 }
240
241 std::unique_ptr<MemoryBuffer>
242 LTOCodeGenerator::compileOptimized(std::string &ErrMsg) {
243   const char *name;
244   if (!compileOptimizedToFile(&name, ErrMsg))
245     return nullptr;
246
247   // read .o file into memory buffer
248   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
249       MemoryBuffer::getFile(name, -1, false);
250   if (std::error_code EC = BufferOrErr.getError()) {
251     ErrMsg = EC.message();
252     sys::fs::remove(NativeObjectPath);
253     return nullptr;
254   }
255
256   // remove temp files
257   sys::fs::remove(NativeObjectPath);
258
259   return std::move(*BufferOrErr);
260 }
261
262 bool LTOCodeGenerator::compile_to_file(const char **Name, bool DisableInline,
263                                        bool DisableGVNLoadPRE,
264                                        bool DisableVectorization,
265                                        std::string &ErrMsg) {
266   if (!optimize(DisableInline, DisableGVNLoadPRE, DisableVectorization, ErrMsg))
267     return false;
268
269   return compileOptimizedToFile(Name, ErrMsg);
270 }
271
272 std::unique_ptr<MemoryBuffer>
273 LTOCodeGenerator::compile(bool DisableInline, bool DisableGVNLoadPRE,
274                           bool DisableVectorization, std::string &ErrMsg) {
275   if (!optimize(DisableInline, DisableGVNLoadPRE, DisableVectorization, ErrMsg))
276     return nullptr;
277
278   return compileOptimized(ErrMsg);
279 }
280
281 bool LTOCodeGenerator::determineTarget(std::string &ErrMsg) {
282   if (TargetMach)
283     return true;
284
285   std::string TripleStr = MergedModule->getTargetTriple();
286   if (TripleStr.empty()) {
287     TripleStr = sys::getDefaultTargetTriple();
288     MergedModule->setTargetTriple(TripleStr);
289   }
290   llvm::Triple Triple(TripleStr);
291
292   // create target machine from info for merged modules
293   const Target *march = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
294   if (!march)
295     return false;
296
297   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
298   // the default set of features.
299   SubtargetFeatures Features(MAttr);
300   Features.getDefaultSubtargetFeatures(Triple);
301   FeatureStr = Features.getString();
302   // Set a default CPU for Darwin triples.
303   if (MCpu.empty() && Triple.isOSDarwin()) {
304     if (Triple.getArch() == llvm::Triple::x86_64)
305       MCpu = "core2";
306     else if (Triple.getArch() == llvm::Triple::x86)
307       MCpu = "yonah";
308     else if (Triple.getArch() == llvm::Triple::aarch64)
309       MCpu = "cyclone";
310   }
311
312   TargetMach.reset(march->createTargetMachine(TripleStr, MCpu, FeatureStr,
313                                               Options, RelocModel,
314                                               CodeModel::Default, CGOptLevel));
315   return true;
316 }
317
318 void LTOCodeGenerator::
319 applyRestriction(GlobalValue &GV,
320                  ArrayRef<StringRef> Libcalls,
321                  std::vector<const char*> &MustPreserveList,
322                  SmallPtrSetImpl<GlobalValue*> &AsmUsed,
323                  Mangler &Mangler) {
324   // There are no restrictions to apply to declarations.
325   if (GV.isDeclaration())
326     return;
327
328   // There is nothing more restrictive than private linkage.
329   if (GV.hasPrivateLinkage())
330     return;
331
332   SmallString<64> Buffer;
333   TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
334
335   if (MustPreserveSymbols.count(Buffer))
336     MustPreserveList.push_back(GV.getName().data());
337   if (AsmUndefinedRefs.count(Buffer))
338     AsmUsed.insert(&GV);
339
340   // Conservatively append user-supplied runtime library functions to
341   // llvm.compiler.used.  These could be internalized and deleted by
342   // optimizations like -globalopt, causing problems when later optimizations
343   // add new library calls (e.g., llvm.memset => memset and printf => puts).
344   // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
345   if (isa<Function>(GV) &&
346       std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
347     AsmUsed.insert(&GV);
348 }
349
350 static void findUsedValues(GlobalVariable *LLVMUsed,
351                            SmallPtrSetImpl<GlobalValue*> &UsedValues) {
352   if (!LLVMUsed) return;
353
354   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
355   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
356     if (GlobalValue *GV =
357         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
358       UsedValues.insert(GV);
359 }
360
361 // Collect names of runtime library functions. User-defined functions with the
362 // same names are added to llvm.compiler.used to prevent them from being
363 // deleted by optimizations.
364 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
365                                       const TargetLibraryInfo& TLI,
366                                       const Module &Mod,
367                                       const TargetMachine &TM) {
368   // TargetLibraryInfo has info on C runtime library calls on the current
369   // target.
370   for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
371        I != E; ++I) {
372     LibFunc::Func F = static_cast<LibFunc::Func>(I);
373     if (TLI.has(F))
374       Libcalls.push_back(TLI.getName(F));
375   }
376
377   SmallPtrSet<const TargetLowering *, 1> TLSet;
378
379   for (const Function &F : Mod) {
380     const TargetLowering *Lowering =
381         TM.getSubtargetImpl(F)->getTargetLowering();
382
383     if (Lowering && TLSet.insert(Lowering).second)
384       // TargetLowering has info on library calls that CodeGen expects to be
385       // available, both from the C runtime and compiler-rt.
386       for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
387            I != E; ++I)
388         if (const char *Name =
389                 Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
390           Libcalls.push_back(Name);
391   }
392
393   array_pod_sort(Libcalls.begin(), Libcalls.end());
394   Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
395                  Libcalls.end());
396 }
397
398 void LTOCodeGenerator::applyScopeRestrictions() {
399   if (ScopeRestrictionsDone || !ShouldInternalize)
400     return;
401
402   // Start off with a verification pass.
403   legacy::PassManager passes;
404   passes.add(createVerifierPass());
405
406   // mark which symbols can not be internalized
407   Mangler Mangler;
408   std::vector<const char*> MustPreserveList;
409   SmallPtrSet<GlobalValue*, 8> AsmUsed;
410   std::vector<StringRef> Libcalls;
411   TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
412   TargetLibraryInfo TLI(TLII);
413
414   accumulateAndSortLibcalls(Libcalls, TLI, *MergedModule, *TargetMach);
415
416   for (Function &f : *MergedModule)
417     applyRestriction(f, Libcalls, MustPreserveList, AsmUsed, Mangler);
418   for (GlobalVariable &v : MergedModule->globals())
419     applyRestriction(v, Libcalls, MustPreserveList, AsmUsed, Mangler);
420   for (GlobalAlias &a : MergedModule->aliases())
421     applyRestriction(a, Libcalls, MustPreserveList, AsmUsed, Mangler);
422
423   GlobalVariable *LLVMCompilerUsed =
424     MergedModule->getGlobalVariable("llvm.compiler.used");
425   findUsedValues(LLVMCompilerUsed, AsmUsed);
426   if (LLVMCompilerUsed)
427     LLVMCompilerUsed->eraseFromParent();
428
429   if (!AsmUsed.empty()) {
430     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
431     std::vector<Constant*> asmUsed2;
432     for (auto *GV : AsmUsed) {
433       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
434       asmUsed2.push_back(c);
435     }
436
437     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
438     LLVMCompilerUsed =
439       new llvm::GlobalVariable(*MergedModule, ATy, false,
440                                llvm::GlobalValue::AppendingLinkage,
441                                llvm::ConstantArray::get(ATy, asmUsed2),
442                                "llvm.compiler.used");
443
444     LLVMCompilerUsed->setSection("llvm.metadata");
445   }
446
447   passes.add(createInternalizePass(MustPreserveList));
448
449   // apply scope restrictions
450   passes.run(*MergedModule);
451
452   ScopeRestrictionsDone = true;
453 }
454
455 /// Optimize merged modules using various IPO passes
456 bool LTOCodeGenerator::optimize(bool DisableInline, bool DisableGVNLoadPRE,
457                                 bool DisableVectorization,
458                                 std::string &ErrMsg) {
459   if (!this->determineTarget(ErrMsg))
460     return false;
461
462   // Mark which symbols can not be internalized
463   this->applyScopeRestrictions();
464
465   // Instantiate the pass manager to organize the passes.
466   legacy::PassManager passes;
467
468   // Add an appropriate DataLayout instance for this module...
469   MergedModule->setDataLayout(TargetMach->createDataLayout());
470
471   passes.add(
472       createTargetTransformInfoWrapperPass(TargetMach->getTargetIRAnalysis()));
473
474   Triple TargetTriple(TargetMach->getTargetTriple());
475   PassManagerBuilder PMB;
476   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
477   PMB.LoopVectorize = !DisableVectorization;
478   PMB.SLPVectorize = !DisableVectorization;
479   if (!DisableInline)
480     PMB.Inliner = createFunctionInliningPass();
481   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
482   PMB.OptLevel = OptLevel;
483   PMB.VerifyInput = true;
484   PMB.VerifyOutput = true;
485
486   PMB.populateLTOPassManager(passes);
487
488   // Run our queue of passes all at once now, efficiently.
489   passes.run(*MergedModule);
490
491   return true;
492 }
493
494 bool LTOCodeGenerator::compileOptimized(ArrayRef<raw_pwrite_stream *> Out,
495                                         std::string &ErrMsg) {
496   if (!this->determineTarget(ErrMsg))
497     return false;
498
499   legacy::PassManager preCodeGenPasses;
500
501   // If the bitcode files contain ARC code and were compiled with optimization,
502   // the ObjCARCContractPass must be run, so do it unconditionally here.
503   preCodeGenPasses.add(createObjCARCContractPass());
504   preCodeGenPasses.run(*MergedModule);
505
506   // Do code generation. We need to preserve the module in case the client calls
507   // writeMergedModules() after compilation, but we only need to allow this at
508   // parallelism level 1. This is achieved by having splitCodeGen return the
509   // original module at parallelism level 1 which we then assign back to
510   // MergedModule.
511   MergedModule =
512       splitCodeGen(std::move(MergedModule), Out, MCpu, FeatureStr, Options,
513                    RelocModel, CodeModel::Default, CGOptLevel);
514
515   return true;
516 }
517
518 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
519 /// LTO problems.
520 void LTOCodeGenerator::setCodeGenDebugOptions(const char *Options) {
521   for (std::pair<StringRef, StringRef> o = getToken(Options); !o.first.empty();
522        o = getToken(o.second))
523     CodegenOptions.push_back(o.first);
524 }
525
526 void LTOCodeGenerator::parseCodeGenDebugOptions() {
527   // if options were requested, set them
528   if (!CodegenOptions.empty()) {
529     // ParseCommandLineOptions() expects argv[0] to be program name.
530     std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
531     for (std::string &Arg : CodegenOptions)
532       CodegenArgv.push_back(Arg.c_str());
533     cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
534   }
535 }
536
537 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
538                                          void *Context) {
539   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
540 }
541
542 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
543   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
544   lto_codegen_diagnostic_severity_t Severity;
545   switch (DI.getSeverity()) {
546   case DS_Error:
547     Severity = LTO_DS_ERROR;
548     break;
549   case DS_Warning:
550     Severity = LTO_DS_WARNING;
551     break;
552   case DS_Remark:
553     Severity = LTO_DS_REMARK;
554     break;
555   case DS_Note:
556     Severity = LTO_DS_NOTE;
557     break;
558   }
559   // Create the string that will be reported to the external diagnostic handler.
560   std::string MsgStorage;
561   raw_string_ostream Stream(MsgStorage);
562   DiagnosticPrinterRawOStream DP(Stream);
563   DI.print(DP);
564   Stream.flush();
565
566   // If this method has been called it means someone has set up an external
567   // diagnostic handler. Assert on that.
568   assert(DiagHandler && "Invalid diagnostic handler");
569   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
570 }
571
572 void
573 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
574                                        void *Ctxt) {
575   this->DiagHandler = DiagHandler;
576   this->DiagContext = Ctxt;
577   if (!DiagHandler)
578     return Context.setDiagnosticHandler(nullptr, nullptr);
579   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
580   // diagnostic to the external DiagHandler.
581   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
582                                /* RespectFilters */ true);
583 }