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/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/TargetOptions.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Target/Mangler.h"
46 #include "llvm/Transforms/IPO.h"
47 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
48 #include "llvm/Transforms/ObjCARC.h"
51 const char* LTOCodeGenerator::getVersionString() {
52 #ifdef LLVM_VERSION_INFO
53 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
55 return PACKAGE_NAME " version " PACKAGE_VERSION;
59 LTOCodeGenerator::LTOCodeGenerator()
60 : Context(getGlobalContext()), Linker(new Module("ld-temp.o", Context)),
61 TargetMach(NULL), EmitDwarfDebugInfo(false), ScopeRestrictionsDone(false),
62 CodeModel(LTO_CODEGEN_PIC_MODEL_DYNAMIC), NativeObjectFile(NULL) {
63 initializeLTOPasses();
66 LTOCodeGenerator::~LTOCodeGenerator() {
68 delete NativeObjectFile;
69 delete Linker.getModule();
71 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
72 E = CodegenOptions.end();
77 // Initialize LTO passes. Please keep this funciton in sync with
78 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
79 // passes are initialized.
81 void LTOCodeGenerator::initializeLTOPasses() {
82 PassRegistry &R = *PassRegistry::getPassRegistry();
84 initializeInternalizePassPass(R);
85 initializeIPSCCPPass(R);
86 initializeGlobalOptPass(R);
87 initializeConstantMergePass(R);
89 initializeInstCombinerPass(R);
90 initializeSimpleInlinerPass(R);
91 initializePruneEHPass(R);
92 initializeGlobalDCEPass(R);
93 initializeArgPromotionPass(R);
94 initializeJumpThreadingPass(R);
95 initializeSROAPass(R);
96 initializeSROA_DTPass(R);
97 initializeSROA_SSAUpPass(R);
98 initializeFunctionAttrsPass(R);
99 initializeGlobalsModRefPass(R);
100 initializeLICMPass(R);
101 initializeGVNPass(R);
102 initializeMemCpyOptPass(R);
103 initializeDCEPass(R);
104 initializeCFGSimplifyPassPass(R);
107 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
108 bool ret = Linker.linkInModule(mod->getLLVVMModule(), &errMsg);
110 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
111 for (int i = 0, e = undefs.size(); i != e; ++i)
112 AsmUndefinedRefs[undefs[i]] = 1;
117 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
118 Options.LessPreciseFPMADOption = options.LessPreciseFPMADOption;
119 Options.NoFramePointerElim = options.NoFramePointerElim;
120 Options.AllowFPOpFusion = options.AllowFPOpFusion;
121 Options.UnsafeFPMath = options.UnsafeFPMath;
122 Options.NoInfsFPMath = options.NoInfsFPMath;
123 Options.NoNaNsFPMath = options.NoNaNsFPMath;
124 Options.HonorSignDependentRoundingFPMathOption =
125 options.HonorSignDependentRoundingFPMathOption;
126 Options.UseSoftFloat = options.UseSoftFloat;
127 Options.FloatABIType = options.FloatABIType;
128 Options.NoZerosInBSS = options.NoZerosInBSS;
129 Options.GuaranteedTailCallOpt = options.GuaranteedTailCallOpt;
130 Options.DisableTailCalls = options.DisableTailCalls;
131 Options.StackAlignmentOverride = options.StackAlignmentOverride;
132 Options.TrapFuncName = options.TrapFuncName;
133 Options.PositionIndependentExecutable = options.PositionIndependentExecutable;
134 Options.EnableSegmentedStacks = options.EnableSegmentedStacks;
135 Options.UseInitArray = options.UseInitArray;
138 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
140 case LTO_DEBUG_MODEL_NONE:
141 EmitDwarfDebugInfo = false;
144 case LTO_DEBUG_MODEL_DWARF:
145 EmitDwarfDebugInfo = true;
148 llvm_unreachable("Unknown debug format!");
151 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
153 case LTO_CODEGEN_PIC_MODEL_STATIC:
154 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
155 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
159 llvm_unreachable("Unknown PIC model!");
162 bool LTOCodeGenerator::writeMergedModules(const char *path,
163 std::string &errMsg) {
164 if (!determineTarget(errMsg))
167 // mark which symbols can not be internalized
168 applyScopeRestrictions();
170 // create output file
172 tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
173 if (!ErrInfo.empty()) {
174 errMsg = "could not open bitcode file for writing: ";
179 // write bitcode to it
180 WriteBitcodeToFile(Linker.getModule(), Out.os());
183 if (Out.os().has_error()) {
184 errMsg = "could not write bitcode file: ";
186 Out.os().clear_error();
194 bool LTOCodeGenerator::compile_to_file(const char** name,
197 bool disableGVNLoadPRE,
198 std::string& errMsg) {
199 // make unique temp .o file to put generated object file
200 SmallString<128> Filename;
202 error_code EC = sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
204 errMsg = EC.message();
208 // generate object file
209 tool_output_file objFile(Filename.c_str(), FD);
211 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
212 disableGVNLoadPRE, errMsg);
213 objFile.os().close();
214 if (objFile.os().has_error()) {
215 objFile.os().clear_error();
216 sys::fs::remove(Twine(Filename));
222 sys::fs::remove(Twine(Filename));
226 NativeObjectPath = Filename.c_str();
227 *name = NativeObjectPath.c_str();
231 const void* LTOCodeGenerator::compile(size_t* length,
234 bool disableGVNLoadPRE,
235 std::string& errMsg) {
237 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
241 // remove old buffer if compile() called twice
242 delete NativeObjectFile;
244 // read .o file into memory buffer
245 OwningPtr<MemoryBuffer> BuffPtr;
246 if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
247 errMsg = ec.message();
248 sys::fs::remove(NativeObjectPath);
251 NativeObjectFile = BuffPtr.take();
254 sys::fs::remove(NativeObjectPath);
256 // return buffer, unless error
257 if (NativeObjectFile == NULL)
259 *length = NativeObjectFile->getBufferSize();
260 return NativeObjectFile->getBufferStart();
263 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
264 if (TargetMach != NULL)
267 std::string TripleStr = Linker.getModule()->getTargetTriple();
268 if (TripleStr.empty())
269 TripleStr = sys::getDefaultTargetTriple();
270 llvm::Triple Triple(TripleStr);
272 // create target machine from info for merged modules
273 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
277 // The relocation model is actually a static member of TargetMachine and
278 // needs to be set before the TargetMachine is instantiated.
279 Reloc::Model RelocModel = Reloc::Default;
281 case LTO_CODEGEN_PIC_MODEL_STATIC:
282 RelocModel = Reloc::Static;
284 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
285 RelocModel = Reloc::PIC_;
287 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
288 RelocModel = Reloc::DynamicNoPIC;
292 // construct LTOModule, hand over ownership of module and target
293 SubtargetFeatures Features;
294 Features.getDefaultSubtargetFeatures(Triple);
295 std::string FeatureStr = Features.getString();
296 // Set a default CPU for Darwin triples.
297 if (MCpu.empty() && Triple.isOSDarwin()) {
298 if (Triple.getArch() == llvm::Triple::x86_64)
300 else if (Triple.getArch() == llvm::Triple::x86)
304 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
305 RelocModel, CodeModel::Default,
306 CodeGenOpt::Aggressive);
310 void LTOCodeGenerator::
311 applyRestriction(GlobalValue &GV,
312 std::vector<const char*> &MustPreserveList,
313 SmallPtrSet<GlobalValue*, 8> &AsmUsed,
315 SmallString<64> Buffer;
316 Mangler.getNameWithPrefix(Buffer, &GV, false);
318 if (GV.isDeclaration())
320 if (MustPreserveSymbols.count(Buffer))
321 MustPreserveList.push_back(GV.getName().data());
322 if (AsmUndefinedRefs.count(Buffer))
326 static void findUsedValues(GlobalVariable *LLVMUsed,
327 SmallPtrSet<GlobalValue*, 8> &UsedValues) {
328 if (LLVMUsed == 0) return;
330 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
331 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
332 if (GlobalValue *GV =
333 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
334 UsedValues.insert(GV);
337 void LTOCodeGenerator::applyScopeRestrictions() {
338 if (ScopeRestrictionsDone)
340 Module *mergedModule = Linker.getModule();
342 // Start off with a verification pass.
344 passes.add(createVerifierPass());
346 // mark which symbols can not be internalized
347 MCContext MContext(TargetMach->getMCAsmInfo(), TargetMach->getRegisterInfo(),
349 Mangler Mangler(MContext, TargetMach);
350 std::vector<const char*> MustPreserveList;
351 SmallPtrSet<GlobalValue*, 8> AsmUsed;
353 for (Module::iterator f = mergedModule->begin(),
354 e = mergedModule->end(); f != e; ++f)
355 applyRestriction(*f, MustPreserveList, AsmUsed, Mangler);
356 for (Module::global_iterator v = mergedModule->global_begin(),
357 e = mergedModule->global_end(); v != e; ++v)
358 applyRestriction(*v, MustPreserveList, AsmUsed, Mangler);
359 for (Module::alias_iterator a = mergedModule->alias_begin(),
360 e = mergedModule->alias_end(); a != e; ++a)
361 applyRestriction(*a, MustPreserveList, AsmUsed, Mangler);
363 GlobalVariable *LLVMCompilerUsed =
364 mergedModule->getGlobalVariable("llvm.compiler.used");
365 findUsedValues(LLVMCompilerUsed, AsmUsed);
366 if (LLVMCompilerUsed)
367 LLVMCompilerUsed->eraseFromParent();
369 if (!AsmUsed.empty()) {
370 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
371 std::vector<Constant*> asmUsed2;
372 for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
373 e = AsmUsed.end(); i !=e; ++i) {
374 GlobalValue *GV = *i;
375 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
376 asmUsed2.push_back(c);
379 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
381 new llvm::GlobalVariable(*mergedModule, ATy, false,
382 llvm::GlobalValue::AppendingLinkage,
383 llvm::ConstantArray::get(ATy, asmUsed2),
384 "llvm.compiler.used");
386 LLVMCompilerUsed->setSection("llvm.metadata");
389 passes.add(createInternalizePass(MustPreserveList));
391 // apply scope restrictions
392 passes.run(*mergedModule);
394 ScopeRestrictionsDone = true;
397 /// Optimize merged modules using various IPO passes
398 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
401 bool DisableGVNLoadPRE,
402 std::string &errMsg) {
403 if (!this->determineTarget(errMsg))
406 Module *mergedModule = Linker.getModule();
408 // Mark which symbols can not be internalized
409 this->applyScopeRestrictions();
411 // Instantiate the pass manager to organize the passes.
414 // Start off with a verification pass.
415 passes.add(createVerifierPass());
417 // Add an appropriate DataLayout instance for this module...
418 passes.add(new DataLayout(*TargetMach->getDataLayout()));
419 TargetMach->addAnalysisPasses(passes);
421 // Enabling internalize here would use its AllButMain variant. It
422 // keeps only main if it exists and does nothing for libraries. Instead
423 // we create the pass ourselves with the symbol list provided by the linker.
425 PassManagerBuilder().populateLTOPassManager(passes,
426 /*Internalize=*/false,
430 // Make sure everything is still good.
431 passes.add(createVerifierPass());
433 PassManager codeGenPasses;
435 codeGenPasses.add(new DataLayout(*TargetMach->getDataLayout()));
436 TargetMach->addAnalysisPasses(codeGenPasses);
438 formatted_raw_ostream Out(out);
440 // If the bitcode files contain ARC code and were compiled with optimization,
441 // the ObjCARCContractPass must be run, so do it unconditionally here.
442 codeGenPasses.add(createObjCARCContractPass());
444 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
445 TargetMachine::CGFT_ObjectFile)) {
446 errMsg = "target file type not supported";
450 // Run our queue of passes all at once now, efficiently.
451 passes.run(*mergedModule);
453 // Run the code generator, and write assembly file
454 codeGenPasses.run(*mergedModule);
459 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
461 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
462 for (std::pair<StringRef, StringRef> o = getToken(options);
463 !o.first.empty(); o = getToken(o.second)) {
464 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
466 if (CodegenOptions.empty())
467 CodegenOptions.push_back(strdup("libLLVMLTO"));
468 CodegenOptions.push_back(strdup(o.first.str().c_str()));
472 void LTOCodeGenerator::parseCodeGenDebugOptions() {
473 // if options were requested, set them
474 if (!CodegenOptions.empty())
475 cl::ParseCommandLineOptions(CodegenOptions.size(),
476 const_cast<char **>(&CodegenOptions[0]));