[LTO] Scan all per-function subtargets when collecting runtime library names.
[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/Bitcode/ReaderWriter.h"
20 #include "llvm/CodeGen/RuntimeLibcalls.h"
21 #include "llvm/Config/config.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/DiagnosticInfo.h"
26 #include "llvm/IR/DiagnosticPrinter.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Mangler.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Verifier.h"
31 #include "llvm/InitializePasses.h"
32 #include "llvm/LTO/LTOModule.h"
33 #include "llvm/Linker/Linker.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/SubtargetFeature.h"
37 #include "llvm/PassManager.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/FormattedStream.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   initialize();
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   initialize();
75 }
76
77 void LTOCodeGenerator::initialize() {
78   TargetMach = nullptr;
79   EmitDwarfDebugInfo = false;
80   ScopeRestrictionsDone = false;
81   CodeModel = LTO_CODEGEN_PIC_MODEL_DEFAULT;
82   DiagHandler = nullptr;
83   DiagContext = nullptr;
84
85   initializeLTOPasses();
86 }
87
88 LTOCodeGenerator::~LTOCodeGenerator() {
89   delete TargetMach;
90   TargetMach = nullptr;
91
92   IRLinker.deleteModule();
93
94   for (std::vector<char *>::iterator I = CodegenOptions.begin(),
95                                      E = CodegenOptions.end();
96        I != E; ++I)
97     free(*I);
98 }
99
100 // Initialize LTO passes. Please keep this funciton in sync with
101 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
102 // passes are initialized.
103 void LTOCodeGenerator::initializeLTOPasses() {
104   PassRegistry &R = *PassRegistry::getPassRegistry();
105
106   initializeInternalizePassPass(R);
107   initializeIPSCCPPass(R);
108   initializeGlobalOptPass(R);
109   initializeConstantMergePass(R);
110   initializeDAHPass(R);
111   initializeInstructionCombiningPassPass(R);
112   initializeSimpleInlinerPass(R);
113   initializePruneEHPass(R);
114   initializeGlobalDCEPass(R);
115   initializeArgPromotionPass(R);
116   initializeJumpThreadingPass(R);
117   initializeSROAPass(R);
118   initializeSROA_DTPass(R);
119   initializeSROA_SSAUpPass(R);
120   initializeFunctionAttrsPass(R);
121   initializeGlobalsModRefPass(R);
122   initializeLICMPass(R);
123   initializeMergedLoadStoreMotionPass(R);
124   initializeGVNPass(R);
125   initializeMemCpyOptPass(R);
126   initializeDCEPass(R);
127   initializeCFGSimplifyPassPass(R);
128 }
129
130 bool LTOCodeGenerator::addModule(LTOModule *mod) {
131   assert(&mod->getModule().getContext() == &Context &&
132          "Expected module in same context");
133
134   bool ret = IRLinker.linkInModule(&mod->getModule());
135
136   const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
137   for (int i = 0, e = undefs.size(); i != e; ++i)
138     AsmUndefinedRefs[undefs[i]] = 1;
139
140   return !ret;
141 }
142
143 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
144   Options = options;
145 }
146
147 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
148   switch (debug) {
149   case LTO_DEBUG_MODEL_NONE:
150     EmitDwarfDebugInfo = false;
151     return;
152
153   case LTO_DEBUG_MODEL_DWARF:
154     EmitDwarfDebugInfo = true;
155     return;
156   }
157   llvm_unreachable("Unknown debug format!");
158 }
159
160 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
161   switch (model) {
162   case LTO_CODEGEN_PIC_MODEL_STATIC:
163   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
164   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
165   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
166     CodeModel = model;
167     return;
168   }
169   llvm_unreachable("Unknown PIC model!");
170 }
171
172 bool LTOCodeGenerator::writeMergedModules(const char *path,
173                                           std::string &errMsg) {
174   if (!determineTarget(errMsg))
175     return false;
176
177   // mark which symbols can not be internalized
178   applyScopeRestrictions();
179
180   // create output file
181   std::error_code EC;
182   tool_output_file Out(path, EC, sys::fs::F_None);
183   if (EC) {
184     errMsg = "could not open bitcode file for writing: ";
185     errMsg += path;
186     return false;
187   }
188
189   // write bitcode to it
190   WriteBitcodeToFile(IRLinker.getModule(), Out.os());
191   Out.os().close();
192
193   if (Out.os().has_error()) {
194     errMsg = "could not write bitcode file: ";
195     errMsg += path;
196     Out.os().clear_error();
197     return false;
198   }
199
200   Out.keep();
201   return true;
202 }
203
204 bool LTOCodeGenerator::compile_to_file(const char** name,
205                                        bool disableOpt,
206                                        bool disableInline,
207                                        bool disableGVNLoadPRE,
208                                        bool disableVectorization,
209                                        std::string& errMsg) {
210   // make unique temp .o file to put generated object file
211   SmallString<128> Filename;
212   int FD;
213   std::error_code EC =
214       sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
215   if (EC) {
216     errMsg = EC.message();
217     return false;
218   }
219
220   // generate object file
221   tool_output_file objFile(Filename.c_str(), FD);
222
223   bool genResult =
224       generateObjectFile(objFile.os(), disableOpt, disableInline,
225                          disableGVNLoadPRE, disableVectorization, errMsg);
226   objFile.os().close();
227   if (objFile.os().has_error()) {
228     objFile.os().clear_error();
229     sys::fs::remove(Twine(Filename));
230     return false;
231   }
232
233   objFile.keep();
234   if (!genResult) {
235     sys::fs::remove(Twine(Filename));
236     return false;
237   }
238
239   NativeObjectPath = Filename.c_str();
240   *name = NativeObjectPath.c_str();
241   return true;
242 }
243
244 const void* LTOCodeGenerator::compile(size_t* length,
245                                       bool disableOpt,
246                                       bool disableInline,
247                                       bool disableGVNLoadPRE,
248                                       bool disableVectorization,
249                                       std::string& errMsg) {
250   const char *name;
251   if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
252                        disableVectorization, errMsg))
253     return nullptr;
254
255   // read .o file into memory buffer
256   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
257       MemoryBuffer::getFile(name, -1, false);
258   if (std::error_code EC = BufferOrErr.getError()) {
259     errMsg = EC.message();
260     sys::fs::remove(NativeObjectPath);
261     return nullptr;
262   }
263   NativeObjectFile = std::move(*BufferOrErr);
264
265   // remove temp files
266   sys::fs::remove(NativeObjectPath);
267
268   // return buffer, unless error
269   if (!NativeObjectFile)
270     return nullptr;
271   *length = NativeObjectFile->getBufferSize();
272   return NativeObjectFile->getBufferStart();
273 }
274
275 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
276   if (TargetMach)
277     return true;
278
279   std::string TripleStr = IRLinker.getModule()->getTargetTriple();
280   if (TripleStr.empty())
281     TripleStr = sys::getDefaultTargetTriple();
282   llvm::Triple Triple(TripleStr);
283
284   // create target machine from info for merged modules
285   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
286   if (!march)
287     return false;
288
289   // The relocation model is actually a static member of TargetMachine and
290   // needs to be set before the TargetMachine is instantiated.
291   Reloc::Model RelocModel = Reloc::Default;
292   switch (CodeModel) {
293   case LTO_CODEGEN_PIC_MODEL_STATIC:
294     RelocModel = Reloc::Static;
295     break;
296   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
297     RelocModel = Reloc::PIC_;
298     break;
299   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
300     RelocModel = Reloc::DynamicNoPIC;
301     break;
302   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
303     // RelocModel is already the default, so leave it that way.
304     break;
305   }
306
307   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
308   // the default set of features.
309   SubtargetFeatures Features(MAttr);
310   Features.getDefaultSubtargetFeatures(Triple);
311   std::string FeatureStr = Features.getString();
312   // Set a default CPU for Darwin triples.
313   if (MCpu.empty() && Triple.isOSDarwin()) {
314     if (Triple.getArch() == llvm::Triple::x86_64)
315       MCpu = "core2";
316     else if (Triple.getArch() == llvm::Triple::x86)
317       MCpu = "yonah";
318     else if (Triple.getArch() == llvm::Triple::aarch64)
319       MCpu = "cyclone";
320   }
321
322   TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
323                                           RelocModel, CodeModel::Default,
324                                           CodeGenOpt::Aggressive);
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)
410     return;
411   Module *mergedModule = IRLinker.getModule();
412
413   // Start off with a verification pass.
414   PassManager passes;
415   passes.add(createVerifierPass());
416   passes.add(createDebugInfoVerifierPass());
417
418   // mark which symbols can not be internalized
419   Mangler Mangler(TargetMach->getDataLayout());
420   std::vector<const char*> MustPreserveList;
421   SmallPtrSet<GlobalValue*, 8> AsmUsed;
422   std::vector<StringRef> Libcalls;
423   TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
424   TargetLibraryInfo TLI(TLII);
425
426   accumulateAndSortLibcalls(Libcalls, TLI, *mergedModule, *TargetMach);
427
428   for (Module::iterator f = mergedModule->begin(),
429          e = mergedModule->end(); f != e; ++f)
430     applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
431   for (Module::global_iterator v = mergedModule->global_begin(),
432          e = mergedModule->global_end(); v !=  e; ++v)
433     applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
434   for (Module::alias_iterator a = mergedModule->alias_begin(),
435          e = mergedModule->alias_end(); a != e; ++a)
436     applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
437
438   GlobalVariable *LLVMCompilerUsed =
439     mergedModule->getGlobalVariable("llvm.compiler.used");
440   findUsedValues(LLVMCompilerUsed, AsmUsed);
441   if (LLVMCompilerUsed)
442     LLVMCompilerUsed->eraseFromParent();
443
444   if (!AsmUsed.empty()) {
445     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
446     std::vector<Constant*> asmUsed2;
447     for (auto *GV : AsmUsed) {
448       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
449       asmUsed2.push_back(c);
450     }
451
452     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
453     LLVMCompilerUsed =
454       new llvm::GlobalVariable(*mergedModule, ATy, false,
455                                llvm::GlobalValue::AppendingLinkage,
456                                llvm::ConstantArray::get(ATy, asmUsed2),
457                                "llvm.compiler.used");
458
459     LLVMCompilerUsed->setSection("llvm.metadata");
460   }
461
462   passes.add(createInternalizePass(MustPreserveList));
463
464   // apply scope restrictions
465   passes.run(*mergedModule);
466
467   ScopeRestrictionsDone = true;
468 }
469
470 /// Optimize merged modules using various IPO passes
471 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
472                                           bool DisableOpt,
473                                           bool DisableInline,
474                                           bool DisableGVNLoadPRE,
475                                           bool DisableVectorization,
476                                           std::string &errMsg) {
477   if (!this->determineTarget(errMsg))
478     return false;
479
480   Module *mergedModule = IRLinker.getModule();
481
482   // Mark which symbols can not be internalized
483   this->applyScopeRestrictions();
484
485   // Instantiate the pass manager to organize the passes.
486   PassManager passes;
487
488   // Add an appropriate DataLayout instance for this module...
489   mergedModule->setDataLayout(TargetMach->getDataLayout());
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   if (DisableOpt)
500     PMB.OptLevel = 0;
501   PMB.VerifyInput = true;
502   PMB.VerifyOutput = true;
503
504   PMB.populateLTOPassManager(passes, TargetMach);
505
506   PassManager codeGenPasses;
507
508   codeGenPasses.add(new DataLayoutPass());
509
510   formatted_raw_ostream Out(out);
511
512   // If the bitcode files contain ARC code and were compiled with optimization,
513   // the ObjCARCContractPass must be run, so do it unconditionally here.
514   codeGenPasses.add(createObjCARCContractPass());
515
516   if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
517                                       TargetMachine::CGFT_ObjectFile)) {
518     errMsg = "target file type not supported";
519     return false;
520   }
521
522   // Run our queue of passes all at once now, efficiently.
523   passes.run(*mergedModule);
524
525   // Run the code generator, and write assembly file
526   codeGenPasses.run(*mergedModule);
527
528   return true;
529 }
530
531 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
532 /// LTO problems.
533 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
534   for (std::pair<StringRef, StringRef> o = getToken(options);
535        !o.first.empty(); o = getToken(o.second)) {
536     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
537     // that.
538     if (CodegenOptions.empty())
539       CodegenOptions.push_back(strdup("libLLVMLTO"));
540     CodegenOptions.push_back(strdup(o.first.str().c_str()));
541   }
542 }
543
544 void LTOCodeGenerator::parseCodeGenDebugOptions() {
545   // if options were requested, set them
546   if (!CodegenOptions.empty())
547     cl::ParseCommandLineOptions(CodegenOptions.size(),
548                                 const_cast<char **>(&CodegenOptions[0]));
549 }
550
551 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
552                                          void *Context) {
553   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
554 }
555
556 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
557   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
558   lto_codegen_diagnostic_severity_t Severity;
559   switch (DI.getSeverity()) {
560   case DS_Error:
561     Severity = LTO_DS_ERROR;
562     break;
563   case DS_Warning:
564     Severity = LTO_DS_WARNING;
565     break;
566   case DS_Remark:
567     Severity = LTO_DS_REMARK;
568     break;
569   case DS_Note:
570     Severity = LTO_DS_NOTE;
571     break;
572   }
573   // Create the string that will be reported to the external diagnostic handler.
574   std::string MsgStorage;
575   raw_string_ostream Stream(MsgStorage);
576   DiagnosticPrinterRawOStream DP(Stream);
577   DI.print(DP);
578   Stream.flush();
579
580   // If this method has been called it means someone has set up an external
581   // diagnostic handler. Assert on that.
582   assert(DiagHandler && "Invalid diagnostic handler");
583   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
584 }
585
586 void
587 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
588                                        void *Ctxt) {
589   this->DiagHandler = DiagHandler;
590   this->DiagContext = Ctxt;
591   if (!DiagHandler)
592     return Context.setDiagnosticHandler(nullptr, nullptr);
593   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
594   // diagnostic to the external DiagHandler.
595   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
596                                /* RespectFilters */ true);
597 }