[cleanup] Move the Dominators.h and Verifier.h headers into the IR
[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/LLVMContext.h"
25 #include "llvm/IR/Mangler.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Verifier.h"
28 #include "llvm/InitializePasses.h"
29 #include "llvm/LTO/LTOModule.h"
30 #include "llvm/Linker.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCContext.h"
33 #include "llvm/MC/SubtargetFeature.h"
34 #include "llvm/PassManager.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/Support/Host.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/TargetSelect.h"
43 #include "llvm/Support/ToolOutputFile.h"
44 #include "llvm/Support/system_error.h"
45 #include "llvm/Target/TargetLibraryInfo.h"
46 #include "llvm/Target/TargetLowering.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Target/TargetRegisterInfo.h"
49 #include "llvm/Transforms/IPO.h"
50 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
51 #include "llvm/Transforms/ObjCARC.h"
52 using namespace llvm;
53
54 const char* LTOCodeGenerator::getVersionString() {
55 #ifdef LLVM_VERSION_INFO
56   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
57 #else
58   return PACKAGE_NAME " version " PACKAGE_VERSION;
59 #endif
60 }
61
62 LTOCodeGenerator::LTOCodeGenerator()
63     : Context(getGlobalContext()), Linker(new Module("ld-temp.o", Context)),
64       TargetMach(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false),
65       CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC), NativeObjectFile(NULL) {
66   initializeLTOPasses();
67 }
68
69 LTOCodeGenerator::~LTOCodeGenerator() {
70   delete TargetMach;
71   delete NativeObjectFile;
72   TargetMach = NULL;
73   NativeObjectFile = NULL;
74
75   Linker.deleteModule();
76
77   for (std::vector<char *>::iterator I = CodegenOptions.begin(),
78                                      E = CodegenOptions.end();
79        I != E; ++I)
80     free(*I);
81 }
82
83 // Initialize LTO passes. Please keep this funciton in sync with
84 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
85 // passes are initialized.
86 void LTOCodeGenerator::initializeLTOPasses() {
87   PassRegistry &R = *PassRegistry::getPassRegistry();
88
89   initializeInternalizePassPass(R);
90   initializeIPSCCPPass(R);
91   initializeGlobalOptPass(R);
92   initializeConstantMergePass(R);
93   initializeDAHPass(R);
94   initializeInstCombinerPass(R);
95   initializeSimpleInlinerPass(R);
96   initializePruneEHPass(R);
97   initializeGlobalDCEPass(R);
98   initializeArgPromotionPass(R);
99   initializeJumpThreadingPass(R);
100   initializeSROAPass(R);
101   initializeSROA_DTPass(R);
102   initializeSROA_SSAUpPass(R);
103   initializeFunctionAttrsPass(R);
104   initializeGlobalsModRefPass(R);
105   initializeLICMPass(R);
106   initializeGVNPass(R);
107   initializeMemCpyOptPass(R);
108   initializeDCEPass(R);
109   initializeCFGSimplifyPassPass(R);
110 }
111
112 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
113   bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
114
115   const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
116   for (int i = 0, e = undefs.size(); i != e; ++i)
117     AsmUndefinedRefs[undefs[i]] = 1;
118
119   return !ret;
120 }
121
122 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
123   Options.LessPreciseFPMADOption = options.LessPreciseFPMADOption;
124   Options.NoFramePointerElim = options.NoFramePointerElim;
125   Options.AllowFPOpFusion = options.AllowFPOpFusion;
126   Options.UnsafeFPMath = options.UnsafeFPMath;
127   Options.NoInfsFPMath = options.NoInfsFPMath;
128   Options.NoNaNsFPMath = options.NoNaNsFPMath;
129   Options.HonorSignDependentRoundingFPMathOption =
130     options.HonorSignDependentRoundingFPMathOption;
131   Options.UseSoftFloat = options.UseSoftFloat;
132   Options.FloatABIType = options.FloatABIType;
133   Options.NoZerosInBSS = options.NoZerosInBSS;
134   Options.GuaranteedTailCallOpt = options.GuaranteedTailCallOpt;
135   Options.DisableTailCalls = options.DisableTailCalls;
136   Options.StackAlignmentOverride = options.StackAlignmentOverride;
137   Options.TrapFuncName = options.TrapFuncName;
138   Options.PositionIndependentExecutable = options.PositionIndependentExecutable;
139   Options.EnableSegmentedStacks = options.EnableSegmentedStacks;
140   Options.UseInitArray = options.UseInitArray;
141 }
142
143 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
144   switch (debug) {
145   case LTO_DEBUG_MODEL_NONE:
146     EmitDwarfDebugInfo = false;
147     return;
148
149   case LTO_DEBUG_MODEL_DWARF:
150     EmitDwarfDebugInfo = true;
151     return;
152   }
153   llvm_unreachable("Unknown debug format!");
154 }
155
156 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
157   switch (model) {
158   case LTO_CODEGEN_PIC_MODEL_STATIC:
159   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
160   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
161     CodeModel = model;
162     return;
163   }
164   llvm_unreachable("Unknown PIC model!");
165 }
166
167 bool LTOCodeGenerator::writeMergedModules(const char *path,
168                                           std::string &errMsg) {
169   if (!determineTarget(errMsg))
170     return false;
171
172   // mark which symbols can not be internalized
173   applyScopeRestrictions();
174
175   // create output file
176   std::string ErrInfo;
177   tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
178   if (!ErrInfo.empty()) {
179     errMsg = "could not open bitcode file for writing: ";
180     errMsg += path;
181     return false;
182   }
183
184   // write bitcode to it
185   WriteBitcodeToFile(Linker.getModule(), Out.os());
186   Out.os().close();
187
188   if (Out.os().has_error()) {
189     errMsg = "could not write bitcode file: ";
190     errMsg += path;
191     Out.os().clear_error();
192     return false;
193   }
194
195   Out.keep();
196   return true;
197 }
198
199 bool LTOCodeGenerator::compile_to_file(const char** name,
200                                        bool disableOpt,
201                                        bool disableInline,
202                                        bool disableGVNLoadPRE,
203                                        std::string& errMsg) {
204   // make unique temp .o file to put generated object file
205   SmallString<128> Filename;
206   int FD;
207   error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
208   if (EC) {
209     errMsg = EC.message();
210     return false;
211   }
212
213   // generate object file
214   tool_output_file objFile(Filename.c_str(), FD);
215
216   bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
217                                       disableGVNLoadPRE, errMsg);
218   objFile.os().close();
219   if (objFile.os().has_error()) {
220     objFile.os().clear_error();
221     sys::fs::remove(Twine(Filename));
222     return false;
223   }
224
225   objFile.keep();
226   if (!genResult) {
227     sys::fs::remove(Twine(Filename));
228     return false;
229   }
230
231   NativeObjectPath = Filename.c_str();
232   *name = NativeObjectPath.c_str();
233   return true;
234 }
235
236 const void* LTOCodeGenerator::compile(size_t* length,
237                                       bool disableOpt,
238                                       bool disableInline,
239                                       bool disableGVNLoadPRE,
240                                       std::string& errMsg) {
241   const char *name;
242   if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
243                        errMsg))
244     return NULL;
245
246   // remove old buffer if compile() called twice
247   delete NativeObjectFile;
248
249   // read .o file into memory buffer
250   OwningPtr<MemoryBuffer> BuffPtr;
251   if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
252     errMsg = ec.message();
253     sys::fs::remove(NativeObjectPath);
254     return NULL;
255   }
256   NativeObjectFile = BuffPtr.take();
257
258   // remove temp files
259   sys::fs::remove(NativeObjectPath);
260
261   // return buffer, unless error
262   if (NativeObjectFile == NULL)
263     return NULL;
264   *length = NativeObjectFile->getBufferSize();
265   return NativeObjectFile->getBufferStart();
266 }
267
268 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
269   if (TargetMach != NULL)
270     return true;
271
272   std::string TripleStr = Linker.getModule()->getTargetTriple();
273   if (TripleStr.empty())
274     TripleStr = sys::getDefaultTargetTriple();
275   llvm::Triple Triple(TripleStr);
276
277   // create target machine from info for merged modules
278   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
279   if (march == NULL)
280     return false;
281
282   // The relocation model is actually a static member of TargetMachine and
283   // needs to be set before the TargetMachine is instantiated.
284   Reloc::Model RelocModel = Reloc::Default;
285   switch (CodeModel) {
286   case LTO_CODEGEN_PIC_MODEL_STATIC:
287     RelocModel = Reloc::Static;
288     break;
289   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
290     RelocModel = Reloc::PIC_;
291     break;
292   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
293     RelocModel = Reloc::DynamicNoPIC;
294     break;
295   }
296
297   // construct LTOModule, hand over ownership of module and target
298   SubtargetFeatures Features;
299   Features.getDefaultSubtargetFeatures(Triple);
300   std::string FeatureStr = Features.getString();
301   // Set a default CPU for Darwin triples.
302   if (MCpu.empty() && Triple.isOSDarwin()) {
303     if (Triple.getArch() == llvm::Triple::x86_64)
304       MCpu = "core2";
305     else if (Triple.getArch() == llvm::Triple::x86)
306       MCpu = "yonah";
307   }
308
309   TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
310                                           RelocModel, CodeModel::Default,
311                                           CodeGenOpt::Aggressive);
312   return true;
313 }
314
315 void LTOCodeGenerator::
316 applyRestriction(GlobalValue &GV,
317                  const ArrayRef<StringRef> &Libcalls,
318                  std::vector<const char*> &MustPreserveList,
319                  SmallPtrSet<GlobalValue*, 8> &AsmUsed,
320                  Mangler &Mangler) {
321   SmallString<64> Buffer;
322   Mangler.getNameWithPrefix(Buffer, &GV);
323
324   if (GV.isDeclaration())
325     return;
326   if (MustPreserveSymbols.count(Buffer))
327     MustPreserveList.push_back(GV.getName().data());
328   if (AsmUndefinedRefs.count(Buffer))
329     AsmUsed.insert(&GV);
330
331   // Conservatively append user-supplied runtime library functions to
332   // llvm.compiler.used.  These could be internalized and deleted by
333   // optimizations like -globalopt, causing problems when later optimizations
334   // add new library calls (e.g., llvm.memset => memset and printf => puts).
335   // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
336   if (isa<Function>(GV) &&
337       std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
338     AsmUsed.insert(&GV);
339 }
340
341 static void findUsedValues(GlobalVariable *LLVMUsed,
342                            SmallPtrSet<GlobalValue*, 8> &UsedValues) {
343   if (LLVMUsed == 0) return;
344
345   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
346   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
347     if (GlobalValue *GV =
348         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
349       UsedValues.insert(GV);
350 }
351
352 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
353                                       const TargetLibraryInfo& TLI,
354                                       const TargetLowering *Lowering)
355 {
356   // TargetLibraryInfo has info on C runtime library calls on the current
357   // target.
358   for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
359        I != E; ++I) {
360     LibFunc::Func F = static_cast<LibFunc::Func>(I);
361     if (TLI.has(F))
362       Libcalls.push_back(TLI.getName(F));
363   }
364
365   // TargetLowering has info on library calls that CodeGen expects to be
366   // available, both from the C runtime and compiler-rt.
367   if (Lowering)
368     for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
369          I != E; ++I)
370       if (const char *Name
371           = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
372         Libcalls.push_back(Name);
373
374   array_pod_sort(Libcalls.begin(), Libcalls.end());
375   Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
376                  Libcalls.end());
377 }
378
379 void LTOCodeGenerator::applyScopeRestrictions() {
380   if (ScopeRestrictionsDone)
381     return;
382   Module *mergedModule = Linker.getModule();
383
384   // Start off with a verification pass.
385   PassManager passes;
386   passes.add(createVerifierPass());
387
388   // mark which symbols can not be internalized
389   Mangler Mangler(TargetMach->getDataLayout());
390   std::vector<const char*> MustPreserveList;
391   SmallPtrSet<GlobalValue*, 8> AsmUsed;
392   std::vector<StringRef> Libcalls;
393   TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
394   accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());
395
396   for (Module::iterator f = mergedModule->begin(),
397          e = mergedModule->end(); f != e; ++f)
398     applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
399   for (Module::global_iterator v = mergedModule->global_begin(),
400          e = mergedModule->global_end(); v !=  e; ++v)
401     applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
402   for (Module::alias_iterator a = mergedModule->alias_begin(),
403          e = mergedModule->alias_end(); a != e; ++a)
404     applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
405
406   GlobalVariable *LLVMCompilerUsed =
407     mergedModule->getGlobalVariable("llvm.compiler.used");
408   findUsedValues(LLVMCompilerUsed, AsmUsed);
409   if (LLVMCompilerUsed)
410     LLVMCompilerUsed->eraseFromParent();
411
412   if (!AsmUsed.empty()) {
413     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
414     std::vector<Constant*> asmUsed2;
415     for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
416            e = AsmUsed.end(); i !=e; ++i) {
417       GlobalValue *GV = *i;
418       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
419       asmUsed2.push_back(c);
420     }
421
422     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
423     LLVMCompilerUsed =
424       new llvm::GlobalVariable(*mergedModule, ATy, false,
425                                llvm::GlobalValue::AppendingLinkage,
426                                llvm::ConstantArray::get(ATy, asmUsed2),
427                                "llvm.compiler.used");
428
429     LLVMCompilerUsed->setSection("llvm.metadata");
430   }
431
432   passes.add(createInternalizePass(MustPreserveList));
433
434   // apply scope restrictions
435   passes.run(*mergedModule);
436
437   ScopeRestrictionsDone = true;
438 }
439
440 /// Optimize merged modules using various IPO passes
441 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
442                                           bool DisableOpt,
443                                           bool DisableInline,
444                                           bool DisableGVNLoadPRE,
445                                           std::string &errMsg) {
446   if (!this->determineTarget(errMsg))
447     return false;
448
449   Module *mergedModule = Linker.getModule();
450
451   // Mark which symbols can not be internalized
452   this->applyScopeRestrictions();
453
454   // Instantiate the pass manager to organize the passes.
455   PassManager passes;
456
457   // Start off with a verification pass.
458   passes.add(createVerifierPass());
459
460   // Add an appropriate DataLayout instance for this module...
461   passes.add(new DataLayout(*TargetMach->getDataLayout()));
462
463   // Add appropriate TargetLibraryInfo for this module.
464   passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
465
466   TargetMach->addAnalysisPasses(passes);
467
468   // Enabling internalize here would use its AllButMain variant. It
469   // keeps only main if it exists and does nothing for libraries. Instead
470   // we create the pass ourselves with the symbol list provided by the linker.
471   if (!DisableOpt)
472     PassManagerBuilder().populateLTOPassManager(passes,
473                                               /*Internalize=*/false,
474                                               !DisableInline,
475                                               DisableGVNLoadPRE);
476
477   // Make sure everything is still good.
478   passes.add(createVerifierPass());
479
480   PassManager codeGenPasses;
481
482   codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
483   TargetMach->addAnalysisPasses(codeGenPasses);
484
485   formatted_raw_ostream Out(out);
486
487   // If the bitcode files contain ARC code and were compiled with optimization,
488   // the ObjCARCContractPass must be run, so do it unconditionally here.
489   codeGenPasses.add(createObjCARCContractPass());
490
491   if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
492                                       TargetMachine::CGFT_ObjectFile)) {
493     errMsg = "target file type not supported";
494     return false;
495   }
496
497   // Run our queue of passes all at once now, efficiently.
498   passes.run(*mergedModule);
499
500   // Run the code generator, and write assembly file
501   codeGenPasses.run(*mergedModule);
502
503   return true;
504 }
505
506 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
507 /// LTO problems.
508 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
509   for (std::pair<StringRef, StringRef> o = getToken(options);
510        !o.first.empty(); o = getToken(o.second)) {
511     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
512     // that.
513     if (CodegenOptions.empty())
514       CodegenOptions.push_back(strdup("libLLVMLTO"));
515     CodegenOptions.push_back(strdup(o.first.str().c_str()));
516   }
517 }
518
519 void LTOCodeGenerator::parseCodeGenDebugOptions() {
520   // if options were requested, set them
521   if (!CodegenOptions.empty())
522     cl::ParseCommandLineOptions(CodegenOptions.size(),
523                                 const_cast<char **>(&CodegenOptions[0]));
524 }