Remove memory corruption bug. string.c_str() was returning a temporary that was
[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/TargetAsmInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegistry.h"
33 #include "llvm/Target/TargetSelect.h"
34
35 using namespace llvm;
36
37 bool LTOModule::isBitcodeFile(const void* mem, size_t length)
38 {
39     return ( llvm::sys::IdentifyFileType((char*)mem, length) 
40                                             == llvm::sys::Bitcode_FileType );
41 }
42
43 bool LTOModule::isBitcodeFile(const char* path)
44 {
45     return llvm::sys::Path(path).isBitcodeFile();
46 }
47
48 bool LTOModule::isBitcodeFileForTarget(const void* mem, size_t length,
49                                        const char* triplePrefix) 
50 {
51     MemoryBuffer* buffer = makeBuffer(mem, length);
52     if ( buffer == NULL )
53         return false;
54     return isTargetMatch(buffer, triplePrefix);
55 }
56
57
58 bool LTOModule::isBitcodeFileForTarget(const char* path,
59                                        const char* triplePrefix) 
60 {
61     MemoryBuffer *buffer = MemoryBuffer::getFile(path);
62     if (buffer == NULL)
63         return false;
64     return isTargetMatch(buffer, triplePrefix);
65 }
66
67 // takes ownership of buffer
68 bool LTOModule::isTargetMatch(MemoryBuffer* buffer, const char* triplePrefix)
69 {
70     OwningPtr<ModuleProvider> mp(getBitcodeModuleProvider(buffer,
71                                                           getGlobalContext()));
72     // on success, mp owns buffer and both are deleted at end of this method
73     if ( !mp ) {
74         delete buffer;
75         return false;
76     }
77     std::string actualTarget = mp->getModule()->getTargetTriple();
78     return ( strncmp(actualTarget.c_str(), triplePrefix, 
79                     strlen(triplePrefix)) == 0);
80 }
81
82
83 LTOModule::LTOModule(Module* m, TargetMachine* t) 
84  : _module(m), _target(t), _symbolsParsed(false)
85 {
86 }
87
88 LTOModule* LTOModule::makeLTOModule(const char* path,
89                                     std::string& errMsg)
90 {
91     OwningPtr<MemoryBuffer> buffer(MemoryBuffer::getFile(path, &errMsg));
92     if ( !buffer )
93         return NULL;
94     return makeLTOModule(buffer.get(), errMsg);
95 }
96
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)
102 {
103     const char* startPtr = (char*)mem;
104     const char* endPtr = startPtr+length;
105     if ( (((uintptr_t)endPtr & (sys::Process::GetPageSize()-1)) == 0) 
106         || (*endPtr != 0) ) 
107         return MemoryBuffer::getMemBufferCopy(startPtr, endPtr);
108     else
109         return MemoryBuffer::getMemBuffer(startPtr, endPtr);
110 }
111
112
113 LTOModule* LTOModule::makeLTOModule(const void* mem, size_t length, 
114                                     std::string& errMsg)
115 {
116     OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length));
117     if ( !buffer )
118         return NULL;
119     return makeLTOModule(buffer.get(), errMsg);
120 }
121
122 /// getFeatureString - Return a string listing the features associated with the
123 /// target triple.
124 ///
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();
130
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,
144                                     std::string& errMsg)
145 {
146     InitializeAllTargets();
147
148     // parse bitcode buffer
149     OwningPtr<Module> m(ParseBitcodeFile(buffer, getGlobalContext(), &errMsg));
150     if ( !m )
151         return NULL;
152     // find machine architecture for this module
153     const Target* march = TargetRegistry::lookupTarget(m->getTargetTriple(), 
154                                                        /*FallbackToHost=*/true,
155                                                        /*RequireJIT=*/false,
156                                                        errMsg);
157     if ( march == NULL ) 
158         return NULL;
159
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);
164 }
165
166
167 const char* LTOModule::getTargetTriple()
168 {
169     return _module->getTargetTriple().c_str();
170 }
171
172 void LTOModule::addDefinedFunctionSymbol(Function* f, Mangler &mangler)
173 {
174     // add to list of defined symbols
175     addDefinedSymbol(f, mangler, true); 
176
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);
183             }
184         }
185     }
186 }
187
188 // get string that data pointer points to 
189 bool LTOModule::objcClassNameFromExpression(Constant* c, std::string& name)
190 {
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();
198                     return true;
199                 }
200             }
201         }
202     }
203     return false;
204 }
205
206 // parse i386/ppc ObjC class data structure 
207 void LTOModule::addObjCClass(GlobalVariable* clgv)
208 {
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;
220             }
221         }
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;
234          }
235     }
236 }
237
238
239 // parse i386/ppc ObjC category data structure 
240 void LTOModule::addObjCCategory(GlobalVariable* clgv)
241 {
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;
253             }
254         }
255     }
256 }
257
258
259 // parse i386/ppc ObjC class list data structure 
260 void LTOModule::addObjCClassRef(GlobalVariable* clgv)
261 {
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;
271         }
272     }
273 }
274
275
276 void LTOModule::addDefinedDataSymbol(GlobalValue* v, Mangler& mangler)
277 {    
278     // add to list of defined symbols
279     addDefinedSymbol(v, mangler, false); 
280
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)) {
304                 addObjCClass(gv);
305             }
306         }                        
307     
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)) {
311                 addObjCCategory(gv);
312             }
313         }                        
314         
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)) {
318                 addObjCClassRef(gv);
319             }
320         }                        
321     }
322
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);
327     }
328 }
329
330
331 void LTOModule::addDefinedSymbol(GlobalValue* def, Mangler &mangler, 
332                                  bool isFunction)
333 {    
334     // ignore all llvm.* symbols
335     if (def->getName().startswith("llvm."))
336         return;
337
338     // string is owned by _defines
339     const char* symbolName = ::strdup(mangler.getMangledName(def).c_str());
340
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;
344     
345     // set permissions part
346     if ( isFunction )
347         attr |= LTO_SYMBOL_PERMISSIONS_CODE;
348     else {
349         GlobalVariable* gv = dyn_cast<GlobalVariable>(def);
350         if ( (gv != NULL) && gv->isConstant() )
351             attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
352         else
353             attr |= LTO_SYMBOL_PERMISSIONS_DATA;
354     }
355     
356     // set definition part 
357     if ( def->hasWeakLinkage() || def->hasLinkOnceLinkage() ) {
358         attr |= LTO_SYMBOL_DEFINITION_WEAK;
359     }
360     else if ( def->hasCommonLinkage()) {
361         attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
362     }
363     else { 
364         attr |= LTO_SYMBOL_DEFINITION_REGULAR;
365     }
366     
367     // set scope part
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;
375     else
376         attr |= LTO_SYMBOL_SCOPE_INTERNAL;
377
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;
384 }
385
386 void LTOModule::addAsmGlobalSymbol(const char *name) {
387     // only add new define if not already defined
388     if ( _defines.count(name) == 0 ) 
389         return;
390         
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;
400 }
401
402 void LTOModule::addPotentialUndefinedSymbol(GlobalValue* decl, Mangler &mangler)
403 {   
404     // ignore all llvm.* symbols
405     if (decl->getName().startswith("llvm."))
406         return;
407
408     // ignore all aliases
409     if (isa<GlobalAlias>(decl))
410         return;
411
412     std::string name = mangler.getMangledName(decl);
413
414     // we already have the symbol
415     if (_undefines.find(name) != _undefines.end())
416       return;
417
418     NameAndAttributes info;
419     // string is owned by _undefines
420     info.name = ::strdup(name.c_str());
421     if (decl->hasExternalWeakLinkage())
422       info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
423     else
424       info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
425     _undefines[name] = info;
426 }
427
428
429
430 // Find external symbols referenced by VALUE. This is a recursive function.
431 void LTOModule::findExternalRefs(Value* value, Mangler &mangler) {
432
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(). 
440         return;
441     }
442     
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);
449     }
450 }
451
452 void LTOModule::lazyParseSymbols()
453 {
454     if ( !_symbolsParsed ) {
455         _symbolsParsed = true;
456         
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(' ');
467
468         // add functions
469         for (Module::iterator f = _module->begin(); f != _module->end(); ++f) {
470             if ( f->isDeclaration() ) 
471                 addPotentialUndefinedSymbol(f, mangler);
472             else 
473                 addDefinedFunctionSymbol(f, mangler);
474         }
475         
476         // add data 
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);
481             else 
482                 addDefinedDataSymbol(v, mangler);
483         }
484
485         // add asm globals
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) {
491           // eat .globl
492           pos = pos + 6;
493
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)
497             break;
498
499           // find end-of-line
500           std::string::size_type pend = inlineAsm.find_first_of('\n', pbegin);
501           if (pend == std::string::npos)
502             break;
503
504           asmSymbolName.assign(inlineAsm, pbegin, pend - pbegin);
505           addAsmGlobalSymbol(asmSymbolName.c_str());
506
507           // search next .globl
508           pos = inlineAsm.find(glbl, pend);
509         }
510
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);
519             }
520         }
521     }    
522 }
523
524
525 uint32_t LTOModule::getSymbolCount()
526 {
527     lazyParseSymbols();
528     return _symbols.size();
529 }
530
531
532 lto_symbol_attributes LTOModule::getSymbolAttributes(uint32_t index)
533 {
534     lazyParseSymbols();
535     if ( index < _symbols.size() )
536         return _symbols[index].attributes;
537     else
538         return lto_symbol_attributes(0);
539 }
540
541 const char* LTOModule::getSymbolName(uint32_t index)
542 {
543     lazyParseSymbols();
544     if ( index < _symbols.size() )
545         return _symbols[index].name;
546     else
547         return NULL;
548 }