Add a new attribute called 'jumptable' that creates jump-instruction tables for funct...
[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/Support/system_error.h"
48 #include "llvm/Target/TargetLibraryInfo.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Target/TargetRegisterInfo.h"
52 #include "llvm/Transforms/IPO.h"
53 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 #include "llvm/Transforms/ObjCARC.h"
55 using namespace llvm;
56
57 const char* LTOCodeGenerator::getVersionString() {
58 #ifdef LLVM_VERSION_INFO
59   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
60 #else
61   return PACKAGE_NAME " version " PACKAGE_VERSION;
62 #endif
63 }
64
65 LTOCodeGenerator::LTOCodeGenerator()
66     : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)),
67       TargetMach(nullptr), EmitDwarfDebugInfo(false),
68       ScopeRestrictionsDone(false), CodeModel(LTO_CODEGEN_PIC_MODEL_DEFAULT),
69       NativeObjectFile(nullptr), DiagHandler(nullptr), DiagContext(nullptr) {
70   initializeLTOPasses();
71 }
72
73 LTOCodeGenerator::~LTOCodeGenerator() {
74   delete TargetMach;
75   delete NativeObjectFile;
76   TargetMach = nullptr;
77   NativeObjectFile = nullptr;
78
79   IRLinker.deleteModule();
80
81   for (std::vector<char *>::iterator I = CodegenOptions.begin(),
82                                      E = CodegenOptions.end();
83        I != E; ++I)
84     free(*I);
85 }
86
87 // Initialize LTO passes. Please keep this funciton in sync with
88 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
89 // passes are initialized.
90 void LTOCodeGenerator::initializeLTOPasses() {
91   PassRegistry &R = *PassRegistry::getPassRegistry();
92
93   initializeInternalizePassPass(R);
94   initializeIPSCCPPass(R);
95   initializeGlobalOptPass(R);
96   initializeConstantMergePass(R);
97   initializeDAHPass(R);
98   initializeInstCombinerPass(R);
99   initializeJumpInstrTablesPass(R);
100   initializeSimpleInlinerPass(R);
101   initializePruneEHPass(R);
102   initializeGlobalDCEPass(R);
103   initializeArgPromotionPass(R);
104   initializeJumpThreadingPass(R);
105   initializeSROAPass(R);
106   initializeSROA_DTPass(R);
107   initializeSROA_SSAUpPass(R);
108   initializeFunctionAttrsPass(R);
109   initializeGlobalsModRefPass(R);
110   initializeLICMPass(R);
111   initializeGVNPass(R);
112   initializeMemCpyOptPass(R);
113   initializeDCEPass(R);
114   initializeCFGSimplifyPassPass(R);
115 }
116
117 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
118   bool ret = IRLinker.linkInModule(mod->getLLVVMModule(), &errMsg);
119
120   const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
121   for (int i = 0, e = undefs.size(); i != e; ++i)
122     AsmUndefinedRefs[undefs[i]] = 1;
123
124   return !ret;
125 }
126
127 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
128   Options.LessPreciseFPMADOption = options.LessPreciseFPMADOption;
129   Options.NoFramePointerElim = options.NoFramePointerElim;
130   Options.AllowFPOpFusion = options.AllowFPOpFusion;
131   Options.UnsafeFPMath = options.UnsafeFPMath;
132   Options.NoInfsFPMath = options.NoInfsFPMath;
133   Options.NoNaNsFPMath = options.NoNaNsFPMath;
134   Options.HonorSignDependentRoundingFPMathOption =
135     options.HonorSignDependentRoundingFPMathOption;
136   Options.UseSoftFloat = options.UseSoftFloat;
137   Options.FloatABIType = options.FloatABIType;
138   Options.NoZerosInBSS = options.NoZerosInBSS;
139   Options.GuaranteedTailCallOpt = options.GuaranteedTailCallOpt;
140   Options.DisableTailCalls = options.DisableTailCalls;
141   Options.StackAlignmentOverride = options.StackAlignmentOverride;
142   Options.TrapFuncName = options.TrapFuncName;
143   Options.PositionIndependentExecutable = options.PositionIndependentExecutable;
144   Options.UseInitArray = options.UseInitArray;
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::string ErrInfo;
182   tool_output_file Out(path, ErrInfo, sys::fs::F_None);
183   if (!ErrInfo.empty()) {
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                                        std::string& errMsg) {
209   // make unique temp .o file to put generated object file
210   SmallString<128> Filename;
211   int FD;
212   error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
213   if (EC) {
214     errMsg = EC.message();
215     return false;
216   }
217
218   // generate object file
219   tool_output_file objFile(Filename.c_str(), FD);
220
221   bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
222                                       disableGVNLoadPRE, 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 const void* LTOCodeGenerator::compile(size_t* length,
242                                       bool disableOpt,
243                                       bool disableInline,
244                                       bool disableGVNLoadPRE,
245                                       std::string& errMsg) {
246   const char *name;
247   if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
248                        errMsg))
249     return nullptr;
250
251   // remove old buffer if compile() called twice
252   delete NativeObjectFile;
253
254   // read .o file into memory buffer
255   std::unique_ptr<MemoryBuffer> BuffPtr;
256   if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
257     errMsg = ec.message();
258     sys::fs::remove(NativeObjectPath);
259     return nullptr;
260   }
261   NativeObjectFile = BuffPtr.release();
262
263   // remove temp files
264   sys::fs::remove(NativeObjectPath);
265
266   // return buffer, unless error
267   if (!NativeObjectFile)
268     return nullptr;
269   *length = NativeObjectFile->getBufferSize();
270   return NativeObjectFile->getBufferStart();
271 }
272
273 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
274   if (TargetMach)
275     return true;
276
277   std::string TripleStr = IRLinker.getModule()->getTargetTriple();
278   if (TripleStr.empty())
279     TripleStr = sys::getDefaultTargetTriple();
280   llvm::Triple Triple(TripleStr);
281
282   // create target machine from info for merged modules
283   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
284   if (!march)
285     return false;
286
287   // The relocation model is actually a static member of TargetMachine and
288   // needs to be set before the TargetMachine is instantiated.
289   Reloc::Model RelocModel = Reloc::Default;
290   switch (CodeModel) {
291   case LTO_CODEGEN_PIC_MODEL_STATIC:
292     RelocModel = Reloc::Static;
293     break;
294   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
295     RelocModel = Reloc::PIC_;
296     break;
297   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
298     RelocModel = Reloc::DynamicNoPIC;
299     break;
300   case LTO_CODEGEN_PIC_MODEL_DEFAULT:
301     // RelocModel is already the default, so leave it that way.
302     break;
303   }
304
305   // Construct LTOModule, hand over ownership of module and target. Use MAttr as
306   // the default set of features.
307   SubtargetFeatures Features(MAttr);
308   Features.getDefaultSubtargetFeatures(Triple);
309   std::string FeatureStr = Features.getString();
310   // Set a default CPU for Darwin triples.
311   if (MCpu.empty() && Triple.isOSDarwin()) {
312     if (Triple.getArch() == llvm::Triple::x86_64)
313       MCpu = "core2";
314     else if (Triple.getArch() == llvm::Triple::x86)
315       MCpu = "yonah";
316     else if (Triple.getArch() == llvm::Triple::arm64 ||
317              Triple.getArch() == llvm::Triple::aarch64)
318       MCpu = "cyclone";
319   }
320
321   TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
322                                           RelocModel, CodeModel::Default,
323                                           CodeGenOpt::Aggressive);
324   return true;
325 }
326
327 void LTOCodeGenerator::
328 applyRestriction(GlobalValue &GV,
329                  const ArrayRef<StringRef> &Libcalls,
330                  std::vector<const char*> &MustPreserveList,
331                  SmallPtrSet<GlobalValue*, 8> &AsmUsed,
332                  Mangler &Mangler) {
333   // There are no restrictions to apply to declarations.
334   if (GV.isDeclaration())
335     return;
336
337   // There is nothing more restrictive than private linkage.
338   if (GV.hasPrivateLinkage())
339     return;
340
341   SmallString<64> Buffer;
342   TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
343
344   if (MustPreserveSymbols.count(Buffer))
345     MustPreserveList.push_back(GV.getName().data());
346   if (AsmUndefinedRefs.count(Buffer))
347     AsmUsed.insert(&GV);
348
349   // Conservatively append user-supplied runtime library functions to
350   // llvm.compiler.used.  These could be internalized and deleted by
351   // optimizations like -globalopt, causing problems when later optimizations
352   // add new library calls (e.g., llvm.memset => memset and printf => puts).
353   // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
354   if (isa<Function>(GV) &&
355       std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
356     AsmUsed.insert(&GV);
357 }
358
359 static void findUsedValues(GlobalVariable *LLVMUsed,
360                            SmallPtrSet<GlobalValue*, 8> &UsedValues) {
361   if (!LLVMUsed) return;
362
363   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
364   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
365     if (GlobalValue *GV =
366         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
367       UsedValues.insert(GV);
368 }
369
370 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
371                                       const TargetLibraryInfo& TLI,
372                                       const TargetLowering *Lowering)
373 {
374   // TargetLibraryInfo has info on C runtime library calls on the current
375   // target.
376   for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
377        I != E; ++I) {
378     LibFunc::Func F = static_cast<LibFunc::Func>(I);
379     if (TLI.has(F))
380       Libcalls.push_back(TLI.getName(F));
381   }
382
383   // TargetLowering has info on library calls that CodeGen expects to be
384   // available, both from the C runtime and compiler-rt.
385   if (Lowering)
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   array_pod_sort(Libcalls.begin(), Libcalls.end());
393   Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
394                  Libcalls.end());
395 }
396
397 void LTOCodeGenerator::applyScopeRestrictions() {
398   if (ScopeRestrictionsDone)
399     return;
400   Module *mergedModule = IRLinker.getModule();
401
402   // Start off with a verification pass.
403   PassManager passes;
404   passes.add(createVerifierPass());
405   passes.add(createDebugInfoVerifierPass());
406
407   // mark which symbols can not be internalized
408   Mangler Mangler(TargetMach->getDataLayout());
409   std::vector<const char*> MustPreserveList;
410   SmallPtrSet<GlobalValue*, 8> AsmUsed;
411   std::vector<StringRef> Libcalls;
412   TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
413   accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
414
415   for (Module::iterator f = mergedModule->begin(),
416          e = mergedModule->end(); f != e; ++f)
417     applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
418   for (Module::global_iterator v = mergedModule->global_begin(),
419          e = mergedModule->global_end(); v !=  e; ++v)
420     applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
421   for (Module::alias_iterator a = mergedModule->alias_begin(),
422          e = mergedModule->alias_end(); a != e; ++a)
423     applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
424
425   GlobalVariable *LLVMCompilerUsed =
426     mergedModule->getGlobalVariable("llvm.compiler.used");
427   findUsedValues(LLVMCompilerUsed, AsmUsed);
428   if (LLVMCompilerUsed)
429     LLVMCompilerUsed->eraseFromParent();
430
431   if (!AsmUsed.empty()) {
432     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
433     std::vector<Constant*> asmUsed2;
434     for (auto *GV : AsmUsed) {
435       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
436       asmUsed2.push_back(c);
437     }
438
439     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
440     LLVMCompilerUsed =
441       new llvm::GlobalVariable(*mergedModule, ATy, false,
442                                llvm::GlobalValue::AppendingLinkage,
443                                llvm::ConstantArray::get(ATy, asmUsed2),
444                                "llvm.compiler.used");
445
446     LLVMCompilerUsed->setSection("llvm.metadata");
447   }
448
449   passes.add(createInternalizePass(MustPreserveList));
450
451   // apply scope restrictions
452   passes.run(*mergedModule);
453
454   ScopeRestrictionsDone = true;
455 }
456
457 /// Optimize merged modules using various IPO passes
458 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
459                                           bool DisableOpt,
460                                           bool DisableInline,
461                                           bool DisableGVNLoadPRE,
462                                           std::string &errMsg) {
463   if (!this->determineTarget(errMsg))
464     return false;
465
466   Module *mergedModule = IRLinker.getModule();
467
468   // Mark which symbols can not be internalized
469   this->applyScopeRestrictions();
470
471   // Instantiate the pass manager to organize the passes.
472   PassManager passes;
473
474   // Start off with a verification pass.
475   passes.add(createVerifierPass());
476   passes.add(createDebugInfoVerifierPass());
477
478   // Add an appropriate DataLayout instance for this module...
479   mergedModule->setDataLayout(TargetMach->getDataLayout());
480   passes.add(new DataLayoutPass(mergedModule));
481
482   // Add appropriate TargetLibraryInfo for this module.
483   passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
484
485   TargetMach->addAnalysisPasses(passes);
486
487   // Enabling internalize here would use its AllButMain variant. It
488   // keeps only main if it exists and does nothing for libraries. Instead
489   // we create the pass ourselves with the symbol list provided by the linker.
490   if (!DisableOpt)
491     PassManagerBuilder().populateLTOPassManager(passes,
492                                               /*Internalize=*/false,
493                                               !DisableInline,
494                                               DisableGVNLoadPRE);
495
496   // Make sure everything is still good.
497   passes.add(createVerifierPass());
498   passes.add(createDebugInfoVerifierPass());
499
500   PassManager codeGenPasses;
501
502   codeGenPasses.add(new DataLayoutPass(mergedModule));
503
504   formatted_raw_ostream Out(out);
505
506   // If the bitcode files contain ARC code and were compiled with optimization,
507   // the ObjCARCContractPass must be run, so do it unconditionally here.
508   codeGenPasses.add(createObjCARCContractPass());
509
510   if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
511                                       TargetMachine::CGFT_ObjectFile)) {
512     errMsg = "target file type not supported";
513     return false;
514   }
515
516   // Run our queue of passes all at once now, efficiently.
517   passes.run(*mergedModule);
518
519   // Run the code generator, and write assembly file
520   codeGenPasses.run(*mergedModule);
521
522   return true;
523 }
524
525 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
526 /// LTO problems.
527 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
528   for (std::pair<StringRef, StringRef> o = getToken(options);
529        !o.first.empty(); o = getToken(o.second)) {
530     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
531     // that.
532     if (CodegenOptions.empty())
533       CodegenOptions.push_back(strdup("libLLVMLTO"));
534     CodegenOptions.push_back(strdup(o.first.str().c_str()));
535   }
536 }
537
538 void LTOCodeGenerator::parseCodeGenDebugOptions() {
539   // if options were requested, set them
540   if (!CodegenOptions.empty())
541     cl::ParseCommandLineOptions(CodegenOptions.size(),
542                                 const_cast<char **>(&CodegenOptions[0]));
543 }
544
545 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
546                                          void *Context) {
547   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
548 }
549
550 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
551   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
552   lto_codegen_diagnostic_severity_t Severity;
553   switch (DI.getSeverity()) {
554   case DS_Error:
555     Severity = LTO_DS_ERROR;
556     break;
557   case DS_Warning:
558     Severity = LTO_DS_WARNING;
559     break;
560   case DS_Remark:
561     Severity = LTO_DS_REMARK;
562     break;
563   case DS_Note:
564     Severity = LTO_DS_NOTE;
565     break;
566   }
567   // Create the string that will be reported to the external diagnostic handler.
568   std::string MsgStorage;
569   raw_string_ostream Stream(MsgStorage);
570   DiagnosticPrinterRawOStream DP(Stream);
571   DI.print(DP);
572   Stream.flush();
573
574   // If this method has been called it means someone has set up an external
575   // diagnostic handler. Assert on that.
576   assert(DiagHandler && "Invalid diagnostic handler");
577   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
578 }
579
580 void
581 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
582                                        void *Ctxt) {
583   this->DiagHandler = DiagHandler;
584   this->DiagContext = Ctxt;
585   if (!DiagHandler)
586     return Context.setDiagnosticHandler(nullptr, nullptr);
587   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
588   // diagnostic to the external DiagHandler.
589   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this);
590 }