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