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 bool LTOModule::isBitcodeForTarget(MemoryBuffer *buffer,
72 StringRef triplePrefix) {
73 StringRef Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
74 return Triple.startswith(triplePrefix);
77 LTOModule *LTOModule::createFromFile(const char *path, TargetOptions options,
78 std::string &errMsg) {
79 std::unique_ptr<MemoryBuffer> buffer;
80 if (std::error_code ec = MemoryBuffer::getFile(path, buffer)) {
81 errMsg = ec.message();
84 return makeLTOModule(std::move(buffer), options, errMsg);
87 LTOModule *LTOModule::createFromOpenFile(int fd, const char *path, size_t size,
88 TargetOptions options,
89 std::string &errMsg) {
90 return createFromOpenFileSlice(fd, path, size, 0, options, errMsg);
93 LTOModule *LTOModule::createFromOpenFileSlice(int fd, const char *path,
94 size_t map_size, off_t offset,
95 TargetOptions options,
96 std::string &errMsg) {
97 std::unique_ptr<MemoryBuffer> buffer;
98 if (std::error_code ec =
99 MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
100 errMsg = ec.message();
103 return makeLTOModule(std::move(buffer), options, errMsg);
106 LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length,
107 TargetOptions options,
108 std::string &errMsg, StringRef path) {
109 std::unique_ptr<MemoryBuffer> buffer(makeBuffer(mem, length, path));
112 return makeLTOModule(std::move(buffer), options, errMsg);
115 LTOModule *LTOModule::makeLTOModule(std::unique_ptr<MemoryBuffer> Buffer,
116 TargetOptions options,
117 std::string &errMsg) {
118 // parse bitcode buffer
119 ErrorOr<Module *> ModuleOrErr =
120 getLazyBitcodeModule(Buffer.get(), getGlobalContext());
121 if (std::error_code EC = ModuleOrErr.getError()) {
122 errMsg = EC.message();
126 std::unique_ptr<Module> m(ModuleOrErr.get());
128 std::string TripleStr = m->getTargetTriple();
129 if (TripleStr.empty())
130 TripleStr = sys::getDefaultTargetTriple();
131 llvm::Triple Triple(TripleStr);
133 // find machine architecture for this module
134 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
138 // construct LTOModule, hand over ownership of module and target
139 SubtargetFeatures Features;
140 Features.getDefaultSubtargetFeatures(Triple);
141 std::string FeatureStr = Features.getString();
142 // Set a default CPU for Darwin triples.
144 if (Triple.isOSDarwin()) {
145 if (Triple.getArch() == llvm::Triple::x86_64)
147 else if (Triple.getArch() == llvm::Triple::x86)
149 else if (Triple.getArch() == llvm::Triple::arm64 ||
150 Triple.getArch() == llvm::Triple::aarch64)
154 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
156 m->materializeAllPermanently();
158 LTOModule *Ret = new LTOModule(std::move(m), target);
160 // We need a MCContext set up in order to get mangled names of private
161 // symbols. It is a bit odd that we need to report uses and definitions
162 // of private symbols, but it does look like ld64 expects to be informed
163 // of at least the ones with an 'l' prefix.
164 MCContext &Context = Ret->_context;
165 const TargetLoweringObjectFile &TLOF =
166 target->getTargetLowering()->getObjFileLowering();
167 const_cast<TargetLoweringObjectFile &>(TLOF).Initialize(Context, *target);
169 if (Ret->parseSymbols(errMsg)) {
174 Ret->parseMetadata();
179 /// Create a MemoryBuffer from a memory range with an optional name.
180 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length,
182 const char *startPtr = (const char*)mem;
183 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
186 /// objcClassNameFromExpression - Get string that the data pointer points to.
188 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
189 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
190 Constant *op = ce->getOperand(0);
191 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
192 Constant *cn = gvn->getInitializer();
193 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
194 if (ca->isCString()) {
195 name = ".objc_class_name_" + ca->getAsCString().str();
204 /// addObjCClass - Parse i386/ppc ObjC class data structure.
205 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
206 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
209 // second slot in __OBJC,__class is pointer to superclass name
210 std::string superclassName;
211 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
212 NameAndAttributes info;
213 StringMap<NameAndAttributes>::value_type &entry =
214 _undefines.GetOrCreateValue(superclassName);
215 if (!entry.getValue().name) {
216 const char *symbolName = entry.getKey().data();
217 info.name = symbolName;
218 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
219 info.isFunction = false;
221 entry.setValue(info);
225 // third slot in __OBJC,__class is pointer to class name
226 std::string className;
227 if (objcClassNameFromExpression(c->getOperand(2), className)) {
228 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
231 NameAndAttributes info;
232 info.name = entry.getKey().data();
233 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
234 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
235 info.isFunction = false;
237 _symbols.push_back(info);
241 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
242 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
243 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
246 // second slot in __OBJC,__category is pointer to target class name
247 std::string targetclassName;
248 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
251 NameAndAttributes info;
252 StringMap<NameAndAttributes>::value_type &entry =
253 _undefines.GetOrCreateValue(targetclassName);
255 if (entry.getValue().name)
258 const char *symbolName = entry.getKey().data();
259 info.name = symbolName;
260 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
261 info.isFunction = false;
263 entry.setValue(info);
266 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
267 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
268 std::string targetclassName;
269 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
272 NameAndAttributes info;
273 StringMap<NameAndAttributes>::value_type &entry =
274 _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 void LTOModule::addDefinedDataSymbol(const GlobalValue *V) {
287 SmallString<64> Buffer;
288 _target->getNameWithPrefix(Buffer, V, _mangler);
289 addDefinedDataSymbol(Buffer.c_str(), V);
292 void LTOModule::addDefinedDataSymbol(const char *Name, const GlobalValue *v) {
293 // Add to list of defined symbols.
294 addDefinedSymbol(Name, v, false);
296 if (!v->hasSection() /* || !isTargetDarwin */)
299 // Special case i386/ppc ObjC data structures in magic sections:
300 // The issue is that the old ObjC object format did some strange
301 // contortions to avoid real linker symbols. For instance, the
302 // ObjC class data structure is allocated statically in the executable
303 // that defines that class. That data structures contains a pointer to
304 // its superclass. But instead of just initializing that part of the
305 // struct to the address of its superclass, and letting the static and
306 // dynamic linkers do the rest, the runtime works by having that field
307 // instead point to a C-string that is the name of the superclass.
308 // At runtime the objc initialization updates that pointer and sets
309 // it to point to the actual super class. As far as the linker
310 // knows it is just a pointer to a string. But then someone wanted the
311 // linker to issue errors at build time if the superclass was not found.
312 // So they figured out a way in mach-o object format to use an absolute
313 // symbols (.objc_class_name_Foo = 0) and a floating reference
314 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
315 // a class was missing.
316 // The following synthesizes the implicit .objc_* symbols for the linker
317 // from the ObjC data structures generated by the front end.
319 // special case if this data blob is an ObjC class definition
320 std::string Section = v->getSection();
321 if (Section.compare(0, 15, "__OBJC,__class,") == 0) {
322 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
327 // special case if this data blob is an ObjC category definition
328 else if (Section.compare(0, 18, "__OBJC,__category,") == 0) {
329 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
334 // special case if this data blob is the list of referenced classes
335 else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) {
336 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
342 void LTOModule::addDefinedFunctionSymbol(const Function *F) {
343 SmallString<64> Buffer;
344 _target->getNameWithPrefix(Buffer, F, _mangler);
345 addDefinedFunctionSymbol(Buffer.c_str(), F);
348 void LTOModule::addDefinedFunctionSymbol(const char *Name, const Function *F) {
349 // add to list of defined symbols
350 addDefinedSymbol(Name, F, true);
353 static bool canBeHidden(const GlobalValue *GV) {
354 // FIXME: this is duplicated with another static function in AsmPrinter.cpp
355 GlobalValue::LinkageTypes L = GV->getLinkage();
357 if (L != GlobalValue::LinkOnceODRLinkage)
360 if (GV->hasUnnamedAddr())
363 // If it is a non constant variable, it needs to be uniqued across shared
365 if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
366 if (!Var->isConstant())
371 if (GlobalStatus::analyzeGlobal(GV, GS))
374 return !GS.IsCompared;
377 void LTOModule::addDefinedSymbol(const char *Name, const GlobalValue *def,
379 // ignore all llvm.* symbols
380 if (def->getName().startswith("llvm."))
383 // set alignment part log2() can have rounding errors
384 uint32_t align = def->getAlignment();
385 uint32_t attr = align ? countTrailingZeros(align) : 0;
387 // set permissions part
389 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
391 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
392 if (gv && gv->isConstant())
393 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
395 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
398 // set definition part
399 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
400 attr |= LTO_SYMBOL_DEFINITION_WEAK;
401 else if (def->hasCommonLinkage())
402 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
404 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
407 if (def->hasLocalLinkage())
408 // Ignore visibility if linkage is local.
409 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
410 else if (def->hasHiddenVisibility())
411 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
412 else if (def->hasProtectedVisibility())
413 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
414 else if (canBeHidden(def))
415 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
417 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
419 StringSet::value_type &entry = _defines.GetOrCreateValue(Name);
422 // fill information structure
423 NameAndAttributes info;
424 StringRef NameRef = entry.getKey();
425 info.name = NameRef.data();
426 assert(info.name[NameRef.size()] == '\0');
427 info.attributes = attr;
428 info.isFunction = isFunction;
431 // add to table of symbols
432 _symbols.push_back(info);
435 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
437 void LTOModule::addAsmGlobalSymbol(const char *name,
438 lto_symbol_attributes scope) {
439 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
441 // only add new define if not already defined
442 if (entry.getValue())
447 NameAndAttributes &info = _undefines[entry.getKey().data()];
449 if (info.symbol == nullptr) {
450 // FIXME: This is trying to take care of module ASM like this:
452 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
454 // but is gross and its mother dresses it funny. Have the ASM parser give us
455 // more details for this type of situation so that we're not guessing so
458 // fill information structure
459 info.name = entry.getKey().data();
461 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
462 info.isFunction = false;
463 info.symbol = nullptr;
465 // add to table of symbols
466 _symbols.push_back(info);
471 addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));
473 addDefinedDataSymbol(info.name, info.symbol);
475 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
476 _symbols.back().attributes |= scope;
479 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
481 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
482 StringMap<NameAndAttributes>::value_type &entry =
483 _undefines.GetOrCreateValue(name);
485 _asm_undefines.push_back(entry.getKey().data());
487 // we already have the symbol
488 if (entry.getValue().name)
491 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
492 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
493 NameAndAttributes info;
494 info.name = entry.getKey().data();
495 info.attributes = attr;
496 info.isFunction = false;
497 info.symbol = nullptr;
499 entry.setValue(info);
502 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
503 /// list to be resolved later.
505 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
506 // ignore all llvm.* symbols
507 if (decl->getName().startswith("llvm."))
510 // ignore all aliases
511 if (isa<GlobalAlias>(decl))
514 SmallString<64> name;
515 _target->getNameWithPrefix(name, decl, _mangler);
517 StringMap<NameAndAttributes>::value_type &entry =
518 _undefines.GetOrCreateValue(name);
520 // we already have the symbol
521 if (entry.getValue().name)
524 NameAndAttributes info;
526 info.name = entry.getKey().data();
528 if (decl->hasExternalWeakLinkage())
529 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
531 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
533 info.isFunction = isFunc;
536 entry.setValue(info);
539 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
540 /// defined or undefined lists.
541 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
542 const std::string &inlineAsm = _module->getModuleInlineAsm();
543 if (inlineAsm.empty())
546 std::unique_ptr<RecordStreamer> Streamer(new RecordStreamer(_context));
547 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
549 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
550 std::unique_ptr<MCAsmParser> Parser(
551 createMCAsmParser(SrcMgr, _context, *Streamer, *_target->getMCAsmInfo()));
552 const Target &T = _target->getTarget();
553 std::unique_ptr<MCInstrInfo> MCII(T.createMCInstrInfo());
554 std::unique_ptr<MCSubtargetInfo> STI(T.createMCSubtargetInfo(
555 _target->getTargetTriple(), _target->getTargetCPU(),
556 _target->getTargetFeatureString()));
557 std::unique_ptr<MCTargetAsmParser> TAP(
558 T.createMCAsmParser(*STI, *Parser.get(), *MCII,
559 _target->Options.MCOptions));
561 errMsg = "target " + std::string(T.getName()) +
562 " does not define AsmParser.";
566 Parser->setTargetParser(*TAP);
567 if (Parser->Run(false))
570 for (auto &KV : *Streamer) {
571 StringRef Key = KV.first();
572 RecordStreamer::State Value = KV.second;
573 if (Value == RecordStreamer::DefinedGlobal)
574 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
575 else if (Value == RecordStreamer::Defined)
576 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
577 else if (Value == RecordStreamer::Global ||
578 Value == RecordStreamer::Used)
579 addAsmGlobalSymbolUndef(Key.data());
585 /// isDeclaration - Return 'true' if the global value is a declaration.
586 static bool isDeclaration(const GlobalValue &V) {
587 if (V.hasAvailableExternallyLinkage())
590 if (V.isMaterializable())
593 return V.isDeclaration();
596 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
597 /// them to either the defined or undefined lists.
598 bool LTOModule::parseSymbols(std::string &errMsg) {
600 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
601 if (isDeclaration(*f))
602 addPotentialUndefinedSymbol(f, true);
604 addDefinedFunctionSymbol(f);
608 for (Module::global_iterator v = _module->global_begin(),
609 e = _module->global_end(); v != e; ++v) {
610 if (isDeclaration(*v))
611 addPotentialUndefinedSymbol(v, false);
613 addDefinedDataSymbol(v);
617 if (addAsmGlobalSymbols(errMsg))
621 for (const auto &Alias : _module->aliases())
622 addDefinedDataSymbol(&Alias);
624 // make symbols for all undefines
625 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
626 e = _undefines.end(); u != e; ++u) {
627 // If this symbol also has a definition, then don't make an undefine because
628 // it is a tentative definition.
629 if (_defines.count(u->getKey())) continue;
630 NameAndAttributes info = u->getValue();
631 _symbols.push_back(info);
637 /// parseMetadata - Parse metadata from the module
638 void LTOModule::parseMetadata() {
640 if (Value *Val = _module->getModuleFlag("Linker Options")) {
641 MDNode *LinkerOptions = cast<MDNode>(Val);
642 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
643 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
644 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
645 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
646 StringRef Op = _linkeropt_strings.
647 GetOrCreateValue(MDOption->getString()).getKey();
648 StringRef DepLibName = _target->getTargetLowering()->
649 getObjFileLowering().getDepLibFromLinkerOpt(Op);
650 if (!DepLibName.empty())
651 _deplibs.push_back(DepLibName.data());
652 else if (!Op.empty())
653 _linkeropts.push_back(Op.data());
658 // Add other interesting metadata here.