1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2006-2010 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
22 * @APPLE_LICENSE_HEADER_END@
25 #ifndef __LTO_READER_H__
26 #define __LTO_READER_H__
29 #include <sys/param.h>
30 #include <sys/fcntl.h>
35 #include <mach-o/dyld.h>
38 #include <unordered_set>
39 #include <unordered_map>
43 #include "MachOFileAbstraction.hpp"
44 #include "Architectures.hpp"
46 #include "macho_relocatable_file.h"
49 // #defines are a work around for <rdar://problem/8760268>
50 #define __STDC_LIMIT_MACROS 1
51 #define __STDC_CONSTANT_MACROS 1
52 #include "llvm-c/lto.h"
58 // ld64 only tracks non-internal symbols from an llvm bitcode file.
59 // We model this by having an InternalAtom which represent all internal functions and data.
60 // All non-interal symbols from a bitcode file are represented by an Atom
61 // and each Atom has a reference to the InternalAtom. The InternalAtom
62 // also has references to each symbol external to the bitcode file.
64 class InternalAtom
: public ld::Atom
67 InternalAtom(class File
& f
);
68 // overrides of ld::Atom
69 ld::File
* file() const override
{ return &_file
; }
70 const char* name() const override
{ return "import-atom"; }
71 uint64_t size() const override
{ return 0; }
72 uint64_t objectAddress() const override
{ return 0; }
73 void copyRawContent(uint8_t buffer
[]) const override
{ }
74 ld::Fixup::iterator
fixupsBegin() const override
{ return &_undefs
[0]; }
75 ld::Fixup::iterator
fixupsEnd() const override
{ return &_undefs
[_undefs
.size()]; }
77 // for adding references to symbols outside bitcode file
78 void addReference(const char* nm
)
79 { _undefs
.push_back(ld::Fixup(0, ld::Fixup::k1of1
,
80 ld::Fixup::kindNone
, false, strdup(nm
))); }
84 mutable std::vector
<ld::Fixup
> _undefs
;
91 class File
: public ld::relocatable::File
94 File(const char* path
, time_t mTime
, ld::File::Ordinal ordinal
,
95 const uint8_t* content
, uint32_t contentLength
, cpu_type_t arch
);
98 // overrides of ld::File
99 bool forEachAtom(ld::File::AtomHandler
&) const override
;
100 bool justInTimeforEachAtom(const char* name
, ld::File::AtomHandler
&) const override
102 uint32_t cpuSubType() const override
{ return _cpuSubType
; }
104 // overrides of ld::relocatable::File
105 DebugInfoKind
debugInfo() const override
{ return _debugInfo
; }
106 const char* debugInfoPath() const override
{ return _debugInfoPath
; }
107 time_t debugInfoModificationTime() const override
108 { return _debugInfoModTime
; }
109 const std::vector
<ld::relocatable::File::Stab
>* stabs() const override
{ return NULL
; }
110 bool canScatterAtoms() const override
{ return true; }
111 LinkerOptionsList
* linkerOptions() const override
{ return NULL
; }
112 bool isThinLTO() const { return _isThinLTO
; }
113 void setIsThinLTO(bool ThinLTO
) { _isThinLTO
= ThinLTO
; }
114 // fixme rdar://24734472 objCConstraint() and objcHasCategoryClassProperties()
116 lto_module_t
module() { return _module
; }
117 class InternalAtom
& internalAtom() { return _internalAtom
; }
118 void setDebugInfo(ld::relocatable::File::DebugInfoKind k
,
119 const char* pth
, time_t modTime
, uint32_t subtype
)
121 _debugInfoPath
= pth
;
122 _debugInfoModTime
= modTime
;
123 _cpuSubType
= subtype
;}
125 static bool sSupportsLocalContext
;
126 static bool sHasTriedLocalContext
;
127 bool mergeIntoGenerator(lto_code_gen_t generator
, bool useSetModule
);
128 #if LTO_API_VERSION >= 18
129 void addToThinGenerator(thinlto_code_gen_t generator
, int id
);
133 friend class InternalAtom
;
137 cpu_type_t _architecture
;
138 class InternalAtom _internalAtom
;
139 class Atom
* _atomArray
;
140 uint32_t _atomArrayCount
;
141 lto_module_t _module
;
143 const uint8_t* _content
;
144 uint32_t _contentLength
;
145 const char* _debugInfoPath
;
146 time_t _debugInfoModTime
;
147 ld::Section _section
;
148 ld::Fixup _fixupToInternal
;
149 ld::relocatable::File::DebugInfoKind _debugInfo
;
150 uint32_t _cpuSubType
;
154 // Atom acts as a proxy Atom for the symbols that are exported by LLVM bitcode file. Initially,
155 // Reader creates Atoms to allow linker proceed with usual symbol resolution phase. After
156 // optimization is performed, real Atoms are created for these symobls. However these real Atoms
157 // are not inserted into global symbol table. Atom holds real Atom and forwards appropriate
158 // methods to real atom.
160 class Atom
: public ld::Atom
163 Atom(File
& f
, const char* name
, ld::Atom::Scope s
,
164 ld::Atom::Definition d
, ld::Atom::Combine c
, ld::Atom::Alignment a
, bool ah
);
166 // overrides of ld::Atom
167 const ld::File
* file() const override
{ return (_compiledAtom
? _compiledAtom
->file() : &_file
); }
168 const ld::File
* originalFile() const override
{ return &_file
; }
169 const char* translationUnitSource() const override
170 { return (_compiledAtom
? _compiledAtom
->translationUnitSource() : NULL
); }
171 const char* name() const override
{ return _name
; }
172 uint64_t size() const override
{ return (_compiledAtom
? _compiledAtom
->size() : 0); }
173 uint64_t objectAddress() const override
{ return (_compiledAtom
? _compiledAtom
->objectAddress() : 0); }
174 void copyRawContent(uint8_t buffer
[]) const override
175 { if (_compiledAtom
) _compiledAtom
->copyRawContent(buffer
); }
176 const uint8_t* rawContentPointer() const override
177 { return (_compiledAtom
? _compiledAtom
->rawContentPointer() : NULL
); }
178 unsigned long contentHash(const class ld::IndirectBindingTable
& ibt
) const override
179 { return (_compiledAtom
? _compiledAtom
->contentHash(ibt
) : 0); }
180 bool canCoalesceWith(const ld::Atom
& rhs
, const class ld::IndirectBindingTable
& ibt
) const override
181 { return (_compiledAtom
? _compiledAtom
->canCoalesceWith(rhs
,ibt
) : false); }
182 ld::Fixup::iterator
fixupsBegin() const override
183 { return (_compiledAtom
? _compiledAtom
->fixupsBegin() : (ld::Fixup
*)&_file
._fixupToInternal
); }
184 ld::Fixup::iterator
fixupsEnd() const override
185 { return (_compiledAtom
? _compiledAtom
->fixupsEnd() : &((ld::Fixup
*)&_file
._fixupToInternal
)[1]); }
186 ld::Atom::UnwindInfo::iterator
beginUnwind() const override
187 { return (_compiledAtom
? _compiledAtom
->beginUnwind() : NULL
); }
188 ld::Atom::UnwindInfo::iterator
endUnwind() const override
189 { return (_compiledAtom
? _compiledAtom
->endUnwind() : NULL
); }
190 ld::Atom::LineInfo::iterator
beginLineInfo() const override
191 { return (_compiledAtom
? _compiledAtom
->beginLineInfo() : NULL
); }
192 ld::Atom::LineInfo::iterator
endLineInfo() const override
193 { return (_compiledAtom
? _compiledAtom
->endLineInfo() : NULL
); }
195 const ld::Atom
* compiledAtom() { return _compiledAtom
; }
196 void setCompiledAtom(const ld::Atom
& atom
);
202 const ld::Atom
* _compiledAtom
;
214 static bool validFile(const uint8_t* fileContent
, uint64_t fileLength
, cpu_type_t architecture
, cpu_subtype_t subarch
);
215 static const char* fileKind(const uint8_t* fileContent
, uint64_t fileLength
);
216 static File
* parse(const uint8_t* fileContent
, uint64_t fileLength
, const char* path
,
217 time_t modTime
, ld::File::Ordinal ordinal
, cpu_type_t architecture
, cpu_subtype_t subarch
,
218 bool logAllFiles
, bool verboseOptimizationHints
);
219 static bool libLTOisLoaded() { return (::lto_get_version() != NULL
); }
220 static bool optimize( const std::vector
<const ld::Atom
*>& allAtoms
,
222 const OptimizeOptions
& options
,
223 ld::File::AtomHandler
& handler
,
224 std::vector
<const ld::Atom
*>& newAtoms
,
225 std::vector
<const char*>& additionalUndefines
);
227 static const char* ltoVersion() { return ::lto_get_version(); }
231 static const char* tripletPrefixForArch(cpu_type_t arch
);
232 static ld::relocatable::File
* parseMachOFile(const uint8_t* p
, size_t len
, const std::string
&path
, const OptimizeOptions
& options
,
233 ld::File::Ordinal ordinal
);
234 #if LTO_API_VERSION >= 7
235 static void ltoDiagnosticHandler(lto_codegen_diagnostic_severity_t
, const char*, void*);
238 typedef std::unordered_set
<const char*, ld::CStringHash
, ld::CStringEquals
> CStringSet
;
239 typedef std::unordered_map
<const char*, Atom
*, ld::CStringHash
, ld::CStringEquals
> CStringToAtom
;
241 class AtomSyncer
: public ld::File::AtomHandler
{
243 AtomSyncer(std::vector
<const char*>& a
, std::vector
<const ld::Atom
*>&na
,
244 const CStringToAtom
&la
, const CStringToAtom
&dla
, const OptimizeOptions
& options
) :
245 _options(options
), _additionalUndefines(a
), _newAtoms(na
), _llvmAtoms(la
), _deadllvmAtoms(dla
), _lastProxiedAtom(NULL
), _lastProxiedFile(NULL
) {}
246 void doAtom(const class ld::Atom
&) override
;
247 void doFile(const class ld::File
&) override
{ }
249 const OptimizeOptions
& _options
;
250 std::vector
<const char*>& _additionalUndefines
;
251 std::vector
<const ld::Atom
*>& _newAtoms
;
252 const CStringToAtom
&_llvmAtoms
;
253 const CStringToAtom
&_deadllvmAtoms
;
254 const ld::Atom
* _lastProxiedAtom
;
255 const ld::File
* _lastProxiedFile
;
258 static void setPreservedSymbols(const std::vector
<const ld::Atom
*>& allAtoms
,
260 const OptimizeOptions
& options
,
261 CStringToAtom
&deadllvmAtoms
,
262 CStringToAtom
&llvmAtoms
,
263 lto_code_gen_t generator
);
265 static std::tuple
<uint8_t *, size_t> codegen(const OptimizeOptions
& options
,
267 lto_code_gen_t generator
,
268 std::string
& object_path
);
271 static void loadMachO(ld::relocatable::File
* machoFile
,
272 const OptimizeOptions
& options
,
273 ld::File::AtomHandler
& handler
,
274 std::vector
<const ld::Atom
*>& newAtoms
,
275 std::vector
<const char*>& additionalUndefines
,
276 CStringToAtom
&llvmAtoms
,
277 CStringToAtom
&deadllvmAtoms
);
279 static bool optimizeLTO(const std::vector
<File
*> files
,
280 const std::vector
<const ld::Atom
*>& allAtoms
,
282 const OptimizeOptions
& options
,
283 ld::File::AtomHandler
& handler
,
284 std::vector
<const ld::Atom
*>& newAtoms
,
285 std::vector
<const char*>& additionalUndefines
);
287 static bool optimizeThinLTO(const std::vector
<File
*>& Files
,
288 const std::vector
<const ld::Atom
*>& allAtoms
,
290 const OptimizeOptions
& options
,
291 ld::File::AtomHandler
& handler
,
292 std::vector
<const ld::Atom
*>& newAtoms
,
293 std::vector
<const char*>& additionalUndefines
);
295 #if LTO_API_VERSION >= 18
296 static thinlto_code_gen_t
init_thinlto_codegen(const std::vector
<File
*>& files
,
297 const std::vector
<const ld::Atom
*>& allAtoms
,
299 const OptimizeOptions
& options
,
300 CStringToAtom
& deadllvmAtoms
,
301 CStringToAtom
& llvmAtoms
);
304 static std::vector
<File
*> _s_files
;
305 static bool _s_llvmOptionsProcessed
;
308 std::vector
<File
*> Parser::_s_files
;
309 bool Parser::_s_llvmOptionsProcessed
= false;
312 bool Parser::validFile(const uint8_t* fileContent
, uint64_t fileLength
, cpu_type_t architecture
, cpu_subtype_t subarch
)
314 for (const ArchInfo
* t
=archInfoArray
; t
->archName
!= NULL
; ++t
) {
315 if ( (architecture
== t
->cpuType
) && (!(t
->isSubType
) || (subarch
== t
->cpuSubType
)) ) {
316 bool result
= ::lto_module_is_object_file_in_memory_for_target(fileContent
, fileLength
, t
->llvmTriplePrefix
);
318 // <rdar://problem/8434487> LTO only supports thumbv7 not armv7
319 if ( t
->llvmTriplePrefixAlt
[0] != '\0' ) {
320 result
= ::lto_module_is_object_file_in_memory_for_target(fileContent
, fileLength
, t
->llvmTriplePrefixAlt
);
329 const char* Parser::fileKind(const uint8_t* p
, uint64_t fileLength
)
331 if ( (p
[0] == 0xDE) && (p
[1] == 0xC0) && (p
[2] == 0x17) && (p
[3] == 0x0B) ) {
332 cpu_type_t arch
= LittleEndian::get32(*((uint32_t*)(&p
[16])));
333 for (const ArchInfo
* t
=archInfoArray
; t
->archName
!= NULL
; ++t
) {
334 if ( arch
== t
->cpuType
) {
335 if ( t
->isSubType
) {
336 if ( ::lto_module_is_object_file_in_memory_for_target(p
, fileLength
, t
->llvmTriplePrefix
) )
344 return "unknown bitcode architecture";
349 File
* Parser::parse(const uint8_t* fileContent
, uint64_t fileLength
, const char* path
, time_t modTime
, ld::File::Ordinal ordinal
,
350 cpu_type_t architecture
, cpu_subtype_t subarch
, bool logAllFiles
, bool verboseOptimizationHints
)
352 File
* f
= new File(path
, modTime
, ordinal
, fileContent
, fileLength
, architecture
);
353 _s_files
.push_back(f
);
355 printf("%s\n", path
);
360 ld::relocatable::File
* Parser::parseMachOFile(const uint8_t* p
, size_t len
, const std::string
&path
, const OptimizeOptions
& options
,
361 ld::File::Ordinal ordinal
)
363 mach_o::relocatable::ParserOptions objOpts
;
364 objOpts
.architecture
= options
.arch
;
365 objOpts
.objSubtypeMustMatch
= false;
366 objOpts
.logAllFiles
= false;
367 objOpts
.warnUnwindConversionProblems
= options
.needsUnwindInfoSection
;
368 objOpts
.keepDwarfUnwind
= options
.keepDwarfUnwind
;
369 objOpts
.forceDwarfConversion
= false;
370 objOpts
.neverConvertDwarf
= false;
371 objOpts
.verboseOptimizationHints
= options
.verboseOptimizationHints
;
372 objOpts
.armUsesZeroCostExceptions
= options
.armUsesZeroCostExceptions
;
373 objOpts
.simulator
= options
.simulator
;
374 objOpts
.ignoreMismatchPlatform
= options
.ignoreMismatchPlatform
;
375 objOpts
.platform
= options
.platform
;
376 objOpts
.minOSVersion
= options
.minOSVersion
;
378 objOpts
.srcKind
= ld::relocatable::File::kSourceLTO
;
379 objOpts
.treateBitcodeAsData
= false;
380 objOpts
.usingBitcode
= options
.bitcodeBundle
;
381 objOpts
.maxDefaultCommonAlignment
= options
.maxDefaultCommonAlignment
;
383 const char *object_path
= path
.c_str();
385 object_path
= "/tmp/lto.o";
388 struct stat statBuffer
;
389 if ( stat(object_path
, &statBuffer
) == 0 )
390 modTime
= statBuffer
.st_mtime
;
392 ld::relocatable::File
* result
= mach_o::relocatable::parse(p
, len
, strdup(object_path
), modTime
, ordinal
, objOpts
);
393 if ( result
!= NULL
)
395 throw "LLVM LTO, file is not of required architecture";
400 File::File(const char* pth
, time_t mTime
, ld::File::Ordinal ordinal
, const uint8_t* content
, uint32_t contentLength
, cpu_type_t arch
)
401 : ld::relocatable::File(pth
,mTime
,ordinal
), _isThinLTO(false), _architecture(arch
), _internalAtom(*this),
402 _atomArray(NULL
), _atomArrayCount(0), _module(NULL
), _path(pth
),
403 _content(content
), _contentLength(contentLength
), _debugInfoPath(pth
),
404 _section("__TEXT_", "__tmp_lto", ld::Section::typeTempLTO
),
405 _fixupToInternal(0, ld::Fixup::k1of1
, ld::Fixup::kindNone
, &_internalAtom
),
406 _debugInfo(ld::relocatable::File::kDebugInfoNone
), _cpuSubType(0)
408 const bool log
= false;
410 // create llvm module
411 #if LTO_API_VERSION >= 11
412 if ( sSupportsLocalContext
|| !sHasTriedLocalContext
) {
413 _module
= ::lto_module_create_in_local_context(content
, contentLength
, pth
);
415 if ( !sHasTriedLocalContext
) {
416 sHasTriedLocalContext
= true;
417 sSupportsLocalContext
= (_module
!= NULL
);
419 if ( (_module
== NULL
) && !sSupportsLocalContext
)
421 #if LTO_API_VERSION >= 9
422 _module
= ::lto_module_create_from_memory_with_path(content
, contentLength
, pth
);
423 if ( _module
== NULL
&& !sSupportsLocalContext
)
425 _module
= ::lto_module_create_from_memory(content
, contentLength
);
426 if ( _module
== NULL
)
427 throwf("could not parse object file %s: '%s', using libLTO version '%s'", pth
, ::lto_get_error_message(), ::lto_get_version());
429 if ( log
) fprintf(stderr
, "bitcode file: %s\n", pth
);
431 #if LTO_API_VERSION >= 18
432 _isThinLTO
= ::lto_module_is_thinlto(_module
);
435 // create atom for each global symbol in module
436 uint32_t count
= ::lto_module_get_num_symbols(_module
);
437 _atomArray
= (Atom
*)malloc(sizeof(Atom
)*count
);
438 for (uint32_t i
=0; i
< count
; ++i
) {
439 const char* name
= ::lto_module_get_symbol_name(_module
, i
);
440 lto_symbol_attributes attr
= lto_module_get_symbol_attribute(_module
, i
);
442 // <rdar://problem/6378110> LTO doesn't like dtrace symbols
443 // ignore dtrace static probes for now
444 // later when codegen is done and a mach-o file is produces the probes will be processed
445 if ( (strncmp(name
, "___dtrace_probe$", 16) == 0) || (strncmp(name
, "___dtrace_isenabled$", 20) == 0) )
448 ld::Atom::Definition def
;
449 ld::Atom::Combine combine
= ld::Atom::combineNever
;
450 switch ( attr
& LTO_SYMBOL_DEFINITION_MASK
) {
451 case LTO_SYMBOL_DEFINITION_REGULAR
:
452 def
= ld::Atom::definitionRegular
;
454 case LTO_SYMBOL_DEFINITION_TENTATIVE
:
455 def
= ld::Atom::definitionTentative
;
457 case LTO_SYMBOL_DEFINITION_WEAK
:
458 def
= ld::Atom::definitionRegular
;
459 combine
= ld::Atom::combineByName
;
461 case LTO_SYMBOL_DEFINITION_UNDEFINED
:
462 case LTO_SYMBOL_DEFINITION_WEAKUNDEF
:
463 def
= ld::Atom::definitionProxy
;
466 throwf("unknown definition kind for symbol %s in bitcode file %s", name
, pth
);
469 // make LLVM atoms for definitions and a reference for undefines
470 if ( def
!= ld::Atom::definitionProxy
) {
471 ld::Atom::Scope scope
;
472 bool autohide
= false;
473 switch ( attr
& LTO_SYMBOL_SCOPE_MASK
) {
474 case LTO_SYMBOL_SCOPE_INTERNAL
:
475 scope
= ld::Atom::scopeTranslationUnit
;
477 case LTO_SYMBOL_SCOPE_HIDDEN
:
478 scope
= ld::Atom::scopeLinkageUnit
;
480 case LTO_SYMBOL_SCOPE_DEFAULT
:
481 scope
= ld::Atom::scopeGlobal
;
483 #if LTO_API_VERSION >= 4
484 case LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN
:
485 scope
= ld::Atom::scopeGlobal
;
490 throwf("unknown scope for symbol %s in bitcode file %s", name
, pth
);
492 // only make atoms for non-internal symbols
493 if ( scope
== ld::Atom::scopeTranslationUnit
)
495 uint8_t alignment
= (attr
& LTO_SYMBOL_ALIGNMENT_MASK
);
496 // make Atom using placement new operator
497 new (&_atomArray
[_atomArrayCount
++]) Atom(*this, name
, scope
, def
, combine
, alignment
, autohide
);
498 if ( scope
!= ld::Atom::scopeTranslationUnit
)
499 _internalAtom
.addReference(name
);
500 if ( log
) fprintf(stderr
, "\t0x%08X %s\n", attr
, name
);
503 // add to list of external references
504 _internalAtom
.addReference(name
);
505 if ( log
) fprintf(stderr
, "\t%s (undefined)\n", name
);
509 #if LTO_API_VERSION >= 11
510 if ( sSupportsLocalContext
)
520 bool File::mergeIntoGenerator(lto_code_gen_t generator
, bool useSetModule
) {
521 #if LTO_API_VERSION >= 11
522 if ( sSupportsLocalContext
) {
523 assert(!_module
&& "Expected module to be disposed");
524 _module
= ::lto_module_create_in_codegen_context(_content
, _contentLength
,
526 if ( _module
== NULL
)
527 throwf("could not reparse object file %s: '%s', using libLTO version '%s'",
528 _path
, ::lto_get_error_message(), ::lto_get_version());
531 assert(_module
&& "Expected module to stick around");
532 #if LTO_API_VERSION >= 13
534 // lto_codegen_set_module will transfer ownership of the module to LTO code generator,
535 // so we don't need to release the module here.
536 ::lto_codegen_set_module(generator
, _module
);
540 if ( ::lto_codegen_add_module(generator
, _module
) )
543 // <rdar://problem/15471128> linker should release module as soon as possible
548 #if LTO_API_VERSION >= 18
549 void File::addToThinGenerator(thinlto_code_gen_t generator
, int id
) {
550 assert(!_module
&& "Expected module to be disposed");
551 std::string pathWithID
= _path
;
552 pathWithID
+= std::to_string(id
);
553 ::thinlto_codegen_add_module(generator
, pathWithID
.c_str(), (const char *)_content
, _contentLength
);
559 if ( _module
!= NULL
)
560 ::lto_module_dispose(_module
);
564 bool File::forEachAtom(ld::File::AtomHandler
& handler
) const
566 handler
.doAtom(_internalAtom
);
567 for(uint32_t i
=0; i
< _atomArrayCount
; ++i
) {
568 handler
.doAtom(_atomArray
[i
]);
573 InternalAtom::InternalAtom(File
& f
)
574 : ld::Atom(f
._section
, ld::Atom::definitionRegular
, ld::Atom::combineNever
, ld::Atom::scopeTranslationUnit
,
575 ld::Atom::typeLTOtemporary
, ld::Atom::symbolTableNotIn
, true, false, false, ld::Atom::Alignment(0)),
580 Atom::Atom(File
& f
, const char* nm
, ld::Atom::Scope s
, ld::Atom::Definition d
, ld::Atom::Combine c
,
581 ld::Atom::Alignment a
, bool ah
)
582 : ld::Atom(f
._section
, d
, c
, s
, ld::Atom::typeLTOtemporary
,
583 ld::Atom::symbolTableIn
, false, false, false, a
),
584 _file(f
), _name(strdup(nm
)), _compiledAtom(NULL
)
590 void Atom::setCompiledAtom(const ld::Atom
& atom
)
592 // set delegate so virtual methods go to it
593 _compiledAtom
= &atom
;
595 //fprintf(stderr, "setting lto atom %p to delegate to mach-o atom %p (%s)\n", this, &atom, atom.name());
597 // update fields in ld::Atom to match newly constructed mach-o atom
598 (const_cast<Atom
*>(this))->setAttributesFromAtom(atom
);
603 // <rdar://problem/12379604> The order that files are merged must match command line order
604 struct CommandLineOrderFileSorter
606 bool operator()(File
* left
, File
* right
)
608 return ( left
->ordinal() < right
->ordinal() );
613 #if LTO_API_VERSION >= 7
614 void Parser::ltoDiagnosticHandler(lto_codegen_diagnostic_severity_t severity
, const char* message
, void*)
616 switch ( severity
) {
617 #if LTO_API_VERSION >= 10
619 fprintf(stderr
, "ld: LTO remark: %s\n", message
);
624 warning("%s", message
);
627 throwf("%s", message
);
633 /// Instruct libLTO about the list of symbols to preserve, compute deadllvmAtoms and llvmAtoms
634 void Parser::setPreservedSymbols( const std::vector
<const ld::Atom
*>& allAtoms
,
636 const OptimizeOptions
& options
,
637 CStringToAtom
&deadllvmAtoms
,
638 CStringToAtom
&llvmAtoms
,
639 lto_code_gen_t generator
) {
640 const bool logMustPreserve
= false;
642 // The atom graph uses directed edges (references). Collect all references where
643 // originating atom is not part of any LTO Reader. This allows optimizer to optimize an
644 // external (i.e. not originated from same .o file) reference if all originating atoms are also
645 // defined in llvm bitcode file.
646 CStringSet nonLLVMRefs
;
647 bool hasNonllvmAtoms
= false;
648 for (std::vector
<const ld::Atom
*>::const_iterator it
= allAtoms
.begin(); it
!= allAtoms
.end(); ++it
) {
649 const ld::Atom
* atom
= *it
;
650 // only look at references that come from an atom that is not an LTO atom
651 if (atom
->contentType() != ld::Atom::typeLTOtemporary
||
652 ((lto::File
*)atom
->file())->isThinLTO()) {
653 if ( (atom
->section().type() != ld::Section::typeMachHeader
) && (atom
->definition() != ld::Atom::definitionProxy
) ) {
654 hasNonllvmAtoms
= true;
656 const ld::Atom
* target
;
657 for (ld::Fixup::iterator fit
=atom
->fixupsBegin(); fit
!= atom
->fixupsEnd(); ++fit
) {
658 switch ( fit
->binding
) {
659 case ld::Fixup::bindingDirectlyBound
:
660 // that reference an llvm atom
661 if ( fit
->u
.target
->contentType() == ld::Atom::typeLTOtemporary
)
662 nonLLVMRefs
.insert(fit
->u
.target
->name());
664 case ld::Fixup::bindingsIndirectlyBound
:
665 target
= state
.indirectBindingTable
[fit
->u
.bindingIndex
];
666 if ( (target
!= NULL
) && (target
->contentType() == ld::Atom::typeLTOtemporary
) )
667 nonLLVMRefs
.insert(target
->name());
673 else if ( atom
->scope() >= ld::Atom::scopeLinkageUnit
) {
674 llvmAtoms
[atom
->name()] = (Atom
*)atom
;
677 // if entry point is in a llvm bitcode file, it must be preserved by LTO
678 if ( state
.entryPoint
!= NULL
) {
679 if ( state
.entryPoint
->contentType() == ld::Atom::typeLTOtemporary
)
680 nonLLVMRefs
.insert(state
.entryPoint
->name());
683 // deadAtoms are the atoms that the linker coalesced. For instance weak or tentative definitions
684 // overriden by another atom. If any of these deadAtoms are llvm atoms and they were replaced
685 // with a mach-o atom, we need to tell the lto engine to preserve (not optimize away) its dead
686 // atom so that the linker can replace it with the mach-o one later.
687 for (std::vector
<const ld::Atom
*>::const_iterator it
= allAtoms
.begin(); it
!= allAtoms
.end(); ++it
) {
688 const ld::Atom
* atom
= *it
;
689 if ( atom
->coalescedAway() && (atom
->contentType() == ld::Atom::typeLTOtemporary
) ) {
690 const char* name
= atom
->name();
691 if ( logMustPreserve
) fprintf(stderr
, "lto_codegen_add_must_preserve_symbol(%s) because linker coalesce away and replace with a mach-o atom\n", name
);
692 ::lto_codegen_add_must_preserve_symbol(generator
, name
);
693 deadllvmAtoms
[name
] = (Atom
*)atom
;
696 for (std::vector
<File
*>::iterator it
=_s_files
.begin(); it
!= _s_files
.end(); ++it
) {
698 for(uint32_t i
=0; i
< file
->_atomArrayCount
; ++i
) {
699 Atom
* llvmAtom
= &file
->_atomArray
[i
];
700 if ( llvmAtom
->coalescedAway() ) {
701 const char* name
= llvmAtom
->name();
702 if ( deadllvmAtoms
.find(name
) == deadllvmAtoms
.end() ) {
703 if ( logMustPreserve
)
704 fprintf(stderr
, "lto_codegen_add_must_preserve_symbol(%s) because linker coalesce away and replace with a mach-o atom\n", name
);
705 ::lto_codegen_add_must_preserve_symbol(generator
, name
);
706 deadllvmAtoms
[name
] = (Atom
*)llvmAtom
;
709 else if ( options
.linkerDeadStripping
&& !llvmAtom
->live() ) {
710 const char* name
= llvmAtom
->name();
711 deadllvmAtoms
[name
] = (Atom
*)llvmAtom
;
716 // tell code generator about symbols that must be preserved
717 for (CStringToAtom::iterator it
= llvmAtoms
.begin(); it
!= llvmAtoms
.end(); ++it
) {
718 const char* name
= it
->first
;
719 Atom
* atom
= it
->second
;
720 // Include llvm Symbol in export list if it meets one of following two conditions
721 // 1 - atom scope is global (and not linkage unit).
722 // 2 - included in nonLLVMRefs set.
723 // If a symbol is not listed in exportList then LTO is free to optimize it away.
724 if ( (atom
->scope() == ld::Atom::scopeGlobal
) && options
.preserveAllGlobals
) {
725 if ( logMustPreserve
) fprintf(stderr
, "lto_codegen_add_must_preserve_symbol(%s) because global symbol\n", name
);
726 ::lto_codegen_add_must_preserve_symbol(generator
, name
);
728 else if ( nonLLVMRefs
.find(name
) != nonLLVMRefs
.end() ) {
729 if ( logMustPreserve
) fprintf(stderr
, "lto_codegen_add_must_preserve_symbol(%s) because referenced by a mach-o atom\n", name
);
730 ::lto_codegen_add_must_preserve_symbol(generator
, name
);
732 else if ( options
.relocatable
&& hasNonllvmAtoms
) {
733 // <rdar://problem/14334895> ld -r mode but merging in some mach-o files, so need to keep libLTO from optimizing away anything
734 if ( logMustPreserve
) fprintf(stderr
, "lto_codegen_add_must_preserve_symbol(%s) because -r mode disable LTO dead stripping\n", name
);
735 ::lto_codegen_add_must_preserve_symbol(generator
, name
);
739 // <rdar://problem/16165191> tell code generator to preserve initial undefines
740 for( std::vector
<const char*>::const_iterator it
=options
.initialUndefines
->begin(); it
!= options
.initialUndefines
->end(); ++it
) {
741 if ( logMustPreserve
) fprintf(stderr
, "lto_codegen_add_must_preserve_symbol(%s) because it is an initial undefine\n", *it
);
742 ::lto_codegen_add_must_preserve_symbol(generator
, *it
);
745 // special case running ld -r on all bitcode files to produce another bitcode file (instead of mach-o)
746 if ( options
.relocatable
&& !hasNonllvmAtoms
) {
747 #if LTO_API_VERSION >= 15
748 ::lto_codegen_set_should_embed_uselists(generator
, false);
750 if ( ! ::lto_codegen_write_merged_modules(generator
, options
.outputFilePath
) ) {
751 // HACK, no good way to tell linker we are all done, so just quit
754 warning("could not produce merged bitcode file");
759 // Retrieve the codegen model from the options
760 static lto_codegen_model
getCodeModel(const OptimizeOptions
& options
) {
761 if ( options
.mainExecutable
) {
762 if ( options
.staticExecutable
) {
763 // x86_64 "static" or any "-static -pie" is really dynamic code model
764 if ( (options
.arch
== CPU_TYPE_X86_64
) || options
.pie
)
765 return LTO_CODEGEN_PIC_MODEL_DYNAMIC
;
767 return LTO_CODEGEN_PIC_MODEL_STATIC
;
769 else if ( options
.preload
) {
771 return LTO_CODEGEN_PIC_MODEL_DYNAMIC
;
773 return LTO_CODEGEN_PIC_MODEL_STATIC
;
777 return LTO_CODEGEN_PIC_MODEL_DYNAMIC
;
779 return LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC
;
783 if ( options
.allowTextRelocs
)
784 return LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC
;
786 return LTO_CODEGEN_PIC_MODEL_DYNAMIC
;
791 std::tuple
<uint8_t *, size_t> Parser::codegen(const OptimizeOptions
& options
,
793 lto_code_gen_t generator
,
794 std::string
& object_path
) {
798 if ( ::lto_codegen_set_pic_model(generator
, getCodeModel(options
)) )
799 throwf("could not create set codegen model: %s", lto_get_error_message());
801 // if requested, save off merged bitcode file
802 if ( options
.saveTemps
) {
803 char tempBitcodePath
[MAXPATHLEN
];
804 strcpy(tempBitcodePath
, options
.outputFilePath
);
805 strcat(tempBitcodePath
, ".lto.bc");
806 #if LTO_API_VERSION >= 15
807 ::lto_codegen_set_should_embed_uselists(generator
, true);
809 ::lto_codegen_write_merged_modules(generator
, tempBitcodePath
);
812 #if LTO_API_VERSION >= 3
813 // find assembler next to linker
815 uint32_t bufSize
= PATH_MAX
;
816 if ( _NSGetExecutablePath(path
, &bufSize
) != -1 ) {
817 char* lastSlash
= strrchr(path
, '/');
818 if ( lastSlash
!= NULL
) {
819 strcpy(lastSlash
+1, "as");
820 struct stat statInfo
;
821 if ( stat(path
, &statInfo
) == 0 )
822 ::lto_codegen_set_assembler_path(generator
, path
);
827 // When lto API version is greater than or equal to 12, we use lto_codegen_optimize and lto_codegen_compile_optimized
828 // instead of lto_codegen_compile, and we save the merged bitcode file in between.
829 bool useSplitAPI
= false;
830 #if LTO_API_VERSION >= 12
831 if ( ::lto_api_version() >= 12)
836 #if LTO_API_VERSION >= 12
837 #if LTO_API_VERSION >= 14
838 if ( ::lto_api_version() >= 14 && options
.ltoCodegenOnly
)
839 lto_codegen_set_should_internalize(generator
, false);
842 if ( !options
.ltoCodegenOnly
&& ::lto_codegen_optimize(generator
) )
843 throwf("could not do LTO optimization: '%s', using libLTO version '%s'", ::lto_get_error_message(), ::lto_get_version());
845 if ( options
.saveTemps
|| options
.bitcodeBundle
) {
846 // save off merged bitcode file
847 char tempOptBitcodePath
[MAXPATHLEN
];
848 strcpy(tempOptBitcodePath
, options
.outputFilePath
);
849 strcat(tempOptBitcodePath
, ".lto.opt.bc");
850 #if LTO_API_VERSION >= 15
851 ::lto_codegen_set_should_embed_uselists(generator
, true);
853 ::lto_codegen_write_merged_modules(generator
, tempOptBitcodePath
);
854 if ( options
.bitcodeBundle
)
855 state
.ltoBitcodePath
.push_back(tempOptBitcodePath
);
858 // run code generator
859 machOFile
= (uint8_t*)::lto_codegen_compile_optimized(generator
, &machOFileLen
);
861 if ( machOFile
== NULL
)
862 throwf("could not do LTO codegen: '%s', using libLTO version '%s'", ::lto_get_error_message(), ::lto_get_version());
865 // run optimizer and code generator
866 machOFile
= (uint8_t*)::lto_codegen_compile(generator
, &machOFileLen
);
867 if ( machOFile
== NULL
)
868 throwf("could not do LTO codegen: '%s', using libLTO version '%s'", ::lto_get_error_message(), ::lto_get_version());
869 if ( options
.saveTemps
) {
870 // save off merged bitcode file
871 char tempOptBitcodePath
[MAXPATHLEN
];
872 strcpy(tempOptBitcodePath
, options
.outputFilePath
);
873 strcat(tempOptBitcodePath
, ".lto.opt.bc");
874 #if LTO_API_VERSION >= 15
875 ::lto_codegen_set_should_embed_uselists(generator
, true);
877 ::lto_codegen_write_merged_modules(generator
, tempOptBitcodePath
);
881 // if requested, save off temp mach-o file
882 if ( options
.saveTemps
) {
883 char tempMachoPath
[MAXPATHLEN
];
884 strcpy(tempMachoPath
, options
.outputFilePath
);
885 strcat(tempMachoPath
, ".lto.o");
886 int fd
= ::open(tempMachoPath
, O_CREAT
| O_WRONLY
| O_TRUNC
, 0666);
888 ::write(fd
, machOFile
, machOFileLen
);
893 // if needed, save temp mach-o file to specific location
894 if ( !object_path
.empty() ) {
895 int fd
= ::open(object_path
.c_str(), O_CREAT
| O_WRONLY
| O_TRUNC
, 0666);
897 ::write(fd
, machOFile
, machOFileLen
);
901 warning("could not write LTO temp file '%s', errno=%d", object_path
.c_str(), errno
);
904 return std::make_tuple(machOFile
, machOFileLen
);
907 /// Load the MachO located in buffer \p machOFile with size \p machOFileLen.
908 /// The loaded atoms are sync'ed using all the supplied lists.
909 void Parser::loadMachO(ld::relocatable::File
* machoFile
,
910 const OptimizeOptions
& options
,
911 ld::File::AtomHandler
& handler
,
912 std::vector
<const ld::Atom
*>& newAtoms
,
913 std::vector
<const char*>& additionalUndefines
,
914 CStringToAtom
&llvmAtoms
,
915 CStringToAtom
&deadllvmAtoms
) {
916 const bool logAtomsBeforeSync
= false;
918 // sync generated mach-o atoms with existing atoms ld knows about
919 if ( logAtomsBeforeSync
) {
920 fprintf(stderr
, "llvmAtoms:\n");
921 for (CStringToAtom::iterator it
= llvmAtoms
.begin(); it
!= llvmAtoms
.end(); ++it
) {
922 const char* name
= it
->first
;
923 Atom
* atom
= it
->second
;
924 fprintf(stderr
, "\t%p\t%s\n", atom
, name
);
926 fprintf(stderr
, "deadllvmAtoms:\n");
927 for (CStringToAtom::iterator it
= deadllvmAtoms
.begin(); it
!= deadllvmAtoms
.end(); ++it
) {
928 const char* name
= it
->first
;
929 Atom
* atom
= it
->second
;
930 fprintf(stderr
, "\t%p\t%s\n", atom
, name
);
933 AtomSyncer
syncer(additionalUndefines
, newAtoms
, llvmAtoms
, deadllvmAtoms
, options
);
934 machoFile
->forEachAtom(syncer
);
936 // notify about file level attributes
937 handler
.doFile(*machoFile
);
940 // Full LTO processing
941 bool Parser::optimizeLTO(const std::vector
<File
*> files
,
942 const std::vector
<const ld::Atom
*>& allAtoms
,
944 const OptimizeOptions
& options
,
945 ld::File::AtomHandler
& handler
,
946 std::vector
<const ld::Atom
*>& newAtoms
,
947 std::vector
<const char*>& additionalUndefines
) {
948 const bool logExtraOptions
= false;
949 const bool logBitcodeFiles
= false;
954 // create optimizer and add each Reader
955 lto_code_gen_t generator
= NULL
;
956 #if LTO_API_VERSION >= 11
957 if ( File::sSupportsLocalContext
)
958 generator
= ::lto_codegen_create_in_local_context();
961 generator
= ::lto_codegen_create();
962 #if LTO_API_VERSION >= 7
963 lto_codegen_set_diagnostic_handler(generator
, ltoDiagnosticHandler
, NULL
);
966 ld::File::Ordinal lastOrdinal
;
968 // When flto_codegen_only is on and we have a single .bc file, use lto_codegen_set_module instead of
969 // lto_codegen_add_module, to make sure the the destination module will be the same as the input .bc file.
970 bool useSetModule
= false;
971 #if LTO_API_VERSION >= 13
972 useSetModule
= (files
.size() == 1) && options
.ltoCodegenOnly
&& (::lto_api_version() >= 13);
974 for (auto *f
: files
) {
975 assert(f
->ordinal() > lastOrdinal
);
976 if ( logBitcodeFiles
&& !useSetModule
) fprintf(stderr
, "lto_codegen_add_module(%s)\n", f
->path());
977 if ( logBitcodeFiles
&& useSetModule
) fprintf(stderr
, "lto_codegen_set_module(%s)\n", f
->path());
978 if ( f
->mergeIntoGenerator(generator
, useSetModule
) )
979 throwf("lto: could not merge in %s because '%s', using libLTO version '%s'", f
->path(), ::lto_get_error_message(), ::lto_get_version());
980 lastOrdinal
= f
->ordinal();
983 // add any -mllvm command line options
984 if ( !_s_llvmOptionsProcessed
) {
985 for (const char* opt
: *options
.llvmOptions
) {
986 if ( logExtraOptions
) fprintf(stderr
, "passing option to llvm: %s\n", opt
);
987 ::lto_codegen_debug_options(generator
, opt
);
989 _s_llvmOptionsProcessed
= true;
992 // <rdar://problem/13687397> Need a way for LTO to get cpu variants (until that info is in bitcode)
993 if ( options
.mcpu
!= NULL
)
994 ::lto_codegen_set_cpu(generator
, options
.mcpu
);
996 // Compute the preserved symbols
997 CStringToAtom deadllvmAtoms
, llvmAtoms
;
998 setPreservedSymbols(allAtoms
, state
, options
, deadllvmAtoms
, llvmAtoms
, generator
);
1000 size_t machOFileLen
= 0;
1001 const uint8_t* machOFile
= NULL
;
1003 // mach-o parsing is done in-memory, but need path for debug notes
1004 std::string object_path
;
1005 if ( options
.tmpObjectFilePath
!= NULL
) {
1006 object_path
= options
.tmpObjectFilePath
;
1007 // If the path exists and is a directory (for instance if some files
1008 // were processed with ThinLTO before), we create the LTO file inside
1010 struct stat statBuffer
;
1011 if( stat(object_path
.c_str(), &statBuffer
) == 0 && S_ISDIR(statBuffer
.st_mode
) ) {
1012 object_path
+= "/lto.o";
1017 std::tie(machOFile
, machOFileLen
) = codegen(options
, state
, generator
, object_path
);
1019 // parse generated mach-o file into a MachOReader
1020 ld::relocatable::File
* machoFile
= parseMachOFile(machOFile
, machOFileLen
, object_path
, options
, ld::File::Ordinal::LTOOrdinal());
1022 // Load the generated MachO file
1023 loadMachO(machoFile
, options
, handler
, newAtoms
, additionalUndefines
, llvmAtoms
, deadllvmAtoms
);
1025 // Remove Atoms from ld if code generator optimized them away
1026 for (CStringToAtom::iterator li
= llvmAtoms
.begin(), le
= llvmAtoms
.end(); li
!= le
; ++li
) {
1027 // check if setRealAtom() called on this Atom
1028 if ( li
->second
->compiledAtom() == NULL
) {
1029 //fprintf(stderr, "llvm optimized away %p %s\n", li->second, li->second->name());
1030 li
->second
->setCoalescedAway();
1034 // if final mach-o file has debug info, update original bitcode files to match
1035 for (auto *f
: files
) {
1036 f
->setDebugInfo(machoFile
->debugInfo(), machoFile
->path(), machoFile
->modificationTime(), machoFile
->cpuSubType());
1042 #if LTO_API_VERSION >= 18
1043 // Create the ThinLTO codegenerator
1044 thinlto_code_gen_t
Parser::init_thinlto_codegen(const std::vector
<File
*>& files
,
1045 const std::vector
<const ld::Atom
*>& allAtoms
,
1046 ld::Internal
& state
,
1047 const OptimizeOptions
& options
,
1048 CStringToAtom
& deadllvmAtoms
,
1049 CStringToAtom
& llvmAtoms
) {
1050 const bool logMustPreserve
= false;
1052 thinlto_code_gen_t thingenerator
= ::thinlto_create_codegen();
1055 if (options
.ltoCachePath
&& !options
.bitcodeBundle
) {
1056 struct stat statBuffer
;
1057 if( stat(options
.ltoCachePath
, &statBuffer
) != 0 || !S_ISDIR(statBuffer
.st_mode
) ) {
1058 if ( mkdir(options
.ltoCachePath
, 0700) !=0 ) {
1059 warning("unable to create ThinLTO cache directory: %s", options
.ltoCachePath
);
1062 thinlto_codegen_set_cache_dir(thingenerator
, options
.ltoCachePath
);
1063 thinlto_codegen_set_cache_pruning_interval(thingenerator
, options
.ltoPruneInterval
);
1064 thinlto_codegen_set_cache_entry_expiration(thingenerator
, options
.ltoPruneAfter
);
1065 thinlto_codegen_set_final_cache_size_relative_to_available_space(thingenerator
, options
.ltoMaxCacheSize
);
1068 // if requested, ask the code generator to save off intermediate bitcode files
1069 if ( options
.saveTemps
) {
1070 std::string tempPath
= options
.outputFilePath
;
1071 tempPath
+= ".thinlto.bcs/";
1072 struct stat statBuffer
;
1073 if( stat(tempPath
.c_str(), &statBuffer
) != 0 || !S_ISDIR(statBuffer
.st_mode
) ) {
1074 if ( mkdir(tempPath
.c_str(), 0700) !=0 ) {
1075 warning("unable to create ThinLTO output directory for temporary bitcode files: %s", tempPath
.c_str());
1078 thinlto_codegen_set_savetemps_dir(thingenerator
, tempPath
.c_str());
1081 // Set some codegen options
1082 if ( thinlto_codegen_set_pic_model(thingenerator
, getCodeModel(options
)) )
1083 throwf("could not create set codegen model: %s", lto_get_error_message());
1085 // Expose reachability informations for internalization in LTO
1087 // The atom graph uses directed edges (references). Collect all references where
1088 // originating atom is not part of any LTO Reader. This allows optimizer to optimize an
1089 // external (i.e. not originated from same .o file) reference if all originating atoms are also
1090 // defined in llvm bitcode file.
1091 CStringSet nonLLVMRefs
;
1092 CStringSet LLVMRefs
;
1093 for (std::vector
<const ld::Atom
*>::const_iterator it
= allAtoms
.begin(); it
!= allAtoms
.end(); ++it
) {
1094 const ld::Atom
* atom
= *it
;
1095 const ld::Atom
* target
;
1096 for (ld::Fixup::iterator fit
=atom
->fixupsBegin(); fit
!= atom
->fixupsEnd(); ++fit
) {
1097 switch ( fit
->binding
) {
1098 case ld::Fixup::bindingDirectlyBound
:
1099 // that reference a ThinLTO llvm atom
1100 target
= fit
->u
.target
;
1101 if ( target
->contentType() == ld::Atom::typeLTOtemporary
&&
1102 ((lto::File
*)target
->file())->isThinLTO() &&
1103 atom
->file() != target
->file()
1105 if (atom
->contentType() != ld::Atom::typeLTOtemporary
||
1106 !((lto::File
*)atom
->file())->isThinLTO())
1107 nonLLVMRefs
.insert(target
->name());
1109 LLVMRefs
.insert(target
->name());
1110 if ( logMustPreserve
)
1111 fprintf(stderr
, "Found a reference from %s -> %s\n", atom
->name(), target
->name());
1114 case ld::Fixup::bindingsIndirectlyBound
:
1115 target
= state
.indirectBindingTable
[fit
->u
.bindingIndex
];
1116 if ( (target
!= NULL
) && (target
->contentType() == ld::Atom::typeLTOtemporary
) &&
1117 ((lto::File
*)target
->file())->isThinLTO() &&
1118 atom
->file() != target
->file()
1120 if (atom
->contentType() != ld::Atom::typeLTOtemporary
||
1121 !((lto::File
*)atom
->file())->isThinLTO())
1122 nonLLVMRefs
.insert(target
->name());
1124 LLVMRefs
.insert(target
->name());
1125 if ( logMustPreserve
)
1126 fprintf(stderr
, "Found a reference from %s -> %s\n", atom
->name(), target
->name());
1132 if (atom
->contentType() == ld::Atom::typeLTOtemporary
&&
1133 ((lto::File
*)atom
->file())->isThinLTO()) {
1134 llvmAtoms
[atom
->name()] = (Atom
*)atom
;
1137 // if entry point is in a llvm bitcode file, it must be preserved by LTO
1138 if ( state
.entryPoint
!= NULL
) {
1139 if ( state
.entryPoint
->contentType() == ld::Atom::typeLTOtemporary
)
1140 nonLLVMRefs
.insert(state
.entryPoint
->name());
1142 for (auto file
: files
) {
1143 for(uint32_t i
=0; i
< file
->_atomArrayCount
; ++i
) {
1144 Atom
* llvmAtom
= &file
->_atomArray
[i
];
1145 if ( llvmAtom
->coalescedAway() ) {
1146 const char* name
= llvmAtom
->name();
1147 if ( deadllvmAtoms
.find(name
) == deadllvmAtoms
.end() ) {
1148 if ( logMustPreserve
)
1149 fprintf(stderr
, "lto_codegen_add_must_preserve_symbol(%s) because linker coalesce away and replace with a mach-o atom\n", name
);
1150 ::thinlto_codegen_add_must_preserve_symbol(thingenerator
, name
, strlen(name
));
1151 deadllvmAtoms
[name
] = (Atom
*)llvmAtom
;
1154 else if ( options
.linkerDeadStripping
&& !llvmAtom
->live() ) {
1155 const char* name
= llvmAtom
->name();
1156 deadllvmAtoms
[name
] = (Atom
*)llvmAtom
;
1161 // tell code generator about symbols that must be preserved
1162 for (CStringToAtom::iterator it
= llvmAtoms
.begin(); it
!= llvmAtoms
.end(); ++it
) {
1163 const char* name
= it
->first
;
1164 Atom
* atom
= it
->second
;
1165 // Include llvm Symbol in export list if it meets one of following two conditions
1166 // 1 - atom scope is global (and not linkage unit).
1167 // 2 - included in nonLLVMRefs set.
1168 // If a symbol is not listed in exportList then LTO is free to optimize it away.
1169 if ( (atom
->scope() == ld::Atom::scopeGlobal
) && options
.preserveAllGlobals
) {
1170 if ( logMustPreserve
) fprintf(stderr
, "lto_codegen_add_must_preserve_symbol(%s) because global symbol\n", name
);
1171 ::thinlto_codegen_add_must_preserve_symbol(thingenerator
, name
, strlen(name
));
1173 else if ( nonLLVMRefs
.find(name
) != nonLLVMRefs
.end() ) {
1174 if ( logMustPreserve
) fprintf(stderr
, "lto_codegen_add_must_preserve_symbol(%s) because referenced from outside of ThinLTO\n", name
);
1175 ::thinlto_codegen_add_must_preserve_symbol(thingenerator
, name
, strlen(name
));
1177 else if ( LLVMRefs
.find(name
) != LLVMRefs
.end() ) {
1178 if ( logMustPreserve
) fprintf(stderr
, "lto_codegen_add_must_preserve_symbol(%s) because referenced from another file\n", name
);
1179 ::thinlto_codegen_add_cross_referenced_symbol(thingenerator
, name
, strlen(name
));
1181 if ( logMustPreserve
) fprintf(stderr
, "NOT preserving(%s)\n", name
);
1183 // FIXME: to be implemented
1184 // else if ( options.relocatable && hasNonllvmAtoms ) {
1185 // // <rdar://problem/14334895> ld -r mode but merging in some mach-o files, so need to keep libLTO from optimizing away anything
1186 // if ( logMustPreserve ) fprintf(stderr, "lto_codegen_add_must_preserve_symbol(%s) because -r mode disable LTO dead stripping\n", name);
1187 // ::thinlto_codegen_add_must_preserve_symbol(thingenerator, name, strlen(name));
1191 return thingenerator
;
1195 // Full LTO processing
1196 bool Parser::optimizeThinLTO(const std::vector
<File
*>& files
,
1197 const std::vector
<const ld::Atom
*>& allAtoms
,
1198 ld::Internal
& state
,
1199 const OptimizeOptions
& options
,
1200 ld::File::AtomHandler
& handler
,
1201 std::vector
<const ld::Atom
*>& newAtoms
,
1202 std::vector
<const char*>& additionalUndefines
) {
1203 const bool logBitcodeFiles
= false;
1208 #if LTO_API_VERSION >= 18
1210 if (::lto_api_version() < 18)
1211 throwf("lto: could not use -thinlto because libLTO is too old (version '%d', >=18 is required)", ::lto_api_version());
1213 // Handle -mllvm options
1214 if ( !_s_llvmOptionsProcessed
) {
1215 thinlto_debug_options(options
.llvmOptions
->data(), options
.llvmOptions
->size());
1216 _s_llvmOptionsProcessed
= true;
1219 // Create the ThinLTO codegenerator
1220 CStringToAtom deadllvmAtoms
;
1221 CStringToAtom llvmAtoms
;
1222 thinlto_code_gen_t thingenerator
= init_thinlto_codegen(files
, allAtoms
, state
, options
, deadllvmAtoms
, llvmAtoms
);
1225 ld::File::Ordinal lastOrdinal
;
1227 for (auto *f
: files
) {
1228 if ( logBitcodeFiles
) fprintf(stderr
, "thinlto_codegen_add_module(%s)\n", f
->path());
1229 f
->addToThinGenerator(thingenerator
, FileId
++);
1230 lastOrdinal
= f
->ordinal();
1233 #if LTO_API_VERSION >= 19
1234 // In the bitcode bundle case, we first run the generator with codegen disabled
1235 // and get the bitcode output. These files are added for later bundling, and a
1236 // new codegenerator is setup with these as input, and the optimizer disabled.
1237 if (options
.bitcodeBundle
) {
1238 // Bitcode Bundle case
1239 thinlto_codegen_disable_codegen(thingenerator
, true);
1240 // Process the optimizer only
1241 thinlto_codegen_process(thingenerator
);
1242 auto numObjects
= thinlto_module_get_num_objects(thingenerator
);
1243 // Save the codegenerator
1244 thinlto_code_gen_t bitcode_generator
= thingenerator
;
1245 // Create a new codegen generator for the codegen part.
1246 thingenerator
= init_thinlto_codegen(files
, allAtoms
, state
, options
, deadllvmAtoms
, llvmAtoms
);
1247 // Disable the optimizer
1248 thinlto_codegen_set_codegen_only(thingenerator
, true);
1250 // Save bitcode files for later, and add them to the codegen generator.
1251 for (unsigned bufID
= 0; bufID
< numObjects
; ++bufID
) {
1252 auto machOFile
= thinlto_module_get_object(bitcode_generator
, bufID
);
1253 std::string tempMachoPath
= options
.outputFilePath
;
1254 tempMachoPath
+= ".";
1255 tempMachoPath
+= std::to_string(bufID
);
1256 tempMachoPath
+= ".thinlto.o.bc";
1257 state
.ltoBitcodePath
.push_back(tempMachoPath
);
1258 int fd
= ::open(tempMachoPath
.c_str(), O_CREAT
| O_WRONLY
| O_TRUNC
, 0666);
1260 ::write(fd
, machOFile
.Buffer
, machOFile
.Size
);
1263 throwf("unable to write temporary ThinLTO output: %s", tempMachoPath
.c_str());
1266 // Add the optimized bitcode to the codegen generator now.
1267 ::thinlto_codegen_add_module(thingenerator
, tempMachoPath
.c_str(), (const char *)machOFile
.Buffer
, machOFile
.Size
);
1271 if (options
.ltoCodegenOnly
)
1272 // Disable the optimizer
1273 thinlto_codegen_set_codegen_only(thingenerator
, true);
1276 // If object_path_lto is used, we switch to a file-based API: libLTO will
1277 // generate the files on disk and we'll map them on-demand.
1279 #if LTO_API_VERSION >= 21
1280 bool useFileBasedAPI
= (options
.tmpObjectFilePath
&& ::lto_api_version() >= 21);
1281 if ( useFileBasedAPI
)
1282 thinlto_set_generated_objects_dir(thingenerator
, options
.tmpObjectFilePath
);
1285 // run code generator
1286 thinlto_codegen_process(thingenerator
);
1288 unsigned numObjects
;
1289 #if LTO_API_VERSION >= 21
1290 if ( useFileBasedAPI
)
1291 numObjects
= thinlto_module_get_num_object_files(thingenerator
);
1294 numObjects
= thinlto_module_get_num_objects(thingenerator
);
1295 if ( numObjects
== 0 )
1296 throwf("could not do ThinLTO codegen (thinlto_codegen_process didn't produce any object): '%s', using libLTO version '%s'", ::lto_get_error_message(), ::lto_get_version());
1298 // if requested, save off objects files
1299 if ( options
.saveTemps
) {
1300 for (unsigned bufID
= 0; bufID
< numObjects
; ++bufID
) {
1301 auto machOFile
= thinlto_module_get_object(thingenerator
, bufID
);
1302 std::string tempMachoPath
= options
.outputFilePath
;
1303 tempMachoPath
+= ".";
1304 tempMachoPath
+= std::to_string(bufID
);
1305 tempMachoPath
+= ".thinlto.o";
1306 int fd
= ::open(tempMachoPath
.c_str(), O_CREAT
| O_WRONLY
| O_TRUNC
, 0666);
1308 ::write(fd
, machOFile
.Buffer
, machOFile
.Size
);
1312 warning("unable to write temporary ThinLTO output: %s", tempMachoPath
.c_str());
1317 // mach-o parsing is done in-memory, but need path for debug notes
1318 std::string macho_dirpath
= "/tmp/thinlto.o";
1319 if ( options
.tmpObjectFilePath
!= NULL
) {
1320 macho_dirpath
= options
.tmpObjectFilePath
;
1321 struct stat statBuffer
;
1322 if( stat(macho_dirpath
.c_str(), &statBuffer
) != 0 || !S_ISDIR(statBuffer
.st_mode
) ) {
1323 unlink(macho_dirpath
.c_str());
1324 if ( mkdir(macho_dirpath
.c_str(), 0700) !=0 ) {
1325 warning("unable to create ThinLTO output directory for temporary object files: %s", macho_dirpath
.c_str());
1330 auto get_thinlto_buffer_or_load_file
= [&] (unsigned ID
) {
1331 #if LTO_API_VERSION >= 21
1332 if ( useFileBasedAPI
) {
1333 const char* path
= thinlto_module_get_object_file(thingenerator
, ID
);
1334 // map in whole file
1335 struct stat stat_buf
;
1336 int fd
= ::open(path
, O_RDONLY
, 0);
1338 throwf("can't open thinlto file '%s', errno=%d", path
, errno
);
1339 if ( ::fstat(fd
, &stat_buf
) != 0 )
1340 throwf("fstat thinlto file '%s' failed, errno=%d\n", path
, errno
);
1341 size_t len
= stat_buf
.st_size
;
1343 throwf("ThinLTO file '%s' too small (length=%zu)", path
, len
);
1344 const char* p
= (const char*)::mmap(NULL
, len
, PROT_READ
, MAP_FILE
| MAP_PRIVATE
, fd
, 0);
1345 if ( p
== (const char*)(-1) )
1346 throwf("can't map file, errno=%d", errno
);
1348 return LTOObjectBuffer
{ p
, len
};
1351 return thinlto_module_get_object(thingenerator
, ID
);
1354 auto ordinal
= ld::File::Ordinal::LTOOrdinal().nextFileListOrdinal();
1355 for (unsigned bufID
= 0; bufID
< numObjects
; ++bufID
) {
1356 auto machOFile
= get_thinlto_buffer_or_load_file(bufID
);
1357 if (!machOFile
.Size
) {
1358 warning("Ignoring empty buffer generated by ThinLTO");
1362 // mach-o parsing is done in-memory, but need path for debug notes
1363 std::string tmp_path
;
1364 #if LTO_API_VERSION >= 21
1365 if ( useFileBasedAPI
) {
1366 tmp_path
= thinlto_module_get_object_file(thingenerator
, bufID
);
1370 if ( options
.tmpObjectFilePath
!= NULL
) {
1371 tmp_path
= macho_dirpath
+ "/" + std::to_string(bufID
) + ".o";
1372 // if needed, save temp mach-o file to specific location
1373 int fd
= ::open(tmp_path
.c_str(), O_CREAT
| O_WRONLY
| O_TRUNC
, 0666);
1375 ::write(fd
, (const uint8_t *)machOFile
.Buffer
, machOFile
.Size
);
1379 warning("could not write ThinLTO temp file '%s', errno=%d", tmp_path
.c_str(), errno
);
1383 // parse generated mach-o file into a MachOReader
1384 ld::relocatable::File
* machoFile
= parseMachOFile((const uint8_t *)machOFile
.Buffer
, machOFile
.Size
, tmp_path
, options
, ordinal
);
1385 ordinal
= ordinal
.nextFileListOrdinal();
1387 // Load the generated MachO file
1388 loadMachO(machoFile
, options
, handler
, newAtoms
, additionalUndefines
, llvmAtoms
, deadllvmAtoms
);
1391 // Remove Atoms from ld if code generator optimized them away
1392 for (CStringToAtom::iterator li
= llvmAtoms
.begin(), le
= llvmAtoms
.end(); li
!= le
; ++li
) {
1393 // check if setRealAtom() called on this Atom
1394 if ( li
->second
->compiledAtom() == NULL
) {
1395 //fprintf(stderr, "llvm optimized away %p %s\n", li->second, li->second->name());
1396 li
->second
->setCoalescedAway();
1401 #else // ! (LTO_API_VERSION >= 18)
1402 throwf("lto: could not use -thinlto because ld was built against a version of libLTO too old (version '%d', >=18 is required)", LTO_API_VERSION
);
1406 bool Parser::optimize( const std::vector
<const ld::Atom
*>& allAtoms
,
1407 ld::Internal
& state
,
1408 const OptimizeOptions
& options
,
1409 ld::File::AtomHandler
& handler
,
1410 std::vector
<const ld::Atom
*>& newAtoms
,
1411 std::vector
<const char*>& additionalUndefines
)
1414 // exit quickly if nothing to do
1415 if ( _s_files
.size() == 0 )
1418 // print out LTO version string if -v was used
1419 if ( options
.verbose
)
1420 fprintf(stderr
, "%s\n", ::lto_get_version());
1422 // <rdar://problem/12379604> The order that files are merged must match command line order
1423 std::sort(_s_files
.begin(), _s_files
.end(), CommandLineOrderFileSorter());
1425 #if LTO_API_VERSION >= 19
1426 // If ltoCodegenOnly is set, we don't want to merge any bitcode files and perform FullLTO
1427 // we just take the ThinLTO path (optimization will be disabled anyway).
1428 if (options
.ltoCodegenOnly
) {
1429 for (auto *file
: _s_files
) {
1430 file
->setIsThinLTO(true);
1435 std::vector
<File
*> theLTOFiles
;
1436 std::vector
<File
*> theThinLTOFiles
;
1437 for (auto *file
: _s_files
) {
1438 if (file
->isThinLTO()) {
1439 theThinLTOFiles
.push_back(file
);
1441 theLTOFiles
.push_back(file
);
1445 auto result
= optimizeThinLTO(theThinLTOFiles
, allAtoms
, state
, options
, handler
, newAtoms
, additionalUndefines
) &&
1446 optimizeLTO(theLTOFiles
, allAtoms
, state
, options
, handler
, newAtoms
, additionalUndefines
);
1448 // Remove InternalAtoms from ld
1449 for (std::vector
<File
*>::iterator it
=_s_files
.begin(); it
!= _s_files
.end(); ++it
) {
1450 (*it
)->internalAtom().setCoalescedAway();
1457 void Parser::AtomSyncer::doAtom(const ld::Atom
& machoAtom
)
1459 static const bool log
= false;
1460 // update proxy atoms to point to real atoms and find new atoms
1461 const char* name
= machoAtom
.name();
1462 CStringToAtom::const_iterator pos
= _llvmAtoms
.find(name
);
1463 if ( pos
!= _llvmAtoms
.end() ) {
1464 // turn Atom into a proxy for this mach-o atom
1465 if (pos
->second
->scope() == ld::Atom::scopeLinkageUnit
) {
1466 if (log
) fprintf(stderr
, "demote %s to hidden after LTO\n", name
);
1467 (const_cast<ld::Atom
*>(&machoAtom
))->setScope(ld::Atom::scopeLinkageUnit
);
1469 pos
->second
->setCompiledAtom(machoAtom
);
1470 _lastProxiedAtom
= &machoAtom
;
1471 _lastProxiedFile
= pos
->second
->file();
1472 if (log
) fprintf(stderr
, "AtomSyncer, mach-o atom %p synced to lto atom %p (name=%s)\n", &machoAtom
, pos
->second
, machoAtom
.name());
1475 // an atom of this name was not in the allAtoms list the linker gave us
1476 auto llvmAtom
= _deadllvmAtoms
.find(name
);
1477 if ( llvmAtom
!= _deadllvmAtoms
.end() ) {
1478 // this corresponding to an atom that the linker coalesced away or marked not-live
1479 if ( _options
.linkerDeadStripping
) {
1480 // llvm seems to want this atom and -dead_strip is enabled, so it will be deleted if not needed, so add back
1481 llvmAtom
->second
->setCompiledAtom(machoAtom
);
1482 _newAtoms
.push_back(&machoAtom
);
1483 if (log
) fprintf(stderr
, "AtomSyncer, mach-o atom %p matches dead lto atom %p but adding back (name=%s)\n", &machoAtom
, llvmAtom
->second
, machoAtom
.name());
1486 // Don't pass it back as a new atom
1487 if (log
) fprintf(stderr
, "AtomSyncer, mach-o atom %p matches dead lto atom %p (name=%s)\n", &machoAtom
, llvmAtom
->second
, machoAtom
.name());
1488 if ( llvmAtom
->second
->coalescedAway() ) {
1489 if (log
) fprintf(stderr
, "AtomSyncer: dead coalesced atom %s\n", machoAtom
.name());
1490 // <rdar://problem/28269547>
1491 // We told libLTO to keep a weak atom that will replaced by an native mach-o atom.
1492 // We also need to remove any atoms directly dependent on this (FDE, LSDA).
1493 for (ld::Fixup::iterator fit
=machoAtom
.fixupsBegin(), fend
=machoAtom
.fixupsEnd(); fit
!= fend
; ++fit
) {
1494 switch ( fit
->kind
) {
1495 case ld::Fixup::kindNoneGroupSubordinate
:
1496 case ld::Fixup::kindNoneGroupSubordinateFDE
:
1497 case ld::Fixup::kindNoneGroupSubordinateLSDA
:
1498 assert(fit
->binding
== ld::Fixup::bindingDirectlyBound
);
1499 (const_cast<ld::Atom
*>(fit
->u
.target
))->setCoalescedAway();
1500 if (log
) fprintf(stderr
, "AtomSyncer: mark coalesced-away subordinate atom %s\n", fit
->u
.target
->name());
1511 // this is something new that lto conjured up, tell ld its new
1512 _newAtoms
.push_back(&machoAtom
);
1513 // <rdar://problem/15469363> if new static atom in same section as previous non-static atom, assign to same file as previous
1514 if ( (_lastProxiedAtom
!= NULL
) && (_lastProxiedAtom
->section() == machoAtom
.section()) ) {
1515 ld::Atom
* ma
= const_cast<ld::Atom
*>(&machoAtom
);
1516 ma
->setFile(_lastProxiedFile
);
1517 if (log
) fprintf(stderr
, "AtomSyncer, mach-o atom %s is proxied to %s (path=%s)\n", machoAtom
.name(), _lastProxiedAtom
->name(), _lastProxiedFile
->path());
1519 if (log
) fprintf(stderr
, "AtomSyncer, mach-o atom %p is totally new (name=%s)\n", &machoAtom
, machoAtom
.name());
1523 // adjust fixups to go through proxy atoms
1524 if (log
) fprintf(stderr
, " adjusting fixups in atom: %s\n", machoAtom
.name());
1525 for (ld::Fixup::iterator fit
=machoAtom
.fixupsBegin(); fit
!= machoAtom
.fixupsEnd(); ++fit
) {
1526 switch ( fit
->binding
) {
1527 case ld::Fixup::bindingNone
:
1529 case ld::Fixup::bindingByNameUnbound
:
1530 // don't know if this target has been seen by linker before or if it is new
1531 // be conservative and tell linker it is new
1532 _additionalUndefines
.push_back(fit
->u
.name
);
1533 if (log
) fprintf(stderr
, " adding by-name symbol %s\n", fit
->u
.name
);
1535 case ld::Fixup::bindingDirectlyBound
:
1536 // If mach-o atom is referencing another mach-o atom then
1537 // reference is not going through Atom proxy. Fix it here to ensure that all
1538 // llvm symbol references always go through Atom proxy.
1540 const char* targetName
= fit
->u
.target
->name();
1541 CStringToAtom::const_iterator post
= _llvmAtoms
.find(targetName
);
1542 if ( post
!= _llvmAtoms
.end() ) {
1543 const ld::Atom
* t
= post
->second
;
1544 if (log
) fprintf(stderr
, " updating direct reference to %p to be ref to %p: %s\n", fit
->u
.target
, t
, targetName
);
1548 // <rdar://problem/12859831> Don't unbind follow-on reference into by-name reference
1549 if ( (_deadllvmAtoms
.find(targetName
) != _deadllvmAtoms
.end()) && (fit
->kind
!= ld::Fixup::kindNoneFollowOn
) && (fit
->u
.target
->scope() != ld::Atom::scopeTranslationUnit
) ) {
1550 // target was coalesed away and replace by mach-o atom from a non llvm .o file
1551 fit
->binding
= ld::Fixup::bindingByNameUnbound
;
1552 fit
->u
.name
= targetName
;
1556 //fprintf(stderr, " direct ref to: %s (scope=%d)\n", fit->u.target->name(), fit->u.target->scope());
1558 case ld::Fixup::bindingByContentBound
:
1559 //fprintf(stderr, " direct by content to: %s\n", fit->u.target->name());
1561 case ld::Fixup::bindingsIndirectlyBound
:
1562 assert(0 && "indirect binding found in initial mach-o file?");
1563 //fprintf(stderr, " indirect by content to: %u\n", fit->u.bindingIndex);
1571 static pthread_mutex_t lto_lock
;
1573 Mutex() { pthread_mutex_lock(<o_lock
); }
1574 ~Mutex() { pthread_mutex_unlock(<o_lock
); }
1576 pthread_mutex_t
Mutex::lto_lock
= PTHREAD_MUTEX_INITIALIZER
;
1577 bool File::sSupportsLocalContext
= false;
1578 bool File::sHasTriedLocalContext
= false;
1581 // Used by archive reader to see if member is an llvm bitcode file
1583 bool isObjectFile(const uint8_t* fileContent
, uint64_t fileLength
, cpu_type_t architecture
, cpu_subtype_t subarch
)
1586 return Parser::validFile(fileContent
, fileLength
, architecture
, subarch
);
1590 // Used by archive reader to see if member defines a Category (for -ObjC semantics)
1592 bool hasObjCCategory(const uint8_t* fileContent
, uint64_t fileLength
)
1594 #if LTO_API_VERSION >= 20
1595 // note: if run with older libLTO.dylib that does not implement
1596 // lto_module_has_objc_category, the call will return 0 which is "false"
1597 return lto_module_has_objc_category(fileContent
, fileLength
);
1604 static ld::relocatable::File
*parseImpl(
1605 const uint8_t *fileContent
, uint64_t fileLength
, const char *path
,
1606 time_t modTime
, ld::File::Ordinal ordinal
, cpu_type_t architecture
,
1607 cpu_subtype_t subarch
, bool logAllFiles
,
1608 bool verboseOptimizationHints
)
1610 if ( Parser::validFile(fileContent
, fileLength
, architecture
, subarch
) )
1611 return Parser::parse(fileContent
, fileLength
, path
, modTime
, ordinal
, architecture
, subarch
, logAllFiles
, verboseOptimizationHints
);
1617 // main function used by linker to instantiate ld::Files
1619 ld::relocatable::File
* parse(const uint8_t* fileContent
, uint64_t fileLength
,
1620 const char* path
, time_t modTime
, ld::File::Ordinal ordinal
,
1621 cpu_type_t architecture
, cpu_subtype_t subarch
, bool logAllFiles
,
1622 bool verboseOptimizationHints
)
1624 // do light weight check before acquiring lock
1625 if ( fileLength
< 4 )
1627 if ( (fileContent
[0] != 0xDE) || (fileContent
[1] != 0xC0) || (fileContent
[2] != 0x17) || (fileContent
[3] != 0x0B) )
1630 // Note: Once lto_module_create_in_local_context() and friends are thread safe
1631 // this lock can be removed.
1633 return parseImpl(fileContent
, fileLength
, path
, modTime
, ordinal
,
1634 architecture
, subarch
, logAllFiles
,
1635 verboseOptimizationHints
);
1639 // used by "ld -v" to report version of libLTO.dylib being used
1641 const char* version()
1644 return ::lto_get_version();
1649 // used by ld for error reporting
1651 bool libLTOisLoaded()
1654 return (::lto_get_version() != NULL
);
1658 // used by ld for error reporting
1660 const char* archName(const uint8_t* fileContent
, uint64_t fileLength
)
1663 return Parser::fileKind(fileContent
, fileLength
);
1667 // used by ld for doing link time optimization
1669 bool optimize( const std::vector
<const ld::Atom
*>& allAtoms
,
1670 ld::Internal
& state
,
1671 const OptimizeOptions
& options
,
1672 ld::File::AtomHandler
& handler
,
1673 std::vector
<const ld::Atom
*>& newAtoms
,
1674 std::vector
<const char*>& additionalUndefines
)
1677 return Parser::optimize(allAtoms
, state
, options
, handler
, newAtoms
, additionalUndefines
);