Add an option to the LTO code generator to disable vectorization during LTO
[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) {
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::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                                        bool disableVectorization,
192                                        std::string& errMsg) {
193   // make unique temp .o file to put generated object file
194   SmallString<128> Filename;
195   int FD;
196   std::error_code EC =
197       sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
198   if (EC) {
199     errMsg = EC.message();
200     return false;
201   }
202
203   // generate object file
204   tool_output_file objFile(Filename.c_str(), FD);
205
206   bool genResult =
207       generateObjectFile(objFile.os(), disableOpt, disableInline,
208                          disableGVNLoadPRE, disableVectorization, errMsg);
209   objFile.os().close();
210   if (objFile.os().has_error()) {
211     objFile.os().clear_error();
212     sys::fs::remove(Twine(Filename));
213     return false;
214   }
215
216   objFile.keep();
217   if (!genResult) {
218     sys::fs::remove(Twine(Filename));
219     return false;
220   }
221
222   NativeObjectPath = Filename.c_str();
223   *name = NativeObjectPath.c_str();
224   return true;
225 }
226
227 const void* LTOCodeGenerator::compile(size_t* length,
228                                       bool disableOpt,
229                                       bool disableInline,
230                                       bool disableGVNLoadPRE,
231                                       bool disableVectorization,
232                                       std::string& errMsg) {
233   const char *name;
234   if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
235                        disableVectorization, errMsg))
236     return nullptr;
237
238   // read .o file into memory buffer
239   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
240       MemoryBuffer::getFile(name, -1, false);
241   if (std::error_code EC = BufferOrErr.getError()) {
242     errMsg = EC.message();
243     sys::fs::remove(NativeObjectPath);
244     return nullptr;
245   }
246   NativeObjectFile = std::move(*BufferOrErr);
247
248   // remove temp files
249   sys::fs::remove(NativeObjectPath);
250
251   // return buffer, unless error
252   if (!NativeObjectFile)
253     return nullptr;
254   *length = NativeObjectFile->getBufferSize();
255   return NativeObjectFile->getBufferStart();
256 }
257
258 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
259   if (TargetMach)
260     return true;
261
262   std::string TripleStr = IRLinker.getModule()->getTargetTriple();
263   if (TripleStr.empty())
264     TripleStr = sys::getDefaultTargetTriple();
265   llvm::Triple Triple(TripleStr);
266
267   // create target machine from info for merged modules
268   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
269   if (!march)
270     return false;
271
272   // The relocation model is actually a static member of TargetMachine and
273   // needs to be set before the TargetMachine is instantiated.
274   Reloc::Model RelocModel = Reloc::Default;
275   switch (CodeModel) {
276   case LTO_CODEGEN_PIC_MODEL_STATIC:
277     RelocModel = Reloc::Static;
278     break;
279   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
280     RelocModel = Reloc::PIC_;
281     break;
282   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
283     RelocModel = Reloc::DynamicNoPIC;
284     break;
285   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
286     // RelocModel is already the default, so leave it that way.
287     break;
288   }
289
290   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
291   // the default set of features.
292   SubtargetFeatures Features(MAttr);
293   Features.getDefaultSubtargetFeatures(Triple);
294   std::string FeatureStr = Features.getString();
295   // Set a default CPU for Darwin triples.
296   if (MCpu.empty() && Triple.isOSDarwin()) {
297     if (Triple.getArch() == llvm::Triple::x86_64)
298       MCpu = "core2";
299     else if (Triple.getArch() == llvm::Triple::x86)
300       MCpu = "yonah";
301     else if (Triple.getArch() == llvm::Triple::aarch64)
302       MCpu = "cyclone";
303   }
304
305   TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
306                                           RelocModel, CodeModel::Default,
307                                           CodeGenOpt::Aggressive);
308   return true;
309 }
310
311 void LTOCodeGenerator::
312 applyRestriction(GlobalValue &GV,
313                  ArrayRef<StringRef> Libcalls,
314                  std::vector<const char*> &MustPreserveList,
315                  SmallPtrSetImpl<GlobalValue*> &AsmUsed,
316                  Mangler &Mangler) {
317   // There are no restrictions to apply to declarations.
318   if (GV.isDeclaration())
319     return;
320
321   // There is nothing more restrictive than private linkage.
322   if (GV.hasPrivateLinkage())
323     return;
324
325   SmallString<64> Buffer;
326   TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
327
328   if (MustPreserveSymbols.count(Buffer))
329     MustPreserveList.push_back(GV.getName().data());
330   if (AsmUndefinedRefs.count(Buffer))
331     AsmUsed.insert(&GV);
332
333   // Conservatively append user-supplied runtime library functions to
334   // llvm.compiler.used.  These could be internalized and deleted by
335   // optimizations like -globalopt, causing problems when later optimizations
336   // add new library calls (e.g., llvm.memset => memset and printf => puts).
337   // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
338   if (isa<Function>(GV) &&
339       std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
340     AsmUsed.insert(&GV);
341 }
342
343 static void findUsedValues(GlobalVariable *LLVMUsed,
344                            SmallPtrSetImpl<GlobalValue*> &UsedValues) {
345   if (!LLVMUsed) return;
346
347   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
348   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
349     if (GlobalValue *GV =
350         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
351       UsedValues.insert(GV);
352 }
353
354 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
355                                       const TargetLibraryInfo& TLI,
356                                       const TargetLowering *Lowering)
357 {
358   // TargetLibraryInfo has info on C runtime library calls on the current
359   // target.
360   for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
361        I != E; ++I) {
362     LibFunc::Func F = static_cast<LibFunc::Func>(I);
363     if (TLI.has(F))
364       Libcalls.push_back(TLI.getName(F));
365   }
366
367   // TargetLowering has info on library calls that CodeGen expects to be
368   // available, both from the C runtime and compiler-rt.
369   if (Lowering)
370     for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
371          I != E; ++I)
372       if (const char *Name
373           = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
374         Libcalls.push_back(Name);
375
376   array_pod_sort(Libcalls.begin(), Libcalls.end());
377   Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
378                  Libcalls.end());
379 }
380
381 void LTOCodeGenerator::applyScopeRestrictions() {
382   if (ScopeRestrictionsDone)
383     return;
384   Module *mergedModule = IRLinker.getModule();
385
386   // Start off with a verification pass.
387   PassManager passes;
388   passes.add(createVerifierPass());
389   passes.add(createDebugInfoVerifierPass());
390
391   // mark which symbols can not be internalized
392   Mangler Mangler(TargetMach->getSubtargetImpl()->getDataLayout());
393   std::vector<const char*> MustPreserveList;
394   SmallPtrSet<GlobalValue*, 8> AsmUsed;
395   std::vector<StringRef> Libcalls;
396   TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
397   accumulateAndSortLibcalls(
398       Libcalls, TLI, TargetMach->getSubtargetImpl()->getTargetLowering());
399
400   for (Module::iterator f = mergedModule->begin(),
401          e = mergedModule->end(); f != e; ++f)
402     applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
403   for (Module::global_iterator v = mergedModule->global_begin(),
404          e = mergedModule->global_end(); v !=  e; ++v)
405     applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
406   for (Module::alias_iterator a = mergedModule->alias_begin(),
407          e = mergedModule->alias_end(); a != e; ++a)
408     applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
409
410   GlobalVariable *LLVMCompilerUsed =
411     mergedModule->getGlobalVariable("llvm.compiler.used");
412   findUsedValues(LLVMCompilerUsed, AsmUsed);
413   if (LLVMCompilerUsed)
414     LLVMCompilerUsed->eraseFromParent();
415
416   if (!AsmUsed.empty()) {
417     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
418     std::vector<Constant*> asmUsed2;
419     for (auto *GV : AsmUsed) {
420       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
421       asmUsed2.push_back(c);
422     }
423
424     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
425     LLVMCompilerUsed =
426       new llvm::GlobalVariable(*mergedModule, ATy, false,
427                                llvm::GlobalValue::AppendingLinkage,
428                                llvm::ConstantArray::get(ATy, asmUsed2),
429                                "llvm.compiler.used");
430
431     LLVMCompilerUsed->setSection("llvm.metadata");
432   }
433
434   passes.add(createInternalizePass(MustPreserveList));
435
436   // apply scope restrictions
437   passes.run(*mergedModule);
438
439   ScopeRestrictionsDone = true;
440 }
441
442 /// Optimize merged modules using various IPO passes
443 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
444                                           bool DisableOpt,
445                                           bool DisableInline,
446                                           bool DisableGVNLoadPRE,
447                                           bool DisableVectorization,
448                                           std::string &errMsg) {
449   if (!this->determineTarget(errMsg))
450     return false;
451
452   Module *mergedModule = IRLinker.getModule();
453
454   // Mark which symbols can not be internalized
455   this->applyScopeRestrictions();
456
457   // Instantiate the pass manager to organize the passes.
458   PassManager passes;
459
460   // Add an appropriate DataLayout instance for this module...
461   mergedModule->setDataLayout(TargetMach->getSubtargetImpl()->getDataLayout());
462
463   Triple TargetTriple(TargetMach->getTargetTriple());
464   PassManagerBuilder PMB;
465   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
466   PMB.LoopVectorize = !DisableVectorization;
467   PMB.SLPVectorize = !DisableVectorization;
468   if (!DisableInline)
469     PMB.Inliner = createFunctionInliningPass();
470   PMB.LibraryInfo = new TargetLibraryInfo(TargetTriple);
471   if (DisableOpt)
472     PMB.OptLevel = 0;
473   PMB.VerifyInput = true;
474   PMB.VerifyOutput = true;
475
476   PMB.populateLTOPassManager(passes, TargetMach);
477
478   PassManager codeGenPasses;
479
480   codeGenPasses.add(new DataLayoutPass());
481
482   formatted_raw_ostream Out(out);
483
484   // If the bitcode files contain ARC code and were compiled with optimization,
485   // the ObjCARCContractPass must be run, so do it unconditionally here.
486   codeGenPasses.add(createObjCARCContractPass());
487
488   if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
489                                       TargetMachine::CGFT_ObjectFile)) {
490     errMsg = "target file type not supported";
491     return false;
492   }
493
494   // Run our queue of passes all at once now, efficiently.
495   passes.run(*mergedModule);
496
497   // Run the code generator, and write assembly file
498   codeGenPasses.run(*mergedModule);
499
500   return true;
501 }
502
503 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
504 /// LTO problems.
505 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
506   for (std::pair<StringRef, StringRef> o = getToken(options);
507        !o.first.empty(); o = getToken(o.second)) {
508     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
509     // that.
510     if (CodegenOptions.empty())
511       CodegenOptions.push_back(strdup("libLLVMLTO"));
512     CodegenOptions.push_back(strdup(o.first.str().c_str()));
513   }
514 }
515
516 void LTOCodeGenerator::parseCodeGenDebugOptions() {
517   // if options were requested, set them
518   if (!CodegenOptions.empty())
519     cl::ParseCommandLineOptions(CodegenOptions.size(),
520                                 const_cast<char **>(&CodegenOptions[0]));
521 }
522
523 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
524                                          void *Context) {
525   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
526 }
527
528 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
529   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
530   lto_codegen_diagnostic_severity_t Severity;
531   switch (DI.getSeverity()) {
532   case DS_Error:
533     Severity = LTO_DS_ERROR;
534     break;
535   case DS_Warning:
536     Severity = LTO_DS_WARNING;
537     break;
538   case DS_Remark:
539     Severity = LTO_DS_REMARK;
540     break;
541   case DS_Note:
542     Severity = LTO_DS_NOTE;
543     break;
544   }
545   // Create the string that will be reported to the external diagnostic handler.
546   std::string MsgStorage;
547   raw_string_ostream Stream(MsgStorage);
548   DiagnosticPrinterRawOStream DP(Stream);
549   DI.print(DP);
550   Stream.flush();
551
552   // If this method has been called it means someone has set up an external
553   // diagnostic handler. Assert on that.
554   assert(DiagHandler && "Invalid diagnostic handler");
555   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
556 }
557
558 void
559 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
560                                        void *Ctxt) {
561   this->DiagHandler = DiagHandler;
562   this->DiagContext = Ctxt;
563   if (!DiagHandler)
564     return Context.setDiagnosticHandler(nullptr, nullptr);
565   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
566   // diagnostic to the external DiagHandler.
567   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
568                                /* RespectFilters */ true);
569 }