[LTO] Add a hook to map LLVM diagnostics into the clients of 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.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/raw_ostream.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/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()), Linker(new Module("ld-temp.o", Context)),
67       TargetMach(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false),
68       CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC),
69       InternalizeStrategy(LTO_INTERNALIZE_FULL), NativeObjectFile(NULL),
70       DiagHandler(NULL), DiagContext(NULL) {
71   initializeLTOPasses();
72 }
73
74 LTOCodeGenerator::~LTOCodeGenerator() {
75   delete TargetMach;
76   delete NativeObjectFile;
77   TargetMach = NULL;
78   NativeObjectFile = NULL;
79
80   Linker.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   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 = Linker.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.EnableSegmentedStacks = options.EnableSegmentedStacks;
145   Options.UseInitArray = options.UseInitArray;
146 }
147
148 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
149   switch (debug) {
150   case LTO_DEBUG_MODEL_NONE:
151     EmitDwarfDebugInfo = false;
152     return;
153
154   case LTO_DEBUG_MODEL_DWARF:
155     EmitDwarfDebugInfo = true;
156     return;
157   }
158   llvm_unreachable("Unknown debug format!");
159 }
160
161 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
162   switch (model) {
163   case LTO_CODEGEN_PIC_MODEL_STATIC:
164   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
165   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
166     CodeModel = model;
167     return;
168   }
169   llvm_unreachable("Unknown PIC model!");
170 }
171
172 void
173 LTOCodeGenerator::setInternalizeStrategy(lto_internalize_strategy Strategy) {
174   switch (Strategy) {
175   case LTO_INTERNALIZE_FULL:
176   case LTO_INTERNALIZE_NONE:
177   case LTO_INTERNALIZE_HIDDEN:
178     InternalizeStrategy = Strategy;
179     return;
180   }
181   llvm_unreachable("Unknown internalize strategy!");
182 }
183
184 bool LTOCodeGenerator::writeMergedModules(const char *path,
185                                           std::string &errMsg) {
186   if (!determineTarget(errMsg))
187     return false;
188
189   // mark which symbols can not be internalized
190   applyScopeRestrictions();
191
192   // create output file
193   std::string ErrInfo;
194   tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
195   if (!ErrInfo.empty()) {
196     errMsg = "could not open bitcode file for writing: ";
197     errMsg += path;
198     return false;
199   }
200
201   // write bitcode to it
202   WriteBitcodeToFile(Linker.getModule(), Out.os());
203   Out.os().close();
204
205   if (Out.os().has_error()) {
206     errMsg = "could not write bitcode file: ";
207     errMsg += path;
208     Out.os().clear_error();
209     return false;
210   }
211
212   Out.keep();
213   return true;
214 }
215
216 bool LTOCodeGenerator::compile_to_file(const char** name,
217                                        bool disableOpt,
218                                        bool disableInline,
219                                        bool disableGVNLoadPRE,
220                                        std::string& errMsg) {
221   // make unique temp .o file to put generated object file
222   SmallString<128> Filename;
223   int FD;
224   error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
225   if (EC) {
226     errMsg = EC.message();
227     return false;
228   }
229
230   // generate object file
231   tool_output_file objFile(Filename.c_str(), FD);
232
233   bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
234                                       disableGVNLoadPRE, errMsg);
235   objFile.os().close();
236   if (objFile.os().has_error()) {
237     objFile.os().clear_error();
238     sys::fs::remove(Twine(Filename));
239     return false;
240   }
241
242   objFile.keep();
243   if (!genResult) {
244     sys::fs::remove(Twine(Filename));
245     return false;
246   }
247
248   NativeObjectPath = Filename.c_str();
249   *name = NativeObjectPath.c_str();
250   return true;
251 }
252
253 const void* LTOCodeGenerator::compile(size_t* length,
254                                       bool disableOpt,
255                                       bool disableInline,
256                                       bool disableGVNLoadPRE,
257                                       std::string& errMsg) {
258   const char *name;
259   if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
260                        errMsg))
261     return NULL;
262
263   // remove old buffer if compile() called twice
264   delete NativeObjectFile;
265
266   // read .o file into memory buffer
267   OwningPtr<MemoryBuffer> BuffPtr;
268   if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
269     errMsg = ec.message();
270     sys::fs::remove(NativeObjectPath);
271     return NULL;
272   }
273   NativeObjectFile = BuffPtr.take();
274
275   // remove temp files
276   sys::fs::remove(NativeObjectPath);
277
278   // return buffer, unless error
279   if (NativeObjectFile == NULL)
280     return NULL;
281   *length = NativeObjectFile->getBufferSize();
282   return NativeObjectFile->getBufferStart();
283 }
284
285 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
286   if (TargetMach != NULL)
287     return true;
288
289   std::string TripleStr = Linker.getModule()->getTargetTriple();
290   if (TripleStr.empty())
291     TripleStr = sys::getDefaultTargetTriple();
292   llvm::Triple Triple(TripleStr);
293
294   // create target machine from info for merged modules
295   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
296   if (march == NULL)
297     return false;
298
299   // The relocation model is actually a static member of TargetMachine and
300   // needs to be set before the TargetMachine is instantiated.
301   Reloc::Model RelocModel = Reloc::Default;
302   switch (CodeModel) {
303   case LTO_CODEGEN_PIC_MODEL_STATIC:
304     RelocModel = Reloc::Static;
305     break;
306   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
307     RelocModel = Reloc::PIC_;
308     break;
309   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
310     RelocModel = Reloc::DynamicNoPIC;
311     break;
312   }
313
314   // construct LTOModule, hand over ownership of module and target
315   SubtargetFeatures Features;
316   Features.getDefaultSubtargetFeatures(Triple);
317   std::string FeatureStr = Features.getString();
318   // Set a default CPU for Darwin triples.
319   if (MCpu.empty() && Triple.isOSDarwin()) {
320     if (Triple.getArch() == llvm::Triple::x86_64)
321       MCpu = "core2";
322     else if (Triple.getArch() == llvm::Triple::x86)
323       MCpu = "yonah";
324   }
325
326   TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
327                                           RelocModel, CodeModel::Default,
328                                           CodeGenOpt::Aggressive);
329   return true;
330 }
331
332 void LTOCodeGenerator::
333 applyRestriction(GlobalValue &GV,
334                  const ArrayRef<StringRef> &Libcalls,
335                  std::vector<const char*> &MustPreserveList,
336                  SmallPtrSet<GlobalValue*, 8> &AsmUsed,
337                  Mangler &Mangler) {
338   SmallString<64> Buffer;
339   Mangler.getNameWithPrefix(Buffer, &GV);
340
341   if (GV.isDeclaration())
342     return;
343   if (MustPreserveSymbols.count(Buffer))
344     MustPreserveList.push_back(GV.getName().data());
345   if (AsmUndefinedRefs.count(Buffer))
346     AsmUsed.insert(&GV);
347
348   // Conservatively append user-supplied runtime library functions to
349   // llvm.compiler.used.  These could be internalized and deleted by
350   // optimizations like -globalopt, causing problems when later optimizations
351   // add new library calls (e.g., llvm.memset => memset and printf => puts).
352   // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
353   if (isa<Function>(GV) &&
354       std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
355     AsmUsed.insert(&GV);
356 }
357
358 static void findUsedValues(GlobalVariable *LLVMUsed,
359                            SmallPtrSet<GlobalValue*, 8> &UsedValues) {
360   if (LLVMUsed == 0) return;
361
362   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
363   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
364     if (GlobalValue *GV =
365         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
366       UsedValues.insert(GV);
367 }
368
369 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
370                                       const TargetLibraryInfo& TLI,
371                                       const TargetLowering *Lowering)
372 {
373   // TargetLibraryInfo has info on C runtime library calls on the current
374   // target.
375   for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
376        I != E; ++I) {
377     LibFunc::Func F = static_cast<LibFunc::Func>(I);
378     if (TLI.has(F))
379       Libcalls.push_back(TLI.getName(F));
380   }
381
382   // TargetLowering has info on library calls that CodeGen expects to be
383   // available, both from the C runtime and compiler-rt.
384   if (Lowering)
385     for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
386          I != E; ++I)
387       if (const char *Name
388           = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
389         Libcalls.push_back(Name);
390
391   array_pod_sort(Libcalls.begin(), Libcalls.end());
392   Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
393                  Libcalls.end());
394 }
395
396 void LTOCodeGenerator::applyScopeRestrictions() {
397   if (ScopeRestrictionsDone || !shouldInternalize())
398     return;
399   Module *mergedModule = Linker.getModule();
400
401   // Start off with a verification pass.
402   PassManager passes;
403   passes.add(createVerifierPass());
404
405   // mark which symbols can not be internalized
406   Mangler Mangler(TargetMach->getDataLayout());
407   std::vector<const char*> MustPreserveList;
408   SmallPtrSet<GlobalValue*, 8> AsmUsed;
409   std::vector<StringRef> Libcalls;
410   TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
411   accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
412
413   for (Module::iterator f = mergedModule->begin(),
414          e = mergedModule->end(); f != e; ++f)
415     applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
416   for (Module::global_iterator v = mergedModule->global_begin(),
417          e = mergedModule->global_end(); v !=  e; ++v)
418     applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
419   for (Module::alias_iterator a = mergedModule->alias_begin(),
420          e = mergedModule->alias_end(); a != e; ++a)
421     applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
422
423   GlobalVariable *LLVMCompilerUsed =
424     mergedModule->getGlobalVariable("llvm.compiler.used");
425   findUsedValues(LLVMCompilerUsed, AsmUsed);
426   if (LLVMCompilerUsed)
427     LLVMCompilerUsed->eraseFromParent();
428
429   if (!AsmUsed.empty()) {
430     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
431     std::vector<Constant*> asmUsed2;
432     for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
433            e = AsmUsed.end(); i !=e; ++i) {
434       GlobalValue *GV = *i;
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(
450       createInternalizePass(MustPreserveList, shouldOnlyInternalizeHidden()));
451
452   // apply scope restrictions
453   passes.run(*mergedModule);
454
455   ScopeRestrictionsDone = true;
456 }
457
458 /// Optimize merged modules using various IPO passes
459 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
460                                           bool DisableOpt,
461                                           bool DisableInline,
462                                           bool DisableGVNLoadPRE,
463                                           std::string &errMsg) {
464   if (!this->determineTarget(errMsg))
465     return false;
466
467   Module *mergedModule = Linker.getModule();
468
469   // Mark which symbols can not be internalized
470   this->applyScopeRestrictions();
471
472   // Instantiate the pass manager to organize the passes.
473   PassManager passes;
474
475   // Start off with a verification pass.
476   passes.add(createVerifierPass());
477
478   // Add an appropriate DataLayout instance for this module...
479   passes.add(new DataLayout(*TargetMach->getDataLayout()));
480
481   // Add appropriate TargetLibraryInfo for this module.
482   passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
483
484   TargetMach->addAnalysisPasses(passes);
485
486   // Enabling internalize here would use its AllButMain variant. It
487   // keeps only main if it exists and does nothing for libraries. Instead
488   // we create the pass ourselves with the symbol list provided by the linker.
489   if (!DisableOpt)
490     PassManagerBuilder().populateLTOPassManager(passes,
491                                               /*Internalize=*/false,
492                                               !DisableInline,
493                                               DisableGVNLoadPRE);
494
495   // Make sure everything is still good.
496   passes.add(createVerifierPass());
497
498   PassManager codeGenPasses;
499
500   codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
501   TargetMach->addAnalysisPasses(codeGenPasses);
502
503   formatted_raw_ostream Out(out);
504
505   // If the bitcode files contain ARC code and were compiled with optimization,
506   // the ObjCARCContractPass must be run, so do it unconditionally here.
507   codeGenPasses.add(createObjCARCContractPass());
508
509   if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
510                                       TargetMachine::CGFT_ObjectFile)) {
511     errMsg = "target file type not supported";
512     return false;
513   }
514
515   // Run our queue of passes all at once now, efficiently.
516   passes.run(*mergedModule);
517
518   // Run the code generator, and write assembly file
519   codeGenPasses.run(*mergedModule);
520
521   return true;
522 }
523
524 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
525 /// LTO problems.
526 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
527   for (std::pair<StringRef, StringRef> o = getToken(options);
528        !o.first.empty(); o = getToken(o.second)) {
529     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
530     // that.
531     if (CodegenOptions.empty())
532       CodegenOptions.push_back(strdup("libLLVMLTO"));
533     CodegenOptions.push_back(strdup(o.first.str().c_str()));
534   }
535 }
536
537 void LTOCodeGenerator::parseCodeGenDebugOptions() {
538   // if options were requested, set them
539   if (!CodegenOptions.empty())
540     cl::ParseCommandLineOptions(CodegenOptions.size(),
541                                 const_cast<char **>(&CodegenOptions[0]));
542 }
543
544 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
545                                          void *Context) {
546   ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
547 }
548
549 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
550   // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
551   lto_codegen_diagnostic_severity_t Severity;
552   switch (DI.getSeverity()) {
553   case DS_Error:
554     Severity = LTO_DS_ERROR;
555     break;
556   case DS_Warning:
557     Severity = LTO_DS_WARNING;
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(NULL, NULL);
583   // Register the LTOCodeGenerator stub in the LLVMContext to forward the
584   // diagnostic to the external DiagHandler.
585   Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this);
586 }