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