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