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 "LTOModule.h"
17 #include "llvm/Constants.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Bitcode/ReaderWriter.h"
23 #include "llvm/Support/SystemUtils.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/System/Host.h"
27 #include "llvm/System/Path.h"
28 #include "llvm/System/Process.h"
29 #include "llvm/Target/Mangler.h"
30 #include "llvm/Target/SubtargetFeature.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCContext.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegistry.h"
35 #include "llvm/Target/TargetSelect.h"
39 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
40 return llvm::sys::IdentifyFileType((char*)mem, length)
41 == llvm::sys::Bitcode_FileType;
44 bool LTOModule::isBitcodeFile(const char *path) {
45 return llvm::sys::Path(path).isBitcodeFile();
48 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
49 const char *triplePrefix) {
50 MemoryBuffer *buffer = makeBuffer(mem, length);
53 return isTargetMatch(buffer, triplePrefix);
57 bool LTOModule::isBitcodeFileForTarget(const char *path,
58 const char *triplePrefix) {
59 MemoryBuffer *buffer = MemoryBuffer::getFile(path);
62 return isTargetMatch(buffer, triplePrefix);
65 // Takes ownership of buffer.
66 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
67 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext()));
68 // On success, m owns buffer and both are deleted at end of this method.
73 std::string actualTarget = m->getTargetTriple();
74 return (strncmp(actualTarget.c_str(), triplePrefix,
75 strlen(triplePrefix)) == 0);
79 LTOModule::LTOModule(Module *m, TargetMachine *t)
80 : _module(m), _target(t), _symbolsParsed(false)
84 LTOModule *LTOModule::makeLTOModule(const char *path,
85 std::string &errMsg) {
86 OwningPtr<MemoryBuffer> buffer(MemoryBuffer::getFile(path, &errMsg));
89 return makeLTOModule(buffer.get(), errMsg);
92 /// makeBuffer - Create a MemoryBuffer from a memory range. MemoryBuffer
93 /// requires the byte past end of the buffer to be a zero. We might get lucky
94 /// and already be that way, otherwise make a copy. Also if next byte is on a
95 /// different page, don't assume it is readable.
96 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
97 const char *startPtr = (char*)mem;
98 const char *endPtr = startPtr+length;
99 if (((uintptr_t)endPtr & (sys::Process::GetPageSize()-1)) == 0 ||
101 return MemoryBuffer::getMemBufferCopy(StringRef(startPtr, length));
103 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length));
107 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
108 std::string &errMsg) {
109 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
112 return makeLTOModule(buffer.get(), errMsg);
115 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
116 std::string &errMsg) {
117 InitializeAllTargets();
119 // parse bitcode buffer
120 OwningPtr<Module> m(ParseBitcodeFile(buffer, getGlobalContext(), &errMsg));
124 std::string Triple = m->getTargetTriple();
126 Triple = sys::getHostTriple();
128 // find machine architecture for this module
129 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
133 // construct LTModule, hand over ownership of module and target
134 SubtargetFeatures Features;
135 Features.getDefaultSubtargetFeatures("" /* cpu */, llvm::Triple(Triple));
136 std::string FeatureStr = Features.getString();
137 TargetMachine *target = march->createTargetMachine(Triple, FeatureStr);
138 return new LTOModule(m.take(), target);
142 const char *LTOModule::getTargetTriple() {
143 return _module->getTargetTriple().c_str();
146 void LTOModule::setTargetTriple(const char *triple) {
147 _module->setTargetTriple(triple);
150 void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
151 // add to list of defined symbols
152 addDefinedSymbol(f, mangler, true);
154 // add external symbols referenced by this function.
155 for (Function::iterator b = f->begin(); b != f->end(); ++b) {
156 for (BasicBlock::iterator i = b->begin(); i != b->end(); ++i) {
157 for (unsigned count = 0, total = i->getNumOperands();
158 count != total; ++count) {
159 findExternalRefs(i->getOperand(count), mangler);
165 // Get string that data pointer points to.
166 bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
167 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
168 Constant *op = ce->getOperand(0);
169 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
170 Constant *cn = gvn->getInitializer();
171 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
172 if (ca->isCString()) {
173 name = ".objc_class_name_" + ca->getAsString();
182 // Parse i386/ppc ObjC class data structure.
183 void LTOModule::addObjCClass(GlobalVariable *clgv) {
184 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
185 // second slot in __OBJC,__class is pointer to superclass name
186 std::string superclassName;
187 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
188 NameAndAttributes info;
189 if (_undefines.find(superclassName.c_str()) == _undefines.end()) {
190 const char *symbolName = ::strdup(superclassName.c_str());
191 info.name = ::strdup(symbolName);
192 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
193 // string is owned by _undefines
194 _undefines[info.name] = info;
197 // third slot in __OBJC,__class is pointer to class name
198 std::string className;
199 if (objcClassNameFromExpression(c->getOperand(2), className)) {
200 const char *symbolName = ::strdup(className.c_str());
201 NameAndAttributes info;
202 info.name = symbolName;
203 info.attributes = (lto_symbol_attributes)
204 (LTO_SYMBOL_PERMISSIONS_DATA |
205 LTO_SYMBOL_DEFINITION_REGULAR |
206 LTO_SYMBOL_SCOPE_DEFAULT);
207 _symbols.push_back(info);
208 _defines[info.name] = 1;
214 // Parse i386/ppc ObjC category data structure.
215 void LTOModule::addObjCCategory(GlobalVariable *clgv) {
216 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
217 // second slot in __OBJC,__category is pointer to target class name
218 std::string targetclassName;
219 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
220 NameAndAttributes info;
221 if (_undefines.find(targetclassName.c_str()) == _undefines.end()) {
222 const char *symbolName = ::strdup(targetclassName.c_str());
223 info.name = ::strdup(symbolName);
224 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
225 // string is owned by _undefines
226 _undefines[info.name] = info;
233 // Parse i386/ppc ObjC class list data structure.
234 void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
235 std::string targetclassName;
236 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
237 NameAndAttributes info;
238 if (_undefines.find(targetclassName.c_str()) == _undefines.end()) {
239 const char *symbolName = ::strdup(targetclassName.c_str());
240 info.name = ::strdup(symbolName);
241 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
242 // string is owned by _undefines
243 _undefines[info.name] = info;
249 void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
250 // Add to list of defined symbols.
251 addDefinedSymbol(v, mangler, false);
253 // Special case i386/ppc ObjC data structures in magic sections:
254 // The issue is that the old ObjC object format did some strange
255 // contortions to avoid real linker symbols. For instance, the
256 // ObjC class data structure is allocated statically in the executable
257 // that defines that class. That data structures contains a pointer to
258 // its superclass. But instead of just initializing that part of the
259 // struct to the address of its superclass, and letting the static and
260 // dynamic linkers do the rest, the runtime works by having that field
261 // instead point to a C-string that is the name of the superclass.
262 // At runtime the objc initialization updates that pointer and sets
263 // it to point to the actual super class. As far as the linker
264 // knows it is just a pointer to a string. But then someone wanted the
265 // linker to issue errors at build time if the superclass was not found.
266 // So they figured out a way in mach-o object format to use an absolute
267 // symbols (.objc_class_name_Foo = 0) and a floating reference
268 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
269 // a class was missing.
270 // The following synthesizes the implicit .objc_* symbols for the linker
271 // from the ObjC data structures generated by the front end.
272 if (v->hasSection() /* && isTargetDarwin */) {
273 // special case if this data blob is an ObjC class definition
274 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
275 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
280 // special case if this data blob is an ObjC category definition
281 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
282 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
287 // special case if this data blob is the list of referenced classes
288 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
289 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
295 // add external symbols referenced by this data.
296 for (unsigned count = 0, total = v->getNumOperands();
297 count != total; ++count) {
298 findExternalRefs(v->getOperand(count), mangler);
303 void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
305 // ignore all llvm.* symbols
306 if (def->getName().startswith("llvm."))
309 // string is owned by _defines
310 const char *symbolName = ::strdup(mangler.getNameWithPrefix(def).c_str());
312 // set alignment part log2() can have rounding errors
313 uint32_t align = def->getAlignment();
314 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
316 // set permissions part
318 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
320 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
321 if (gv && gv->isConstant())
322 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
324 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
327 // set definition part
328 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage()) {
329 attr |= LTO_SYMBOL_DEFINITION_WEAK;
331 else if (def->hasCommonLinkage()) {
332 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
335 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
339 if (def->hasHiddenVisibility())
340 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
341 else if (def->hasProtectedVisibility())
342 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
343 else if (def->hasExternalLinkage() || def->hasWeakLinkage()
344 || def->hasLinkOnceLinkage() || def->hasCommonLinkage())
345 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
347 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
349 // add to table of symbols
350 NameAndAttributes info;
351 info.name = symbolName;
352 info.attributes = (lto_symbol_attributes)attr;
353 _symbols.push_back(info);
354 _defines[info.name] = 1;
357 void LTOModule::addAsmGlobalSymbol(const char *name) {
358 // only add new define if not already defined
359 if (_defines.count(name) == 0)
362 // string is owned by _defines
363 const char *symbolName = ::strdup(name);
364 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
365 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
366 NameAndAttributes info;
367 info.name = symbolName;
368 info.attributes = (lto_symbol_attributes)attr;
369 _symbols.push_back(info);
370 _defines[info.name] = 1;
373 void LTOModule::addPotentialUndefinedSymbol(GlobalValue *decl,
375 // ignore all llvm.* symbols
376 if (decl->getName().startswith("llvm."))
379 // ignore all aliases
380 if (isa<GlobalAlias>(decl))
383 std::string name = mangler.getNameWithPrefix(decl);
385 // we already have the symbol
386 if (_undefines.find(name) != _undefines.end())
389 NameAndAttributes info;
390 // string is owned by _undefines
391 info.name = ::strdup(name.c_str());
392 if (decl->hasExternalWeakLinkage())
393 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
395 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
396 _undefines[name] = info;
401 // Find external symbols referenced by VALUE. This is a recursive function.
402 void LTOModule::findExternalRefs(Value *value, Mangler &mangler) {
403 if (GlobalValue *gv = dyn_cast<GlobalValue>(value)) {
404 if (!gv->hasExternalLinkage())
405 addPotentialUndefinedSymbol(gv, mangler);
406 // If this is a variable definition, do not recursively process
407 // initializer. It might contain a reference to this variable
408 // and cause an infinite loop. The initializer will be
409 // processed in addDefinedDataSymbol().
413 // GlobalValue, even with InternalLinkage type, may have operands with
414 // ExternalLinkage type. Do not ignore these operands.
415 if (Constant *c = dyn_cast<Constant>(value)) {
416 // Handle ConstantExpr, ConstantStruct, ConstantArry etc.
417 for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i)
418 findExternalRefs(c->getOperand(i), mangler);
422 void LTOModule::lazyParseSymbols() {
423 if (!_symbolsParsed) {
424 _symbolsParsed = true;
426 // Use mangler to add GlobalPrefix to names to match linker names.
427 MCContext Context(*_target->getMCAsmInfo());
428 Mangler mangler(Context, *_target->getTargetData());
431 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
432 if (f->isDeclaration())
433 addPotentialUndefinedSymbol(f, mangler);
435 addDefinedFunctionSymbol(f, mangler);
439 for (Module::global_iterator v = _module->global_begin(),
440 e = _module->global_end(); v != e; ++v) {
441 if (v->isDeclaration())
442 addPotentialUndefinedSymbol(v, mangler);
444 addDefinedDataSymbol(v, mangler);
448 const std::string &inlineAsm = _module->getModuleInlineAsm();
449 const std::string glbl = ".globl";
450 std::string asmSymbolName;
451 std::string::size_type pos = inlineAsm.find(glbl, 0);
452 while (pos != std::string::npos) {
456 // skip white space between .globl and symbol name
457 std::string::size_type pbegin = inlineAsm.find_first_not_of(' ', pos);
458 if (pbegin == std::string::npos)
462 std::string::size_type pend = inlineAsm.find_first_of('\n', pbegin);
463 if (pend == std::string::npos)
466 asmSymbolName.assign(inlineAsm, pbegin, pend - pbegin);
467 addAsmGlobalSymbol(asmSymbolName.c_str());
469 // search next .globl
470 pos = inlineAsm.find(glbl, pend);
473 // make symbols for all undefines
474 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
475 it != _undefines.end(); ++it) {
476 // if this symbol also has a definition, then don't make an undefine
477 // because it is a tentative definition
478 if (_defines.count(it->getKey()) == 0) {
479 NameAndAttributes info = it->getValue();
480 _symbols.push_back(info);
487 uint32_t LTOModule::getSymbolCount() {
489 return _symbols.size();
493 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
495 if (index < _symbols.size())
496 return _symbols[index].attributes;
498 return lto_symbol_attributes(0);
501 const char *LTOModule::getSymbolName(uint32_t index) {
503 if (index < _symbols.size())
504 return _symbols[index].name;