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/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/DiagnosticInfo.h"
25 #include "llvm/IR/DiagnosticPrinter.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Mangler.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Verifier.h"
30 #include "llvm/InitializePasses.h"
31 #include "llvm/LTO/LTOModule.h"
32 #include "llvm/Linker/Linker.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCContext.h"
35 #include "llvm/MC/SubtargetFeature.h"
36 #include "llvm/PassManager.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/Host.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/Signals.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/ToolOutputFile.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Target/TargetLibraryInfo.h"
48 #include "llvm/Target/TargetLowering.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
51 #include "llvm/Target/TargetSubtargetInfo.h"
52 #include "llvm/Transforms/IPO.h"
53 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 #include "llvm/Transforms/ObjCARC.h"
55 #include <system_error>
58 const char* LTOCodeGenerator::getVersionString() {
59 #ifdef LLVM_VERSION_INFO
60 return PACKAGE_NAME " version " PACKAGE_VERSION ", " LLVM_VERSION_INFO;
62 return PACKAGE_NAME " version " PACKAGE_VERSION;
66 LTOCodeGenerator::LTOCodeGenerator()
67 : Context(getGlobalContext()), IRLinker(new Module("ld-temp.o", Context)),
68 TargetMach(nullptr), EmitDwarfDebugInfo(false),
69 ScopeRestrictionsDone(false), CodeModel(LTO_CODEGEN_PIC_MODEL_DEFAULT),
70 DiagHandler(nullptr), DiagContext(nullptr) {
71 initializeLTOPasses();
74 LTOCodeGenerator::~LTOCodeGenerator() {
78 IRLinker.deleteModule();
80 for (std::vector<char *>::iterator I = CodegenOptions.begin(),
81 E = CodegenOptions.end();
86 // Initialize LTO passes. Please keep this funciton in sync with
87 // PassManagerBuilder::populateLTOPassManager(), and make sure all LTO
88 // passes are initialized.
89 void LTOCodeGenerator::initializeLTOPasses() {
90 PassRegistry &R = *PassRegistry::getPassRegistry();
92 initializeInternalizePassPass(R);
93 initializeIPSCCPPass(R);
94 initializeGlobalOptPass(R);
95 initializeConstantMergePass(R);
97 initializeInstCombinerPass(R);
98 initializeSimpleInlinerPass(R);
99 initializePruneEHPass(R);
100 initializeGlobalDCEPass(R);
101 initializeArgPromotionPass(R);
102 initializeJumpThreadingPass(R);
103 initializeSROAPass(R);
104 initializeSROA_DTPass(R);
105 initializeSROA_SSAUpPass(R);
106 initializeFunctionAttrsPass(R);
107 initializeGlobalsModRefPass(R);
108 initializeLICMPass(R);
109 initializeMergedLoadStoreMotionPass(R);
110 initializeGVNPass(R);
111 initializeMemCpyOptPass(R);
112 initializeDCEPass(R);
113 initializeCFGSimplifyPassPass(R);
116 bool LTOCodeGenerator::addModule(LTOModule* mod, std::string& errMsg) {
117 bool ret = IRLinker.linkInModule(&mod->getModule(), &errMsg);
119 const std::vector<const char*> &undefs = mod->getAsmUndefinedRefs();
120 for (int i = 0, e = undefs.size(); i != e; ++i)
121 AsmUndefinedRefs[undefs[i]] = 1;
126 void LTOCodeGenerator::setTargetOptions(TargetOptions options) {
130 void LTOCodeGenerator::setDebugInfo(lto_debug_model debug) {
132 case LTO_DEBUG_MODEL_NONE:
133 EmitDwarfDebugInfo = false;
136 case LTO_DEBUG_MODEL_DWARF:
137 EmitDwarfDebugInfo = true;
140 llvm_unreachable("Unknown debug format!");
143 void LTOCodeGenerator::setCodePICModel(lto_codegen_model model) {
145 case LTO_CODEGEN_PIC_MODEL_STATIC:
146 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
147 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
148 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
152 llvm_unreachable("Unknown PIC model!");
155 bool LTOCodeGenerator::writeMergedModules(const char *path,
156 std::string &errMsg) {
157 if (!determineTarget(errMsg))
160 // mark which symbols can not be internalized
161 applyScopeRestrictions();
163 // create output file
165 tool_output_file Out(path, EC, sys::fs::F_None);
167 errMsg = "could not open bitcode file for writing: ";
172 // write bitcode to it
173 WriteBitcodeToFile(IRLinker.getModule(), Out.os());
176 if (Out.os().has_error()) {
177 errMsg = "could not write bitcode file: ";
179 Out.os().clear_error();
187 bool LTOCodeGenerator::compile_to_file(const char** name,
190 bool disableGVNLoadPRE,
191 std::string& errMsg) {
192 // make unique temp .o file to put generated object file
193 SmallString<128> Filename;
196 sys::fs::createTemporaryFile("lto-llvm", "o", FD, Filename);
198 errMsg = EC.message();
202 // generate object file
203 tool_output_file objFile(Filename.c_str(), FD);
205 bool genResult = generateObjectFile(objFile.os(), disableOpt, disableInline,
206 disableGVNLoadPRE, errMsg);
207 objFile.os().close();
208 if (objFile.os().has_error()) {
209 objFile.os().clear_error();
210 sys::fs::remove(Twine(Filename));
216 sys::fs::remove(Twine(Filename));
220 NativeObjectPath = Filename.c_str();
221 *name = NativeObjectPath.c_str();
225 const void* LTOCodeGenerator::compile(size_t* length,
228 bool disableGVNLoadPRE,
229 std::string& errMsg) {
231 if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
235 // read .o file into memory buffer
236 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
237 MemoryBuffer::getFile(name, -1, false);
238 if (std::error_code EC = BufferOrErr.getError()) {
239 errMsg = EC.message();
240 sys::fs::remove(NativeObjectPath);
243 NativeObjectFile = std::move(*BufferOrErr);
246 sys::fs::remove(NativeObjectPath);
248 // return buffer, unless error
249 if (!NativeObjectFile)
251 *length = NativeObjectFile->getBufferSize();
252 return NativeObjectFile->getBufferStart();
255 bool LTOCodeGenerator::determineTarget(std::string &errMsg) {
259 std::string TripleStr = IRLinker.getModule()->getTargetTriple();
260 if (TripleStr.empty())
261 TripleStr = sys::getDefaultTargetTriple();
262 llvm::Triple Triple(TripleStr);
264 // create target machine from info for merged modules
265 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
269 // The relocation model is actually a static member of TargetMachine and
270 // needs to be set before the TargetMachine is instantiated.
271 Reloc::Model RelocModel = Reloc::Default;
273 case LTO_CODEGEN_PIC_MODEL_STATIC:
274 RelocModel = Reloc::Static;
276 case LTO_CODEGEN_PIC_MODEL_DYNAMIC:
277 RelocModel = Reloc::PIC_;
279 case LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC:
280 RelocModel = Reloc::DynamicNoPIC;
282 case LTO_CODEGEN_PIC_MODEL_DEFAULT:
283 // RelocModel is already the default, so leave it that way.
287 // Construct LTOModule, hand over ownership of module and target. Use MAttr as
288 // the default set of features.
289 SubtargetFeatures Features(MAttr);
290 Features.getDefaultSubtargetFeatures(Triple);
291 std::string FeatureStr = Features.getString();
292 // Set a default CPU for Darwin triples.
293 if (MCpu.empty() && Triple.isOSDarwin()) {
294 if (Triple.getArch() == llvm::Triple::x86_64)
296 else if (Triple.getArch() == llvm::Triple::x86)
298 else if (Triple.getArch() == llvm::Triple::aarch64)
302 TargetMach = march->createTargetMachine(TripleStr, MCpu, FeatureStr, Options,
303 RelocModel, CodeModel::Default,
304 CodeGenOpt::Aggressive);
308 void LTOCodeGenerator::
309 applyRestriction(GlobalValue &GV,
310 ArrayRef<StringRef> Libcalls,
311 std::vector<const char*> &MustPreserveList,
312 SmallPtrSetImpl<GlobalValue*> &AsmUsed,
314 // There are no restrictions to apply to declarations.
315 if (GV.isDeclaration())
318 // There is nothing more restrictive than private linkage.
319 if (GV.hasPrivateLinkage())
322 SmallString<64> Buffer;
323 TargetMach->getNameWithPrefix(Buffer, &GV, Mangler);
325 if (MustPreserveSymbols.count(Buffer))
326 MustPreserveList.push_back(GV.getName().data());
327 if (AsmUndefinedRefs.count(Buffer))
330 // Conservatively append user-supplied runtime library functions to
331 // llvm.compiler.used. These could be internalized and deleted by
332 // optimizations like -globalopt, causing problems when later optimizations
333 // add new library calls (e.g., llvm.memset => memset and printf => puts).
334 // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
335 if (isa<Function>(GV) &&
336 std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
340 static void findUsedValues(GlobalVariable *LLVMUsed,
341 SmallPtrSetImpl<GlobalValue*> &UsedValues) {
342 if (!LLVMUsed) return;
344 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
345 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
346 if (GlobalValue *GV =
347 dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
348 UsedValues.insert(GV);
351 static void accumulateAndSortLibcalls(std::vector<StringRef> &Libcalls,
352 const TargetLibraryInfo& TLI,
353 const TargetLowering *Lowering)
355 // TargetLibraryInfo has info on C runtime library calls on the current
357 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
359 LibFunc::Func F = static_cast<LibFunc::Func>(I);
361 Libcalls.push_back(TLI.getName(F));
364 // TargetLowering has info on library calls that CodeGen expects to be
365 // available, both from the C runtime and compiler-rt.
367 for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
370 = Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
371 Libcalls.push_back(Name);
373 array_pod_sort(Libcalls.begin(), Libcalls.end());
374 Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
378 void LTOCodeGenerator::applyScopeRestrictions() {
379 if (ScopeRestrictionsDone)
381 Module *mergedModule = IRLinker.getModule();
383 // Start off with a verification pass.
385 passes.add(createVerifierPass());
386 passes.add(createDebugInfoVerifierPass());
388 // mark which symbols can not be internalized
389 Mangler Mangler(TargetMach->getSubtargetImpl()->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(
395 Libcalls, TLI, TargetMach->getSubtargetImpl()->getTargetLowering());
397 for (Module::iterator f = mergedModule->begin(),
398 e = mergedModule->end(); f != e; ++f)
399 applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
400 for (Module::global_iterator v = mergedModule->global_begin(),
401 e = mergedModule->global_end(); v != e; ++v)
402 applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
403 for (Module::alias_iterator a = mergedModule->alias_begin(),
404 e = mergedModule->alias_end(); a != e; ++a)
405 applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);
407 GlobalVariable *LLVMCompilerUsed =
408 mergedModule->getGlobalVariable("llvm.compiler.used");
409 findUsedValues(LLVMCompilerUsed, AsmUsed);
410 if (LLVMCompilerUsed)
411 LLVMCompilerUsed->eraseFromParent();
413 if (!AsmUsed.empty()) {
414 llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
415 std::vector<Constant*> asmUsed2;
416 for (auto *GV : AsmUsed) {
417 Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
418 asmUsed2.push_back(c);
421 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
423 new llvm::GlobalVariable(*mergedModule, ATy, false,
424 llvm::GlobalValue::AppendingLinkage,
425 llvm::ConstantArray::get(ATy, asmUsed2),
426 "llvm.compiler.used");
428 LLVMCompilerUsed->setSection("llvm.metadata");
431 passes.add(createInternalizePass(MustPreserveList));
433 // apply scope restrictions
434 passes.run(*mergedModule);
436 ScopeRestrictionsDone = true;
439 /// Optimize merged modules using various IPO passes
440 bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
443 bool DisableGVNLoadPRE,
444 std::string &errMsg) {
445 if (!this->determineTarget(errMsg))
448 Module *mergedModule = IRLinker.getModule();
450 // Mark which symbols can not be internalized
451 this->applyScopeRestrictions();
453 // Instantiate the pass manager to organize the passes.
456 // Add an appropriate DataLayout instance for this module...
457 mergedModule->setDataLayout(TargetMach->getSubtargetImpl()->getDataLayout());
459 Triple TargetTriple(TargetMach->getTargetTriple());
460 PassManagerBuilder PMB;
461 PMB.DisableGVNLoadPRE = DisableGVNLoadPRE;
463 PMB.Inliner = createFunctionInliningPass();
464 PMB.LibraryInfo = new TargetLibraryInfo(TargetTriple);
467 PMB.VerifyInput = true;
468 PMB.VerifyOutput = true;
470 PMB.populateLTOPassManager(passes, TargetMach);
472 PassManager codeGenPasses;
474 codeGenPasses.add(new DataLayoutPass(mergedModule));
476 formatted_raw_ostream Out(out);
478 // If the bitcode files contain ARC code and were compiled with optimization,
479 // the ObjCARCContractPass must be run, so do it unconditionally here.
480 codeGenPasses.add(createObjCARCContractPass());
482 if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
483 TargetMachine::CGFT_ObjectFile)) {
484 errMsg = "target file type not supported";
488 // Run our queue of passes all at once now, efficiently.
489 passes.run(*mergedModule);
491 // Run the code generator, and write assembly file
492 codeGenPasses.run(*mergedModule);
497 /// setCodeGenDebugOptions - Set codegen debugging options to aid in debugging
499 void LTOCodeGenerator::setCodeGenDebugOptions(const char *options) {
500 for (std::pair<StringRef, StringRef> o = getToken(options);
501 !o.first.empty(); o = getToken(o.second)) {
502 // ParseCommandLineOptions() expects argv[0] to be program name. Lazily add
504 if (CodegenOptions.empty())
505 CodegenOptions.push_back(strdup("libLLVMLTO"));
506 CodegenOptions.push_back(strdup(o.first.str().c_str()));
510 void LTOCodeGenerator::parseCodeGenDebugOptions() {
511 // if options were requested, set them
512 if (!CodegenOptions.empty())
513 cl::ParseCommandLineOptions(CodegenOptions.size(),
514 const_cast<char **>(&CodegenOptions[0]));
517 void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI,
519 ((LTOCodeGenerator *)Context)->DiagnosticHandler2(DI);
522 void LTOCodeGenerator::DiagnosticHandler2(const DiagnosticInfo &DI) {
523 // Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
524 lto_codegen_diagnostic_severity_t Severity;
525 switch (DI.getSeverity()) {
527 Severity = LTO_DS_ERROR;
530 Severity = LTO_DS_WARNING;
533 Severity = LTO_DS_REMARK;
536 Severity = LTO_DS_NOTE;
539 // Create the string that will be reported to the external diagnostic handler.
540 std::string MsgStorage;
541 raw_string_ostream Stream(MsgStorage);
542 DiagnosticPrinterRawOStream DP(Stream);
546 // If this method has been called it means someone has set up an external
547 // diagnostic handler. Assert on that.
548 assert(DiagHandler && "Invalid diagnostic handler");
549 (*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
553 LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
555 this->DiagHandler = DiagHandler;
556 this->DiagContext = Ctxt;
558 return Context.setDiagnosticHandler(nullptr, nullptr);
559 // Register the LTOCodeGenerator stub in the LLVMContext to forward the
560 // diagnostic to the external DiagHandler.
561 Context.setDiagnosticHandler(LTOCodeGenerator::DiagnosticHandler, this);