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