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 "llvm/LTO/LTOModule.h" 16#include "llvm/ADT/OwningPtr.h" 17#include "llvm/ADT/Triple.h" 18#include "llvm/Bitcode/ReaderWriter.h" 19#include "llvm/IR/Constants.h" 20#include "llvm/IR/LLVMContext.h" 21#include "llvm/IR/Module.h" 22#include "llvm/MC/MCExpr.h" 23#include "llvm/MC/MCInst.h" 24#include "llvm/MC/MCInstrInfo.h" 25#include "llvm/MC/MCParser/MCAsmParser.h" 26#include "llvm/MC/MCStreamer.h" 27#include "llvm/MC/MCSubtargetInfo.h" 28#include "llvm/MC/MCSymbol.h" 29#include "llvm/MC/MCTargetAsmParser.h" 30#include "llvm/MC/SubtargetFeature.h" 31#include "llvm/Support/CommandLine.h" 32#include "llvm/Support/Host.h" 33#include "llvm/Support/FileSystem.h" 34#include "llvm/Support/MemoryBuffer.h" 35#include "llvm/Support/Path.h" 36#include "llvm/Support/SourceMgr.h" 37#include "llvm/Support/TargetRegistry.h" 38#include "llvm/Support/TargetSelect.h" 39#include "llvm/Support/system_error.h" 40#include "llvm/Target/TargetRegisterInfo.h" 41#include "llvm/Transforms/Utils/GlobalStatus.h" 42using namespace llvm; 43 44LTOModule::LTOModule(llvm::Module *m, llvm::TargetMachine *t) 45 : _module(m), _target(t), 46 _context(_target->getMCAsmInfo(), _target->getRegisterInfo(), NULL), 47 _mangler(t) {} 48 49/// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM 50/// bitcode. 51bool LTOModule::isBitcodeFile(const void *mem, size_t length) { 52 return sys::fs::identify_magic(StringRef((const char *)mem, length)) == 53 sys::fs::file_magic::bitcode; 54} 55 56bool LTOModule::isBitcodeFile(const char *path) { 57 sys::fs::file_magic type; 58 if (sys::fs::identify_magic(path, type)) 59 return false; 60 return type == sys::fs::file_magic::bitcode; 61} 62 63/// isBitcodeFileForTarget - Returns 'true' if the file (or memory contents) is 64/// LLVM bitcode for the specified triple. 65bool LTOModule::isBitcodeFileForTarget(const void *mem, size_t length, 66 const char *triplePrefix) { 67 MemoryBuffer *buffer = makeBuffer(mem, length); 68 if (!buffer) 69 return false; 70 return isTargetMatch(buffer, triplePrefix); 71} 72 73bool LTOModule::isBitcodeFileForTarget(const char *path, 74 const char *triplePrefix) { 75 OwningPtr<MemoryBuffer> buffer; 76 if (MemoryBuffer::getFile(path, buffer)) 77 return false; 78 return isTargetMatch(buffer.take(), triplePrefix); 79} 80 81/// isTargetMatch - Returns 'true' if the memory buffer is for the specified 82/// target triple. 83bool LTOModule::isTargetMatch(MemoryBuffer *buffer, const char *triplePrefix) { 84 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext()); 85 delete buffer; 86 return strncmp(Triple.c_str(), triplePrefix, strlen(triplePrefix)) == 0; 87} 88 89/// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of 90/// the buffer. 91LTOModule *LTOModule::makeLTOModule(const char *path, TargetOptions options, 92 std::string &errMsg) { 93 OwningPtr<MemoryBuffer> buffer; 94 if (error_code ec = MemoryBuffer::getFile(path, buffer)) { 95 errMsg = ec.message(); 96 return NULL; 97 } 98 return makeLTOModule(buffer.take(), options, errMsg); 99} 100 101LTOModule *LTOModule::makeLTOModule(int fd, const char *path, 102 size_t size, TargetOptions options, 103 std::string &errMsg) { 104 return makeLTOModule(fd, path, size, 0, options, errMsg); 105} 106 107LTOModule *LTOModule::makeLTOModule(int fd, const char *path, 108 size_t map_size, 109 off_t offset, 110 TargetOptions options, 111 std::string &errMsg) { 112 OwningPtr<MemoryBuffer> buffer; 113 if (error_code ec = 114 MemoryBuffer::getOpenFileSlice(fd, path, buffer, map_size, offset)) { 115 errMsg = ec.message(); 116 return NULL; 117 } 118 return makeLTOModule(buffer.take(), options, errMsg); 119} 120 121LTOModule *LTOModule::makeLTOModule(const void *mem, size_t length, 122 TargetOptions options, 123 std::string &errMsg) { 124 OwningPtr<MemoryBuffer> buffer(makeBuffer(mem, length)); 125 if (!buffer) 126 return NULL; 127 return makeLTOModule(buffer.take(), options, errMsg); 128} 129 130LTOModule *LTOModule::makeLTOModule(MemoryBuffer *buffer, 131 TargetOptions options, 132 std::string &errMsg) { 133 // parse bitcode buffer 134 OwningPtr<Module> m(getLazyBitcodeModule(buffer, getGlobalContext(), 135 &errMsg)); 136 if (!m) { 137 delete buffer; 138 return NULL; 139 } 140 141 std::string TripleStr = m->getTargetTriple(); 142 if (TripleStr.empty()) 143 TripleStr = sys::getDefaultTargetTriple(); 144 llvm::Triple Triple(TripleStr); 145 146 // find machine architecture for this module 147 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg); 148 if (!march) 149 return NULL; 150 151 // construct LTOModule, hand over ownership of module and target 152 SubtargetFeatures Features; 153 Features.getDefaultSubtargetFeatures(Triple); 154 std::string FeatureStr = Features.getString(); 155 // Set a default CPU for Darwin triples. 156 std::string CPU; 157 if (Triple.isOSDarwin()) { 158 if (Triple.getArch() == llvm::Triple::x86_64) 159 CPU = "core2"; 160 else if (Triple.getArch() == llvm::Triple::x86) 161 CPU = "yonah"; 162 } 163 164 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr, 165 options); 166 m->MaterializeAllPermanently(); 167 168 LTOModule *Ret = new LTOModule(m.take(), target); 169 if (Ret->parseSymbols(errMsg)) { 170 delete Ret; 171 return NULL; 172 } 173 174 return Ret; 175} 176 177/// makeBuffer - Create a MemoryBuffer from a memory range. 178MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length) { 179 const char *startPtr = (const char*)mem; 180 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), "", false); 181} 182 183/// objcClassNameFromExpression - Get string that the data pointer points to. 184bool 185LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) { 186 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) { 187 Constant *op = ce->getOperand(0); 188 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) { 189 Constant *cn = gvn->getInitializer(); 190 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) { 191 if (ca->isCString()) { 192 name = ".objc_class_name_" + ca->getAsCString().str(); 193 return true; 194 } 195 } 196 } 197 } 198 return false; 199} 200 201/// addObjCClass - Parse i386/ppc ObjC class data structure. 202void LTOModule::addObjCClass(const GlobalVariable *clgv) { 203 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer()); 204 if (!c) return; 205 206 // second slot in __OBJC,__class is pointer to superclass name 207 std::string superclassName; 208 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) { 209 NameAndAttributes info; 210 StringMap<NameAndAttributes>::value_type &entry = 211 _undefines.GetOrCreateValue(superclassName); 212 if (!entry.getValue().name) { 213 const char *symbolName = entry.getKey().data(); 214 info.name = symbolName; 215 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 216 info.isFunction = false; 217 info.symbol = clgv; 218 entry.setValue(info); 219 } 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 StringSet::value_type &entry = _defines.GetOrCreateValue(className); 226 entry.setValue(1); 227 228 NameAndAttributes info; 229 info.name = entry.getKey().data(); 230 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA | 231 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT; 232 info.isFunction = false; 233 info.symbol = clgv; 234 _symbols.push_back(info); 235 } 236} 237 238/// addObjCCategory - Parse i386/ppc ObjC category data structure. 239void LTOModule::addObjCCategory(const GlobalVariable *clgv) { 240 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer()); 241 if (!c) return; 242 243 // second slot in __OBJC,__category is pointer to target class name 244 std::string targetclassName; 245 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName)) 246 return; 247 248 NameAndAttributes info; 249 StringMap<NameAndAttributes>::value_type &entry = 250 _undefines.GetOrCreateValue(targetclassName); 251 252 if (entry.getValue().name) 253 return; 254 255 const char *symbolName = entry.getKey().data(); 256 info.name = symbolName; 257 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 258 info.isFunction = false; 259 info.symbol = clgv; 260 entry.setValue(info); 261} 262 263/// addObjCClassRef - Parse i386/ppc ObjC class list data structure. 264void LTOModule::addObjCClassRef(const GlobalVariable *clgv) { 265 std::string targetclassName; 266 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) 267 return; 268 269 NameAndAttributes info; 270 StringMap<NameAndAttributes>::value_type &entry = 271 _undefines.GetOrCreateValue(targetclassName); 272 if (entry.getValue().name) 273 return; 274 275 const char *symbolName = entry.getKey().data(); 276 info.name = symbolName; 277 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 278 info.isFunction = false; 279 info.symbol = clgv; 280 entry.setValue(info); 281} 282 283/// addDefinedDataSymbol - Add a data symbol as defined to the list. 284void LTOModule::addDefinedDataSymbol(const GlobalValue *v) { 285 // Add to list of defined symbols. 286 addDefinedSymbol(v, false); 287 288 if (!v->hasSection() /* || !isTargetDarwin */) 289 return; 290 291 // Special case i386/ppc ObjC data structures in magic sections: 292 // The issue is that the old ObjC object format did some strange 293 // contortions to avoid real linker symbols. For instance, the 294 // ObjC class data structure is allocated statically in the executable 295 // that defines that class. That data structures contains a pointer to 296 // its superclass. But instead of just initializing that part of the 297 // struct to the address of its superclass, and letting the static and 298 // dynamic linkers do the rest, the runtime works by having that field 299 // instead point to a C-string that is the name of the superclass. 300 // At runtime the objc initialization updates that pointer and sets 301 // it to point to the actual super class. As far as the linker 302 // knows it is just a pointer to a string. But then someone wanted the 303 // linker to issue errors at build time if the superclass was not found. 304 // So they figured out a way in mach-o object format to use an absolute 305 // symbols (.objc_class_name_Foo = 0) and a floating reference 306 // (.reference .objc_class_name_Bar) to cause the linker into erroring when 307 // a class was missing. 308 // The following synthesizes the implicit .objc_* symbols for the linker 309 // from the ObjC data structures generated by the front end. 310 311 // special case if this data blob is an ObjC class definition 312 if (v->getSection().compare(0, 15, "__OBJC,__class,") == 0) { 313 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) { 314 addObjCClass(gv); 315 } 316 } 317 318 // special case if this data blob is an ObjC category definition 319 else if (v->getSection().compare(0, 18, "__OBJC,__category,") == 0) { 320 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) { 321 addObjCCategory(gv); 322 } 323 } 324 325 // special case if this data blob is the list of referenced classes 326 else if (v->getSection().compare(0, 18, "__OBJC,__cls_refs,") == 0) { 327 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) { 328 addObjCClassRef(gv); 329 } 330 } 331} 332 333/// addDefinedFunctionSymbol - Add a function symbol as defined to the list. 334void LTOModule::addDefinedFunctionSymbol(const Function *f) { 335 // add to list of defined symbols 336 addDefinedSymbol(f, true); 337} 338 339static bool canBeHidden(const GlobalValue *GV) { 340 GlobalValue::LinkageTypes L = GV->getLinkage(); 341 342 if (L != GlobalValue::LinkOnceODRLinkage) 343 return false; 344 345 if (GV->hasUnnamedAddr()) 346 return true; 347 348 GlobalStatus GS; 349 if (GlobalStatus::analyzeGlobal(GV, GS)) 350 return false; 351 352 return !GS.IsCompared; 353} 354 355/// addDefinedSymbol - Add a defined symbol to the list. 356void LTOModule::addDefinedSymbol(const GlobalValue *def, bool isFunction) { 357 // ignore all llvm.* symbols 358 if (def->getName().startswith("llvm.")) 359 return; 360 361 // string is owned by _defines 362 SmallString<64> Buffer; 363 _mangler.getNameWithPrefix(Buffer, def, false); 364 365 // set alignment part log2() can have rounding errors 366 uint32_t align = def->getAlignment(); 367 uint32_t attr = align ? countTrailingZeros(def->getAlignment()) : 0; 368 369 // set permissions part 370 if (isFunction) { 371 attr |= LTO_SYMBOL_PERMISSIONS_CODE; 372 } else { 373 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def); 374 if (gv && gv->isConstant()) 375 attr |= LTO_SYMBOL_PERMISSIONS_RODATA; 376 else 377 attr |= LTO_SYMBOL_PERMISSIONS_DATA; 378 } 379 380 // set definition part 381 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage() || 382 def->hasLinkerPrivateWeakLinkage()) 383 attr |= LTO_SYMBOL_DEFINITION_WEAK; 384 else if (def->hasCommonLinkage()) 385 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE; 386 else 387 attr |= LTO_SYMBOL_DEFINITION_REGULAR; 388 389 // set scope part 390 if (def->hasHiddenVisibility()) 391 attr |= LTO_SYMBOL_SCOPE_HIDDEN; 392 else if (def->hasProtectedVisibility()) 393 attr |= LTO_SYMBOL_SCOPE_PROTECTED; 394 else if (canBeHidden(def)) 395 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN; 396 else if (def->hasExternalLinkage() || def->hasWeakLinkage() || 397 def->hasLinkOnceLinkage() || def->hasCommonLinkage() || 398 def->hasLinkerPrivateWeakLinkage()) 399 attr |= LTO_SYMBOL_SCOPE_DEFAULT; 400 else 401 attr |= LTO_SYMBOL_SCOPE_INTERNAL; 402 403 StringSet::value_type &entry = _defines.GetOrCreateValue(Buffer); 404 entry.setValue(1); 405 406 // fill information structure 407 NameAndAttributes info; 408 StringRef Name = entry.getKey(); 409 info.name = Name.data(); 410 assert(info.name[Name.size()] == '\0'); 411 info.attributes = attr; 412 info.isFunction = isFunction; 413 info.symbol = def; 414 415 // add to table of symbols 416 _symbols.push_back(info); 417} 418 419/// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the 420/// defined list. 421void LTOModule::addAsmGlobalSymbol(const char *name, 422 lto_symbol_attributes scope) { 423 StringSet::value_type &entry = _defines.GetOrCreateValue(name); 424 425 // only add new define if not already defined 426 if (entry.getValue()) 427 return; 428 429 entry.setValue(1); 430 431 NameAndAttributes &info = _undefines[entry.getKey().data()]; 432 433 if (info.symbol == 0) { 434 // FIXME: This is trying to take care of module ASM like this: 435 // 436 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0" 437 // 438 // but is gross and its mother dresses it funny. Have the ASM parser give us 439 // more details for this type of situation so that we're not guessing so 440 // much. 441 442 // fill information structure 443 info.name = entry.getKey().data(); 444 info.attributes = 445 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope; 446 info.isFunction = false; 447 info.symbol = 0; 448 449 // add to table of symbols 450 _symbols.push_back(info); 451 return; 452 } 453 454 if (info.isFunction) 455 addDefinedFunctionSymbol(cast<Function>(info.symbol)); 456 else 457 addDefinedDataSymbol(info.symbol); 458 459 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK; 460 _symbols.back().attributes |= scope; 461} 462 463/// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the 464/// undefined list. 465void LTOModule::addAsmGlobalSymbolUndef(const char *name) { 466 StringMap<NameAndAttributes>::value_type &entry = 467 _undefines.GetOrCreateValue(name); 468 469 _asm_undefines.push_back(entry.getKey().data()); 470 471 // we already have the symbol 472 if (entry.getValue().name) 473 return; 474 475 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;; 476 attr |= LTO_SYMBOL_SCOPE_DEFAULT; 477 NameAndAttributes info; 478 info.name = entry.getKey().data(); 479 info.attributes = attr; 480 info.isFunction = false; 481 info.symbol = 0; 482 483 entry.setValue(info); 484} 485 486/// addPotentialUndefinedSymbol - Add a symbol which isn't defined just yet to a 487/// list to be resolved later. 488void 489LTOModule::addPotentialUndefinedSymbol(const GlobalValue *decl, bool isFunc) { 490 // ignore all llvm.* symbols 491 if (decl->getName().startswith("llvm.")) 492 return; 493 494 // ignore all aliases 495 if (isa<GlobalAlias>(decl)) 496 return; 497 498 SmallString<64> name; 499 _mangler.getNameWithPrefix(name, decl, false); 500 501 StringMap<NameAndAttributes>::value_type &entry = 502 _undefines.GetOrCreateValue(name); 503 504 // we already have the symbol 505 if (entry.getValue().name) 506 return; 507 508 NameAndAttributes info; 509 510 info.name = entry.getKey().data(); 511 512 if (decl->hasExternalWeakLinkage()) 513 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF; 514 else 515 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 516 517 info.isFunction = isFunc; 518 info.symbol = decl; 519 520 entry.setValue(info); 521} 522 523namespace { 524 class RecordStreamer : public MCStreamer { 525 public: 526 enum State { NeverSeen, Global, Defined, DefinedGlobal, Used }; 527 528 private: 529 StringMap<State> Symbols; 530 531 void markDefined(const MCSymbol &Symbol) { 532 State &S = Symbols[Symbol.getName()]; 533 switch (S) { 534 case DefinedGlobal: 535 case Global: 536 S = DefinedGlobal; 537 break; 538 case NeverSeen: 539 case Defined: 540 case Used: 541 S = Defined; 542 break; 543 } 544 } 545 void markGlobal(const MCSymbol &Symbol) { 546 State &S = Symbols[Symbol.getName()]; 547 switch (S) { 548 case DefinedGlobal: 549 case Defined: 550 S = DefinedGlobal; 551 break; 552 553 case NeverSeen: 554 case Global: 555 case Used: 556 S = Global; 557 break; 558 } 559 } 560 void markUsed(const MCSymbol &Symbol) { 561 State &S = Symbols[Symbol.getName()]; 562 switch (S) { 563 case DefinedGlobal: 564 case Defined: 565 case Global: 566 break; 567 568 case NeverSeen: 569 case Used: 570 S = Used; 571 break; 572 } 573 } 574 575 // FIXME: mostly copied for the obj streamer. 576 void AddValueSymbols(const MCExpr *Value) { 577 switch (Value->getKind()) { 578 case MCExpr::Target: 579 // FIXME: What should we do in here? 580 break; 581 582 case MCExpr::Constant: 583 break; 584 585 case MCExpr::Binary: { 586 const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value); 587 AddValueSymbols(BE->getLHS()); 588 AddValueSymbols(BE->getRHS()); 589 break; 590 } 591 592 case MCExpr::SymbolRef: 593 markUsed(cast<MCSymbolRefExpr>(Value)->getSymbol()); 594 break; 595 596 case MCExpr::Unary: 597 AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr()); 598 break; 599 } 600 } 601 602 public: 603 typedef StringMap<State>::const_iterator const_iterator; 604 605 const_iterator begin() { 606 return Symbols.begin(); 607 } 608 609 const_iterator end() { 610 return Symbols.end(); 611 } 612 613 RecordStreamer(MCContext &Context) : MCStreamer(Context, 0) {} 614 615 virtual void EmitInstruction(const MCInst &Inst) { 616 // Scan for values. 617 for (unsigned i = Inst.getNumOperands(); i--; ) 618 if (Inst.getOperand(i).isExpr()) 619 AddValueSymbols(Inst.getOperand(i).getExpr()); 620 } 621 virtual void EmitLabel(MCSymbol *Symbol) { 622 Symbol->setSection(*getCurrentSection().first); 623 markDefined(*Symbol); 624 } 625 virtual void EmitDebugLabel(MCSymbol *Symbol) { 626 EmitLabel(Symbol); 627 } 628 virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) { 629 // FIXME: should we handle aliases? 630 markDefined(*Symbol); 631 } 632 virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) { 633 if (Attribute == MCSA_Global) 634 markGlobal(*Symbol); 635 return true; 636 } 637 virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol, 638 uint64_t Size , unsigned ByteAlignment) { 639 markDefined(*Symbol); 640 } 641 virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size, 642 unsigned ByteAlignment) { 643 markDefined(*Symbol); 644 } 645 646 virtual void EmitBundleAlignMode(unsigned AlignPow2) {} 647 virtual void EmitBundleLock(bool AlignToEnd) {} 648 virtual void EmitBundleUnlock() {} 649 650 // Noop calls. 651 virtual void ChangeSection(const MCSection *Section, 652 const MCExpr *Subsection) {} 653 virtual void InitToTextSection() {} 654 virtual void InitSections() {} 655 virtual void EmitAssemblerFlag(MCAssemblerFlag Flag) {} 656 virtual void EmitThumbFunc(MCSymbol *Func) {} 657 virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {} 658 virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {} 659 virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {} 660 virtual void EmitCOFFSymbolStorageClass(int StorageClass) {} 661 virtual void EmitCOFFSymbolType(int Type) {} 662 virtual void EndCOFFSymbolDef() {} 663 virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {} 664 virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size, 665 unsigned ByteAlignment) {} 666 virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol, 667 uint64_t Size, unsigned ByteAlignment) {} 668 virtual void EmitBytes(StringRef Data) {} 669 virtual void EmitValueImpl(const MCExpr *Value, unsigned Size) {} 670 virtual void EmitULEB128Value(const MCExpr *Value) {} 671 virtual void EmitSLEB128Value(const MCExpr *Value) {} 672 virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value, 673 unsigned ValueSize, 674 unsigned MaxBytesToEmit) {} 675 virtual void EmitCodeAlignment(unsigned ByteAlignment, 676 unsigned MaxBytesToEmit) {} 677 virtual bool EmitValueToOffset(const MCExpr *Offset, 678 unsigned char Value ) { return false; } 679 virtual void EmitFileDirective(StringRef Filename) {} 680 virtual void EmitDwarfAdvanceLineAddr(int64_t LineDelta, 681 const MCSymbol *LastLabel, 682 const MCSymbol *Label, 683 unsigned PointerSize) {} 684 virtual void FinishImpl() {} 685 virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) { 686 RecordProcEnd(Frame); 687 } 688 }; 689} // end anonymous namespace 690 691/// addAsmGlobalSymbols - Add global symbols from module-level ASM to the 692/// defined or undefined lists. 693bool LTOModule::addAsmGlobalSymbols(std::string &errMsg) { 694 const std::string &inlineAsm = _module->getModuleInlineAsm(); 695 if (inlineAsm.empty()) 696 return false; 697 698 OwningPtr<RecordStreamer> Streamer(new RecordStreamer(_context)); 699 MemoryBuffer *Buffer = MemoryBuffer::getMemBuffer(inlineAsm); 700 SourceMgr SrcMgr; 701 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc()); 702 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, 703 _context, *Streamer, 704 *_target->getMCAsmInfo())); 705 const Target &T = _target->getTarget(); 706 OwningPtr<MCInstrInfo> MCII(T.createMCInstrInfo()); 707 OwningPtr<MCSubtargetInfo> 708 STI(T.createMCSubtargetInfo(_target->getTargetTriple(), 709 _target->getTargetCPU(), 710 _target->getTargetFeatureString())); 711 OwningPtr<MCTargetAsmParser> TAP(T.createMCAsmParser(*STI, *Parser.get(), *MCII)); 712 if (!TAP) { 713 errMsg = "target " + std::string(T.getName()) + 714 " does not define AsmParser."; 715 return true; 716 } 717 718 Parser->setTargetParser(*TAP); 719 if (Parser->Run(false)) 720 return true; 721 722 for (RecordStreamer::const_iterator i = Streamer->begin(), 723 e = Streamer->end(); i != e; ++i) { 724 StringRef Key = i->first(); 725 RecordStreamer::State Value = i->second; 726 if (Value == RecordStreamer::DefinedGlobal) 727 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_DEFAULT); 728 else if (Value == RecordStreamer::Defined) 729 addAsmGlobalSymbol(Key.data(), LTO_SYMBOL_SCOPE_INTERNAL); 730 else if (Value == RecordStreamer::Global || 731 Value == RecordStreamer::Used) 732 addAsmGlobalSymbolUndef(Key.data()); 733 } 734 735 return false; 736} 737 738/// isDeclaration - Return 'true' if the global value is a declaration. 739static bool isDeclaration(const GlobalValue &V) { 740 if (V.hasAvailableExternallyLinkage()) 741 return true; 742 743 if (V.isMaterializable()) 744 return false; 745 746 return V.isDeclaration(); 747} 748 749/// parseSymbols - Parse the symbols from the module and model-level ASM and add 750/// them to either the defined or undefined lists. 751bool LTOModule::parseSymbols(std::string &errMsg) { 752 // add functions 753 for (Module::iterator f = _module->begin(), e = _module->end(); f != e; ++f) { 754 if (isDeclaration(*f)) 755 addPotentialUndefinedSymbol(f, true); 756 else 757 addDefinedFunctionSymbol(f); 758 } 759 760 // add data 761 for (Module::global_iterator v = _module->global_begin(), 762 e = _module->global_end(); v != e; ++v) { 763 if (isDeclaration(*v)) 764 addPotentialUndefinedSymbol(v, false); 765 else 766 addDefinedDataSymbol(v); 767 } 768 769 // add asm globals 770 if (addAsmGlobalSymbols(errMsg)) 771 return true; 772 773 // add aliases 774 for (Module::alias_iterator a = _module->alias_begin(), 775 e = _module->alias_end(); a != e; ++a) { 776 if (isDeclaration(*a->getAliasedGlobal())) 777 // Is an alias to a declaration. 778 addPotentialUndefinedSymbol(a, false); 779 else 780 addDefinedDataSymbol(a); 781 } 782 783 // make symbols for all undefines 784 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(), 785 e = _undefines.end(); u != e; ++u) { 786 // If this symbol also has a definition, then don't make an undefine because 787 // it is a tentative definition. 788 if (_defines.count(u->getKey())) continue; 789 NameAndAttributes info = u->getValue(); 790 _symbols.push_back(info); 791 } 792 793 return false; 794} 795