1 //===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/LTO/LTOCodeGenerator.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Analysis/Verifier.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/CodeGen/RuntimeLibcalls.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/Mangler.h"
27 #include "llvm/IR/Module.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"
54 const char* LTOCodeGenerator::getVersionString() {
55 #ifdef LLVM_VERSION_INFO
56 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
58 return PACKAGE_NAME " version " PACKAGE_VERSION;
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();
69 LTOCodeGenerator::~LTOCodeGenerator() {
71 delete NativeObjectFile;
73 NativeObjectFile = NULL;
75 Linker.deleteModule();
77 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
78 E = CodegenOptions.end();
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();
89 initializeInternalizePassPass(R);
90 initializeIPSCCPPass(R);
91 initializeGlobalOptPass(R);
92 initializeConstantMergePass(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);
112 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
113 bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
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;
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;
143 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
145 case LTO_DEBUG_MODEL_NONE:
146 EmitDwarfDebugInfo = false;
149 case LTO_DEBUG_MODEL_DWARF:
150 EmitDwarfDebugInfo = true;
153 llvm_unreachable("Unknown debug format!");
156 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
158 case LTO_CODEGEN_PIC_MODEL_STATIC:
159 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
160 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
164 llvm_unreachable("Unknown PIC model!");
167 bool LTOCodeGenerator::writeMergedModules(const char *path,
168 std::string &errMsg) {
169 if (!determineTarget(errMsg))
172 // mark which symbols can not be internalized
173 applyScopeRestrictions();
175 // create output file
177 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
178 if (!ErrInfo.empty()) {
179 errMsg = "could not open bitcode file for writing: ";
184 // write bitcode to it
185 WriteBitcodeToFile(Linker.getModule(), Out.os());
188 if (Out.os().has_error()) {
189 errMsg = "could not write bitcode file: ";
191 Out.os().clear_error();
199 bool LTOCodeGenerator::compile_to_file(const char** name,
202 bool disableGVNLoadPRE,
203 std::string& errMsg) {
204 // make unique temp .o file to put generated object file
205 SmallString<128> Filename;
207 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
209 errMsg = EC.message();
213 // generate object file
214 tool_output_file objFile(Filename.c_str(), FD);
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));
227 sys::fs::remove(Twine(Filename));
231 NativeObjectPath = Filename.c_str();
232 *name = NativeObjectPath.c_str();
236 const void* LTOCodeGenerator::compile(size_t* length,
239 bool disableGVNLoadPRE,
240 std::string& errMsg) {
242 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
246 // remove old buffer if compile() called twice
247 delete NativeObjectFile;
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);
256 NativeObjectFile = BuffPtr.take();
259 sys::fs::remove(NativeObjectPath);
261 // return buffer, unless error
262 if (NativeObjectFile == NULL)
264 *length = NativeObjectFile->getBufferSize();
265 return NativeObjectFile->getBufferStart();
268 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
269 if (TargetMach != NULL)
272 std::string TripleStr = Linker.getModule()->getTargetTriple();
273 if (TripleStr.empty())
274 TripleStr = sys::getDefaultTargetTriple();
275 llvm::Triple Triple(TripleStr);
277 // create target machine from info for merged modules
278 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
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;
286 case LTO_CODEGEN_PIC_MODEL_STATIC:
287 RelocModel = Reloc::Static;
289 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
290 RelocModel = Reloc::PIC_;
292 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
293 RelocModel = Reloc::DynamicNoPIC;
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)
305 else if (Triple.getArch() == llvm::Triple::x86)
309 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
310 RelocModel, CodeModel::Default,
311 CodeGenOpt::Aggressive);
315 void LTOCodeGenerator::
316 applyRestriction(GlobalValue &GV,
317 const ArrayRef<StringRef> &Libcalls,
318 std::vector<const char*> &MustPreserveList,
319 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
321 SmallString<64> Buffer;
322 Mangler.getNameWithPrefix(Buffer, &GV);
324 if (GV.isDeclaration())
326 if (MustPreserveSymbols.count(Buffer))
327 MustPreserveList.push_back(GV.getName().data());
328 if (AsmUndefinedRefs.count(Buffer))
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()))
341 static void findUsedValues(GlobalVariable *LLVMUsed,
342 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
343 if (LLVMUsed == 0) return;
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);
352 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
353 const TargetLibraryInfo& TLI,
354 const TargetLowering *Lowering)
356 // TargetLibraryInfo has info on C runtime library calls on the current
358 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
360 LibFunc::Func F = static_cast<LibFunc::Func>(I);
362 Libcalls.push_back(TLI.getName(F));
365 // TargetLowering has info on library calls that CodeGen expects to be
366 // available, both from the C runtime and compiler-rt.
368 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
371 = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
372 Libcalls.push_back(Name);
374 array_pod_sort(Libcalls.begin(), Libcalls.end());
375 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
379 void LTOCodeGenerator::applyScopeRestrictions() {
380 if (ScopeRestrictionsDone)
382 Module *mergedModule = Linker.getModule();
384 // Start off with a verification pass.
386 passes.add(createVerifierPass());
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());
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);
406 GlobalVariable *LLVMCompilerUsed =
407 mergedModule->getGlobalVariable("llvm.compiler.used");
408 findUsedValues(LLVMCompilerUsed, AsmUsed);
409 if (LLVMCompilerUsed)
410 LLVMCompilerUsed->eraseFromParent();
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);
422 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
424 new llvm::GlobalVariable(*mergedModule, ATy, false,
425 llvm::GlobalValue::AppendingLinkage,
426 llvm::ConstantArray::get(ATy, asmUsed2),
427 "llvm.compiler.used");
429 LLVMCompilerUsed->setSection("llvm.metadata");
432 passes.add(createInternalizePass(MustPreserveList));
434 // apply scope restrictions
435 passes.run(*mergedModule);
437 ScopeRestrictionsDone = true;
440 /// Optimize merged modules using various IPO passes
441 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
444 bool DisableGVNLoadPRE,
445 std::string &errMsg) {
446 if (!this->determineTarget(errMsg))
449 Module *mergedModule = Linker.getModule();
451 // Mark which symbols can not be internalized
452 this->applyScopeRestrictions();
454 // Instantiate the pass manager to organize the passes.
457 // Start off with a verification pass.
458 passes.add(createVerifierPass());
460 // Add an appropriate DataLayout instance for this module...
461 passes.add(new DataLayout(*TargetMach->getDataLayout()));
463 // Add appropriate TargetLibraryInfo for this module.
464 passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));
466 TargetMach->addAnalysisPasses(passes);
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.
472 PassManagerBuilder().populateLTOPassManager(passes,
473 /*Internalize=*/false,
477 // Make sure everything is still good.
478 passes.add(createVerifierPass());
480 PassManager codeGenPasses;
482 codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
483 TargetMach->addAnalysisPasses(codeGenPasses);
485 formatted_raw_ostream Out(out);
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());
491 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
492 TargetMachine::CGFT_ObjectFile)) {
493 errMsg = "target file type not supported";
497 // Run our queue of passes all at once now, efficiently.
498 passes.run(*mergedModule);
500 // Run the code generator, and write assembly file
501 codeGenPasses.run(*mergedModule);
506 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
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
513 if (CodegenOptions.empty())
514 CodegenOptions.push_back(strdup("libLLVMLTO"));
515 CodegenOptions.push_back(strdup(o.first.str().c_str()));
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]));