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