Move DataLayout back to the TargetMachine from TargetSubtargetInfo
[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 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
372                                       const TargetLibraryInfo& TLI,
373                                       const TargetLowering *Lowering)
374 {
375   // TargetLibraryInfo has info on C runtime library calls on the current
376   // target.
377   for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
378        I != E; ++I) {
379     LibFunc::Func F = static_cast<LibFunc::Func>(I);
380     if (TLI.has(F))
381       Libcalls.push_back(TLI.getName(F));
382   }
383
384   // TargetLowering has info on library calls that CodeGen expects to be
385   // available, both from the C runtime and compiler-rt.
386   if (Lowering)
387     for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
388          I != E; ++I)
389       if (const char *Name
390           = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
391         Libcalls.push_back(Name);
392
393   array_pod_sort(Libcalls.begin(), Libcalls.end());
394   Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
395                  Libcalls.end());
396 }
397
398 void LTOCodeGenerator::applyScopeRestrictions() {
399   if (ScopeRestrictionsDone)
400     return;
401   Module *mergedModule = IRLinker.getModule();
402
403   // Start off with a verification pass.
404   PassManager passes;
405   passes.add(createVerifierPass());
406   passes.add(createDebugInfoVerifierPass());
407
408   // mark which symbols can not be internalized
409   Mangler Mangler(TargetMach->getDataLayout());
410   std::vector<const char*> MustPreserveList;
411   SmallPtrSet<GlobalValue*, 8> AsmUsed;
412   std::vector<StringRef> Libcalls;
413   TargetLibraryInfoImpl TLII(Triple(TargetMach->getTargetTriple()));
414   TargetLibraryInfo TLI(TLII);
415   accumulateAndSortLibcalls(
416       Libcalls, TLI, TargetMach->getSubtargetImpl()->getTargetLowering());
417
418   for (Module::iterator f = mergedModule->begin(),
419          e = mergedModule->end(); f != e; ++f)
420     applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
421   for (Module::global_iterator v = mergedModule->global_begin(),
422          e = mergedModule->global_end(); v !=  e; ++v)
423     applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
424   for (Module::alias_iterator a = mergedModule->alias_begin(),
425          e = mergedModule->alias_end(); a != e; ++a)
426     applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
427
428   GlobalVariable *LLVMCompilerUsed =
429     mergedModule->getGlobalVariable("llvm.compiler.used");
430   findUsedValues(LLVMCompilerUsed, AsmUsed);
431   if (LLVMCompilerUsed)
432     LLVMCompilerUsed->eraseFromParent();
433
434   if (!AsmUsed.empty()) {
435     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
436     std::vector<Constant*> asmUsed2;
437     for (auto *GV : AsmUsed) {
438       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
439       asmUsed2.push_back(c);
440     }
441
442     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
443     LLVMCompilerUsed =
444       new llvm::GlobalVariable(*mergedModule, ATy, false,
445                                llvm::GlobalValue::AppendingLinkage,
446                                llvm::ConstantArray::get(ATy, asmUsed2),
447                                "llvm.compiler.used");
448
449     LLVMCompilerUsed->setSection("llvm.metadata");
450   }
451
452   passes.add(createInternalizePass(MustPreserveList));
453
454   // apply scope restrictions
455   passes.run(*mergedModule);
456
457   ScopeRestrictionsDone = true;
458 }
459
460 /// Optimize merged modules using various IPO passes
461 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
462                                           bool DisableOpt,
463                                           bool DisableInline,
464                                           bool DisableGVNLoadPRE,
465                                           bool DisableVectorization,
466                                           std::string &errMsg) {
467   if (!this->determineTarget(errMsg))
468     return false;
469
470   Module *mergedModule = IRLinker.getModule();
471
472   // Mark which symbols can not be internalized
473   this->applyScopeRestrictions();
474
475   // Instantiate the pass manager to organize the passes.
476   PassManager passes;
477
478   // Add an appropriate DataLayout instance for this module...
479   mergedModule->setDataLayout(TargetMach->getDataLayout());
480
481   Triple TargetTriple(TargetMach->getTargetTriple());
482   PassManagerBuilder PMB;
483   PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
484   PMB.LoopVectorize = !DisableVectorization;
485   PMB.SLPVectorize = !DisableVectorization;
486   if (!DisableInline)
487     PMB.Inliner = createFunctionInliningPass();
488   PMB.LibraryInfo = new TargetLibraryInfoImpl(TargetTriple);
489   if (DisableOpt)
490     PMB.OptLevel = 0;
491   PMB.VerifyInput = true;
492   PMB.VerifyOutput = true;
493
494   PMB.populateLTOPassManager(passes, TargetMach);
495
496   PassManager codeGenPasses;
497
498   codeGenPasses.add(new DataLayoutPass());
499
500   formatted_raw_ostream Out(out);
501
502   // If the bitcode files contain ARC code and were compiled with optimization,
503   // the ObjCARCContractPass must be run, so do it unconditionally here.
504   codeGenPasses.add(createObjCARCContractPass());
505
506   if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
507                                       TargetMachine::CGFT_ObjectFile)) {
508     errMsg = "target file type not supported";
509     return false;
510   }
511
512   // Run our queue of passes all at once now, efficiently.
513   passes.run(*mergedModule);
514
515   // Run the code generator, and write assembly file
516   codeGenPasses.run(*mergedModule);
517
518   return true;
519 }
520
521 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
522 /// LTO problems.
523 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
524   for (std::pair<StringRef, StringRef> o = getToken(options);
525        !o.first.empty(); o = getToken(o.second)) {
526     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
527     // that.
528     if (CodegenOptions.empty())
529       CodegenOptions.push_back(strdup("libLLVMLTO"));
530     CodegenOptions.push_back(strdup(o.first.str().c_str()));
531   }
532 }
533
534 void LTOCodeGenerator::parseCodeGenDebugOptions() {
535   // if options were requested, set them
536   if (!CodegenOptions.empty())
537     cl::ParseCommandLineOptions(CodegenOptions.size(),
538                                 const_cast<char **>(&CodegenOptions[0]));
539 }
540
541 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
542                                          void *Context) {
543   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
544 }
545
546 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
547   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
548   lto_codegen_diagnostic_severity_t Severity;
549   switch (DI.getSeverity()) {
550   case DS_Error:
551     Severity = LTO_DS_ERROR;
552     break;
553   case DS_Warning:
554     Severity = LTO_DS_WARNING;
555     break;
556   case DS_Remark:
557     Severity = LTO_DS_REMARK;
558     break;
559   case DS_Note:
560     Severity = LTO_DS_NOTE;
561     break;
562   }
563   // Create the string that will be reported to the external diagnostic handler.
564   std::string MsgStorage;
565   raw_string_ostream Stream(MsgStorage);
566   DiagnosticPrinterRawOStream DP(Stream);
567   DI.print(DP);
568   Stream.flush();
569
570   // If this method has been called it means someone has set up an external
571   // diagnostic handler. Assert on that.
572   assert(DiagHandler && "Invalid diagnostic handler");
573   (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
574 }
575
576 void
577 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
578                                        void *Ctxt) {
579   this->DiagHandler = DiagHandler;
580   this->DiagContext = Ctxt;
581   if (!DiagHandler)
582     return Context.setDiagnosticHandler(nullptr, nullptr);
583   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
584   // diagnostic to the external DiagHandler.
585   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this,
586                                /* RespectFilters */ true);
587 }