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 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
74 return StringRef(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 /// addDefinedDataSymbol - Add a data symbol as defined to the list.
287 void LTOModule::addDefinedDataSymbol(const GlobalValue *v) {
288 // Add to list of defined symbols.
289 addDefinedSymbol(v, false);
291 if (!v->hasSection() /* || !isTargetDarwin */)
294 // Special case i386/ppc ObjC data structures in magic sections:
295 // The issue is that the old ObjC object format did some strange
296 // contortions to avoid real linker symbols. For instance, the
297 // ObjC class data structure is allocated statically in the executable
298 // that defines that class. That data structures contains a pointer to
299 // its superclass. But instead of just initializing that part of the
300 // struct to the address of its superclass, and letting the static and
301 // dynamic linkers do the rest, the runtime works by having that field
302 // instead point to a C-string that is the name of the superclass.
303 // At runtime the objc initialization updates that pointer and sets
304 // it to point to the actual super class. As far as the linker
305 // knows it is just a pointer to a string. But then someone wanted the
306 // linker to issue errors at build time if the superclass was not found.
307 // So they figured out a way in mach-o object format to use an absolute
308 // symbols (.objc_class_name_Foo = 0) and a floating reference
309 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
310 // a class was missing.
311 // The following synthesizes the implicit .objc_* symbols for the linker
312 // from the ObjC data structures generated by the front end.
314 // special case if this data blob is an ObjC class definition
315 std::string Section = v->getSection();
316 if (Section.compare(0, 15, "__OBJC,__class,") == 0) {
317 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
322 // special case if this data blob is an ObjC category definition
323 else if (Section.compare(0, 18, "__OBJC,__category,") == 0) {
324 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
329 // special case if this data blob is the list of referenced classes
330 else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) {
331 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
337 /// addDefinedFunctionSymbol - Add a function symbol as defined to the list.
338 void LTOModule::addDefinedFunctionSymbol(const Function *f) {
339 // add to list of defined symbols
340 addDefinedSymbol(f, true);
343 static bool canBeHidden(const GlobalValue *GV) {
344 // FIXME: this is duplicated with another static function in AsmPrinter.cpp
345 GlobalValue::LinkageTypes L = GV->getLinkage();
347 if (L != GlobalValue::LinkOnceODRLinkage)
350 if (GV->hasUnnamedAddr())
353 // If it is a non constant variable, it needs to be uniqued across shared
355 if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
356 if (!Var->isConstant())
361 if (GlobalStatus::analyzeGlobal(GV, GS))
364 return !GS.IsCompared;
367 /// addDefinedSymbol - Add a defined symbol to the list.
368 void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) {
369 // ignore all llvm.* symbols
370 if (def->getName().startswith("llvm."))
373 // string is owned by _defines
374 SmallString<64> Buffer;
375 _target->getNameWithPrefix(Buffer, def, _mangler);
377 // set alignment part log2() can have rounding errors
378 uint32_t align = def->getAlignment();
379 uint32_t attr = align ? countTrailingZeros(align) : 0;
381 // set permissions part
383 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
385 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
386 if (gv && gv->isConstant())
387 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
389 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
392 // set definition part
393 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
394 attr |= LTO_SYMBOL_DEFINITION_WEAK;
395 else if (def->hasCommonLinkage())
396 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
398 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
401 if (def->hasLocalLinkage())
402 // Ignore visibility if linkage is local.
403 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
404 else if (def->hasHiddenVisibility())
405 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
406 else if (def->hasProtectedVisibility())
407 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
408 else if (canBeHidden(def))
409 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
411 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
413 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer);
416 // fill information structure
417 NameAndAttributes info;
418 StringRef Name = entry.getKey();
419 info.name = Name.data();
420 assert(info.name[Name.size()] == '\0');
421 info.attributes = attr;
422 info.isFunction = isFunction;
425 // add to table of symbols
426 _symbols.push_back(info);
429 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
431 void LTOModule::addAsmGlobalSymbol(const char *name,
432 lto_symbol_attributes scope) {
433 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
435 // only add new define if not already defined
436 if (entry.getValue())
441 NameAndAttributes &info = _undefines[entry.getKey().data()];
443 if (info.symbol == nullptr) {
444 // FIXME: This is trying to take care of module ASM like this:
446 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
448 // but is gross and its mother dresses it funny. Have the ASM parser give us
449 // more details for this type of situation so that we're not guessing so
452 // fill information structure
453 info.name = entry.getKey().data();
455 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
456 info.isFunction = false;
457 info.symbol = nullptr;
459 // add to table of symbols
460 _symbols.push_back(info);
465 addDefinedFunctionSymbol(cast<Function>(info.symbol));
467 addDefinedDataSymbol(info.symbol);
469 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
470 _symbols.back().attributes |= scope;
473 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
475 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
476 StringMap<NameAndAttributes>::value_type &entry =
477 _undefines.GetOrCreateValue(name);
479 _asm_undefines.push_back(entry.getKey().data());
481 // we already have the symbol
482 if (entry.getValue().name)
485 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
486 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
487 NameAndAttributes info;
488 info.name = entry.getKey().data();
489 info.attributes = attr;
490 info.isFunction = false;
491 info.symbol = nullptr;
493 entry.setValue(info);
496 /// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a
497 /// list to be resolved later.
499 LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) {
500 // ignore all llvm.* symbols
501 if (decl->getName().startswith("llvm."))
504 // ignore all aliases
505 if (isa<GlobalAlias>(decl))
508 SmallString<64> name;
509 _target->getNameWithPrefix(name, decl, _mangler);
511 StringMap<NameAndAttributes>::value_type &entry =
512 _undefines.GetOrCreateValue(name);
514 // we already have the symbol
515 if (entry.getValue().name)
518 NameAndAttributes info;
520 info.name = entry.getKey().data();
522 if (decl->hasExternalWeakLinkage())
523 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
525 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
527 info.isFunction = isFunc;
530 entry.setValue(info);
533 /// addAsmGlobalSymbols - Add global symbols from module-level ASM to the
534 /// defined or undefined lists.
535 bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) {
536 const std::string &inlineAsm = _module->getModuleInlineAsm();
537 if (inlineAsm.empty())
540 std::unique_ptr<RecordStreamer> Streamer(new RecordStreamer(_context));
541 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm);
543 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
544 std::unique_ptr<MCAsmParser> Parser(
545 createMCAsmParser(SrcMgr, _context, *Streamer, *_target->getMCAsmInfo()));
546 const Target &T = _target->getTarget();
547 std::unique_ptr<MCInstrInfo> MCII(T.createMCInstrInfo());
548 std::unique_ptr<MCSubtargetInfo> STI(T.createMCSubtargetInfo(
549 _target->getTargetTriple(), _target->getTargetCPU(),
550 _target->getTargetFeatureString()));
551 std::unique_ptr<MCTargetAsmParser> TAP(
552 T.createMCAsmParser(*STI, *Parser.get(), *MCII,
553 _target->Options.MCOptions));
555 errMsg = "target " + std::string(T.getName()) +
556 " does not define AsmParser.";
560 Parser->setTargetParser(*TAP);
561 if (Parser->Run(false))
564 for (auto &KV : *Streamer) {
565 StringRef Key = KV.first();
566 RecordStreamer::State Value = KV.second;
567 if (Value == RecordStreamer::DefinedGlobal)
568 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT);
569 else if (Value == RecordStreamer::Defined)
570 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL);
571 else if (Value == RecordStreamer::Global ||
572 Value == RecordStreamer::Used)
573 addAsmGlobalSymbolUndef(Key.data());
579 /// isDeclaration - Return 'true' if the global value is a declaration.
580 static bool isDeclaration(const GlobalValue &V) {
581 if (V.hasAvailableExternallyLinkage())
584 if (V.isMaterializable())
587 return V.isDeclaration();
590 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
591 /// them to either the defined or undefined lists.
592 bool LTOModule::parseSymbols(std::string &errMsg) {
594 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) {
595 if (isDeclaration(*f))
596 addPotentialUndefinedSymbol(f, true);
598 addDefinedFunctionSymbol(f);
602 for (Module::global_iterator v = _module->global_begin(),
603 e = _module->global_end(); v != e; ++v) {
604 if (isDeclaration(*v))
605 addPotentialUndefinedSymbol(v, false);
607 addDefinedDataSymbol(v);
611 if (addAsmGlobalSymbols(errMsg))
615 for (const auto &Alias : _module->aliases())
616 addDefinedDataSymbol(&Alias);
618 // make symbols for all undefines
619 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
620 e = _undefines.end(); u != e; ++u) {
621 // If this symbol also has a definition, then don't make an undefine because
622 // it is a tentative definition.
623 if (_defines.count(u->getKey())) continue;
624 NameAndAttributes info = u->getValue();
625 _symbols.push_back(info);
631 /// parseMetadata - Parse metadata from the module
632 void LTOModule::parseMetadata() {
634 if (Value *Val = _module->getModuleFlag("Linker Options")) {
635 MDNode *LinkerOptions = cast<MDNode>(Val);
636 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
637 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
638 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
639 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
640 StringRef Op = _linkeropt_strings.
641 GetOrCreateValue(MDOption->getString()).getKey();
642 StringRef DepLibName = _target->getTargetLowering()->
643 getObjFileLowering().getDepLibFromLinkerOpt(Op);
644 if (!DepLibName.empty())
645 _deplibs.push_back(DepLibName.data());
646 else if (!Op.empty())
647 _linkeropts.push_back(Op.data());
652 // Add other interesting metadata here.