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