22e9754bcfa80460cf44a91d4208798a44593928
[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/LTO/LTOModule.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Analysis/Passes.h"
19 #include "llvm/Analysis/Verifier.h"
20 #include "llvm/Bitcode/ReaderWriter.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/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/InitializePasses.h"
28 #include "llvm/Linker.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/SubtargetFeature.h"
32 #include "llvm/PassManager.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/FormattedStream.h"
36 #include "llvm/Support/Host.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/Signals.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/ToolOutputFile.h"
42 #include "llvm/Support/system_error.h"
43 #include "llvm/Target/TargetRegisterInfo.h"
44 #include "llvm/Target/Mangler.h"
45 #include "llvm/Transforms/IPO.h"
46 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
47 #include "llvm/Transforms/ObjCARC.h"
48 using namespace llvm;
49
50 static cl::opt<bool>
51 DisableOpt("disable-opt", cl::init(false),
52   cl::desc("Do not run any optimization passes"));
53
54 static cl::opt<bool>
55 DisableInline("disable-inlining", cl::init(false),
56   cl::desc("Do not run the inliner pass"));
57
58 static cl::opt<bool>
59 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
60   cl::desc("Do not run the GVN load PRE pass"));
61
62 const char* LTOCodeGenerator::getVersionString() {
63 #ifdef LLVM_VERSION_INFO
64   return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
65 #else
66   return PACKAGE_NAME " version " PACKAGE_VERSION;
67 #endif
68 }
69
70 LTOCodeGenerator::LTOCodeGenerator()
71     : Context(getGlobalContext()), Linker(new Module("ld-temp.o", Context)),
72       TargetMach(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false),
73       CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC), NativeObjectFile(NULL) {
74   initializeLTOPasses();
75 }
76
77 LTOCodeGenerator::~LTOCodeGenerator() {
78   delete TargetMach;
79   delete NativeObjectFile;
80   delete Linker.getModule();
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 //
92 void LTOCodeGenerator::initializeLTOPasses() {
93   PassRegistry &R = *PassRegistry::getPassRegistry();
94
95   initializeInternalizePassPass(R);
96   initializeIPSCCPPass(R);
97   initializeGlobalOptPass(R);
98   initializeConstantMergePass(R);
99   initializeDAHPass(R);
100   initializeInstCombinerPass(R);
101   initializeSimpleInlinerPass(R);
102   initializePruneEHPass(R);
103   initializeGlobalDCEPass(R);
104   initializeArgPromotionPass(R);
105   initializeJumpThreadingPass(R);
106   initializeSROAPass(R);
107   initializeSROA_DTPass(R);
108   initializeSROA_SSAUpPass(R);
109   initializeFunctionAttrsPass(R);
110   initializeGlobalsModRefPass(R);
111   initializeLICMPass(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 = Linker.linkInModule(mod->getLLVVMModule(), &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::setDebugInfo(lto_debug_model debug) {
129   switch (debug) {
130   case LTO_DEBUG_MODEL_NONE:
131     EmitDwarfDebugInfo = false;
132     return;
133
134   case LTO_DEBUG_MODEL_DWARF:
135     EmitDwarfDebugInfo = true;
136     return;
137   }
138   llvm_unreachable("Unknown debug format!");
139 }
140
141 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
142   switch (model) {
143   case LTO_CODEGEN_PIC_MODEL_STATIC:
144   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
145   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
146     CodeModel = model;
147     return;
148   }
149   llvm_unreachable("Unknown PIC model!");
150 }
151
152 bool LTOCodeGenerator::writeMergedModules(const char *path,
153                                           std::string &errMsg) {
154   if (!determineTarget(errMsg))
155     return false;
156
157   // mark which symbols can not be internalized
158   applyScopeRestrictions();
159
160   // create output file
161   std::string ErrInfo;
162   tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
163   if (!ErrInfo.empty()) {
164     errMsg = "could not open bitcode file for writing: ";
165     errMsg += path;
166     return false;
167   }
168
169   // write bitcode to it
170   WriteBitcodeToFile(Linker.getModule(), Out.os());
171   Out.os().close();
172
173   if (Out.os().has_error()) {
174     errMsg = "could not write bitcode file: ";
175     errMsg += path;
176     Out.os().clear_error();
177     return false;
178   }
179
180   Out.keep();
181   return true;
182 }
183
184 bool LTOCodeGenerator::compile_to_file(const char** name, std::string& errMsg) {
185   // make unique temp .o file to put generated object file
186   SmallString<128> Filename;
187   int FD;
188   error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
189   if (EC) {
190     errMsg = EC.message();
191     return false;
192   }
193
194   // generate object file
195   tool_output_file objFile(Filename.c_str(), FD);
196
197   bool genResult = generateObjectFile(objFile.os(), errMsg);
198   objFile.os().close();
199   if (objFile.os().has_error()) {
200     objFile.os().clear_error();
201     sys::fs::remove(Twine(Filename));
202     return false;
203   }
204
205   objFile.keep();
206   if (!genResult) {
207     sys::fs::remove(Twine(Filename));
208     return false;
209   }
210
211   NativeObjectPath = Filename.c_str();
212   *name = NativeObjectPath.c_str();
213   return true;
214 }
215
216 const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
217   const char *name;
218   if (!compile_to_file(&name, errMsg))
219     return NULL;
220
221   // remove old buffer if compile() called twice
222   delete NativeObjectFile;
223
224   // read .o file into memory buffer
225   OwningPtr<MemoryBuffer> BuffPtr;
226   if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
227     errMsg = ec.message();
228     sys::fs::remove(NativeObjectPath);
229     return NULL;
230   }
231   NativeObjectFile = BuffPtr.take();
232
233   // remove temp files
234   sys::fs::remove(NativeObjectPath);
235
236   // return buffer, unless error
237   if (NativeObjectFile == NULL)
238     return NULL;
239   *length = NativeObjectFile->getBufferSize();
240   return NativeObjectFile->getBufferStart();
241 }
242
243 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
244   if (TargetMach != NULL)
245     return true;
246
247   // if options were requested, set them
248   if (!CodegenOptions.empty())
249     cl::ParseCommandLineOptions(CodegenOptions.size(),
250                                 const_cast<char **>(&CodegenOptions[0]));
251
252   std::string TripleStr = Linker.getModule()->getTargetTriple();
253   if (TripleStr.empty())
254     TripleStr = sys::getDefaultTargetTriple();
255   llvm::Triple Triple(TripleStr);
256
257   // create target machine from info for merged modules
258   const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
259   if (march == NULL)
260     return false;
261
262   // The relocation model is actually a static member of TargetMachine and
263   // needs to be set before the TargetMachine is instantiated.
264   Reloc::Model RelocModel = Reloc::Default;
265   switch (CodeModel) {
266   case LTO_CODEGEN_PIC_MODEL_STATIC:
267     RelocModel = Reloc::Static;
268     break;
269   case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
270     RelocModel = Reloc::PIC_;
271     break;
272   case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
273     RelocModel = Reloc::DynamicNoPIC;
274     break;
275   }
276
277   // construct LTOModule, hand over ownership of module and target
278   SubtargetFeatures Features;
279   Features.getDefaultSubtargetFeatures(Triple);
280   std::string FeatureStr = Features.getString();
281   // Set a default CPU for Darwin triples.
282   if (MCpu.empty() && Triple.isOSDarwin()) {
283     if (Triple.getArch() == llvm::Triple::x86_64)
284       MCpu = "core2";
285     else if (Triple.getArch() == llvm::Triple::x86)
286       MCpu = "yonah";
287   }
288   TargetOptions Options;
289   LTOModule::getTargetOptions(Options);
290   TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
291                                           RelocModel, CodeModel::Default,
292                                           CodeGenOpt::Aggressive);
293   return true;
294 }
295
296 void LTOCodeGenerator::
297 applyRestriction(GlobalValue &GV,
298                  std::vector<const char*> &MustPreserveList,
299                  SmallPtrSet<GlobalValue*, 8> &AsmUsed,
300                  Mangler &Mangler) {
301   SmallString<64> Buffer;
302   Mangler.getNameWithPrefix(Buffer, &GV, false);
303
304   if (GV.isDeclaration())
305     return;
306   if (MustPreserveSymbols.count(Buffer))
307     MustPreserveList.push_back(GV.getName().data());
308   if (AsmUndefinedRefs.count(Buffer))
309     AsmUsed.insert(&GV);
310 }
311
312 static void findUsedValues(GlobalVariable *LLVMUsed,
313                            SmallPtrSet<GlobalValue*, 8> &UsedValues) {
314   if (LLVMUsed == 0) return;
315
316   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
317   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
318     if (GlobalValue *GV =
319         dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
320       UsedValues.insert(GV);
321 }
322
323 void LTOCodeGenerator::applyScopeRestrictions() {
324   if (ScopeRestrictionsDone)
325     return;
326   Module *mergedModule = Linker.getModule();
327
328   // Start off with a verification pass.
329   PassManager passes;
330   passes.add(createVerifierPass());
331
332   // mark which symbols can not be internalized
333   MCContext MContext(TargetMach->getMCAsmInfo(), TargetMach->getRegisterInfo(),
334                      NULL);
335   Mangler Mangler(MContext, TargetMach);
336   std::vector<const char*> MustPreserveList;
337   SmallPtrSet<GlobalValue*, 8> AsmUsed;
338
339   for (Module::iterator f = mergedModule->begin(),
340          e = mergedModule->end(); f != e; ++f)
341     applyRestriction(*f, MustPreserveList, AsmUsed, Mangler);
342   for (Module::global_iterator v = mergedModule->global_begin(),
343          e = mergedModule->global_end(); v !=  e; ++v)
344     applyRestriction(*v, MustPreserveList, AsmUsed, Mangler);
345   for (Module::alias_iterator a = mergedModule->alias_begin(),
346          e = mergedModule->alias_end(); a != e; ++a)
347     applyRestriction(*a, MustPreserveList, AsmUsed, Mangler);
348
349   GlobalVariable *LLVMCompilerUsed =
350     mergedModule->getGlobalVariable("llvm.compiler.used");
351   findUsedValues(LLVMCompilerUsed, AsmUsed);
352   if (LLVMCompilerUsed)
353     LLVMCompilerUsed->eraseFromParent();
354
355   if (!AsmUsed.empty()) {
356     llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
357     std::vector<Constant*> asmUsed2;
358     for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
359            e = AsmUsed.end(); i !=e; ++i) {
360       GlobalValue *GV = *i;
361       Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
362       asmUsed2.push_back(c);
363     }
364
365     llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
366     LLVMCompilerUsed =
367       new llvm::GlobalVariable(*mergedModule, ATy, false,
368                                llvm::GlobalValue::AppendingLinkage,
369                                llvm::ConstantArray::get(ATy, asmUsed2),
370                                "llvm.compiler.used");
371
372     LLVMCompilerUsed->setSection("llvm.metadata");
373   }
374
375   passes.add(createInternalizePass(MustPreserveList));
376
377   // apply scope restrictions
378   passes.run(*mergedModule);
379
380   ScopeRestrictionsDone = true;
381 }
382
383 /// Optimize merged modules using various IPO passes
384 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
385                                           std::string &errMsg) {
386   if (!this->determineTarget(errMsg))
387     return false;
388
389   Module *mergedModule = Linker.getModule();
390
391   // Mark which symbols can not be internalized
392   this->applyScopeRestrictions();
393
394   // Instantiate the pass manager to organize the passes.
395   PassManager passes;
396
397   // Start off with a verification pass.
398   passes.add(createVerifierPass());
399
400   // Add an appropriate DataLayout instance for this module...
401   passes.add(new DataLayout(*TargetMach->getDataLayout()));
402   TargetMach->addAnalysisPasses(passes);
403
404   // Enabling internalize here would use its AllButMain variant. It
405   // keeps only main if it exists and does nothing for libraries. Instead
406   // we create the pass ourselves with the symbol list provided by the linker.
407   if (!DisableOpt)
408     PassManagerBuilder().populateLTOPassManager(passes,
409                                               /*Internalize=*/false,
410                                               !DisableInline,
411                                               DisableGVNLoadPRE);
412
413   // Make sure everything is still good.
414   passes.add(createVerifierPass());
415
416   PassManager codeGenPasses;
417
418   codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
419   TargetMach->addAnalysisPasses(codeGenPasses);
420
421   formatted_raw_ostream Out(out);
422
423   // If the bitcode files contain ARC code and were compiled with optimization,
424   // the ObjCARCContractPass must be run, so do it unconditionally here.
425   codeGenPasses.add(createObjCARCContractPass());
426
427   if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
428                                       TargetMachine::CGFT_ObjectFile)) {
429     errMsg = "target file type not supported";
430     return false;
431   }
432
433   // Run our queue of passes all at once now, efficiently.
434   passes.run(*mergedModule);
435
436   // Run the code generator, and write assembly file
437   codeGenPasses.run(*mergedModule);
438
439   return true;
440 }
441
442 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
443 /// LTO problems.
444 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
445   for (std::pair<StringRef, StringRef> o = getToken(options);
446        !o.first.empty(); o = getToken(o.second)) {
447     // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
448     // that.
449     if (CodegenOptions.empty())
450       CodegenOptions.push_back(strdup("libLLVMLTO"));
451     CodegenOptions.push_back(strdup(o.first.str().c_str()));
452   }
453 }