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/Support/CommandLine.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/TargetSelect.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Transforms/Utils/GlobalStatus.h"
43 #include <system_error>
46 LTOModule::LTOModule(std::unique_ptr<object::IRObjectFile> Obj,
47 llvm::TargetMachine *TM)
48 : IRFile(std::move(Obj)), _target(TM) {}
50 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
52 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
53 return sys::fs::identify_magic(StringRef((const char *)mem, length)) ==
54 sys::fs::file_magic::bitcode;
57 bool LTOModule::isBitcodeFile(const char *path) {
58 sys::fs::file_magic type;
59 if (sys::fs::identify_magic(path, type))
61 return type == sys::fs::file_magic::bitcode;
64 bool LTOModule::isBitcodeForTarget(MemoryBuffer *buffer,
65 StringRef triplePrefix) {
66 StringRef Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
67 return Triple.startswith(triplePrefix);
70 LTOModule *LTOModule::createFromFile(const char *path, TargetOptions options,
71 std::string &errMsg) {
72 std::unique_ptr<MemoryBuffer> buffer;
73 if (std::error_code ec = MemoryBuffer::getFile(path, buffer)) {
74 errMsg = ec.message();
77 return makeLTOModule(std::move(buffer), options, errMsg);
80 LTOModule *LTOModule::createFromOpenFile(int fd, const char *path, size_t size,
81 TargetOptions options,
82 std::string &errMsg) {
83 return createFromOpenFileSlice(fd, path, size, 0, options, errMsg);
86 LTOModule *LTOModule::createFromOpenFileSlice(int fd, const char *path,
87 size_t map_size, off_t offset,
88 TargetOptions options,
89 std::string &errMsg) {
90 std::unique_ptr<MemoryBuffer> buffer;
91 if (std::error_code ec =
92 MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) {
93 errMsg = ec.message();
96 return makeLTOModule(std::move(buffer), options, errMsg);
99 LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length,
100 TargetOptions options,
101 std::string &errMsg, StringRef path) {
102 std::unique_ptr<MemoryBuffer> buffer(makeBuffer(mem, length, path));
105 return makeLTOModule(std::move(buffer), options, errMsg);
108 LTOModule *LTOModule::makeLTOModule(std::unique_ptr<MemoryBuffer> Buffer,
109 TargetOptions options,
110 std::string &errMsg) {
111 ErrorOr<Module *> MOrErr =
112 getLazyBitcodeModule(Buffer.get(), getGlobalContext());
113 if (std::error_code EC = MOrErr.getError()) {
114 errMsg = EC.message();
117 std::unique_ptr<Module> M(MOrErr.get());
119 std::string TripleStr = M->getTargetTriple();
120 if (TripleStr.empty())
121 TripleStr = sys::getDefaultTargetTriple();
122 llvm::Triple Triple(TripleStr);
124 // find machine architecture for this module
125 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
129 // construct LTOModule, hand over ownership of module and target
130 SubtargetFeatures Features;
131 Features.getDefaultSubtargetFeatures(Triple);
132 std::string FeatureStr = Features.getString();
133 // Set a default CPU for Darwin triples.
135 if (Triple.isOSDarwin()) {
136 if (Triple.getArch() == llvm::Triple::x86_64)
138 else if (Triple.getArch() == llvm::Triple::x86)
140 else if (Triple.getArch() == llvm::Triple::arm64 ||
141 Triple.getArch() == llvm::Triple::aarch64)
145 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr,
147 M->materializeAllPermanently(true);
148 M->setDataLayout(target->getDataLayout());
150 std::unique_ptr<object::IRObjectFile> IRObj(
151 new object::IRObjectFile(std::move(Buffer), std::move(M)));
153 LTOModule *Ret = new LTOModule(std::move(IRObj), target);
155 if (Ret->parseSymbols(errMsg)) {
160 Ret->parseMetadata();
165 /// Create a MemoryBuffer from a memory range with an optional name.
166 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length,
168 const char *startPtr = (const char*)mem;
169 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
172 /// objcClassNameFromExpression - Get string that the data pointer points to.
174 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
175 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
176 Constant *op = ce->getOperand(0);
177 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
178 Constant *cn = gvn->getInitializer();
179 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
180 if (ca->isCString()) {
181 name = ".objc_class_name_" + ca->getAsCString().str();
190 /// addObjCClass - Parse i386/ppc ObjC class data structure.
191 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
192 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
195 // second slot in __OBJC,__class is pointer to superclass name
196 std::string superclassName;
197 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
198 NameAndAttributes info;
199 StringMap<NameAndAttributes>::value_type &entry =
200 _undefines.GetOrCreateValue(superclassName);
201 if (!entry.getValue().name) {
202 const char *symbolName = entry.getKey().data();
203 info.name = symbolName;
204 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
205 info.isFunction = false;
207 entry.setValue(info);
211 // third slot in __OBJC,__class is pointer to class name
212 std::string className;
213 if (objcClassNameFromExpression(c->getOperand(2), className)) {
214 StringSet::value_type &entry = _defines.GetOrCreateValue(className);
217 NameAndAttributes info;
218 info.name = entry.getKey().data();
219 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
220 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
221 info.isFunction = false;
223 _symbols.push_back(info);
227 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
228 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
229 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
232 // second slot in __OBJC,__category is pointer to target class name
233 std::string targetclassName;
234 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
237 NameAndAttributes info;
238 StringMap<NameAndAttributes>::value_type &entry =
239 _undefines.GetOrCreateValue(targetclassName);
241 if (entry.getValue().name)
244 const char *symbolName = entry.getKey().data();
245 info.name = symbolName;
246 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
247 info.isFunction = false;
249 entry.setValue(info);
252 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
253 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
254 std::string targetclassName;
255 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
258 NameAndAttributes info;
259 StringMap<NameAndAttributes>::value_type &entry =
260 _undefines.GetOrCreateValue(targetclassName);
261 if (entry.getValue().name)
264 const char *symbolName = entry.getKey().data();
265 info.name = symbolName;
266 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
267 info.isFunction = false;
269 entry.setValue(info);
272 void LTOModule::addDefinedDataSymbol(const object::BasicSymbolRef &Sym) {
273 SmallString<64> Buffer;
275 raw_svector_ostream OS(Buffer);
279 const GlobalValue *V = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
280 addDefinedDataSymbol(Buffer.c_str(), V);
283 void LTOModule::addDefinedDataSymbol(const char *Name, const GlobalValue *v) {
284 // Add to list of defined symbols.
285 addDefinedSymbol(Name, v, false);
287 if (!v->hasSection() /* || !isTargetDarwin */)
290 // Special case i386/ppc ObjC data structures in magic sections:
291 // The issue is that the old ObjC object format did some strange
292 // contortions to avoid real linker symbols. For instance, the
293 // ObjC class data structure is allocated statically in the executable
294 // that defines that class. That data structures contains a pointer to
295 // its superclass. But instead of just initializing that part of the
296 // struct to the address of its superclass, and letting the static and
297 // dynamic linkers do the rest, the runtime works by having that field
298 // instead point to a C-string that is the name of the superclass.
299 // At runtime the objc initialization updates that pointer and sets
300 // it to point to the actual super class. As far as the linker
301 // knows it is just a pointer to a string. But then someone wanted the
302 // linker to issue errors at build time if the superclass was not found.
303 // So they figured out a way in mach-o object format to use an absolute
304 // symbols (.objc_class_name_Foo = 0) and a floating reference
305 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
306 // a class was missing.
307 // The following synthesizes the implicit .objc_* symbols for the linker
308 // from the ObjC data structures generated by the front end.
310 // special case if this data blob is an ObjC class definition
311 std::string Section = v->getSection();
312 if (Section.compare(0, 15, "__OBJC,__class,") == 0) {
313 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
318 // special case if this data blob is an ObjC category definition
319 else if (Section.compare(0, 18, "__OBJC,__category,") == 0) {
320 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
325 // special case if this data blob is the list of referenced classes
326 else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) {
327 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
333 void LTOModule::addDefinedFunctionSymbol(const object::BasicSymbolRef &Sym) {
334 SmallString<64> Buffer;
336 raw_svector_ostream OS(Buffer);
341 cast<Function>(IRFile->getSymbolGV(Sym.getRawDataRefImpl()));
342 addDefinedFunctionSymbol(Buffer.c_str(), F);
345 void LTOModule::addDefinedFunctionSymbol(const char *Name, const Function *F) {
346 // add to list of defined symbols
347 addDefinedSymbol(Name, F, true);
350 static bool canBeHidden(const GlobalValue *GV) {
351 // FIXME: this is duplicated with another static function in AsmPrinter.cpp
352 GlobalValue::LinkageTypes L = GV->getLinkage();
354 if (L != GlobalValue::LinkOnceODRLinkage)
357 if (GV->hasUnnamedAddr())
360 // If it is a non constant variable, it needs to be uniqued across shared
362 if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
363 if (!Var->isConstant())
368 if (GlobalStatus::analyzeGlobal(GV, GS))
371 return !GS.IsCompared;
374 void LTOModule::addDefinedSymbol(const char *Name, const GlobalValue *def,
376 // set alignment part log2() can have rounding errors
377 uint32_t align = def->getAlignment();
378 uint32_t attr = align ? countTrailingZeros(align) : 0;
380 // set permissions part
382 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
384 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
385 if (gv && gv->isConstant())
386 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
388 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
391 // set definition part
392 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
393 attr |= LTO_SYMBOL_DEFINITION_WEAK;
394 else if (def->hasCommonLinkage())
395 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
397 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
400 if (def->hasLocalLinkage())
401 // Ignore visibility if linkage is local.
402 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
403 else if (def->hasHiddenVisibility())
404 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
405 else if (def->hasProtectedVisibility())
406 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
407 else if (canBeHidden(def))
408 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
410 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
412 StringSet::value_type &entry = _defines.GetOrCreateValue(Name);
415 // fill information structure
416 NameAndAttributes info;
417 StringRef NameRef = entry.getKey();
418 info.name = NameRef.data();
419 assert(info.name[NameRef.size()] == '\0');
420 info.attributes = attr;
421 info.isFunction = isFunction;
424 // add to table of symbols
425 _symbols.push_back(info);
428 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
430 void LTOModule::addAsmGlobalSymbol(const char *name,
431 lto_symbol_attributes scope) {
432 StringSet::value_type &entry = _defines.GetOrCreateValue(name);
434 // only add new define if not already defined
435 if (entry.getValue())
440 NameAndAttributes &info = _undefines[entry.getKey().data()];
442 if (info.symbol == nullptr) {
443 // FIXME: This is trying to take care of module ASM like this:
445 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
447 // but is gross and its mother dresses it funny. Have the ASM parser give us
448 // more details for this type of situation so that we're not guessing so
451 // fill information structure
452 info.name = entry.getKey().data();
454 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
455 info.isFunction = false;
456 info.symbol = nullptr;
458 // add to table of symbols
459 _symbols.push_back(info);
464 addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));
466 addDefinedDataSymbol(info.name, info.symbol);
468 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
469 _symbols.back().attributes |= scope;
472 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
474 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
475 StringMap<NameAndAttributes>::value_type &entry =
476 _undefines.GetOrCreateValue(name);
478 _asm_undefines.push_back(entry.getKey().data());
480 // we already have the symbol
481 if (entry.getValue().name)
484 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
485 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
486 NameAndAttributes info;
487 info.name = entry.getKey().data();
488 info.attributes = attr;
489 info.isFunction = false;
490 info.symbol = nullptr;
492 entry.setValue(info);
495 /// Add a symbol which isn't defined just yet to a list to be resolved later.
496 void LTOModule::addPotentialUndefinedSymbol(const object::BasicSymbolRef &Sym,
498 SmallString<64> name;
500 raw_svector_ostream OS(name);
504 StringMap<NameAndAttributes>::value_type &entry =
505 _undefines.GetOrCreateValue(name);
507 // we already have the symbol
508 if (entry.getValue().name)
511 NameAndAttributes info;
513 info.name = entry.getKey().data();
515 const GlobalValue *decl = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
517 if (decl->hasExternalWeakLinkage())
518 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
520 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
522 info.isFunction = isFunc;
525 entry.setValue(info);
528 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
529 /// them to either the defined or undefined lists.
530 bool LTOModule::parseSymbols(std::string &errMsg) {
531 for (auto &Sym : IRFile->symbols()) {
532 const GlobalValue *GV = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
533 uint32_t Flags = Sym.getFlags();
534 if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
537 bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined;
540 SmallString<64> Buffer;
542 raw_svector_ostream OS(Buffer);
545 const char *Name = Buffer.c_str();
548 addAsmGlobalSymbolUndef(Name);
549 else if (Flags & object::BasicSymbolRef::SF_Global)
550 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_DEFAULT);
552 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_INTERNAL);
556 auto *F = dyn_cast<Function>(GV);
558 addPotentialUndefinedSymbol(Sym, F != nullptr);
563 addDefinedFunctionSymbol(Sym);
567 if (isa<GlobalVariable>(GV)) {
568 addDefinedDataSymbol(Sym);
572 assert(isa<GlobalAlias>(GV));
573 addDefinedDataSymbol(Sym);
576 // make symbols for all undefines
577 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
578 e = _undefines.end(); u != e; ++u) {
579 // If this symbol also has a definition, then don't make an undefine because
580 // it is a tentative definition.
581 if (_defines.count(u->getKey())) continue;
582 NameAndAttributes info = u->getValue();
583 _symbols.push_back(info);
589 /// parseMetadata - Parse metadata from the module
590 void LTOModule::parseMetadata() {
592 if (Value *Val = getModule().getModuleFlag("Linker Options")) {
593 MDNode *LinkerOptions = cast<MDNode>(Val);
594 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
595 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
596 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
597 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
598 StringRef Op = _linkeropt_strings.
599 GetOrCreateValue(MDOption->getString()).getKey();
600 StringRef DepLibName = _target->getTargetLowering()->
601 getObjFileLowering().getDepLibFromLinkerOpt(Op);
602 if (!DepLibName.empty())
603 _deplibs.push_back(DepLibName.data());
604 else if (!Op.empty())
605 _linkeropts.push_back(Op.data());
610 // Add other interesting metadata here.