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/ModuleProvider.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/Bitcode/ReaderWriter.h"
23 #include "llvm/Support/SystemUtils.h"
24 #include "llvm/Support/Mangler.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/System/Path.h"
28 #include "llvm/System/Process.h"
29 #include "llvm/Target/SubtargetFeature.h"
30 #include "llvm/Target/TargetAsmInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegistry.h"
33 #include "llvm/Target/TargetSelect.h"
37 bool LTOModule::isBitcodeFile(const void* mem, size_t length)
39 return ( llvm::sys::IdentifyFileType((char*)mem, length)
40 == llvm::sys::Bitcode_FileType );
43 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)
51 MemoryBuffer* buffer = makeBuffer(mem, length);
54 return isTargetMatch(buffer, triplePrefix);
58 bool LTOModule::isBitcodeFileForTarget(const char* path,
59 const char* triplePrefix)
61 MemoryBuffer *buffer = MemoryBuffer::getFile(path);
64 return isTargetMatch(buffer, triplePrefix);
67 // takes ownership of buffer
68 bool LTOModule::isTargetMatch(MemoryBuffer* buffer, const char* triplePrefix)
70 OwningPtr<ModuleProvider> mp(getBitcodeModuleProvider(buffer,
72 // on success, mp owns buffer and both are deleted at end of this method
77 std::string actualTarget = mp->getModule()->getTargetTriple();
78 return ( strncmp(actualTarget.c_str(), triplePrefix,
79 strlen(triplePrefix)) == 0);
83 LTOModule::LTOModule(Module* m, TargetMachine* t)
84 : _module(m), _target(t), _symbolsParsed(false)
88 LTOModule* LTOModule::makeLTOModule(const char* path,
91 OwningPtr<MemoryBuffer> buffer(MemoryBuffer::getFile(path, &errMsg));
94 return makeLTOModule(buffer.get(), errMsg);
97 /// makeBuffer - create a MemoryBuffer from a memory range.
98 /// MemoryBuffer requires the byte past end of the buffer to be a zero.
99 /// We might get lucky and already be that way, otherwise make a copy.
100 /// Also if next byte is on a different page, don't assume it is readable.
101 MemoryBuffer* LTOModule::makeBuffer(const void* mem, size_t length)
103 const char* startPtr = (char*)mem;
104 const char* endPtr = startPtr+length;
105 if ( (((uintptr_t)endPtr & (sys::Process::GetPageSize()-1)) == 0)
107 return MemoryBuffer::getMemBufferCopy(startPtr, endPtr);
109 return MemoryBuffer::getMemBuffer(startPtr, endPtr);
113 LTOModule* LTOModule::makeLTOModule(const void* mem, size_t length,
116 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
119 return makeLTOModule(buffer.get(), errMsg);
122 /// getFeatureString - Return a string listing the features associated with the
125 /// FIXME: This is an inelegant way of specifying the features of a
126 /// subtarget. It would be better if we could encode this information into the
127 /// IR. See <rdar://5972456>.
128 std::string getFeatureString(const char *TargetTriple) {
129 InitializeAllTargets();
131 SubtargetFeatures Features;
133 if (strncmp(TargetTriple, "powerpc-apple-", 14) == 0) {
134 Features.AddFeature("altivec", true);
135 } else if (strncmp(TargetTriple, "powerpc64-apple-", 16) == 0) {
136 Features.AddFeature("64bit", true);
137 Features.AddFeature("altivec", true);
140 return Features.getString();
143 LTOModule* LTOModule::makeLTOModule(MemoryBuffer* buffer,
146 InitializeAllTargets();
148 // parse bitcode buffer
149 OwningPtr<Module> m(ParseBitcodeFile(buffer, getGlobalContext(), &errMsg));
152 // find machine architecture for this module
153 const Target* march = TargetRegistry::lookupTarget(m->getTargetTriple(),
154 /*FallbackToHost=*/true,
155 /*RequireJIT=*/false,
160 // construct LTModule, hand over ownership of module and target
161 std::string FeatureStr = getFeatureString(m->getTargetTriple().c_str());
162 TargetMachine* target = march->createTargetMachine(*m, FeatureStr);
163 return new LTOModule(m.take(), target);
167 const char* LTOModule::getTargetTriple()
169 return _module->getTargetTriple().c_str();
172 void LTOModule::addDefinedFunctionSymbol(Function* f, Mangler &mangler)
174 // add to list of defined symbols
175 addDefinedSymbol(f, mangler, true);
177 // add external symbols referenced by this function.
178 for (Function::iterator b = f->begin(); b != f->end(); ++b) {
179 for (BasicBlock::iterator i = b->begin(); i != b->end(); ++i) {
180 for (unsigned count = 0, total = i->getNumOperands();
181 count != total; ++count) {
182 findExternalRefs(i->getOperand(count), mangler);
188 // get string that data pointer points to
189 bool LTOModule::objcClassNameFromExpression(Constant* c, std::string& name)
191 if (ConstantExpr* ce = dyn_cast<ConstantExpr>(c)) {
192 Constant* op = ce->getOperand(0);
193 if (GlobalVariable* gvn = dyn_cast<GlobalVariable>(op)) {
194 Constant* cn = gvn->getInitializer();
195 if (ConstantArray* ca = dyn_cast<ConstantArray>(cn)) {
196 if ( ca->isCString() ) {
197 name = ".objc_class_name_" + ca->getAsString();
206 // parse i386/ppc ObjC class data structure
207 void LTOModule::addObjCClass(GlobalVariable* clgv)
209 if (ConstantStruct* c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
210 // second slot in __OBJC,__class is pointer to superclass name
211 std::string superclassName;
212 if ( objcClassNameFromExpression(c->getOperand(1), superclassName) ) {
213 NameAndAttributes info;
214 if ( _undefines.find(superclassName.c_str()) == _undefines.end() ) {
215 const char* symbolName = ::strdup(superclassName.c_str());
216 info.name = ::strdup(symbolName);
217 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
218 // string is owned by _undefines
219 _undefines[info.name] = info;
222 // third slot in __OBJC,__class is pointer to class name
223 std::string className;
224 if ( objcClassNameFromExpression(c->getOperand(2), className) ) {
225 const char* symbolName = ::strdup(className.c_str());
226 NameAndAttributes info;
227 info.name = symbolName;
228 info.attributes = (lto_symbol_attributes)
229 (LTO_SYMBOL_PERMISSIONS_DATA |
230 LTO_SYMBOL_DEFINITION_REGULAR |
231 LTO_SYMBOL_SCOPE_DEFAULT);
232 _symbols.push_back(info);
233 _defines[info.name] = 1;
239 // parse i386/ppc ObjC category data structure
240 void LTOModule::addObjCCategory(GlobalVariable* clgv)
242 if (ConstantStruct* c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
243 // second slot in __OBJC,__category is pointer to target class name
244 std::string targetclassName;
245 if ( objcClassNameFromExpression(c->getOperand(1), targetclassName) ) {
246 NameAndAttributes info;
247 if ( _undefines.find(targetclassName.c_str()) == _undefines.end() ){
248 const char* symbolName = ::strdup(targetclassName.c_str());
249 info.name = ::strdup(symbolName);
250 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
251 // string is owned by _undefines
252 _undefines[info.name] = info;
259 // parse i386/ppc ObjC class list data structure
260 void LTOModule::addObjCClassRef(GlobalVariable* clgv)
262 std::string targetclassName;
263 if ( objcClassNameFromExpression(clgv->getInitializer(), targetclassName) ){
264 NameAndAttributes info;
265 if ( _undefines.find(targetclassName.c_str()) == _undefines.end() ) {
266 const char* symbolName = ::strdup(targetclassName.c_str());
267 info.name = ::strdup(symbolName);
268 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
269 // string is owned by _undefines
270 _undefines[info.name] = info;
276 void LTOModule::addDefinedDataSymbol(GlobalValue* v, Mangler& mangler)
278 // add to list of defined symbols
279 addDefinedSymbol(v, mangler, false);
281 // Special case i386/ppc ObjC data structures in magic sections:
282 // The issue is that the old ObjC object format did some strange
283 // contortions to avoid real linker symbols. For instance, the
284 // ObjC class data structure is allocated statically in the executable
285 // that defines that class. That data structures contains a pointer to
286 // its superclass. But instead of just initializing that part of the
287 // struct to the address of its superclass, and letting the static and
288 // dynamic linkers do the rest, the runtime works by having that field
289 // instead point to a C-string that is the name of the superclass.
290 // At runtime the objc initialization updates that pointer and sets
291 // it to point to the actual super class. As far as the linker
292 // knows it is just a pointer to a string. But then someone wanted the
293 // linker to issue errors at build time if the superclass was not found.
294 // So they figured out a way in mach-o object format to use an absolute
295 // symbols (.objc_class_name_Foo = 0) and a floating reference
296 // (.reference .objc_class_name_Bar) to cause the linker into erroring when
297 // a class was missing.
298 // The following synthesizes the implicit .objc_* symbols for the linker
299 // from the ObjC data structures generated by the front end.
300 if ( v->hasSection() /* && isTargetDarwin */ ) {
301 // special case if this data blob is an ObjC class definition
302 if ( v->getSection().compare(0, 15, "__OBJC,__class,") == 0 ) {
303 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(v)) {
308 // special case if this data blob is an ObjC category definition
309 else if ( v->getSection().compare(0, 18, "__OBJC,__category,") == 0 ) {
310 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(v)) {
315 // special case if this data blob is the list of referenced classes
316 else if ( v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0 ) {
317 if (GlobalVariable* gv = dyn_cast<GlobalVariable>(v)) {
323 // add external symbols referenced by this data.
324 for (unsigned count = 0, total = v->getNumOperands();
325 count != total; ++count) {
326 findExternalRefs(v->getOperand(count), mangler);
331 void LTOModule::addDefinedSymbol(GlobalValue* def, Mangler &mangler,
334 // ignore all llvm.* symbols
335 if (def->getName().startswith("llvm."))
338 // string is owned by _defines
339 const char* symbolName = ::strdup(mangler.getMangledName(def).c_str());
341 // set alignment part log2() can have rounding errors
342 uint32_t align = def->getAlignment();
343 uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
345 // set permissions part
347 attr |= LTO_SYMBOL_PERMISSIONS_CODE;
349 GlobalVariable* gv = dyn_cast<GlobalVariable>(def);
350 if ( (gv != NULL) && gv->isConstant() )
351 attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
353 attr |= LTO_SYMBOL_PERMISSIONS_DATA;
356 // set definition part
357 if ( def->hasWeakLinkage() || def->hasLinkOnceLinkage() ) {
358 attr |= LTO_SYMBOL_DEFINITION_WEAK;
360 else if ( def->hasCommonLinkage()) {
361 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
364 attr |= LTO_SYMBOL_DEFINITION_REGULAR;
368 if ( def->hasHiddenVisibility() )
369 attr |= LTO_SYMBOL_SCOPE_HIDDEN;
370 else if ( def->hasProtectedVisibility() )
371 attr |= LTO_SYMBOL_SCOPE_PROTECTED;
372 else if ( def->hasExternalLinkage() || def->hasWeakLinkage()
373 || def->hasLinkOnceLinkage() || def->hasCommonLinkage() )
374 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
376 attr |= LTO_SYMBOL_SCOPE_INTERNAL;
378 // add to table of symbols
379 NameAndAttributes info;
380 info.name = symbolName;
381 info.attributes = (lto_symbol_attributes)attr;
382 _symbols.push_back(info);
383 _defines[info.name] = 1;
386 void LTOModule::addAsmGlobalSymbol(const char *name) {
387 // only add new define if not already defined
388 if ( _defines.count(name) == 0 )
391 // string is owned by _defines
392 const char *symbolName = ::strdup(name);
393 uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
394 attr |= LTO_SYMBOL_SCOPE_DEFAULT;
395 NameAndAttributes info;
396 info.name = symbolName;
397 info.attributes = (lto_symbol_attributes)attr;
398 _symbols.push_back(info);
399 _defines[info.name] = 1;
402 void LTOModule::addPotentialUndefinedSymbol(GlobalValue* decl, Mangler &mangler)
404 // ignore all llvm.* symbols
405 if (decl->getName().startswith("llvm."))
408 // ignore all aliases
409 if (isa<GlobalAlias>(decl))
412 const char* name = mangler.getMangledName(decl).c_str();
414 // we already have the symbol
415 if (_undefines.find(name) != _undefines.end())
418 NameAndAttributes info;
419 // string is owned by _undefines
420 info.name = ::strdup(name);
421 if (decl->hasExternalWeakLinkage())
422 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
424 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
425 _undefines[name] = info;
430 // Find external symbols referenced by VALUE. This is a recursive function.
431 void LTOModule::findExternalRefs(Value* value, Mangler &mangler) {
433 if (GlobalValue* gv = dyn_cast<GlobalValue>(value)) {
434 if ( !gv->hasExternalLinkage() )
435 addPotentialUndefinedSymbol(gv, mangler);
436 // If this is a variable definition, do not recursively process
437 // initializer. It might contain a reference to this variable
438 // and cause an infinite loop. The initializer will be
439 // processed in addDefinedDataSymbol().
443 // GlobalValue, even with InternalLinkage type, may have operands with
444 // ExternalLinkage type. Do not ignore these operands.
445 if (Constant* c = dyn_cast<Constant>(value)) {
446 // Handle ConstantExpr, ConstantStruct, ConstantArry etc..
447 for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i)
448 findExternalRefs(c->getOperand(i), mangler);
452 void LTOModule::lazyParseSymbols()
454 if ( !_symbolsParsed ) {
455 _symbolsParsed = true;
457 // Use mangler to add GlobalPrefix to names to match linker names.
458 Mangler mangler(*_module, _target->getTargetAsmInfo()->getGlobalPrefix());
459 // add chars used in ObjC method names so method names aren't mangled
460 mangler.markCharAcceptable('[');
461 mangler.markCharAcceptable(']');
462 mangler.markCharAcceptable('(');
463 mangler.markCharAcceptable(')');
464 mangler.markCharAcceptable('-');
465 mangler.markCharAcceptable('+');
466 mangler.markCharAcceptable(' ');
469 for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
470 if ( f->isDeclaration() )
471 addPotentialUndefinedSymbol(f, mangler);
473 addDefinedFunctionSymbol(f, mangler);
477 for (Module::global_iterator v = _module->global_begin(),
478 e = _module->global_end(); v != e; ++v) {
479 if ( v->isDeclaration() )
480 addPotentialUndefinedSymbol(v, mangler);
482 addDefinedDataSymbol(v, mangler);
486 const std::string &inlineAsm = _module->getModuleInlineAsm();
487 const std::string glbl = ".globl";
488 std::string asmSymbolName;
489 std::string::size_type pos = inlineAsm.find(glbl, 0);
490 while (pos != std::string::npos) {
494 // skip white space between .globl and symbol name
495 std::string::size_type pbegin = inlineAsm.find_first_not_of(' ', pos);
496 if (pbegin == std::string::npos)
500 std::string::size_type pend = inlineAsm.find_first_of('\n', pbegin);
501 if (pend == std::string::npos)
504 asmSymbolName.assign(inlineAsm, pbegin, pend - pbegin);
505 addAsmGlobalSymbol(asmSymbolName.c_str());
507 // search next .globl
508 pos = inlineAsm.find(glbl, pend);
511 // make symbols for all undefines
512 for (StringMap<NameAndAttributes>::iterator it=_undefines.begin();
513 it != _undefines.end(); ++it) {
514 // if this symbol also has a definition, then don't make an undefine
515 // because it is a tentative definition
516 if ( _defines.count(it->getKey()) == 0 ) {
517 NameAndAttributes info = it->getValue();
518 _symbols.push_back(info);
525 uint32_t LTOModule::getSymbolCount()
528 return _symbols.size();
532 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index)
535 if ( index < _symbols.size() )
536 return _symbols[index].attributes;
538 return lto_symbol_attributes(0);
541 const char* LTOModule::getSymbolName(uint32_t index)
544 if ( index < _symbols.size() )
545 return _symbols[index].name;