1 //===-- LTOModule.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/LTOModule.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Bitcode/ReaderWriter.h"
18 #include "llvm/CodeGen/Analysis.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DiagnosticPrinter.h"
21 #include "llvm/IR/LLVMContext.h"
22 #include "llvm/IR/Mangler.h"
23 #include "llvm/IR/Metadata.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/MC/MCExpr.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCTargetAsmParser.h"
33 #include "llvm/MC/SubtargetFeature.h"
34 #include "llvm/Object/IRObjectFile.h"
35 #include "llvm/Object/ObjectFile.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Host.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/Target/TargetLowering.h"
45 #include "llvm/Target/TargetLoweringObjectFile.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
47 #include "llvm/Target/TargetSubtargetInfo.h"
48 #include "llvm/Transforms/Utils/GlobalStatus.h"
49 #include <system_error>
51 using namespace llvm::object;
53 LTOModule::LTOModule(std::unique_ptr<object::IRObjectFile> Obj,
54 llvm::TargetMachine *TM)
55 : IRFile(std::move(Obj)), _target(TM) {}
57 LTOModule::LTOModule(std::unique_ptr<object::IRObjectFile> Obj,
58 llvm::TargetMachine *TM,
59 std::unique_ptr<LLVMContext> Context)
60 : OwnedContext(std::move(Context)), IRFile(std::move(Obj)), _target(TM) {}
62 LTOModule::~LTOModule() {}
64 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
66 bool LTOModule::isBitcodeFile(const void *Mem, size_t Length) {
67 ErrorOr<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(
68 MemoryBufferRef(StringRef((const char *)Mem, Length), "<mem>"));
72 bool LTOModule::isBitcodeFile(const char *Path) {
73 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
74 MemoryBuffer::getFile(Path);
78 ErrorOr<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(
79 BufferOrErr.get()->getMemBufferRef());
83 bool LTOModule::isBitcodeForTarget(MemoryBuffer *Buffer,
84 StringRef TriplePrefix) {
85 ErrorOr<MemoryBufferRef> BCOrErr =
86 IRObjectFile::findBitcodeInMemBuffer(Buffer->getMemBufferRef());
90 std::string Triple = getBitcodeTargetTriple(*BCOrErr, Context);
91 return StringRef(Triple).startswith(TriplePrefix);
94 LTOModule *LTOModule::createFromFile(const char *path, TargetOptions options,
95 std::string &errMsg) {
96 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
97 MemoryBuffer::getFile(path);
98 if (std::error_code EC = BufferOrErr.getError()) {
99 errMsg = EC.message();
102 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
103 return makeLTOModule(Buffer->getMemBufferRef(), options, errMsg,
104 &getGlobalContext());
107 LTOModule *LTOModule::createFromOpenFile(int fd, const char *path, size_t size,
108 TargetOptions options,
109 std::string &errMsg) {
110 return createFromOpenFileSlice(fd, path, size, 0, options, errMsg);
113 LTOModule *LTOModule::createFromOpenFileSlice(int fd, const char *path,
114 size_t map_size, off_t offset,
115 TargetOptions options,
116 std::string &errMsg) {
117 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
118 MemoryBuffer::getOpenFileSlice(fd, path, map_size, offset);
119 if (std::error_code EC = BufferOrErr.getError()) {
120 errMsg = EC.message();
123 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
124 return makeLTOModule(Buffer->getMemBufferRef(), options, errMsg,
125 &getGlobalContext());
128 LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length,
129 TargetOptions options,
130 std::string &errMsg, StringRef path) {
131 return createInContext(mem, length, options, errMsg, path,
132 &getGlobalContext());
135 LTOModule *LTOModule::createInLocalContext(const void *mem, size_t length,
136 TargetOptions options,
139 return createInContext(mem, length, options, errMsg, path, nullptr);
142 LTOModule *LTOModule::createInContext(const void *mem, size_t length,
143 TargetOptions options,
144 std::string &errMsg, StringRef path,
145 LLVMContext *Context) {
146 StringRef Data((const char *)mem, length);
147 MemoryBufferRef Buffer(Data, path);
148 return makeLTOModule(Buffer, options, errMsg, Context);
151 static std::unique_ptr<Module> parseBitcodeFileImpl(MemoryBufferRef Buffer,
152 LLVMContext &Context,
154 std::string &ErrMsg) {
157 ErrorOr<MemoryBufferRef> MBOrErr =
158 IRObjectFile::findBitcodeInMemBuffer(Buffer);
159 if (std::error_code EC = MBOrErr.getError()) {
160 ErrMsg = EC.message();
164 std::function<void(const DiagnosticInfo &)> DiagnosticHandler =
165 [&ErrMsg](const DiagnosticInfo &DI) {
166 raw_string_ostream Stream(ErrMsg);
167 DiagnosticPrinterRawOStream DP(Stream);
172 // Parse the full file.
173 ErrorOr<std::unique_ptr<Module>> M =
174 parseBitcodeFile(*MBOrErr, Context, DiagnosticHandler);
177 return std::move(*M);
181 std::unique_ptr<MemoryBuffer> LightweightBuf =
182 MemoryBuffer::getMemBuffer(*MBOrErr, false);
183 ErrorOr<std::unique_ptr<Module>> M =
184 getLazyBitcodeModule(std::move(LightweightBuf), Context,
185 DiagnosticHandler, true /*ShouldLazyLoadMetadata*/);
188 return std::move(*M);
191 LTOModule *LTOModule::makeLTOModule(MemoryBufferRef Buffer,
192 TargetOptions options, std::string &errMsg,
193 LLVMContext *Context) {
194 std::unique_ptr<LLVMContext> OwnedContext;
196 OwnedContext = llvm::make_unique<LLVMContext>();
197 Context = OwnedContext.get();
200 // If we own a context, we know this is being used only for symbol
201 // extraction, not linking. Be lazy in that case.
202 std::unique_ptr<Module> M = parseBitcodeFileImpl(
204 /* ShouldBeLazy */ static_cast<bool>(OwnedContext), errMsg);
208 std::string TripleStr = M->getTargetTriple();
209 if (TripleStr.empty())
210 TripleStr = sys::getDefaultTargetTriple();
211 llvm::Triple Triple(TripleStr);
213 // find machine architecture for this module
214 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
218 // construct LTOModule, hand over ownership of module and target
219 SubtargetFeatures Features;
220 Features.getDefaultSubtargetFeatures(Triple);
221 std::string FeatureStr = Features.getString();
222 // Set a default CPU for Darwin triples.
224 if (Triple.isOSDarwin()) {
225 if (Triple.getArch() == llvm::Triple::x86_64)
227 else if (Triple.getArch() == llvm::Triple::x86)
229 else if (Triple.getArch() == llvm::Triple::aarch64)
233 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
235 M->setDataLayout(target->createDataLayout());
237 std::unique_ptr<object::IRObjectFile> IRObj(
238 new object::IRObjectFile(Buffer, std::move(M)));
242 Ret = new LTOModule(std::move(IRObj), target, std::move(OwnedContext));
244 Ret = new LTOModule(std::move(IRObj), target);
246 if (Ret->parseSymbols(errMsg)) {
251 Ret->parseMetadata();
256 /// Create a MemoryBuffer from a memory range with an optional name.
257 std::unique_ptr<MemoryBuffer>
258 LTOModule::makeBuffer(const void *mem, size_t length, StringRef name) {
259 const char *startPtr = (const char*)mem;
260 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
263 /// objcClassNameFromExpression - Get string that the data pointer points to.
265 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
266 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
267 Constant *op = ce->getOperand(0);
268 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
269 Constant *cn = gvn->getInitializer();
270 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
271 if (ca->isCString()) {
272 name = (".objc_class_name_" + ca->getAsCString()).str();
281 /// addObjCClass - Parse i386/ppc ObjC class data structure.
282 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
283 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
286 // second slot in __OBJC,__class is pointer to superclass name
287 std::string superclassName;
288 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
290 _undefines.insert(std::make_pair(superclassName, NameAndAttributes()));
291 if (IterBool.second) {
292 NameAndAttributes &info = IterBool.first->second;
293 info.name = IterBool.first->first().data();
294 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
295 info.isFunction = false;
300 // third slot in __OBJC,__class is pointer to class name
301 std::string className;
302 if (objcClassNameFromExpression(c->getOperand(2), className)) {
303 auto Iter = _defines.insert(className).first;
305 NameAndAttributes info;
306 info.name = Iter->first().data();
307 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
308 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
309 info.isFunction = false;
311 _symbols.push_back(info);
315 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
316 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
317 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
320 // second slot in __OBJC,__category is pointer to target class name
321 std::string targetclassName;
322 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
326 _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
328 if (!IterBool.second)
331 NameAndAttributes &info = IterBool.first->second;
332 info.name = IterBool.first->first().data();
333 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
334 info.isFunction = false;
338 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
339 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
340 std::string targetclassName;
341 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
345 _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
347 if (!IterBool.second)
350 NameAndAttributes &info = IterBool.first->second;
351 info.name = IterBool.first->first().data();
352 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
353 info.isFunction = false;
357 void LTOModule::addDefinedDataSymbol(const object::BasicSymbolRef &Sym) {
358 SmallString<64> Buffer;
360 raw_svector_ostream OS(Buffer);
364 const GlobalValue *V = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
365 addDefinedDataSymbol(Buffer.c_str(), V);
368 void LTOModule::addDefinedDataSymbol(const char *Name, const GlobalValue *v) {
369 // Add to list of defined symbols.
370 addDefinedSymbol(Name, v, false);
372 if (!v->hasSection() /* || !isTargetDarwin */)
375 // Special case i386/ppc ObjC data structures in magic sections:
376 // The issue is that the old ObjC object format did some strange
377 // contortions to avoid real linker symbols. For instance, the
378 // ObjC class data structure is allocated statically in the executable
379 // that defines that class. That data structures contains a pointer to
380 // its superclass. But instead of just initializing that part of the
381 // struct to the address of its superclass, and letting the static and
382 // dynamic linkers do the rest, the runtime works by having that field
383 // instead point to a C-string that is the name of the superclass.
384 // At runtime the objc initialization updates that pointer and sets
385 // it to point to the actual super class. As far as the linker
386 // knows it is just a pointer to a string. But then someone wanted the
387 // linker to issue errors at build time if the superclass was not found.
388 // So they figured out a way in mach-o object format to use an absolute
389 // symbols (.objc_class_name_Foo = 0) and a floating reference
390 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
391 // a class was missing.
392 // The following synthesizes the implicit .objc_* symbols for the linker
393 // from the ObjC data structures generated by the front end.
395 // special case if this data blob is an ObjC class definition
396 std::string Section = v->getSection();
397 if (Section.compare(0, 15, "__OBJC,__class,") == 0) {
398 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
403 // special case if this data blob is an ObjC category definition
404 else if (Section.compare(0, 18, "__OBJC,__category,") == 0) {
405 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
410 // special case if this data blob is the list of referenced classes
411 else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) {
412 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
418 void LTOModule::addDefinedFunctionSymbol(const object::BasicSymbolRef &Sym) {
419 SmallString<64> Buffer;
421 raw_svector_ostream OS(Buffer);
426 cast<Function>(IRFile->getSymbolGV(Sym.getRawDataRefImpl()));
427 addDefinedFunctionSymbol(Buffer.c_str(), F);
430 void LTOModule::addDefinedFunctionSymbol(const char *Name, const Function *F) {
431 // add to list of defined symbols
432 addDefinedSymbol(Name, F, true);
435 void LTOModule::addDefinedSymbol(const char *Name, const GlobalValue *def,
437 // set alignment part log2() can have rounding errors
438 uint32_t align = def->getAlignment();
439 uint32_t attr = align ? countTrailingZeros(align) : 0;
441 // set permissions part
443 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
445 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
446 if (gv && gv->isConstant())
447 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
449 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
452 // set definition part
453 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
454 attr |= LTO_SYMBOL_DEFINITION_WEAK;
455 else if (def->hasCommonLinkage())
456 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
458 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
461 if (def->hasLocalLinkage())
462 // Ignore visibility if linkage is local.
463 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
464 else if (def->hasHiddenVisibility())
465 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
466 else if (def->hasProtectedVisibility())
467 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
468 else if (canBeOmittedFromSymbolTable(def))
469 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
471 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
473 if (def->hasComdat())
474 attr |= LTO_SYMBOL_COMDAT;
476 if (isa<GlobalAlias>(def))
477 attr |= LTO_SYMBOL_ALIAS;
479 auto Iter = _defines.insert(Name).first;
481 // fill information structure
482 NameAndAttributes info;
483 StringRef NameRef = Iter->first();
484 info.name = NameRef.data();
485 assert(info.name[NameRef.size()] == '\0');
486 info.attributes = attr;
487 info.isFunction = isFunction;
490 // add to table of symbols
491 _symbols.push_back(info);
494 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
496 void LTOModule::addAsmGlobalSymbol(const char *name,
497 lto_symbol_attributes scope) {
498 auto IterBool = _defines.insert(name);
500 // only add new define if not already defined
501 if (!IterBool.second)
504 NameAndAttributes &info = _undefines[IterBool.first->first().data()];
506 if (info.symbol == nullptr) {
507 // FIXME: This is trying to take care of module ASM like this:
509 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
511 // but is gross and its mother dresses it funny. Have the ASM parser give us
512 // more details for this type of situation so that we're not guessing so
515 // fill information structure
516 info.name = IterBool.first->first().data();
518 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
519 info.isFunction = false;
520 info.symbol = nullptr;
522 // add to table of symbols
523 _symbols.push_back(info);
528 addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));
530 addDefinedDataSymbol(info.name, info.symbol);
532 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
533 _symbols.back().attributes |= scope;
536 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
538 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
539 auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
541 _asm_undefines.push_back(IterBool.first->first().data());
543 // we already have the symbol
544 if (!IterBool.second)
547 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
548 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
549 NameAndAttributes &info = IterBool.first->second;
550 info.name = IterBool.first->first().data();
551 info.attributes = attr;
552 info.isFunction = false;
553 info.symbol = nullptr;
556 /// Add a symbol which isn't defined just yet to a list to be resolved later.
557 void LTOModule::addPotentialUndefinedSymbol(const object::BasicSymbolRef &Sym,
559 SmallString<64> name;
561 raw_svector_ostream OS(name);
565 auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
567 // we already have the symbol
568 if (!IterBool.second)
571 NameAndAttributes &info = IterBool.first->second;
573 info.name = IterBool.first->first().data();
575 const GlobalValue *decl = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
577 if (decl->hasExternalWeakLinkage())
578 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
580 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
582 info.isFunction = isFunc;
586 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
587 /// them to either the defined or undefined lists.
588 bool LTOModule::parseSymbols(std::string &errMsg) {
589 for (auto &Sym : IRFile->symbols()) {
590 const GlobalValue *GV = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
591 uint32_t Flags = Sym.getFlags();
592 if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
595 bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined;
598 SmallString<64> Buffer;
600 raw_svector_ostream OS(Buffer);
603 const char *Name = Buffer.c_str();
606 addAsmGlobalSymbolUndef(Name);
607 else if (Flags & object::BasicSymbolRef::SF_Global)
608 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_DEFAULT);
610 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_INTERNAL);
614 auto *F = dyn_cast<Function>(GV);
616 addPotentialUndefinedSymbol(Sym, F != nullptr);
621 addDefinedFunctionSymbol(Sym);
625 if (isa<GlobalVariable>(GV)) {
626 addDefinedDataSymbol(Sym);
630 assert(isa<GlobalAlias>(GV));
631 addDefinedDataSymbol(Sym);
634 // make symbols for all undefines
635 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
636 e = _undefines.end(); u != e; ++u) {
637 // If this symbol also has a definition, then don't make an undefine because
638 // it is a tentative definition.
639 if (_defines.count(u->getKey())) continue;
640 NameAndAttributes info = u->getValue();
641 _symbols.push_back(info);
647 /// parseMetadata - Parse metadata from the module
648 void LTOModule::parseMetadata() {
649 raw_string_ostream OS(LinkerOpts);
652 if (Metadata *Val = getModule().getModuleFlag("Linker Options")) {
653 MDNode *LinkerOptions = cast<MDNode>(Val);
654 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
655 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
656 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
657 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
658 OS << " " << MDOption->getString();
665 for (const NameAndAttributes &Sym : _symbols) {
668 _target->getObjFileLowering()->emitLinkerFlagsForGlobal(OS, Sym.symbol,
672 // Add other interesting metadata here.