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/Support/Host.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/Process.h"
29 #include "llvm/Support/system_error.h"
30 #include "llvm/Target/Mangler.h"
31 #include "llvm/Target/SubtargetFeature.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCContext.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetRegistry.h"
36 #include "llvm/Target/TargetSelect.h"
40 bool LTOModule::isBitcodeFile(const void *mem, size_t length) {
41 return llvm::sys::IdentifyFileType((char*)mem, length)
42 == llvm::sys::Bitcode_FileType;
45 bool LTOModule::isBitcodeFile(const char *path) {
46 return llvm::sys::Path(path).isBitcodeFile();
49 bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length,
50 const char *triplePrefix) {
51 MemoryBuffer *buffer = makeBuffer(mem, length);
54 return isTargetMatch(buffer, triplePrefix);
58 bool LTOModule::isBitcodeFileForTarget(const char *path,
59 const char *triplePrefix) {
60 OwningPtr<MemoryBuffer> buffer;
61 if (MemoryBuffer::getFile(path, buffer))
63 return isTargetMatch(buffer.take(), triplePrefix);
66 // Takes ownership of buffer.
67 bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) {
68 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext());
70 return (strncmp(Triple.c_str(), triplePrefix,
71 strlen(triplePrefix)) == 0);
75 LTOModule::LTOModule(Module *m, TargetMachine *t)
76 : _module(m), _target(t), _symbolsParsed(false)
80 LTOModule *LTOModule::makeLTOModule(const char *path,
81 std::string &errMsg) {
82 OwningPtr<MemoryBuffer> buffer;
83 if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
84 errMsg = ec.message();
87 return makeLTOModule(buffer.get(), errMsg);
90 /// makeBuffer - Create a MemoryBuffer from a memory range. MemoryBuffer
91 /// requires the byte past end of the buffer to be a zero. We might get lucky
92 /// and already be that way, otherwise make a copy. Also if next byte is on a
93 /// different page, don't assume it is readable.
94 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) {
95 const char *startPtr = (char*)mem;
96 const char *endPtr = startPtr+length;
97 if (((uintptr_t)endPtr & (sys::Process::GetPageSize()-1)) == 0 ||
99 return MemoryBuffer::getMemBufferCopy(StringRef(startPtr, length));
101 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length));
105 LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length,
106 std::string &errMsg) {
107 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
110 return makeLTOModule(buffer.get(), errMsg);
113 LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer,
114 std::string &errMsg) {
115 InitializeAllTargets();
117 // parse bitcode buffer
118 OwningPtr<Module> m(ParseBitcodeFile(buffer, getGlobalContext(), &errMsg));
122 std::string Triple = m->getTargetTriple();
124 Triple = sys::getHostTriple();
126 // find machine architecture for this module
127 const Target *march = TargetRegistry::lookupTarget(Triple, errMsg);
131 // construct LTModule, hand over ownership of module and target
132 SubtargetFeatures Features;
133 Features.getDefaultSubtargetFeatures("" /* cpu */, llvm::Triple(Triple));
134 std::string FeatureStr = Features.getString();
135 TargetMachine *target = march->createTargetMachine(Triple, FeatureStr);
136 return new LTOModule(m.take(), target);
140 const char *LTOModule::getTargetTriple() {
141 return _module->getTargetTriple().c_str();
144 void LTOModule::setTargetTriple(const char *triple) {
145 _module->setTargetTriple(triple);
148 void LTOModule::addDefinedFunctionSymbol(Function *f, Mangler &mangler) {
149 // add to list of defined symbols
150 addDefinedSymbol(f, mangler, true);
152 // add external symbols referenced by this function.
153 for (Function::iterator b = f->begin(); b != f->end(); ++b) {
154 for (BasicBlock::iterator i = b->begin(); i != b->end(); ++i) {
155 for (unsigned count = 0, total = i->getNumOperands();
156 count != total; ++count) {
157 findExternalRefs(i->getOperand(count), mangler);
163 // Get string that data pointer points to.
164 bool LTOModule::objcClassNameFromExpression(Constant *c, std::string &name) {
165 if (ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
166 Constant *op = ce->getOperand(0);
167 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
168 Constant *cn = gvn->getInitializer();
169 if (ConstantArray *ca = dyn_cast<ConstantArray>(cn)) {
170 if (ca->isCString()) {
171 name = ".objc_class_name_" + ca->getAsString();
180 // Parse i386/ppc ObjC class data structure.
181 void LTOModule::addObjCClass(GlobalVariable *clgv) {
182 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
183 // second slot in __OBJC,__class is pointer to superclass name
184 std::string superclassName;
185 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
186 NameAndAttributes info;
187 if (_undefines.find(superclassName.c_str()) == _undefines.end()) {
188 const char *symbolName = ::strdup(superclassName.c_str());
189 info.name = symbolName;
190 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
191 // string is owned by _undefines
192 _undefines[info.name] = info;
195 // third slot in __OBJC,__class is pointer to class name
196 std::string className;
197 if (objcClassNameFromExpression(c->getOperand(2), className)) {
198 const char *symbolName = ::strdup(className.c_str());
199 NameAndAttributes info;
200 info.name = symbolName;
201 info.attributes = (lto_symbol_attributes)
202 (LTO_SYMBOL_PERMISSIONS_DATA |
203 LTO_SYMBOL_DEFINITION_REGULAR |
204 LTO_SYMBOL_SCOPE_DEFAULT);
205 _symbols.push_back(info);
206 _defines[info.name] = 1;
212 // Parse i386/ppc ObjC category data structure.
213 void LTOModule::addObjCCategory(GlobalVariable *clgv) {
214 if (ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
215 // second slot in __OBJC,__category is pointer to target class name
216 std::string targetclassName;
217 if (objcClassNameFromExpression(c->getOperand(1), targetclassName)) {
218 NameAndAttributes info;
219 if (_undefines.find(targetclassName.c_str()) == _undefines.end()) {
220 const char *symbolName = ::strdup(targetclassName.c_str());
221 info.name = symbolName;
222 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
223 // string is owned by _undefines
224 _undefines[info.name] = info;
231 // Parse i386/ppc ObjC class list data structure.
232 void LTOModule::addObjCClassRef(GlobalVariable *clgv) {
233 std::string targetclassName;
234 if (objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) {
235 NameAndAttributes info;
236 if (_undefines.find(targetclassName.c_str()) == _undefines.end()) {
237 const char *symbolName = ::strdup(targetclassName.c_str());
238 info.name = symbolName;
239 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
240 // string is owned by _undefines
241 _undefines[info.name] = info;
247 void LTOModule::addDefinedDataSymbol(GlobalValue *v, Mangler &mangler) {
248 // Add to list of defined symbols.
249 addDefinedSymbol(v, mangler, false);
251 // Special case i386/ppc ObjC data structures in magic sections:
252 // The issue is that the old ObjC object format did some strange
253 // contortions to avoid real linker symbols. For instance, the
254 // ObjC class data structure is allocated statically in the executable
255 // that defines that class. That data structures contains a pointer to
256 // its superclass. But instead of just initializing that part of the
257 // struct to the address of its superclass, and letting the static and
258 // dynamic linkers do the rest, the runtime works by having that field
259 // instead point to a C-string that is the name of the superclass.
260 // At runtime the objc initialization updates that pointer and sets
261 // it to point to the actual super class. As far as the linker
262 // knows it is just a pointer to a string. But then someone wanted the
263 // linker to issue errors at build time if the superclass was not found.
264 // So they figured out a way in mach-o object format to use an absolute
265 // symbols (.objc_class_name_Foo = 0) and a floating reference
266 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
267 // a class was missing.
268 // The following synthesizes the implicit .objc_* symbols for the linker
269 // from the ObjC data structures generated by the front end.
270 if (v->hasSection() /* && isTargetDarwin */) {
271 // special case if this data blob is an ObjC class definition
272 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) {
273 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
278 // special case if this data blob is an ObjC category definition
279 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) {
280 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
285 // special case if this data blob is the list of referenced classes
286 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) {
287 if (GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
293 // add external symbols referenced by this data.
294 for (unsigned count = 0, total = v->getNumOperands();
295 count != total; ++count) {
296 findExternalRefs(v->getOperand(count), mangler);
301 void LTOModule::addDefinedSymbol(GlobalValue *def, Mangler &mangler,
303 // ignore all llvm.* symbols
304 if (def->getName().startswith("llvm."))
307 // string is owned by _defines
308 const char *symbolName = ::strdup(mangler.getNameWithPrefix(def).c_str());
310 // set alignment part log2() can have rounding errors
311 uint32_t align = def->getAlignment();
312 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
314 // set permissions part
316 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
318 GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
319 if (gv && gv->isConstant())
320 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
322 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
325 // set definition part
326 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() ||
327 def->hasLinkerPrivateWeakLinkage() ||
328 def->hasLinkerPrivateWeakDefAutoLinkage())
329 attr |= LTO_SYMBOL_DEFINITION_WEAK;
330 else if (def->hasCommonLinkage())
331 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
333 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
336 if (def->hasHiddenVisibility())
337 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
338 else if (def->hasProtectedVisibility())
339 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
340 else if (def->hasExternalLinkage() || def->hasWeakLinkage() ||
341 def->hasLinkOnceLinkage() || def->hasCommonLinkage() ||
342 def->hasLinkerPrivateWeakLinkage())
343 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
344 else if (def->hasLinkerPrivateWeakDefAutoLinkage())
345 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
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))
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() {
426 _symbolsParsed = true;
428 // Use mangler to add GlobalPrefix to names to match linker names.
429 MCContext Context(*_target->getMCAsmInfo(), NULL);
430 Mangler mangler(Context, *_target->getTargetData());
433 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
434 if (f->isDeclaration())
435 addPotentialUndefinedSymbol(f, mangler);
437 addDefinedFunctionSymbol(f, mangler);
441 for (Module::global_iterator v = _module->global_begin(),
442 e = _module->global_end(); v != e; ++v) {
443 if (v->isDeclaration())
444 addPotentialUndefinedSymbol(v, mangler);
446 addDefinedDataSymbol(v, mangler);
450 const std::string &inlineAsm = _module->getModuleInlineAsm();
451 const std::string glbl = ".globl";
452 std::string asmSymbolName;
453 std::string::size_type pos = inlineAsm.find(glbl, 0);
454 while (pos != std::string::npos) {
458 // skip white space between .globl and symbol name
459 std::string::size_type pbegin = inlineAsm.find_first_not_of(' ', pos);
460 if (pbegin == std::string::npos)
464 std::string::size_type pend = inlineAsm.find_first_of('\n', pbegin);
465 if (pend == std::string::npos)
468 asmSymbolName.assign(inlineAsm, pbegin, pend - pbegin);
469 addAsmGlobalSymbol(asmSymbolName.c_str());
471 // search next .globl
472 pos = inlineAsm.find(glbl, pend);
476 for (Module::alias_iterator i = _module->alias_begin(),
477 e = _module->alias_end(); i != e; ++i) {
478 if (i->isDeclaration())
479 addPotentialUndefinedSymbol(i, mangler);
481 addDefinedDataSymbol(i, mangler);
484 // make symbols for all undefines
485 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
486 it != _undefines.end(); ++it) {
487 // if this symbol also has a definition, then don't make an undefine
488 // because it is a tentative definition
489 if (_defines.count(it->getKey()) == 0) {
490 NameAndAttributes info = it->getValue();
491 _symbols.push_back(info);
497 uint32_t LTOModule::getSymbolCount() {
499 return _symbols.size();
503 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index) {
505 if (index < _symbols.size())
506 return _symbols[index].attributes;
508 return lto_symbol_attributes(0);
511 const char *LTOModule::getSymbolName(uint32_t index) {
513 if (index < _symbols.size())
514 return _symbols[index].name;