64e79509017d96ec0d08caca7c455c8d776f3626
[oota-llvm.git] / tools / lto / LTOModule.cpp
1 //===-LTOModule.cpp - LLVM Link Time Optimizer ----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
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.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "LTOModule.h"
16
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/TargetMachine.h"
31 #include "llvm/Target/TargetMachineRegistry.h"
32 #include "llvm/Target/TargetAsmInfo.h"
33
34 #include <fstream>
35
36 using namespace llvm;
37
38 bool LTOModule::isBitcodeFile(const void* mem, size_t length)
39 {
40     return ( llvm::sys::IdentifyFileType((char*)mem, length) 
41                                             == llvm::sys::Bitcode_FileType );
42 }
43
44 bool LTOModule::isBitcodeFile(const char* path)
45 {
46     return llvm::sys::Path(path).isBitcodeFile();
47 }
48
49 bool LTOModule::isBitcodeFileForTarget(const void* mem, size_t length,
50                                        const char* triplePrefix) 
51 {
52     MemoryBuffer* buffer = makeBuffer(mem, length);
53     if ( buffer == NULL )
54         return false;
55     return isTargetMatch(buffer, triplePrefix);
56 }
57
58
59 bool LTOModule::isBitcodeFileForTarget(const char* path,
60                                        const char* triplePrefix) 
61 {
62     MemoryBuffer *buffer = MemoryBuffer::getFile(path);
63     if (buffer == NULL)
64         return false;
65     return isTargetMatch(buffer, triplePrefix);
66 }
67
68 // takes ownership of buffer
69 bool LTOModule::isTargetMatch(MemoryBuffer* buffer, const char* triplePrefix)
70 {
71     OwningPtr<ModuleProvider> mp(getBitcodeModuleProvider(buffer,
72                                                           new LLVMContext()));
73     // on success, mp owns buffer and both are deleted at end of this method
74     if ( !mp ) {
75         delete buffer;
76         return false;
77     }
78     std::string actualTarget = mp->getModule()->getTargetTriple();
79     return ( strncmp(actualTarget.c_str(), triplePrefix, 
80                     strlen(triplePrefix)) == 0);
81 }
82
83
84 LTOModule::LTOModule(Module* m, TargetMachine* t) 
85  : _module(m), _target(t), _symbolsParsed(false)
86 {
87 }
88
89 LTOModule* LTOModule::makeLTOModule(const char* path, LLVMContext* Context,
90                                     std::string& errMsg)
91 {
92     OwningPtr<MemoryBuffer> buffer(MemoryBuffer::getFile(path, &errMsg));
93     if ( !buffer )
94         return NULL;
95     return makeLTOModule(buffer.get(), Context, errMsg);
96 }
97
98 /// makeBuffer - create a MemoryBuffer from a memory range.
99 /// MemoryBuffer requires the byte past end of the buffer to be a zero.
100 /// We might get lucky and already be that way, otherwise make a copy.
101 /// Also if next byte is on a different page, don't assume it is readable.
102 MemoryBuffer* LTOModule::makeBuffer(const void* mem, size_t length)
103 {
104     const char* startPtr = (char*)mem;
105     const char* endPtr = startPtr+length;
106     if ( (((uintptr_t)endPtr & (sys::Process::GetPageSize()-1)) == 0) 
107         || (*endPtr != 0) ) 
108         return MemoryBuffer::getMemBufferCopy(startPtr, endPtr);
109     else
110         return MemoryBuffer::getMemBuffer(startPtr, endPtr);
111 }
112
113
114 LTOModule* LTOModule::makeLTOModule(const void* mem, size_t length, 
115                                     LLVMContext* Context,
116                                     std::string& errMsg)
117 {
118     OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
119     if ( !buffer )
120         return NULL;
121     return makeLTOModule(buffer.get(), Context, errMsg);
122 }
123
124 /// getFeatureString - Return a string listing the features associated with the
125 /// target triple.
126 ///
127 /// FIXME: This is an inelegant way of specifying the features of a
128 /// subtarget. It would be better if we could encode this information into the
129 /// IR. See <rdar://5972456>.
130 std::string getFeatureString(const char *TargetTriple) {
131   SubtargetFeatures Features;
132
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);
138   }
139
140   return Features.getString();
141 }
142
143 LTOModule* LTOModule::makeLTOModule(MemoryBuffer* buffer, LLVMContext* Context,
144                                     std::string& errMsg)
145 {
146     // parse bitcode buffer
147     OwningPtr<Module> m(ParseBitcodeFile(buffer, Context, &errMsg));
148     if ( !m )
149         return NULL;
150     // find machine architecture for this module
151     const TargetMachineRegistry::entry* march = 
152             TargetMachineRegistry::getClosestStaticTargetForModule(*m, errMsg);
153
154     if ( march == NULL ) 
155         return NULL;
156
157     // construct LTModule, hand over ownership of module and target
158     std::string FeatureStr = getFeatureString(m->getTargetTriple().c_str());
159     TargetMachine* target = march->CtorFn(*m, FeatureStr);
160     return new LTOModule(m.take(), target);
161 }
162
163
164 const char* LTOModule::getTargetTriple()
165 {
166     return _module->getTargetTriple().c_str();
167 }
168
169 void LTOModule::addDefinedFunctionSymbol(Function* f, Mangler &mangler)
170 {
171     // add to list of defined symbols
172     addDefinedSymbol(f, mangler, true); 
173
174     // add external symbols referenced by this function.
175     for (Function::iterator b = f->begin(); b != f->end(); ++b) {
176         for (BasicBlock::iterator i = b->begin(); i != b->end(); ++i) {
177             for (unsigned count = 0, total = i->getNumOperands(); 
178                                         count != total; ++count) {
179                 findExternalRefs(i->getOperand(count), mangler);
180             }
181         }
182     }
183 }
184
185 // get string that data pointer points to 
186 bool LTOModule::objcClassNameFromExpression(Constant* c, std::string& name)
187 {
188     if (ConstantExpr* ce = dyn_cast<ConstantExpr>(c)) {
189         Constant* op = ce->getOperand(0);
190         if (GlobalVariable* gvn = dyn_cast<GlobalVariable>(op)) {
191             Constant* cn = gvn->getInitializer(); 
192             if (ConstantArray* ca = dyn_cast<ConstantArray>(cn)) {
193                 if ( ca->isCString() ) {
194                     name = ".objc_class_name_" + ca->getAsString();
195                     return true;
196                 }
197             }
198         }
199     }
200     return false;
201 }
202
203 // parse i386/ppc ObjC class data structure 
204 void LTOModule::addObjCClass(GlobalVariable* clgv)
205 {
206     if (ConstantStruct* c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
207         // second slot in __OBJC,__class is pointer to superclass name
208         std::string superclassName;
209         if ( objcClassNameFromExpression(c->getOperand(1), superclassName) ) {
210             NameAndAttributes info;
211             if ( _undefines.find(superclassName.c_str()) == _undefines.end() ) {
212                 const char* symbolName = ::strdup(superclassName.c_str());
213                 info.name = ::strdup(symbolName);
214                 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
215                 // string is owned by _undefines
216                 _undefines[info.name] = info;
217             }
218         }
219         // third slot in __OBJC,__class is pointer to class name
220         std::string className;
221          if ( objcClassNameFromExpression(c->getOperand(2), className) ) {
222             const char* symbolName = ::strdup(className.c_str());
223             NameAndAttributes info;
224             info.name = symbolName;
225             info.attributes = (lto_symbol_attributes)
226                 (LTO_SYMBOL_PERMISSIONS_DATA |
227                  LTO_SYMBOL_DEFINITION_REGULAR | 
228                  LTO_SYMBOL_SCOPE_DEFAULT);
229             _symbols.push_back(info);
230             _defines[info.name] = 1;
231          }
232     }
233 }
234
235
236 // parse i386/ppc ObjC category data structure 
237 void LTOModule::addObjCCategory(GlobalVariable* clgv)
238 {
239     if (ConstantStruct* c = dyn_cast<ConstantStruct>(clgv->getInitializer())) {
240         // second slot in __OBJC,__category is pointer to target class name
241         std::string targetclassName;
242         if ( objcClassNameFromExpression(c->getOperand(1), targetclassName) ) {
243             NameAndAttributes info;
244             if ( _undefines.find(targetclassName.c_str()) == _undefines.end() ){
245                 const char* symbolName = ::strdup(targetclassName.c_str());
246                 info.name = ::strdup(symbolName);
247                 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
248                 // string is owned by _undefines
249                _undefines[info.name] = info;
250             }
251         }
252     }
253 }
254
255
256 // parse i386/ppc ObjC class list data structure 
257 void LTOModule::addObjCClassRef(GlobalVariable* clgv)
258 {
259     std::string targetclassName;
260     if ( objcClassNameFromExpression(clgv->getInitializer(), targetclassName) ){
261         NameAndAttributes info;
262         if ( _undefines.find(targetclassName.c_str()) == _undefines.end() ) {
263             const char* symbolName = ::strdup(targetclassName.c_str());
264             info.name = ::strdup(symbolName);
265             info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
266             // string is owned by _undefines
267             _undefines[info.name] = info;
268         }
269     }
270 }
271
272
273 void LTOModule::addDefinedDataSymbol(GlobalValue* v, Mangler& mangler)
274 {    
275     // add to list of defined symbols
276     addDefinedSymbol(v, mangler, false); 
277
278     // Special case i386/ppc ObjC data structures in magic sections:
279     // The issue is that the old ObjC object format did some strange 
280     // contortions to avoid real linker symbols.  For instance, the 
281     // ObjC class data structure is allocated statically in the executable 
282     // that defines that class.  That data structures contains a pointer to
283     // its superclass.  But instead of just initializing that part of the 
284     // struct to the address of its superclass, and letting the static and 
285     // dynamic linkers do the rest, the runtime works by having that field
286     // instead point to a C-string that is the name of the superclass. 
287     // At runtime the objc initialization updates that pointer and sets 
288     // it to point to the actual super class.  As far as the linker
289     // knows it is just a pointer to a string.  But then someone wanted the 
290     // linker to issue errors at build time if the superclass was not found.  
291     // So they figured out a way in mach-o object format to use an absolute 
292     // symbols (.objc_class_name_Foo = 0) and a floating reference 
293     // (.reference .objc_class_name_Bar) to cause the linker into erroring when
294     // a class was missing.   
295     // The following synthesizes the implicit .objc_* symbols for the linker
296     // from the ObjC data structures generated by the front end.
297     if ( v->hasSection() /* && isTargetDarwin */ ) {
298         // special case if this data blob is an ObjC class definition
299         if ( v->getSection().compare(0, 15, "__OBJC,__class,") == 0 ) {
300             if (GlobalVariable* gv = dyn_cast<GlobalVariable>(v)) {
301                 addObjCClass(gv);
302             }
303         }                        
304     
305         // special case if this data blob is an ObjC category definition
306         else if ( v->getSection().compare(0, 18, "__OBJC,__category,") == 0 ) {
307             if (GlobalVariable* gv = dyn_cast<GlobalVariable>(v)) {
308                 addObjCCategory(gv);
309             }
310         }                        
311         
312         // special case if this data blob is the list of referenced classes
313         else if ( v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0 ) {
314             if (GlobalVariable* gv = dyn_cast<GlobalVariable>(v)) {
315                 addObjCClassRef(gv);
316             }
317         }                        
318     }
319
320     // add external symbols referenced by this data.
321     for (unsigned count = 0, total = v->getNumOperands();
322                                                 count != total; ++count) {
323         findExternalRefs(v->getOperand(count), mangler);
324     }
325 }
326
327
328 void LTOModule::addDefinedSymbol(GlobalValue* def, Mangler &mangler, 
329                                 bool isFunction)
330 {    
331     // ignore all llvm.* symbols
332     if ( strncmp(def->getNameStart(), "llvm.", 5) == 0 )
333         return;
334
335     // string is owned by _defines
336     const char* symbolName = ::strdup(mangler.getValueName(def).c_str());
337
338     // set alignment part log2() can have rounding errors
339     uint32_t align = def->getAlignment();
340     uint32_t attr = align ? CountTrailingZeros_32(def->getAlignment()) : 0;
341     
342     // set permissions part
343     if ( isFunction )
344         attr |= LTO_SYMBOL_PERMISSIONS_CODE;
345     else {
346         GlobalVariable* gv = dyn_cast<GlobalVariable>(def);
347         if ( (gv != NULL) && gv->isConstant() )
348             attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
349         else
350             attr |= LTO_SYMBOL_PERMISSIONS_DATA;
351     }
352     
353     // set definition part 
354     if ( def->hasWeakLinkage() || def->hasLinkOnceLinkage() ) {
355         attr |= LTO_SYMBOL_DEFINITION_WEAK;
356     }
357     else if ( def->hasCommonLinkage()) {
358         attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
359     }
360     else { 
361         attr |= LTO_SYMBOL_DEFINITION_REGULAR;
362     }
363     
364     // set scope part
365     if ( def->hasHiddenVisibility() )
366         attr |= LTO_SYMBOL_SCOPE_HIDDEN;
367     else if ( def->hasProtectedVisibility() )
368         attr |= LTO_SYMBOL_SCOPE_PROTECTED;
369     else if ( def->hasExternalLinkage() || def->hasWeakLinkage() 
370               || def->hasLinkOnceLinkage() || def->hasCommonLinkage() )
371         attr |= LTO_SYMBOL_SCOPE_DEFAULT;
372     else
373         attr |= LTO_SYMBOL_SCOPE_INTERNAL;
374
375     // add to table of symbols
376     NameAndAttributes info;
377     info.name = symbolName;
378     info.attributes = (lto_symbol_attributes)attr;
379     _symbols.push_back(info);
380     _defines[info.name] = 1;
381 }
382
383 void LTOModule::addAsmGlobalSymbol(const char *name) {
384     // only add new define if not already defined
385     if ( _defines.count(name, &name[strlen(name)+1]) == 0 ) 
386         return;
387         
388     // string is owned by _defines
389     const char *symbolName = ::strdup(name);
390     uint32_t attr = LTO_SYMBOL_DEFINITION_REGULAR;
391     attr |= LTO_SYMBOL_SCOPE_DEFAULT;
392     NameAndAttributes info;
393     info.name = symbolName;
394     info.attributes = (lto_symbol_attributes)attr;
395     _symbols.push_back(info);
396     _defines[info.name] = 1;
397 }
398
399 void LTOModule::addPotentialUndefinedSymbol(GlobalValue* decl, Mangler &mangler)
400 {   
401     // ignore all llvm.* symbols
402     if ( strncmp(decl->getNameStart(), "llvm.", 5) == 0 )
403         return;
404
405     const char* name = mangler.getValueName(decl).c_str();
406
407     // we already have the symbol
408     if (_undefines.find(name) != _undefines.end())
409       return;
410
411     NameAndAttributes info;
412     // string is owned by _undefines
413     info.name = ::strdup(name);
414     if (decl->hasExternalWeakLinkage())
415       info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
416     else
417       info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
418     _undefines[name] = info;
419 }
420
421
422
423 // Find exeternal symbols referenced by VALUE. This is a recursive function.
424 void LTOModule::findExternalRefs(Value* value, Mangler &mangler) {
425
426     if (GlobalValue* gv = dyn_cast<GlobalValue>(value)) {
427         if ( !gv->hasExternalLinkage() )
428             addPotentialUndefinedSymbol(gv, mangler);
429         // If this is a variable definition, do not recursively process
430         // initializer.  It might contain a reference to this variable
431         // and cause an infinite loop.  The initializer will be
432         // processed in addDefinedDataSymbol(). 
433         return;
434     }
435     
436     // GlobalValue, even with InternalLinkage type, may have operands with 
437     // ExternalLinkage type. Do not ignore these operands.
438     if (Constant* c = dyn_cast<Constant>(value)) {
439         // Handle ConstantExpr, ConstantStruct, ConstantArry etc..
440         for (unsigned i = 0, e = c->getNumOperands(); i != e; ++i)
441             findExternalRefs(c->getOperand(i), mangler);
442     }
443 }
444
445 void LTOModule::lazyParseSymbols()
446 {
447     if ( !_symbolsParsed ) {
448         _symbolsParsed = true;
449         
450         // Use mangler to add GlobalPrefix to names to match linker names.
451         Mangler mangler(*_module, _target->getTargetAsmInfo()->getGlobalPrefix());
452         // add chars used in ObjC method names so method names aren't mangled
453         mangler.markCharAcceptable('[');
454         mangler.markCharAcceptable(']');
455         mangler.markCharAcceptable('(');
456         mangler.markCharAcceptable(')');
457         mangler.markCharAcceptable('-');
458         mangler.markCharAcceptable('+');
459         mangler.markCharAcceptable(' ');
460
461         // add functions
462         for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
463             if ( f->isDeclaration() ) 
464                 addPotentialUndefinedSymbol(f, mangler);
465             else 
466                 addDefinedFunctionSymbol(f, mangler);
467         }
468         
469         // add data 
470         for (Module::global_iterator v = _module->global_begin(), 
471                                     e = _module->global_end(); v !=  e; ++v) {
472             if ( v->isDeclaration() ) 
473                 addPotentialUndefinedSymbol(v, mangler);
474             else 
475                 addDefinedDataSymbol(v, mangler);
476         }
477
478         // add asm globals
479         const std::string &inlineAsm = _module->getModuleInlineAsm();
480         const std::string glbl = ".globl";
481         std::string asmSymbolName;
482         std::string::size_type pos = inlineAsm.find(glbl, 0);
483         while (pos != std::string::npos) {
484           // eat .globl
485           pos = pos + 6;
486
487           // skip white space between .globl and symbol name
488           std::string::size_type pbegin = inlineAsm.find_first_not_of(' ', pos);
489           if (pbegin == std::string::npos)
490             break;
491
492           // find end-of-line
493           std::string::size_type pend = inlineAsm.find_first_of('\n', pbegin);
494           if (pend == std::string::npos)
495             break;
496
497           asmSymbolName.assign(inlineAsm, pbegin, pend - pbegin);
498           addAsmGlobalSymbol(asmSymbolName.c_str());
499
500           // search next .globl
501           pos = inlineAsm.find(glbl, pend);
502         }
503
504         // make symbols for all undefines
505         for (StringMap<NameAndAttributes>::iterator it=_undefines.begin(); 
506                                                 it != _undefines.end(); ++it) {
507             // if this symbol also has a definition, then don't make an undefine
508             // because it is a tentative definition
509             if ( _defines.count(it->getKeyData(), it->getKeyData()+
510                                                   it->getKeyLength()) == 0 ) {
511               NameAndAttributes info = it->getValue();
512               _symbols.push_back(info);
513             }
514         }
515     }    
516 }
517
518
519 uint32_t LTOModule::getSymbolCount()
520 {
521     lazyParseSymbols();
522     return _symbols.size();
523 }
524
525
526 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index)
527 {
528     lazyParseSymbols();
529     if ( index < _symbols.size() )
530         return _symbols[index].attributes;
531     else
532         return lto_symbol_attributes(0);
533 }
534
535 const char* LTOModule::getSymbolName(uint32_t index)
536 {
537     lazyParseSymbols();
538     if ( index < _symbols.size() )
539         return _symbols[index].name;
540     else
541         return NULL;
542 }
543