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