[MCJIT] Respect target endianness in RuntimeDyldMachO and RuntimeDyldChecker.
[oota-llvm.git] / lib / 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 "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 std::unique_ptr<MemoryBuffer>
169 LTOModule::makeBuffer(const void *mem, size_t length, StringRef name) {
170   const char *startPtr = (const char*)mem;
171   return std::unique_ptr<MemoryBuffer>(
172       MemoryBuffer::getMemBuffer(StringRef(startPtr, length), name, false));
173 }
174
175 /// objcClassNameFromExpression - Get string that the data pointer points to.
176 bool
177 LTOModule::objcClassNameFromExpression(const Constant *c, std::string &name) {
178   if (const ConstantExpr *ce = dyn_cast<ConstantExpr>(c)) {
179     Constant *op = ce->getOperand(0);
180     if (GlobalVariable *gvn = dyn_cast<GlobalVariable>(op)) {
181       Constant *cn = gvn->getInitializer();
182       if (ConstantDataArray *ca = dyn_cast<ConstantDataArray>(cn)) {
183         if (ca->isCString()) {
184           name = ".objc_class_name_" + ca->getAsCString().str();
185           return true;
186         }
187       }
188     }
189   }
190   return false;
191 }
192
193 /// addObjCClass - Parse i386/ppc ObjC class data structure.
194 void LTOModule::addObjCClass(const GlobalVariable *clgv) {
195   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
196   if (!c) return;
197
198   // second slot in __OBJC,__class is pointer to superclass name
199   std::string superclassName;
200   if (objcClassNameFromExpression(c->getOperand(1), superclassName)) {
201     NameAndAttributes info;
202     StringMap<NameAndAttributes>::value_type &entry =
203       _undefines.GetOrCreateValue(superclassName);
204     if (!entry.getValue().name) {
205       const char *symbolName = entry.getKey().data();
206       info.name = symbolName;
207       info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
208       info.isFunction = false;
209       info.symbol = clgv;
210       entry.setValue(info);
211     }
212   }
213
214   // third slot in __OBJC,__class is pointer to class name
215   std::string className;
216   if (objcClassNameFromExpression(c->getOperand(2), className)) {
217     StringSet::value_type &entry = _defines.GetOrCreateValue(className);
218     entry.setValue(1);
219
220     NameAndAttributes info;
221     info.name = entry.getKey().data();
222     info.attributes = LTO_SYMBOL_PERMISSIONS_DATA |
223       LTO_SYMBOL_DEFINITION_REGULAR | LTO_SYMBOL_SCOPE_DEFAULT;
224     info.isFunction = false;
225     info.symbol = clgv;
226     _symbols.push_back(info);
227   }
228 }
229
230 /// addObjCCategory - Parse i386/ppc ObjC category data structure.
231 void LTOModule::addObjCCategory(const GlobalVariable *clgv) {
232   const ConstantStruct *c = dyn_cast<ConstantStruct>(clgv->getInitializer());
233   if (!c) return;
234
235   // second slot in __OBJC,__category is pointer to target class name
236   std::string targetclassName;
237   if (!objcClassNameFromExpression(c->getOperand(1), targetclassName))
238     return;
239
240   NameAndAttributes info;
241   StringMap<NameAndAttributes>::value_type &entry =
242     _undefines.GetOrCreateValue(targetclassName);
243
244   if (entry.getValue().name)
245     return;
246
247   const char *symbolName = entry.getKey().data();
248   info.name = symbolName;
249   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
250   info.isFunction = false;
251   info.symbol = clgv;
252   entry.setValue(info);
253 }
254
255 /// addObjCClassRef - Parse i386/ppc ObjC class list data structure.
256 void LTOModule::addObjCClassRef(const GlobalVariable *clgv) {
257   std::string targetclassName;
258   if (!objcClassNameFromExpression(clgv->getInitializer(), targetclassName))
259     return;
260
261   NameAndAttributes info;
262   StringMap<NameAndAttributes>::value_type &entry =
263     _undefines.GetOrCreateValue(targetclassName);
264   if (entry.getValue().name)
265     return;
266
267   const char *symbolName = entry.getKey().data();
268   info.name = symbolName;
269   info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
270   info.isFunction = false;
271   info.symbol = clgv;
272   entry.setValue(info);
273 }
274
275 void LTOModule::addDefinedDataSymbol(const object::BasicSymbolRef &Sym) {
276   SmallString<64> Buffer;
277   {
278     raw_svector_ostream OS(Buffer);
279     Sym.printName(OS);
280   }
281
282   const GlobalValue *V = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
283   addDefinedDataSymbol(Buffer.c_str(), V);
284 }
285
286 void LTOModule::addDefinedDataSymbol(const char *Name, const GlobalValue *v) {
287   // Add to list of defined symbols.
288   addDefinedSymbol(Name, v, false);
289
290   if (!v->hasSection() /* || !isTargetDarwin */)
291     return;
292
293   // Special case i386/ppc ObjC data structures in magic sections:
294   // The issue is that the old ObjC object format did some strange
295   // contortions to avoid real linker symbols.  For instance, the
296   // ObjC class data structure is allocated statically in the executable
297   // that defines that class.  That data structures contains a pointer to
298   // its superclass.  But instead of just initializing that part of the
299   // struct to the address of its superclass, and letting the static and
300   // dynamic linkers do the rest, the runtime works by having that field
301   // instead point to a C-string that is the name of the superclass.
302   // At runtime the objc initialization updates that pointer and sets
303   // it to point to the actual super class.  As far as the linker
304   // knows it is just a pointer to a string.  But then someone wanted the
305   // linker to issue errors at build time if the superclass was not found.
306   // So they figured out a way in mach-o object format to use an absolute
307   // symbols (.objc_class_name_Foo = 0) and a floating reference
308   // (.reference .objc_class_name_Bar) to cause the linker into erroring when
309   // a class was missing.
310   // The following synthesizes the implicit .objc_* symbols for the linker
311   // from the ObjC data structures generated by the front end.
312
313   // special case if this data blob is an ObjC class definition
314   std::string Section = v->getSection();
315   if (Section.compare(0, 15, "__OBJC,__class,") == 0) {
316     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
317       addObjCClass(gv);
318     }
319   }
320
321   // special case if this data blob is an ObjC category definition
322   else if (Section.compare(0, 18, "__OBJC,__category,") == 0) {
323     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
324       addObjCCategory(gv);
325     }
326   }
327
328   // special case if this data blob is the list of referenced classes
329   else if (Section.compare(0, 18, "__OBJC,__cls_refs,") == 0) {
330     if (const GlobalVariable *gv = dyn_cast<GlobalVariable>(v)) {
331       addObjCClassRef(gv);
332     }
333   }
334 }
335
336 void LTOModule::addDefinedFunctionSymbol(const object::BasicSymbolRef &Sym) {
337   SmallString<64> Buffer;
338   {
339     raw_svector_ostream OS(Buffer);
340     Sym.printName(OS);
341   }
342
343   const Function *F =
344       cast<Function>(IRFile->getSymbolGV(Sym.getRawDataRefImpl()));
345   addDefinedFunctionSymbol(Buffer.c_str(), F);
346 }
347
348 void LTOModule::addDefinedFunctionSymbol(const char *Name, const Function *F) {
349   // add to list of defined symbols
350   addDefinedSymbol(Name, F, true);
351 }
352
353 void LTOModule::addDefinedSymbol(const char *Name, const GlobalValue *def,
354                                  bool isFunction) {
355   // set alignment part log2() can have rounding errors
356   uint32_t align = def->getAlignment();
357   uint32_t attr = align ? countTrailingZeros(align) : 0;
358
359   // set permissions part
360   if (isFunction) {
361     attr |= LTO_SYMBOL_PERMISSIONS_CODE;
362   } else {
363     const GlobalVariable *gv = dyn_cast<GlobalVariable>(def);
364     if (gv && gv->isConstant())
365       attr |= LTO_SYMBOL_PERMISSIONS_RODATA;
366     else
367       attr |= LTO_SYMBOL_PERMISSIONS_DATA;
368   }
369
370   // set definition part
371   if (def->hasWeakLinkage() || def->hasLinkOnceLinkage())
372     attr |= LTO_SYMBOL_DEFINITION_WEAK;
373   else if (def->hasCommonLinkage())
374     attr |= LTO_SYMBOL_DEFINITION_TENTATIVE;
375   else
376     attr |= LTO_SYMBOL_DEFINITION_REGULAR;
377
378   // set scope part
379   if (def->hasLocalLinkage())
380     // Ignore visibility if linkage is local.
381     attr |= LTO_SYMBOL_SCOPE_INTERNAL;
382   else if (def->hasHiddenVisibility())
383     attr |= LTO_SYMBOL_SCOPE_HIDDEN;
384   else if (def->hasProtectedVisibility())
385     attr |= LTO_SYMBOL_SCOPE_PROTECTED;
386   else if (canBeOmittedFromSymbolTable(def))
387     attr |= LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN;
388   else
389     attr |= LTO_SYMBOL_SCOPE_DEFAULT;
390
391   StringSet::value_type &entry = _defines.GetOrCreateValue(Name);
392   entry.setValue(1);
393
394   // fill information structure
395   NameAndAttributes info;
396   StringRef NameRef = entry.getKey();
397   info.name = NameRef.data();
398   assert(info.name[NameRef.size()] == '\0');
399   info.attributes = attr;
400   info.isFunction = isFunction;
401   info.symbol = def;
402
403   // add to table of symbols
404   _symbols.push_back(info);
405 }
406
407 /// addAsmGlobalSymbol - Add a global symbol from module-level ASM to the
408 /// defined list.
409 void LTOModule::addAsmGlobalSymbol(const char *name,
410                                    lto_symbol_attributes scope) {
411   StringSet::value_type &entry = _defines.GetOrCreateValue(name);
412
413   // only add new define if not already defined
414   if (entry.getValue())
415     return;
416
417   entry.setValue(1);
418
419   NameAndAttributes &info = _undefines[entry.getKey().data()];
420
421   if (info.symbol == nullptr) {
422     // FIXME: This is trying to take care of module ASM like this:
423     //
424     //   module asm ".zerofill __FOO, __foo, _bar_baz_qux, 0"
425     //
426     // but is gross and its mother dresses it funny. Have the ASM parser give us
427     // more details for this type of situation so that we're not guessing so
428     // much.
429
430     // fill information structure
431     info.name = entry.getKey().data();
432     info.attributes =
433       LTO_SYMBOL_PERMISSIONS_DATA | LTO_SYMBOL_DEFINITION_REGULAR | scope;
434     info.isFunction = false;
435     info.symbol = nullptr;
436
437     // add to table of symbols
438     _symbols.push_back(info);
439     return;
440   }
441
442   if (info.isFunction)
443     addDefinedFunctionSymbol(info.name, cast<Function>(info.symbol));
444   else
445     addDefinedDataSymbol(info.name, info.symbol);
446
447   _symbols.back().attributes &= ~LTO_SYMBOL_SCOPE_MASK;
448   _symbols.back().attributes |= scope;
449 }
450
451 /// addAsmGlobalSymbolUndef - Add a global symbol from module-level ASM to the
452 /// undefined list.
453 void LTOModule::addAsmGlobalSymbolUndef(const char *name) {
454   StringMap<NameAndAttributes>::value_type &entry =
455     _undefines.GetOrCreateValue(name);
456
457   _asm_undefines.push_back(entry.getKey().data());
458
459   // we already have the symbol
460   if (entry.getValue().name)
461     return;
462
463   uint32_t attr = LTO_SYMBOL_DEFINITION_UNDEFINED;
464   attr |= LTO_SYMBOL_SCOPE_DEFAULT;
465   NameAndAttributes info;
466   info.name = entry.getKey().data();
467   info.attributes = attr;
468   info.isFunction = false;
469   info.symbol = nullptr;
470
471   entry.setValue(info);
472 }
473
474 /// Add a symbol which isn't defined just yet to a list to be resolved later.
475 void LTOModule::addPotentialUndefinedSymbol(const object::BasicSymbolRef &Sym,
476                                             bool isFunc) {
477   SmallString<64> name;
478   {
479     raw_svector_ostream OS(name);
480     Sym.printName(OS);
481   }
482
483   StringMap<NameAndAttributes>::value_type &entry =
484     _undefines.GetOrCreateValue(name);
485
486   // we already have the symbol
487   if (entry.getValue().name)
488     return;
489
490   NameAndAttributes info;
491
492   info.name = entry.getKey().data();
493
494   const GlobalValue *decl = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
495
496   if (decl->hasExternalWeakLinkage())
497     info.attributes = LTO_SYMBOL_DEFINITION_WEAKUNDEF;
498   else
499     info.attributes = LTO_SYMBOL_DEFINITION_UNDEFINED;
500
501   info.isFunction = isFunc;
502   info.symbol = decl;
503
504   entry.setValue(info);
505 }
506
507 /// parseSymbols - Parse the symbols from the module and model-level ASM and add
508 /// them to either the defined or undefined lists.
509 bool LTOModule::parseSymbols(std::string &errMsg) {
510   for (auto &Sym : IRFile->symbols()) {
511     const GlobalValue *GV = IRFile->getSymbolGV(Sym.getRawDataRefImpl());
512     uint32_t Flags = Sym.getFlags();
513     if (Flags & object::BasicSymbolRef::SF_FormatSpecific)
514       continue;
515
516     bool IsUndefined = Flags & object::BasicSymbolRef::SF_Undefined;
517
518     if (!GV) {
519       SmallString<64> Buffer;
520       {
521         raw_svector_ostream OS(Buffer);
522         Sym.printName(OS);
523       }
524       const char *Name = Buffer.c_str();
525
526       if (IsUndefined)
527         addAsmGlobalSymbolUndef(Name);
528       else if (Flags & object::BasicSymbolRef::SF_Global)
529         addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_DEFAULT);
530       else
531         addAsmGlobalSymbol(Name, LTO_SYMBOL_SCOPE_INTERNAL);
532       continue;
533     }
534
535     auto *F = dyn_cast<Function>(GV);
536     if (IsUndefined) {
537       addPotentialUndefinedSymbol(Sym, F != nullptr);
538       continue;
539     }
540
541     if (F) {
542       addDefinedFunctionSymbol(Sym);
543       continue;
544     }
545
546     if (isa<GlobalVariable>(GV)) {
547       addDefinedDataSymbol(Sym);
548       continue;
549     }
550
551     assert(isa<GlobalAlias>(GV));
552     addDefinedDataSymbol(Sym);
553   }
554
555   // make symbols for all undefines
556   for (StringMap<NameAndAttributes>::iterator u =_undefines.begin(),
557          e = _undefines.end(); u != e; ++u) {
558     // If this symbol also has a definition, then don't make an undefine because
559     // it is a tentative definition.
560     if (_defines.count(u->getKey())) continue;
561     NameAndAttributes info = u->getValue();
562     _symbols.push_back(info);
563   }
564
565   return false;
566 }
567
568 /// parseMetadata - Parse metadata from the module
569 void LTOModule::parseMetadata() {
570   // Linker Options
571   if (Value *Val = getModule().getModuleFlag("Linker Options")) {
572     MDNode *LinkerOptions = cast<MDNode>(Val);
573     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
574       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
575       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
576         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
577         StringRef Op = _linkeropt_strings.
578             GetOrCreateValue(MDOption->getString()).getKey();
579         StringRef DepLibName = _target->getSubtargetImpl()
580                                    ->getTargetLowering()
581                                    ->getObjFileLowering()
582                                    .getDepLibFromLinkerOpt(Op);
583         if (!DepLibName.empty())
584           _deplibs.push_back(DepLibName.data());
585         else if (!Op.empty())
586           _linkeropts.push_back(Op.data());
587       }
588     }
589   }
590
591   // Add other interesting metadata here.
592 }