[InstCombine] Signed saturation patterns
[llvm-core.git] / lib / LTO / LTOModule.cpp
blob587b332e706491d5302580feeb4c88ce34252976
1 //===-- LTOModule.cpp - LLVM Link Time Optimizer --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Link Time Optimization library. This library is
10 // intended to be used by linker to optimize code at link time.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/LTO/legacy/LTOModule.h"
15 #include "llvm/ADT/Triple.h"
16 #include "llvm/Bitcode/BitcodeReader.h"
17 #include "llvm/CodeGen/TargetSubtargetInfo.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/LLVMContext.h"
20 #include "llvm/IR/Mangler.h"
21 #include "llvm/IR/Metadata.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCInst.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/SubtargetFeature.h"
30 #include "llvm/Object/IRObjectFile.h"
31 #include "llvm/Object/ObjectFile.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/TargetLoweringObjectFile.h"
40 #include "llvm/Transforms/Utils/GlobalStatus.h"
41 #include <system_error>
42 using namespace llvm;
43 using namespace llvm::object;
45 LTOModule::LTOModule(std::unique_ptr<Module> M, MemoryBufferRef MBRef,
46 llvm::TargetMachine *TM)
47 : Mod(std::move(M)), MBRef(MBRef), _target(TM) {
48 SymTab.addModule(Mod.get());
51 LTOModule::~LTOModule() {}
53 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM
54 /// bitcode.
55 bool LTOModule::isBitcodeFile(const void *Mem, size_t Length) {
56 Expected<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(
57 MemoryBufferRef(StringRef((const char *)Mem, Length), "<mem>"));
58 return !errorToBool(BCData.takeError());
61 bool LTOModule::isBitcodeFile(StringRef Path) {
62 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
63 MemoryBuffer::getFile(Path);
64 if (!BufferOrErr)
65 return false;
67 Expected<MemoryBufferRef> BCData = IRObjectFile::findBitcodeInMemBuffer(
68 BufferOrErr.get()->getMemBufferRef());
69 return !errorToBool(BCData.takeError());
72 bool LTOModule::isThinLTO() {
73 Expected<BitcodeLTOInfo> Result = getBitcodeLTOInfo(MBRef);
74 if (!Result) {
75 logAllUnhandledErrors(Result.takeError(), errs());
76 return false;
78 return Result->IsThinLTO;
81 bool LTOModule::isBitcodeForTarget(MemoryBuffer *Buffer,
82 StringRef TriplePrefix) {
83 Expected<MemoryBufferRef> BCOrErr =
84 IRObjectFile::findBitcodeInMemBuffer(Buffer->getMemBufferRef());
85 if (errorToBool(BCOrErr.takeError()))
86 return false;
87 LLVMContext Context;
88 ErrorOr<std::string> TripleOrErr =
89 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(*BCOrErr));
90 if (!TripleOrErr)
91 return false;
92 return StringRef(*TripleOrErr).startswith(TriplePrefix);
95 std::string LTOModule::getProducerString(MemoryBuffer *Buffer) {
96 Expected<MemoryBufferRef> BCOrErr =
97 IRObjectFile::findBitcodeInMemBuffer(Buffer->getMemBufferRef());
98 if (errorToBool(BCOrErr.takeError()))
99 return "";
100 LLVMContext Context;
101 ErrorOr<std::string> ProducerOrErr = expectedToErrorOrAndEmitErrors(
102 Context, getBitcodeProducerString(*BCOrErr));
103 if (!ProducerOrErr)
104 return "";
105 return *ProducerOrErr;
108 ErrorOr<std::unique_ptr<LTOModule>>
109 LTOModule::createFromFile(LLVMContext &Context, StringRef path,
110 const TargetOptions &options) {
111 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
112 MemoryBuffer::getFile(path);
113 if (std::error_code EC = BufferOrErr.getError()) {
114 Context.emitError(EC.message());
115 return EC;
117 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
118 return makeLTOModule(Buffer->getMemBufferRef(), options, Context,
119 /* ShouldBeLazy*/ false);
122 ErrorOr<std::unique_ptr<LTOModule>>
123 LTOModule::createFromOpenFile(LLVMContext &Context, int fd, StringRef path,
124 size_t size, const TargetOptions &options) {
125 return createFromOpenFileSlice(Context, fd, path, size, 0, options);
128 ErrorOr<std::unique_ptr<LTOModule>>
129 LTOModule::createFromOpenFileSlice(LLVMContext &Context, int fd, StringRef path,
130 size_t map_size, off_t offset,
131 const TargetOptions &options) {
132 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
133 MemoryBuffer::getOpenFileSlice(sys::fs::convertFDToNativeFile(fd), path,
134 map_size, offset);
135 if (std::error_code EC = BufferOrErr.getError()) {
136 Context.emitError(EC.message());
137 return EC;
139 std::unique_ptr<MemoryBuffer> Buffer = std::move(BufferOrErr.get());
140 return makeLTOModule(Buffer->getMemBufferRef(), options, Context,
141 /* ShouldBeLazy */ false);
144 ErrorOr<std::unique_ptr<LTOModule>>
145 LTOModule::createFromBuffer(LLVMContext &Context, const void *mem,
146 size_t length, const TargetOptions &options,
147 StringRef path) {
148 StringRef Data((const char *)mem, length);
149 MemoryBufferRef Buffer(Data, path);
150 return makeLTOModule(Buffer, options, Context, /* ShouldBeLazy */ false);
153 ErrorOr<std::unique_ptr<LTOModule>>
154 LTOModule::createInLocalContext(std::unique_ptr<LLVMContext> Context,
155 const void *mem, size_t length,
156 const TargetOptions &options, StringRef path) {
157 StringRef Data((const char *)mem, length);
158 MemoryBufferRef Buffer(Data, path);
159 // If we own a context, we know this is being used only for symbol extraction,
160 // not linking. Be lazy in that case.
161 ErrorOr<std::unique_ptr<LTOModule>> Ret =
162 makeLTOModule(Buffer, options, *Context, /* ShouldBeLazy */ true);
163 if (Ret)
164 (*Ret)->OwnedContext = std::move(Context);
165 return Ret;
168 static ErrorOr<std::unique_ptr<Module>>
169 parseBitcodeFileImpl(MemoryBufferRef Buffer, LLVMContext &Context,
170 bool ShouldBeLazy) {
171 // Find the buffer.
172 Expected<MemoryBufferRef> MBOrErr =
173 IRObjectFile::findBitcodeInMemBuffer(Buffer);
174 if (Error E = MBOrErr.takeError()) {
175 std::error_code EC = errorToErrorCode(std::move(E));
176 Context.emitError(EC.message());
177 return EC;
180 if (!ShouldBeLazy) {
181 // Parse the full file.
182 return expectedToErrorOrAndEmitErrors(Context,
183 parseBitcodeFile(*MBOrErr, Context));
186 // Parse lazily.
187 return expectedToErrorOrAndEmitErrors(
188 Context,
189 getLazyBitcodeModule(*MBOrErr, Context, true /*ShouldLazyLoadMetadata*/));
192 ErrorOr<std::unique_ptr<LTOModule>>
193 LTOModule::makeLTOModule(MemoryBufferRef Buffer, const TargetOptions &options,
194 LLVMContext &Context, bool ShouldBeLazy) {
195 ErrorOr<std::unique_ptr<Module>> MOrErr =
196 parseBitcodeFileImpl(Buffer, Context, ShouldBeLazy);
197 if (std::error_code EC = MOrErr.getError())
198 return EC;
199 std::unique_ptr<Module> &M = *MOrErr;
201 std::string TripleStr = M->getTargetTriple();
202 if (TripleStr.empty())
203 TripleStr = sys::getDefaultTargetTriple();
204 llvm::Triple Triple(TripleStr);
206 // find machine architecture for this module
207 std::string errMsg;
208 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg);
209 if (!march)
210 return make_error_code(object::object_error::arch_not_found);
212 // construct LTOModule, hand over ownership of module and target
213 SubtargetFeatures Features;
214 Features.getDefaultSubtargetFeatures(Triple);
215 std::string FeatureStr = Features.getString();
216 // Set a default CPU for Darwin triples.
217 std::string CPU;
218 if (Triple.isOSDarwin()) {
219 if (Triple.getArch() == llvm::Triple::x86_64)
220 CPU = "core2";
221 else if (Triple.getArch() == llvm::Triple::x86)
222 CPU = "yonah";
223 else if (Triple.getArch() == llvm::Triple::aarch64 ||
224 Triple.getArch() == llvm::Triple::aarch64_32)
225 CPU = "cyclone";
228 TargetMachine *target =
229 march->createTargetMachine(TripleStr, CPU, FeatureStr, options, None);
231 std::unique_ptr<LTOModule> Ret(new LTOModule(std::move(M), Buffer, target));
232 Ret->parseSymbols();
233 Ret->parseMetadata();
235 return std::move(Ret);
238 /// Create a MemoryBuffer from a memory range with an optional name.
239 std::unique_ptr<MemoryBuffer>
240 LTOModule::makeBuffer(const void *mem, size_t length, StringRef name) {
241 const char *startPtr = (const char*)mem;
242 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false);
245 /// objcClassNameFromExpression - Get string that the data pointer points to.
246 bool
247 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
248 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
249 Constant *op = ce->getOperand(0);
250 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
251 Constant *cn = gvn->getInitializer();
252 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
253 if (ca->isCString()) {
254 name = (".objc_class_name_" + ca->getAsCString()).str();
255 return true;
260 return false;
263 /// addObjCClass - Parse i386/ppc ObjC class data structure.
264 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
265 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
266 if (!c) return;
268 // second slot in __OBJC,__class is pointer to superclass name
269 std::string superclassName;
270 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
271 auto IterBool =
272 _undefines.insert(std::make_pair(superclassName, NameAndAttributes()));
273 if (IterBool.second) {
274 NameAndAttributes &info = IterBool.first->second;
275 info.name = IterBool.first->first();
276 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
277 info.isFunction = false;
278 info.symbol = clgv;
282 // third slot in __OBJC,__class is pointer to class name
283 std::string className;
284 if (objcClassNameFromExpression(c->getOperand(2), className)) {
285 auto Iter = _defines.insert(className).first;
287 NameAndAttributes info;
288 info.name = Iter->first();
289 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
290 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
291 info.isFunction = false;
292 info.symbol = clgv;
293 _symbols.push_back(info);
297 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
298 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
299 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
300 if (!c) return;
302 // second slot in __OBJC,__category is pointer to target class name
303 std::string targetclassName;
304 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
305 return;
307 auto IterBool =
308 _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
310 if (!IterBool.second)
311 return;
313 NameAndAttributes &info = IterBool.first->second;
314 info.name = IterBool.first->first();
315 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
316 info.isFunction = false;
317 info.symbol = clgv;
320 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
321 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
322 std::string targetclassName;
323 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
324 return;
326 auto IterBool =
327 _undefines.insert(std::make_pair(targetclassName, NameAndAttributes()));
329 if (!IterBool.second)
330 return;
332 NameAndAttributes &info = IterBool.first->second;
333 info.name = IterBool.first->first();
334 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
335 info.isFunction = false;
336 info.symbol = clgv;
339 void LTOModule::addDefinedDataSymbol(ModuleSymbolTable::Symbol Sym) {
340 SmallString<64> Buffer;
342 raw_svector_ostream OS(Buffer);
343 SymTab.printSymbolName(OS, Sym);
344 Buffer.c_str();
347 const GlobalValue *V = Sym.get<GlobalValue *>();
348 addDefinedDataSymbol(Buffer, V);
351 void LTOModule::addDefinedDataSymbol(StringRef Name, const GlobalValue *v) {
352 // Add to list of defined symbols.
353 addDefinedSymbol(Name, v, false);
355 if (!v->hasSection() /* || !isTargetDarwin */)
356 return;
358 // Special case i386/ppc ObjC data structures in magic sections:
359 // The issue is that the old ObjC object format did some strange
360 // contortions to avoid real linker symbols. For instance, the
361 // ObjC class data structure is allocated statically in the executable
362 // that defines that class. That data structures contains a pointer to
363 // its superclass. But instead of just initializing that part of the
364 // struct to the address of its superclass, and letting the static and
365 // dynamic linkers do the rest, the runtime works by having that field
366 // instead point to a C-string that is the name of the superclass.
367 // At runtime the objc initialization updates that pointer and sets
368 // it to point to the actual super class. As far as the linker
369 // knows it is just a pointer to a string. But then someone wanted the
370 // linker to issue errors at build time if the superclass was not found.
371 // So they figured out a way in mach-o object format to use an absolute
372 // symbols (.objc_class_name_Foo = 0) and a floating reference
373 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
374 // a class was missing.
375 // The following synthesizes the implicit .objc_* symbols for the linker
376 // from the ObjC data structures generated by the front end.
378 // special case if this data blob is an ObjC class definition
379 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(v)) {
380 StringRef Section = GV->getSection();
381 if (Section.startswith("__OBJC,__class,")) {
382 addObjCClass(GV);
385 // special case if this data blob is an ObjC category definition
386 else if (Section.startswith("__OBJC,__category,")) {
387 addObjCCategory(GV);
390 // special case if this data blob is the list of referenced classes
391 else if (Section.startswith("__OBJC,__cls_refs,")) {
392 addObjCClassRef(GV);
397 void LTOModule::addDefinedFunctionSymbol(ModuleSymbolTable::Symbol Sym) {
398 SmallString<64> Buffer;
400 raw_svector_ostream OS(Buffer);
401 SymTab.printSymbolName(OS, Sym);
402 Buffer.c_str();
405 const Function *F = cast<Function>(Sym.get<GlobalValue *>());
406 addDefinedFunctionSymbol(Buffer, F);
409 void LTOModule::addDefinedFunctionSymbol(StringRef Name, const Function *F) {
410 // add to list of defined symbols
411 addDefinedSymbol(Name, F, true);
414 void LTOModule::addDefinedSymbol(StringRef Name, const GlobalValue *def,
415 bool isFunction) {
416 // set alignment part log2() can have rounding errors
417 uint32_t align = def->getAlignment();
418 uint32_t attr = align ? countTrailingZeros(align) : 0;
420 // set permissions part
421 if (isFunction) {
422 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
423 } else {
424 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
425 if (gv && gv->isConstant())
426 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
427 else
428 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
431 // set definition part
432 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
433 attr |= LTO_SYMBOL_DEFINITION_WEAK;
434 else if (def->hasCommonLinkage())
435 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
436 else
437 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
439 // set scope part
440 if (def->hasLocalLinkage())
441 // Ignore visibility if linkage is local.
442 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
443 else if (def->hasHiddenVisibility())
444 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
445 else if (def->hasProtectedVisibility())
446 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
447 else if (def->canBeOmittedFromSymbolTable())
448 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
449 else
450 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
452 if (def->hasComdat())
453 attr |= LTO_SYMBOL_COMDAT;
455 if (isa<GlobalAlias>(def))
456 attr |= LTO_SYMBOL_ALIAS;
458 auto Iter = _defines.insert(Name).first;
460 // fill information structure
461 NameAndAttributes info;
462 StringRef NameRef = Iter->first();
463 info.name = NameRef;
464 assert(NameRef.data()[NameRef.size()] == '\0');
465 info.attributes = attr;
466 info.isFunction = isFunction;
467 info.symbol = def;
469 // add to table of symbols
470 _symbols.push_back(info);
473 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
474 /// defined list.
475 void LTOModule::addAsmGlobalSymbol(StringRef name,
476 lto_symbol_attributes scope) {
477 auto IterBool = _defines.insert(name);
479 // only add new define if not already defined
480 if (!IterBool.second)
481 return;
483 NameAndAttributes &info = _undefines[IterBool.first->first()];
485 if (info.symbol == nullptr) {
486 // FIXME: This is trying to take care of module ASM like this:
488 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
490 // but is gross and its mother dresses it funny. Have the ASM parser give us
491 // more details for this type of situation so that we're not guessing so
492 // much.
494 // fill information structure
495 info.name = IterBool.first->first();
496 info.attributes =
497 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
498 info.isFunction = false;
499 info.symbol = nullptr;
501 // add to table of symbols
502 _symbols.push_back(info);
503 return;
506 if (info.isFunction)
507 addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));
508 else
509 addDefinedDataSymbol(info.name, info.symbol);
511 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
512 _symbols.back().attributes |= scope;
515 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
516 /// undefined list.
517 void LTOModule::addAsmGlobalSymbolUndef(StringRef name) {
518 auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
520 _asm_undefines.push_back(IterBool.first->first());
522 // we already have the symbol
523 if (!IterBool.second)
524 return;
526 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
527 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
528 NameAndAttributes &info = IterBool.first->second;
529 info.name = IterBool.first->first();
530 info.attributes = attr;
531 info.isFunction = false;
532 info.symbol = nullptr;
535 /// Add a symbol which isn't defined just yet to a list to be resolved later.
536 void LTOModule::addPotentialUndefinedSymbol(ModuleSymbolTable::Symbol Sym,
537 bool isFunc) {
538 SmallString<64> name;
540 raw_svector_ostream OS(name);
541 SymTab.printSymbolName(OS, Sym);
542 name.c_str();
545 auto IterBool = _undefines.insert(std::make_pair(name, NameAndAttributes()));
547 // we already have the symbol
548 if (!IterBool.second)
549 return;
551 NameAndAttributes &info = IterBool.first->second;
553 info.name = IterBool.first->first();
555 const GlobalValue *decl = Sym.dyn_cast<GlobalValue *>();
557 if (decl->hasExternalWeakLinkage())
558 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
559 else
560 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
562 info.isFunction = isFunc;
563 info.symbol = decl;
566 void LTOModule::parseSymbols() {
567 for (auto Sym : SymTab.symbols()) {
568 auto *GV = Sym.dyn_cast<GlobalValue *>();
569 uint32_t Flags = SymTab.getSymbolFlags(Sym);
570 if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
571 continue;
573 bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined;
575 if (!GV) {
576 SmallString<64> Buffer;
578 raw_svector_ostream OS(Buffer);
579 SymTab.printSymbolName(OS, Sym);
580 Buffer.c_str();
582 StringRef Name(Buffer);
584 if (IsUndefined)
585 addAsmGlobalSymbolUndef(Name);
586 else if (Flags & object::BasicSymbolRef::SF_Global)
587 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_DEFAULT);
588 else
589 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_INTERNAL);
590 continue;
593 auto *F = dyn_cast<Function>(GV);
594 if (IsUndefined) {
595 addPotentialUndefinedSymbol(Sym, F != nullptr);
596 continue;
599 if (F) {
600 addDefinedFunctionSymbol(Sym);
601 continue;
604 if (isa<GlobalVariable>(GV)) {
605 addDefinedDataSymbol(Sym);
606 continue;
609 assert(isa<GlobalAlias>(GV));
610 addDefinedDataSymbol(Sym);
613 // make symbols for all undefines
614 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
615 e = _undefines.end(); u != e; ++u) {
616 // If this symbol also has a definition, then don't make an undefine because
617 // it is a tentative definition.
618 if (_defines.count(u->getKey())) continue;
619 NameAndAttributes info = u->getValue();
620 _symbols.push_back(info);
624 /// parseMetadata - Parse metadata from the module
625 void LTOModule::parseMetadata() {
626 raw_string_ostream OS(LinkerOpts);
628 // Linker Options
629 if (NamedMDNode *LinkerOptions =
630 getModule().getNamedMetadata("llvm.linker.options")) {
631 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
632 MDNode *MDOptions = LinkerOptions->getOperand(i);
633 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
634 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
635 OS << " " << MDOption->getString();
640 // Globals - we only need to do this for COFF.
641 const Triple TT(_target->getTargetTriple());
642 if (!TT.isOSBinFormatCOFF())
643 return;
644 Mangler M;
645 for (const NameAndAttributes &Sym : _symbols) {
646 if (!Sym.symbol)
647 continue;
648 emitLinkerFlagsForGlobalCOFF(OS, Sym.symbol, TT, M);
652 lto::InputFile *LTOModule::createInputFile(const void *buffer,
653 size_t buffer_size, const char *path,
654 std::string &outErr) {
655 StringRef Data((const char *)buffer, buffer_size);
656 MemoryBufferRef BufferRef(Data, path);
658 Expected<std::unique_ptr<lto::InputFile>> ObjOrErr =
659 lto::InputFile::create(BufferRef);
661 if (ObjOrErr)
662 return ObjOrErr->release();
664 outErr = std::string(path) +
665 ": Could not read LTO input file: " + toString(ObjOrErr.takeError());
666 return nullptr;
669 size_t LTOModule::getDependentLibraryCount(lto::InputFile *input) {
670 return input->getDependentLibraries().size();
673 const char *LTOModule::getDependentLibrary(lto::InputFile *input, size_t index,
674 size_t *size) {
675 StringRef S = input->getDependentLibraries()[index];
676 *size = S.size();
677 return S.data();