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/Triple.h" 17 #include "llvm/Bitcode/ReaderWriter.h" 18 #include "llvm/CodeGen/Analysis.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/MCSubtargetInfo.h" 29 #include "llvm/MC/MCSymbol.h" 30 #include "llvm/MC/MCTargetAsmParser.h" 31 #include "llvm/MC/SubtargetFeature.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/FileSystem.h" 34 #include "llvm/Support/Host.h" 35 #include "llvm/Support/MemoryBuffer.h" 36 #include "llvm/Support/Path.h" 37 #include "llvm/Support/SourceMgr.h" 38 #include "llvm/Support/TargetRegistry.h" 39 #include "llvm/Support/TargetSelect.h" 40 #include "llvm/Target/TargetLowering.h" 41 #include "llvm/Target/TargetLoweringObjectFile.h" 42 #include "llvm/Target/TargetRegisterInfo.h" 43 #include "llvm/Target/TargetSubtargetInfo.h" 44 #include "llvm/Transforms/Utils/GlobalStatus.h" 45 #include <system_error> 46 using namespace llvm; 47 48 LTOModule::LTOModule(std::unique_ptr<object::IRObjectFile> Obj, 49 llvm::TargetMachine *TM) 50 : IRFile(std::move(Obj)), _target(TM) {} 51 52 /// isBitcodeFile - Returns 'true' if the file (or memory contents) is LLVM 53 /// bitcode. 54 bool LTOModule::isBitcodeFile(const void *mem, size_t length) { 55 return sys::fs::identify_magic(StringRef((const char *)mem, length)) == 56 sys::fs::file_magic::bitcode; 57 } 58 59 bool LTOModule::isBitcodeFile(const char *path) { 60 sys::fs::file_magic type; 61 if (sys::fs::identify_magic(path, type)) 62 return false; 63 return type == sys::fs::file_magic::bitcode; 64 } 65 66 bool LTOModule::isBitcodeForTarget(MemoryBuffer *buffer, 67 StringRef triplePrefix) { 68 std::string Triple = getBitcodeTargetTriple(buffer, getGlobalContext()); 69 return StringRef(Triple).startswith(triplePrefix); 70 } 71 72 LTOModule *LTOModule::createFromFile(const char *path, TargetOptions options, 73 std::string &errMsg) { 74 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = 75 MemoryBuffer::getFile(path); 76 if (std::error_code EC = BufferOrErr.getError()) { 77 errMsg = EC.message(); 78 return nullptr; 79 } 80 return makeLTOModule(std::move(BufferOrErr.get()), options, errMsg); 81 } 82 83 LTOModule *LTOModule::createFromOpenFile(int fd, const char *path, size_t size, 84 TargetOptions options, 85 std::string &errMsg) { 86 return createFromOpenFileSlice(fd, path, size, 0, options, errMsg); 87 } 88 89 LTOModule *LTOModule::createFromOpenFileSlice(int fd, const char *path, 90 size_t map_size, off_t offset, 91 TargetOptions options, 92 std::string &errMsg) { 93 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = 94 MemoryBuffer::getOpenFileSlice(fd, path, map_size, offset); 95 if (std::error_code EC = BufferOrErr.getError()) { 96 errMsg = EC.message(); 97 return nullptr; 98 } 99 return makeLTOModule(std::move(BufferOrErr.get()), options, errMsg); 100 } 101 102 LTOModule *LTOModule::createFromBuffer(const void *mem, size_t length, 103 TargetOptions options, 104 std::string &errMsg, StringRef path) { 105 std::unique_ptr<MemoryBuffer> buffer(makeBuffer(mem, length, path)); 106 if (!buffer) 107 return nullptr; 108 return makeLTOModule(std::move(buffer), options, errMsg); 109 } 110 111 LTOModule *LTOModule::makeLTOModule(std::unique_ptr<MemoryBuffer> Buffer, 112 TargetOptions options, 113 std::string &errMsg) { 114 ErrorOr<Module *> MOrErr = 115 getLazyBitcodeModule(Buffer.get(), getGlobalContext()); 116 if (std::error_code EC = MOrErr.getError()) { 117 errMsg = EC.message(); 118 return nullptr; 119 } 120 std::unique_ptr<Module> M(MOrErr.get()); 121 122 std::string TripleStr = M->getTargetTriple(); 123 if (TripleStr.empty()) 124 TripleStr = sys::getDefaultTargetTriple(); 125 llvm::Triple Triple(TripleStr); 126 127 // find machine architecture for this module 128 const Target *march = TargetRegistry::lookupTarget(TripleStr, errMsg); 129 if (!march) 130 return nullptr; 131 132 // construct LTOModule, hand over ownership of module and target 133 SubtargetFeatures Features; 134 Features.getDefaultSubtargetFeatures(Triple); 135 std::string FeatureStr = Features.getString(); 136 // Set a default CPU for Darwin triples. 137 std::string CPU; 138 if (Triple.isOSDarwin()) { 139 if (Triple.getArch() == llvm::Triple::x86_64) 140 CPU = "core2"; 141 else if (Triple.getArch() == llvm::Triple::x86) 142 CPU = "yonah"; 143 else if (Triple.getArch() == llvm::Triple::aarch64) 144 CPU = "cyclone"; 145 } 146 147 TargetMachine *target = march->createTargetMachine(TripleStr, CPU, FeatureStr, 148 options); 149 M->materializeAllPermanently(true); 150 M->setDataLayout(target->getSubtargetImpl()->getDataLayout()); 151 152 std::unique_ptr<object::IRObjectFile> IRObj( 153 new object::IRObjectFile(std::move(Buffer), std::move(M))); 154 155 LTOModule *Ret = new LTOModule(std::move(IRObj), target); 156 157 if (Ret->parseSymbols(errMsg)) { 158 delete Ret; 159 return nullptr; 160 } 161 162 Ret->parseMetadata(); 163 164 return Ret; 165 } 166 167 /// Create a MemoryBuffer from a memory range with an optional name. 168 MemoryBuffer *LTOModule::makeBuffer(const void *mem, size_t length, 169 StringRef name) { 170 const char *startPtr = (const char*)mem; 171 return MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false); 172 } 173 174 /// objcClassNameFromExpression - Get string that the data pointer points to. 175 bool 176 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) { 177 if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) { 178 Constant *op = ce->getOperand(0); 179 if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) { 180 Constant *cn = gvn->getInitializer(); 181 if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) { 182 if (ca->isCString()) { 183 name = ".objc_class_name_" + ca->getAsCString().str(); 184 return true; 185 } 186 } 187 } 188 } 189 return false; 190 } 191 192 /// addObjCClass - Parse i386/ppc ObjC class data structure. 193 void LTOModule::addObjCClass(const GlobalVariable *clgv) { 194 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer()); 195 if (!c) return; 196 197 // second slot in __OBJC,__class is pointer to superclass name 198 std::string superclassName; 199 if (objcClassNameFromExpression(c->getOperand(1), superclassName)) { 200 NameAndAttributes info; 201 StringMap<NameAndAttributes>::value_type &entry = 202 _undefines.GetOrCreateValue(superclassName); 203 if (!entry.getValue().name) { 204 const char *symbolName = entry.getKey().data(); 205 info.name = symbolName; 206 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 207 info.isFunction = false; 208 info.symbol = clgv; 209 entry.setValue(info); 210 } 211 } 212 213 // third slot in __OBJC,__class is pointer to class name 214 std::string className; 215 if (objcClassNameFromExpression(c->getOperand(2), className)) { 216 StringSet::value_type &entry = _defines.GetOrCreateValue(className); 217 entry.setValue(1); 218 219 NameAndAttributes info; 220 info.name = entry.getKey().data(); 221 info.attributes = LTO_SYMBOL_PERMISSIONS_DATA | 222 LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT; 223 info.isFunction = false; 224 info.symbol = clgv; 225 _symbols.push_back(info); 226 } 227 } 228 229 /// addObjCCategory - Parse i386/ppc ObjC category data structure. 230 void LTOModule::addObjCCategory(const GlobalVariable *clgv) { 231 const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer()); 232 if (!c) return; 233 234 // second slot in __OBJC,__category is pointer to target class name 235 std::string targetclassName; 236 if (!objcClassNameFromExpression(c->getOperand(1), targetclassName)) 237 return; 238 239 NameAndAttributes info; 240 StringMap<NameAndAttributes>::value_type &entry = 241 _undefines.GetOrCreateValue(targetclassName); 242 243 if (entry.getValue().name) 244 return; 245 246 const char *symbolName = entry.getKey().data(); 247 info.name = symbolName; 248 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 249 info.isFunction = false; 250 info.symbol = clgv; 251 entry.setValue(info); 252 } 253 254 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure. 255 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) { 256 std::string targetclassName; 257 if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName)) 258 return; 259 260 NameAndAttributes info; 261 StringMap<NameAndAttributes>::value_type &entry = 262 _undefines.GetOrCreateValue(targetclassName); 263 if (entry.getValue().name) 264 return; 265 266 const char *symbolName = entry.getKey().data(); 267 info.name = symbolName; 268 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 269 info.isFunction = false; 270 info.symbol = clgv; 271 entry.setValue(info); 272 } 273 274 void LTOModule::addDefinedDataSymbol(const object::BasicSymbolRef &Sym) { 275 SmallString<64> Buffer; 276 { 277 raw_svector_ostream OS(Buffer); 278 Sym.printName(OS); 279 } 280 281 const GlobalValue *V = IRFile->getSymbolGV(Sym.getRawDataRefImpl()); 282 addDefinedDataSymbol(Buffer.c_str(), V); 283 } 284 285 void LTOModule::addDefinedDataSymbol(const char *Name, const GlobalValue *v) { 286 // Add to list of defined symbols. 287 addDefinedSymbol(Name, v, false); 288 289 if (!v->hasSection() /* || !isTargetDarwin */) 290 return; 291 292 // Special case i386/ppc ObjC data structures in magic sections: 293 // The issue is that the old ObjC object format did some strange 294 // contortions to avoid real linker symbols. For instance, the 295 // ObjC class data structure is allocated statically in the executable 296 // that defines that class. That data structures contains a pointer to 297 // its superclass. But instead of just initializing that part of the 298 // struct to the address of its superclass, and letting the static and 299 // dynamic linkers do the rest, the runtime works by having that field 300 // instead point to a C-string that is the name of the superclass. 301 // At runtime the objc initialization updates that pointer and sets 302 // it to point to the actual super class. As far as the linker 303 // knows it is just a pointer to a string. But then someone wanted the 304 // linker to issue errors at build time if the superclass was not found. 305 // So they figured out a way in mach-o object format to use an absolute 306 // symbols (.objc_class_name_Foo = 0) and a floating reference 307 // (.reference .objc_class_name_Bar) to cause the linker into erroring when 308 // a class was missing. 309 // The following synthesizes the implicit .objc_* symbols for the linker 310 // from the ObjC data structures generated by the front end. 311 312 // special case if this data blob is an ObjC class definition 313 std::string Section = v->getSection(); 314 if (Section.compare(0, 15, "__OBJC,__class,") == 0) { 315 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) { 316 addObjCClass(gv); 317 } 318 } 319 320 // special case if this data blob is an ObjC category definition 321 else if (Section.compare(0, 18, "__OBJC,__category,") == 0) { 322 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) { 323 addObjCCategory(gv); 324 } 325 } 326 327 // special case if this data blob is the list of referenced classes 328 else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) { 329 if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) { 330 addObjCClassRef(gv); 331 } 332 } 333 } 334 335 void LTOModule::addDefinedFunctionSymbol(const object::BasicSymbolRef &Sym) { 336 SmallString<64> Buffer; 337 { 338 raw_svector_ostream OS(Buffer); 339 Sym.printName(OS); 340 } 341 342 const Function *F = 343 cast<Function>(IRFile->getSymbolGV(Sym.getRawDataRefImpl())); 344 addDefinedFunctionSymbol(Buffer.c_str(), F); 345 } 346 347 void LTOModule::addDefinedFunctionSymbol(const char *Name, const Function *F) { 348 // add to list of defined symbols 349 addDefinedSymbol(Name, F, true); 350 } 351 352 void LTOModule::addDefinedSymbol(const char *Name, const GlobalValue *def, 353 bool isFunction) { 354 // set alignment part log2() can have rounding errors 355 uint32_t align = def->getAlignment(); 356 uint32_t attr = align ? countTrailingZeros(align) : 0; 357 358 // set permissions part 359 if (isFunction) { 360 attr |= LTO_SYMBOL_PERMISSIONS_CODE; 361 } else { 362 const GlobalVariable *gv = dyn_cast<GlobalVariable>(def); 363 if (gv && gv->isConstant()) 364 attr |= LTO_SYMBOL_PERMISSIONS_RODATA; 365 else 366 attr |= LTO_SYMBOL_PERMISSIONS_DATA; 367 } 368 369 // set definition part 370 if (def->hasWeakLinkage() || def->hasLinkOnceLinkage()) 371 attr |= LTO_SYMBOL_DEFINITION_WEAK; 372 else if (def->hasCommonLinkage()) 373 attr |= LTO_SYMBOL_DEFINITION_TENTATIVE; 374 else 375 attr |= LTO_SYMBOL_DEFINITION_REGULAR; 376 377 // set scope part 378 if (def->hasLocalLinkage()) 379 // Ignore visibility if linkage is local. 380 attr |= LTO_SYMBOL_SCOPE_INTERNAL; 381 else if (def->hasHiddenVisibility()) 382 attr |= LTO_SYMBOL_SCOPE_HIDDEN; 383 else if (def->hasProtectedVisibility()) 384 attr |= LTO_SYMBOL_SCOPE_PROTECTED; 385 else if (canBeOmittedFromSymbolTable(def)) 386 attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN; 387 else 388 attr |= LTO_SYMBOL_SCOPE_DEFAULT; 389 390 StringSet::value_type &entry = _defines.GetOrCreateValue(Name); 391 entry.setValue(1); 392 393 // fill information structure 394 NameAndAttributes info; 395 StringRef NameRef = entry.getKey(); 396 info.name = NameRef.data(); 397 assert(info.name[NameRef.size()] == '\0'); 398 info.attributes = attr; 399 info.isFunction = isFunction; 400 info.symbol = def; 401 402 // add to table of symbols 403 _symbols.push_back(info); 404 } 405 406 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the 407 /// defined list. 408 void LTOModule::addAsmGlobalSymbol(const char *name, 409 lto_symbol_attributes scope) { 410 StringSet::value_type &entry = _defines.GetOrCreateValue(name); 411 412 // only add new define if not already defined 413 if (entry.getValue()) 414 return; 415 416 entry.setValue(1); 417 418 NameAndAttributes &info = _undefines[entry.getKey().data()]; 419 420 if (info.symbol == nullptr) { 421 // FIXME: This is trying to take care of module ASM like this: 422 // 423 // module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0" 424 // 425 // but is gross and its mother dresses it funny. Have the ASM parser give us 426 // more details for this type of situation so that we're not guessing so 427 // much. 428 429 // fill information structure 430 info.name = entry.getKey().data(); 431 info.attributes = 432 LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope; 433 info.isFunction = false; 434 info.symbol = nullptr; 435 436 // add to table of symbols 437 _symbols.push_back(info); 438 return; 439 } 440 441 if (info.isFunction) 442 addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol)); 443 else 444 addDefinedDataSymbol(info.name, info.symbol); 445 446 _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK; 447 _symbols.back().attributes |= scope; 448 } 449 450 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the 451 /// undefined list. 452 void LTOModule::addAsmGlobalSymbolUndef(const char *name) { 453 StringMap<NameAndAttributes>::value_type &entry = 454 _undefines.GetOrCreateValue(name); 455 456 _asm_undefines.push_back(entry.getKey().data()); 457 458 // we already have the symbol 459 if (entry.getValue().name) 460 return; 461 462 uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED; 463 attr |= LTO_SYMBOL_SCOPE_DEFAULT; 464 NameAndAttributes info; 465 info.name = entry.getKey().data(); 466 info.attributes = attr; 467 info.isFunction = false; 468 info.symbol = nullptr; 469 470 entry.setValue(info); 471 } 472 473 /// Add a symbol which isn't defined just yet to a list to be resolved later. 474 void LTOModule::addPotentialUndefinedSymbol(const object::BasicSymbolRef &Sym, 475 bool isFunc) { 476 SmallString<64> name; 477 { 478 raw_svector_ostream OS(name); 479 Sym.printName(OS); 480 } 481 482 StringMap<NameAndAttributes>::value_type &entry = 483 _undefines.GetOrCreateValue(name); 484 485 // we already have the symbol 486 if (entry.getValue().name) 487 return; 488 489 NameAndAttributes info; 490 491 info.name = entry.getKey().data(); 492 493 const GlobalValue *decl = IRFile->getSymbolGV(Sym.getRawDataRefImpl()); 494 495 if (decl->hasExternalWeakLinkage()) 496 info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF; 497 else 498 info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED; 499 500 info.isFunction = isFunc; 501 info.symbol = decl; 502 503 entry.setValue(info); 504 } 505 506 /// parseSymbols - Parse the symbols from the module and model-level ASM and add 507 /// them to either the defined or undefined lists. 508 bool LTOModule::parseSymbols(std::string &errMsg) { 509 for (auto &Sym : IRFile->symbols()) { 510 const GlobalValue *GV = IRFile->getSymbolGV(Sym.getRawDataRefImpl()); 511 uint32_t Flags = Sym.getFlags(); 512 if (Flags & object::BasicSymbolRef::SF_FormatSpecific) 513 continue; 514 515 bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined; 516 517 if (!GV) { 518 SmallString<64> Buffer; 519 { 520 raw_svector_ostream OS(Buffer); 521 Sym.printName(OS); 522 } 523 const char *Name = Buffer.c_str(); 524 525 if (IsUndefined) 526 addAsmGlobalSymbolUndef(Name); 527 else if (Flags & object::BasicSymbolRef::SF_Global) 528 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_DEFAULT); 529 else 530 addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_INTERNAL); 531 continue; 532 } 533 534 auto *F = dyn_cast<Function>(GV); 535 if (IsUndefined) { 536 addPotentialUndefinedSymbol(Sym, F != nullptr); 537 continue; 538 } 539 540 if (F) { 541 addDefinedFunctionSymbol(Sym); 542 continue; 543 } 544 545 if (isa<GlobalVariable>(GV)) { 546 addDefinedDataSymbol(Sym); 547 continue; 548 } 549 550 assert(isa<GlobalAlias>(GV)); 551 addDefinedDataSymbol(Sym); 552 } 553 554 // make symbols for all undefines 555 for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(), 556 e = _undefines.end(); u != e; ++u) { 557 // If this symbol also has a definition, then don't make an undefine because 558 // it is a tentative definition. 559 if (_defines.count(u->getKey())) continue; 560 NameAndAttributes info = u->getValue(); 561 _symbols.push_back(info); 562 } 563 564 return false; 565 } 566 567 /// parseMetadata - Parse metadata from the module 568 void LTOModule::parseMetadata() { 569 // Linker Options 570 if (Value *Val = getModule().getModuleFlag("Linker Options")) { 571 MDNode *LinkerOptions = cast<MDNode>(Val); 572 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) { 573 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i)); 574 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) { 575 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii)); 576 StringRef Op = _linkeropt_strings. 577 GetOrCreateValue(MDOption->getString()).getKey(); 578 StringRef DepLibName = _target->getSubtargetImpl() 579 ->getTargetLowering() 580 ->getObjFileLowering() 581 .getDepLibFromLinkerOpt(Op); 582 if (!DepLibName.empty()) 583 _deplibs.push_back(DepLibName.data()); 584 else if (!Op.empty()) 585 _linkeropts.push_back(Op.data()); 586 } 587 } 588 } 589 590 // Add other interesting metadata here. 591 } 592