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/IR/Constants.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Metadata.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 #include "llvm/MC/MCSection.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCTargetAsmParser.h"
30 #include "llvm/MC/SubtargetFeature.h"
31 #include "llvm/Object/RecordStreamer.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Transforms/Utils/GlobalStatus.h"
44 #include <system_error>
47 LTOModule::LTOModule(std::unique_ptr<Module> M, TargetMachine *TM)
48 : _module(std::move(M)), _target(TM),
49 _context(_target->getMCAsmInfo(), _target->getRegisterInfo(),
51 _mangler(TM->getDataLayout()) {
52 ObjFileInfo.InitMCObjectFileInfo(TM->getTargetTriple(),
53 TM->getRelocationModel(), TM->getCodeModel(),
57 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
59 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
60 return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
61 sys::fs::file_magic::bitcode;
64 bool LTOModule::isBitcodeFile(const char *path) {
65 sys::fs::file_magic type;
66 if (sys::fs::identify_magic(path, type))
68 return type == sys::fs::file_magic::bitcode;
71 /// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is
72 /// LLVM bitcode for the specified triple.
73 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
74 const char *triplePrefix) {
75 MemoryBuffer *buffer = makeBuffer(mem, length);
78 return isTargetMatch(buffer, triplePrefix);
81 bool LTOModule::isBitcodeFileForTarget(const char *path,
82 const char *triplePrefix) {
83 std::unique_ptr<MemoryBuffer> buffer;
84 if (MemoryBuffer::getFile(path, buffer))
86 return isTargetMatch(buffer.release(), triplePrefix);
89 /// isTargetMatch - Returns 'true' if the memory buffer is for the specified
91 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
92 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
94 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0;
97 LTOModule *LTOModule::createFromFile(const char *path, TargetOptions options,
98 std::string &errMsg) {
99 std::unique_ptr<MemoryBuffer> buffer;
100 if (std::error_code ec = MemoryBuffer::getFile(path, buffer)) {
101 errMsg = ec.message();
104 return makeLTOModule(std::move(buffer), options, errMsg);
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 std::unique_ptr<MemoryBuffer> buffer;
118 if (std::error_code ec =
119 MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
120 errMsg = ec.message();
123 return makeLTOModule(std::move(buffer), options, errMsg);
126 LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length,
127 TargetOptions options,
128 std::string &errMsg, StringRef path) {
129 std::unique_ptr<MemoryBuffer> buffer(makeBuffer(mem, length, path));
132 return makeLTOModule(std::move(buffer), options, errMsg);
135 LTOModule *LTOModule::makeLTOModule(std::unique_ptr<MemoryBuffer> Buffer,
136 TargetOptions options,
137 std::string &errMsg) {
138 // parse bitcode buffer
139 ErrorOr<Module *> ModuleOrErr =
140 getLazyBitcodeModule(Buffer.get(), getGlobalContext());
141 if (std::error_code EC = ModuleOrErr.getError()) {
142 errMsg = EC.message();
146 std::unique_ptr<Module> m(ModuleOrErr.get());
148 std::string TripleStr = m->getTargetTriple();
149 if (TripleStr.empty())
150 TripleStr = sys::getDefaultTargetTriple();
151 llvm::Triple Triple(TripleStr);
153 // find machine architecture for this module
154 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
158 // construct LTOModule, hand over ownership of module and target
159 SubtargetFeatures Features;
160 Features.getDefaultSubtargetFeatures(Triple);
161 std::string FeatureStr = Features.getString();
162 // Set a default CPU for Darwin triples.
164 if (Triple.isOSDarwin()) {
165 if (Triple.getArch() == llvm::Triple::x86_64)
167 else if (Triple.getArch() == llvm::Triple::x86)
169 else if (Triple.getArch() == llvm::Triple::arm64 ||
170 Triple.getArch() == llvm::Triple::aarch64)
174 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
176 m->materializeAllPermanently();
178 LTOModule *Ret = new LTOModule(std::move(m), target);
180 // We need a MCContext set up in order to get mangled names of private
181 // symbols. It is a bit odd that we need to report uses and definitions
182 // of private symbols, but it does look like ld64 expects to be informed
183 // of at least the ones with an 'l' prefix.
184 MCContext &Context = Ret->_context;
185 const TargetLoweringObjectFile &TLOF =
186 target->getTargetLowering()->getObjFileLowering();
187 const_cast<TargetLoweringObjectFile &>(TLOF).Initialize(Context, *target);
189 if (Ret->parseSymbols(errMsg)) {
194 Ret->parseMetadata();
199 /// Create a MemoryBuffer from a memory range with an optional name.
200 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length,
202 const char *startPtr = (const char*)mem;
203 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
206 /// objcClassNameFromExpression - Get string that the data pointer points to.
208 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
209 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
210 Constant *op = ce->getOperand(0);
211 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
212 Constant *cn = gvn->getInitializer();
213 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
214 if (ca->isCString()) {
215 name = ".objc_class_name_" + ca->getAsCString().str();
224 /// addObjCClass - Parse i386/ppc ObjC class data structure.
225 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
226 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
229 // second slot in __OBJC,__class is pointer to superclass name
230 std::string superclassName;
231 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
232 NameAndAttributes info;
233 StringMap<NameAndAttributes>::value_type &entry =
234 _undefines.GetOrCreateValue(superclassName);
235 if (!entry.getValue().name) {
236 const char *symbolName = entry.getKey().data();
237 info.name = symbolName;
238 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
239 info.isFunction = false;
241 entry.setValue(info);
245 // third slot in __OBJC,__class is pointer to class name
246 std::string className;
247 if (objcClassNameFromExpression(c->getOperand(2), className)) {
248 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
251 NameAndAttributes info;
252 info.name = entry.getKey().data();
253 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
254 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
255 info.isFunction = false;
257 _symbols.push_back(info);
261 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
262 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
263 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
266 // second slot in __OBJC,__category is pointer to target class name
267 std::string targetclassName;
268 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
271 NameAndAttributes info;
272 StringMap<NameAndAttributes>::value_type &entry =
273 _undefines.GetOrCreateValue(targetclassName);
275 if (entry.getValue().name)
278 const char *symbolName = entry.getKey().data();
279 info.name = symbolName;
280 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
281 info.isFunction = false;
283 entry.setValue(info);
286 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
287 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
288 std::string targetclassName;
289 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
292 NameAndAttributes info;
293 StringMap<NameAndAttributes>::value_type &entry =
294 _undefines.GetOrCreateValue(targetclassName);
295 if (entry.getValue().name)
298 const char *symbolName = entry.getKey().data();
299 info.name = symbolName;
300 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
301 info.isFunction = false;
303 entry.setValue(info);
306 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
307 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
308 // Add to list of defined symbols.
309 addDefinedSymbol(v, false);
311 if (!v->hasSection() /* || !isTargetDarwin */)
314 // Special case i386/ppc ObjC data structures in magic sections:
315 // The issue is that the old ObjC object format did some strange
316 // contortions to avoid real linker symbols. For instance, the
317 // ObjC class data structure is allocated statically in the executable
318 // that defines that class. That data structures contains a pointer to
319 // its superclass. But instead of just initializing that part of the
320 // struct to the address of its superclass, and letting the static and
321 // dynamic linkers do the rest, the runtime works by having that field
322 // instead point to a C-string that is the name of the superclass.
323 // At runtime the objc initialization updates that pointer and sets
324 // it to point to the actual super class. As far as the linker
325 // knows it is just a pointer to a string. But then someone wanted the
326 // linker to issue errors at build time if the superclass was not found.
327 // So they figured out a way in mach-o object format to use an absolute
328 // symbols (.objc_class_name_Foo = 0) and a floating reference
329 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
330 // a class was missing.
331 // The following synthesizes the implicit .objc_* symbols for the linker
332 // from the ObjC data structures generated by the front end.
334 // special case if this data blob is an ObjC class definition
335 std::string Section = v->getSection();
336 if (Section.compare(0, 15, "__OBJC,__class,") == 0) {
337 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
342 // special case if this data blob is an ObjC category definition
343 else if (Section.compare(0, 18, "__OBJC,__category,") == 0) {
344 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
349 // special case if this data blob is the list of referenced classes
350 else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) {
351 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
357 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
358 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
359 // add to list of defined symbols
360 addDefinedSymbol(f, true);
363 static bool canBeHidden(const GlobalValue *GV) {
364 // FIXME: this is duplicated with another static function in AsmPrinter.cpp
365 GlobalValue::LinkageTypes L = GV->getLinkage();
367 if (L != GlobalValue::LinkOnceODRLinkage)
370 if (GV->hasUnnamedAddr())
373 // If it is a non constant variable, it needs to be uniqued across shared
375 if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
376 if (!Var->isConstant())
381 if (GlobalStatus::analyzeGlobal(GV, GS))
384 return !GS.IsCompared;
387 /// addDefinedSymbol - Add a defined symbol to the list.
388 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
389 // ignore all llvm.* symbols
390 if (def->getName().startswith("llvm."))
393 // string is owned by _defines
394 SmallString<64> Buffer;
395 _target->getNameWithPrefix(Buffer, def, _mangler);
397 // set alignment part log2() can have rounding errors
398 uint32_t align = def->getAlignment();
399 uint32_t attr = align ? countTrailingZeros(align) : 0;
401 // set permissions part
403 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
405 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
406 if (gv && gv->isConstant())
407 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
409 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
412 // set definition part
413 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
414 attr |= LTO_SYMBOL_DEFINITION_WEAK;
415 else if (def->hasCommonLinkage())
416 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
418 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
421 if (def->hasLocalLinkage())
422 // Ignore visibility if linkage is local.
423 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
424 else if (def->hasHiddenVisibility())
425 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
426 else if (def->hasProtectedVisibility())
427 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
428 else if (canBeHidden(def))
429 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
431 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
433 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
436 // fill information structure
437 NameAndAttributes info;
438 StringRef Name = entry.getKey();
439 info.name = Name.data();
440 assert(info.name[Name.size()] == '\0');
441 info.attributes = attr;
442 info.isFunction = isFunction;
445 // add to table of symbols
446 _symbols.push_back(info);
449 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
451 void LTOModule::addAsmGlobalSymbol(const char *name,
452 lto_symbol_attributes scope) {
453 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
455 // only add new define if not already defined
456 if (entry.getValue())
461 NameAndAttributes &info = _undefines[entry.getKey().data()];
463 if (info.symbol == nullptr) {
464 // FIXME: This is trying to take care of module ASM like this:
466 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
468 // but is gross and its mother dresses it funny. Have the ASM parser give us
469 // more details for this type of situation so that we're not guessing so
472 // fill information structure
473 info.name = entry.getKey().data();
475 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
476 info.isFunction = false;
477 info.symbol = nullptr;
479 // add to table of symbols
480 _symbols.push_back(info);
485 addDefinedFunctionSymbol(cast<Function>(info.symbol));
487 addDefinedDataSymbol(info.symbol);
489 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
490 _symbols.back().attributes |= scope;
493 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
495 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
496 StringMap<NameAndAttributes>::value_type &entry =
497 _undefines.GetOrCreateValue(name);
499 _asm_undefines.push_back(entry.getKey().data());
501 // we already have the symbol
502 if (entry.getValue().name)
505 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
506 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
507 NameAndAttributes info;
508 info.name = entry.getKey().data();
509 info.attributes = attr;
510 info.isFunction = false;
511 info.symbol = nullptr;
513 entry.setValue(info);
516 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
517 /// list to be resolved later.
519 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
520 // ignore all llvm.* symbols
521 if (decl->getName().startswith("llvm."))
524 // ignore all aliases
525 if (isa<GlobalAlias>(decl))
528 SmallString<64> name;
529 _target->getNameWithPrefix(name, decl, _mangler);
531 StringMap<NameAndAttributes>::value_type &entry =
532 _undefines.GetOrCreateValue(name);
534 // we already have the symbol
535 if (entry.getValue().name)
538 NameAndAttributes info;
540 info.name = entry.getKey().data();
542 if (decl->hasExternalWeakLinkage())
543 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
545 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
547 info.isFunction = isFunc;
550 entry.setValue(info);
553 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
554 /// defined or undefined lists.
555 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
556 const std::string &inlineAsm = _module->getModuleInlineAsm();
557 if (inlineAsm.empty())
560 std::unique_ptr<RecordStreamer> Streamer(new RecordStreamer(_context));
561 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
563 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
564 std::unique_ptr<MCAsmParser> Parser(
565 createMCAsmParser(SrcMgr, _context, *Streamer, *_target->getMCAsmInfo()));
566 const Target &T = _target->getTarget();
567 std::unique_ptr<MCInstrInfo> MCII(T.createMCInstrInfo());
568 std::unique_ptr<MCSubtargetInfo> STI(T.createMCSubtargetInfo(
569 _target->getTargetTriple(), _target->getTargetCPU(),
570 _target->getTargetFeatureString()));
571 std::unique_ptr<MCTargetAsmParser> TAP(
572 T.createMCAsmParser(*STI, *Parser.get(), *MCII,
573 _target->Options.MCOptions));
575 errMsg = "target " + std::string(T.getName()) +
576 " does not define AsmParser.";
580 Parser->setTargetParser(*TAP);
581 if (Parser->Run(false))
584 for (auto &KV : *Streamer) {
585 StringRef Key = KV.first();
586 RecordStreamer::State Value = KV.second;
587 if (Value == RecordStreamer::DefinedGlobal)
588 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
589 else if (Value == RecordStreamer::Defined)
590 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
591 else if (Value == RecordStreamer::Global ||
592 Value == RecordStreamer::Used)
593 addAsmGlobalSymbolUndef(Key.data());
599 /// isDeclaration - Return 'true' if the global value is a declaration.
600 static bool isDeclaration(const GlobalValue &V) {
601 if (V.hasAvailableExternallyLinkage())
604 if (V.isMaterializable())
607 return V.isDeclaration();
610 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
611 /// them to either the defined or undefined lists.
612 bool LTOModule::parseSymbols(std::string &errMsg) {
614 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
615 if (isDeclaration(*f))
616 addPotentialUndefinedSymbol(f, true);
618 addDefinedFunctionSymbol(f);
622 for (Module::global_iterator v = _module->global_begin(),
623 e = _module->global_end(); v != e; ++v) {
624 if (isDeclaration(*v))
625 addPotentialUndefinedSymbol(v, false);
627 addDefinedDataSymbol(v);
631 if (addAsmGlobalSymbols(errMsg))
635 for (const auto &Alias : _module->aliases())
636 addDefinedDataSymbol(&Alias);
638 // make symbols for all undefines
639 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
640 e = _undefines.end(); u != e; ++u) {
641 // If this symbol also has a definition, then don't make an undefine because
642 // it is a tentative definition.
643 if (_defines.count(u->getKey())) continue;
644 NameAndAttributes info = u->getValue();
645 _symbols.push_back(info);
651 /// parseMetadata - Parse metadata from the module
652 void LTOModule::parseMetadata() {
654 if (Value *Val = _module->getModuleFlag("Linker Options")) {
655 MDNode *LinkerOptions = cast<MDNode>(Val);
656 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
657 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
658 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
659 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
660 StringRef Op = _linkeropt_strings.
661 GetOrCreateValue(MDOption->getString()).getKey();
662 StringRef DepLibName = _target->getTargetLowering()->
663 getObjFileLowering().getDepLibFromLinkerOpt(Op);
664 if (!DepLibName.empty())
665 _deplibs.push_back(DepLibName.data());
666 else if (!Op.empty())
667 _linkeropts.push_back(Op.data());
672 // Add other interesting metadata here.