1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVM module linker.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Linker.h"
15 #include "llvm-c/Linker.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/TypeFinder.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Transforms/Utils/Cloning.h"
27 //===----------------------------------------------------------------------===//
28 // TypeMap implementation.
29 //===----------------------------------------------------------------------===//
32 class TypeMapTy : public ValueMapTypeRemapper {
33 /// MappedTypes - This is a mapping from a source type to a destination type
35 DenseMap<Type*, Type*> MappedTypes;
37 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
38 /// we speculatively add types to MappedTypes, but keep track of them here in
39 /// case we need to roll back.
40 SmallVector<Type*, 16> SpeculativeTypes;
42 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
43 /// source module that are mapped to an opaque struct in the destination
45 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
47 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
48 /// destination modules who are getting a body from the source module.
49 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
52 /// addTypeMapping - Indicate that the specified type in the destination
53 /// module is conceptually equivalent to the specified type in the source
55 void addTypeMapping(Type *DstTy, Type *SrcTy);
57 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
58 /// module from a type definition in the source module.
59 void linkDefinedTypeBodies();
61 /// get - Return the mapped type to use for the specified input type from the
63 Type *get(Type *SrcTy);
65 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
67 /// dump - Dump out the type map for debugging purposes.
69 for (DenseMap<Type*, Type*>::const_iterator
70 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
71 dbgs() << "TypeMap: ";
80 Type *getImpl(Type *T);
81 /// remapType - Implement the ValueMapTypeRemapper interface.
82 Type *remapType(Type *SrcTy) {
86 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
90 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
91 Type *&Entry = MappedTypes[SrcTy];
99 // Check to see if these types are recursively isomorphic and establish a
100 // mapping between them if so.
101 if (!areTypesIsomorphic(DstTy, SrcTy)) {
102 // Oops, they aren't isomorphic. Just discard this request by rolling out
103 // any speculative mappings we've established.
104 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
105 MappedTypes.erase(SpeculativeTypes[i]);
107 SpeculativeTypes.clear();
110 /// areTypesIsomorphic - Recursively walk this pair of types, returning true
111 /// if they are isomorphic, false if they are not.
112 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
113 // Two types with differing kinds are clearly not isomorphic.
114 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
116 // If we have an entry in the MappedTypes table, then we have our answer.
117 Type *&Entry = MappedTypes[SrcTy];
119 return Entry == DstTy;
121 // Two identical types are clearly isomorphic. Remember this
122 // non-speculatively.
123 if (DstTy == SrcTy) {
128 // Okay, we have two types with identical kinds that we haven't seen before.
130 // If this is an opaque struct type, special case it.
131 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
132 // Mapping an opaque type to any struct, just keep the dest struct.
133 if (SSTy->isOpaque()) {
135 SpeculativeTypes.push_back(SrcTy);
139 // Mapping a non-opaque source type to an opaque dest. If this is the first
140 // type that we're mapping onto this destination type then we succeed. Keep
141 // the dest, but fill it in later. This doesn't need to be speculative. If
142 // this is the second (different) type that we're trying to map onto the
143 // same opaque type then we fail.
144 if (cast<StructType>(DstTy)->isOpaque()) {
145 // We can only map one source type onto the opaque destination type.
146 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
148 SrcDefinitionsToResolve.push_back(SSTy);
154 // If the number of subtypes disagree between the two types, then we fail.
155 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
158 // Fail if any of the extra properties (e.g. array size) of the type disagree.
159 if (isa<IntegerType>(DstTy))
160 return false; // bitwidth disagrees.
161 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
162 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
165 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
166 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
168 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
169 StructType *SSTy = cast<StructType>(SrcTy);
170 if (DSTy->isLiteral() != SSTy->isLiteral() ||
171 DSTy->isPacked() != SSTy->isPacked())
173 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
174 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
176 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
177 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
181 // Otherwise, we speculate that these two types will line up and recursively
182 // check the subelements.
184 SpeculativeTypes.push_back(SrcTy);
186 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
187 if (!areTypesIsomorphic(DstTy->getContainedType(i),
188 SrcTy->getContainedType(i)))
191 // If everything seems to have lined up, then everything is great.
195 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
196 /// module from a type definition in the source module.
197 void TypeMapTy::linkDefinedTypeBodies() {
198 SmallVector<Type*, 16> Elements;
199 SmallString<16> TmpName;
201 // Note that processing entries in this loop (calling 'get') can add new
202 // entries to the SrcDefinitionsToResolve vector.
203 while (!SrcDefinitionsToResolve.empty()) {
204 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
205 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
207 // TypeMap is a many-to-one mapping, if there were multiple types that
208 // provide a body for DstSTy then previous iterations of this loop may have
209 // already handled it. Just ignore this case.
210 if (!DstSTy->isOpaque()) continue;
211 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
213 // Map the body of the source type over to a new body for the dest type.
214 Elements.resize(SrcSTy->getNumElements());
215 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
216 Elements[i] = getImpl(SrcSTy->getElementType(i));
218 DstSTy->setBody(Elements, SrcSTy->isPacked());
220 // If DstSTy has no name or has a longer name than STy, then viciously steal
222 if (!SrcSTy->hasName()) continue;
223 StringRef SrcName = SrcSTy->getName();
225 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
226 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
228 DstSTy->setName(TmpName.str());
233 DstResolvedOpaqueTypes.clear();
236 /// get - Return the mapped type to use for the specified input type from the
238 Type *TypeMapTy::get(Type *Ty) {
239 Type *Result = getImpl(Ty);
241 // If this caused a reference to any struct type, resolve it before returning.
242 if (!SrcDefinitionsToResolve.empty())
243 linkDefinedTypeBodies();
247 /// getImpl - This is the recursive version of get().
248 Type *TypeMapTy::getImpl(Type *Ty) {
249 // If we already have an entry for this type, return it.
250 Type **Entry = &MappedTypes[Ty];
251 if (*Entry) return *Entry;
253 // If this is not a named struct type, then just map all of the elements and
254 // then rebuild the type from inside out.
255 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
256 // If there are no element types to map, then the type is itself. This is
257 // true for the anonymous {} struct, things like 'float', integers, etc.
258 if (Ty->getNumContainedTypes() == 0)
261 // Remap all of the elements, keeping track of whether any of them change.
262 bool AnyChange = false;
263 SmallVector<Type*, 4> ElementTypes;
264 ElementTypes.resize(Ty->getNumContainedTypes());
265 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
266 ElementTypes[i] = getImpl(Ty->getContainedType(i));
267 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
270 // If we found our type while recursively processing stuff, just use it.
271 Entry = &MappedTypes[Ty];
272 if (*Entry) return *Entry;
274 // If all of the element types mapped directly over, then the type is usable
279 // Otherwise, rebuild a modified type.
280 switch (Ty->getTypeID()) {
281 default: llvm_unreachable("unknown derived type to remap");
282 case Type::ArrayTyID:
283 return *Entry = ArrayType::get(ElementTypes[0],
284 cast<ArrayType>(Ty)->getNumElements());
285 case Type::VectorTyID:
286 return *Entry = VectorType::get(ElementTypes[0],
287 cast<VectorType>(Ty)->getNumElements());
288 case Type::PointerTyID:
289 return *Entry = PointerType::get(ElementTypes[0],
290 cast<PointerType>(Ty)->getAddressSpace());
291 case Type::FunctionTyID:
292 return *Entry = FunctionType::get(ElementTypes[0],
293 makeArrayRef(ElementTypes).slice(1),
294 cast<FunctionType>(Ty)->isVarArg());
295 case Type::StructTyID:
296 // Note that this is only reached for anonymous structs.
297 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
298 cast<StructType>(Ty)->isPacked());
302 // Otherwise, this is an unmapped named struct. If the struct can be directly
303 // mapped over, just use it as-is. This happens in a case when the linked-in
304 // module has something like:
305 // %T = type {%T*, i32}
306 // @GV = global %T* null
307 // where T does not exist at all in the destination module.
309 // The other case we watch for is when the type is not in the destination
310 // module, but that it has to be rebuilt because it refers to something that
311 // is already mapped. For example, if the destination module has:
313 // and the source module has something like
314 // %A' = type { i32 }
315 // %B = type { %A'* }
316 // @GV = global %B* null
317 // then we want to create a new type: "%B = type { %A*}" and have it take the
318 // pristine "%B" name from the source module.
320 // To determine which case this is, we have to recursively walk the type graph
321 // speculating that we'll be able to reuse it unmodified. Only if this is
322 // safe would we map the entire thing over. Because this is an optimization,
323 // and is not required for the prettiness of the linked module, we just skip
324 // it and always rebuild a type here.
325 StructType *STy = cast<StructType>(Ty);
327 // If the type is opaque, we can just use it directly.
331 // Otherwise we create a new type and resolve its body later. This will be
332 // resolved by the top level of get().
333 SrcDefinitionsToResolve.push_back(STy);
334 StructType *DTy = StructType::create(STy->getContext());
335 DstResolvedOpaqueTypes.insert(DTy);
339 //===----------------------------------------------------------------------===//
340 // ModuleLinker implementation.
341 //===----------------------------------------------------------------------===//
344 /// ModuleLinker - This is an implementation class for the LinkModules
345 /// function, which is the entrypoint for this file.
351 /// ValueMap - Mapping of values from what they used to be in Src, to what
352 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
353 /// some overhead due to the use of Value handles which the Linker doesn't
354 /// actually need, but this allows us to reuse the ValueMapper code.
355 ValueToValueMapTy ValueMap;
357 struct AppendingVarInfo {
358 GlobalVariable *NewGV; // New aggregate global in dest module.
359 Constant *DstInit; // Old initializer from dest module.
360 Constant *SrcInit; // Old initializer from src module.
363 std::vector<AppendingVarInfo> AppendingVars;
365 unsigned Mode; // Mode to treat source module.
367 // Set of items not to link in from source.
368 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
370 // Vector of functions to lazily link in.
371 std::vector<Function*> LazilyLinkFunctions;
374 std::string ErrorMsg;
376 ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
377 : DstM(dstM), SrcM(srcM), Mode(mode) { }
382 /// emitError - Helper method for setting a message and returning an error
384 bool emitError(const Twine &Message) {
385 ErrorMsg = Message.str();
389 /// getLinkageResult - This analyzes the two global values and determines
390 /// what the result will look like in the destination module.
391 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
392 GlobalValue::LinkageTypes <,
393 GlobalValue::VisibilityTypes &Vis,
396 /// getLinkedToGlobal - Given a global in the source module, return the
397 /// global in the destination module that is being linked to, if any.
398 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
399 // If the source has no name it can't link. If it has local linkage,
400 // there is no name match-up going on.
401 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
404 // Otherwise see if we have a match in the destination module's symtab.
405 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
406 if (DGV == 0) return 0;
408 // If we found a global with the same name in the dest module, but it has
409 // internal linkage, we are really not doing any linkage here.
410 if (DGV->hasLocalLinkage())
413 // Otherwise, we do in fact link to the destination global.
417 void computeTypeMapping();
419 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
420 bool linkGlobalProto(GlobalVariable *SrcGV);
421 bool linkFunctionProto(Function *SrcF);
422 bool linkAliasProto(GlobalAlias *SrcA);
423 bool linkModuleFlagsMetadata();
425 void linkAppendingVarInit(const AppendingVarInfo &AVI);
426 void linkGlobalInits();
427 void linkFunctionBody(Function *Dst, Function *Src);
428 void linkAliasBodies();
429 void linkNamedMDNodes();
433 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
434 /// in the symbol table. This is good for all clients except for us. Go
435 /// through the trouble to force this back.
436 static void forceRenaming(GlobalValue *GV, StringRef Name) {
437 // If the global doesn't force its name or if it already has the right name,
438 // there is nothing for us to do.
439 if (GV->hasLocalLinkage() || GV->getName() == Name)
442 Module *M = GV->getParent();
444 // If there is a conflict, rename the conflict.
445 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
446 GV->takeName(ConflictGV);
447 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
448 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
450 GV->setName(Name); // Force the name back
454 /// copyGVAttributes - copy additional attributes (those not needed to construct
455 /// a GlobalValue) from the SrcGV to the DestGV.
456 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
457 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
458 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
459 DestGV->copyAttributesFrom(SrcGV);
460 DestGV->setAlignment(Alignment);
462 forceRenaming(DestGV, SrcGV->getName());
465 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
466 GlobalValue::VisibilityTypes b) {
467 if (a == GlobalValue::HiddenVisibility)
469 if (b == GlobalValue::HiddenVisibility)
471 if (a == GlobalValue::ProtectedVisibility)
473 if (b == GlobalValue::ProtectedVisibility)
478 /// getLinkageResult - This analyzes the two global values and determines what
479 /// the result will look like in the destination module. In particular, it
480 /// computes the resultant linkage type and visibility, computes whether the
481 /// global in the source should be copied over to the destination (replacing
482 /// the existing one), and computes whether this linkage is an error or not.
483 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
484 GlobalValue::LinkageTypes <,
485 GlobalValue::VisibilityTypes &Vis,
487 assert(Dest && "Must have two globals being queried");
488 assert(!Src->hasLocalLinkage() &&
489 "If Src has internal linkage, Dest shouldn't be set!");
491 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
492 bool DestIsDeclaration = Dest->isDeclaration();
494 if (SrcIsDeclaration) {
495 // If Src is external or if both Src & Dest are external.. Just link the
496 // external globals, we aren't adding anything.
497 if (Src->hasDLLImportLinkage()) {
498 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
499 if (DestIsDeclaration) {
501 LT = Src->getLinkage();
503 } else if (Dest->hasExternalWeakLinkage()) {
504 // If the Dest is weak, use the source linkage.
506 LT = Src->getLinkage();
509 LT = Dest->getLinkage();
511 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
512 // If Dest is external but Src is not:
514 LT = Src->getLinkage();
515 } else if (Src->isWeakForLinker()) {
516 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
518 if (Dest->hasExternalWeakLinkage() ||
519 Dest->hasAvailableExternallyLinkage() ||
520 (Dest->hasLinkOnceLinkage() &&
521 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
523 LT = Src->getLinkage();
526 LT = Dest->getLinkage();
528 } else if (Dest->isWeakForLinker()) {
529 // At this point we know that Src has External* or DLL* linkage.
530 if (Src->hasExternalWeakLinkage()) {
532 LT = Dest->getLinkage();
535 LT = GlobalValue::ExternalLinkage;
538 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
539 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
540 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
541 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
542 "Unexpected linkage type!");
543 return emitError("Linking globals named '" + Src->getName() +
544 "': symbol multiply defined!");
547 // Compute the visibility. We follow the rules in the System V Application
549 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
550 Dest->getVisibility() : Src->getVisibility();
554 /// computeTypeMapping - Loop over all of the linked values to compute type
555 /// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
556 /// we have two struct types 'Foo' but one got renamed when the module was
557 /// loaded into the same LLVMContext.
558 void ModuleLinker::computeTypeMapping() {
559 // Incorporate globals.
560 for (Module::global_iterator I = SrcM->global_begin(),
561 E = SrcM->global_end(); I != E; ++I) {
562 GlobalValue *DGV = getLinkedToGlobal(I);
563 if (DGV == 0) continue;
565 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
566 TypeMap.addTypeMapping(DGV->getType(), I->getType());
570 // Unify the element type of appending arrays.
571 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
572 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
573 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
576 // Incorporate functions.
577 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
578 if (GlobalValue *DGV = getLinkedToGlobal(I))
579 TypeMap.addTypeMapping(DGV->getType(), I->getType());
582 // Incorporate types by name, scanning all the types in the source module.
583 // At this point, the destination module may have a type "%foo = { i32 }" for
584 // example. When the source module got loaded into the same LLVMContext, if
585 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
586 TypeFinder SrcStructTypes;
587 SrcStructTypes.run(*SrcM, true);
588 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
589 SrcStructTypes.end());
591 TypeFinder DstStructTypes;
592 DstStructTypes.run(*DstM, true);
593 SmallPtrSet<StructType*, 32> DstStructTypesSet(DstStructTypes.begin(),
594 DstStructTypes.end());
596 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
597 StructType *ST = SrcStructTypes[i];
598 if (!ST->hasName()) continue;
600 // Check to see if there is a dot in the name followed by a digit.
601 size_t DotPos = ST->getName().rfind('.');
602 if (DotPos == 0 || DotPos == StringRef::npos ||
603 ST->getName().back() == '.' ||
604 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
607 // Check to see if the destination module has a struct with the prefix name.
608 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
609 // Don't use it if this actually came from the source module. They're in
610 // the same LLVMContext after all. Also don't use it unless the type is
611 // actually used in the destination module. This can happen in situations
616 // %Z = type { %A } %B = type { %C.1 }
617 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
618 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
619 // %C = type { i8* } %B.3 = type { %C.1 }
621 // When we link Module B with Module A, the '%B' in Module B is
622 // used. However, that would then use '%C.1'. But when we process '%C.1',
623 // we prefer to take the '%C' version. So we are then left with both
624 // '%C.1' and '%C' being used for the same types. This leads to some
625 // variables using one type and some using the other.
626 if (!SrcStructTypesSet.count(DST) && DstStructTypesSet.count(DST))
627 TypeMap.addTypeMapping(DST, ST);
630 // Don't bother incorporating aliases, they aren't generally typed well.
632 // Now that we have discovered all of the type equivalences, get a body for
633 // any 'opaque' types in the dest module that are now resolved.
634 TypeMap.linkDefinedTypeBodies();
637 /// linkAppendingVarProto - If there were any appending global variables, link
638 /// them together now. Return true on error.
639 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
640 GlobalVariable *SrcGV) {
642 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
643 return emitError("Linking globals named '" + SrcGV->getName() +
644 "': can only link appending global with another appending global!");
646 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
648 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
649 Type *EltTy = DstTy->getElementType();
651 // Check to see that they two arrays agree on type.
652 if (EltTy != SrcTy->getElementType())
653 return emitError("Appending variables with different element types!");
654 if (DstGV->isConstant() != SrcGV->isConstant())
655 return emitError("Appending variables linked with different const'ness!");
657 if (DstGV->getAlignment() != SrcGV->getAlignment())
659 "Appending variables with different alignment need to be linked!");
661 if (DstGV->getVisibility() != SrcGV->getVisibility())
663 "Appending variables with different visibility need to be linked!");
665 if (DstGV->getSection() != SrcGV->getSection())
667 "Appending variables with different section name need to be linked!");
669 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
670 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
672 // Create the new global variable.
674 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
675 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
676 DstGV->getThreadLocalMode(),
677 DstGV->getType()->getAddressSpace());
679 // Propagate alignment, visibility and section info.
680 copyGVAttributes(NG, DstGV);
682 AppendingVarInfo AVI;
684 AVI.DstInit = DstGV->getInitializer();
685 AVI.SrcInit = SrcGV->getInitializer();
686 AppendingVars.push_back(AVI);
688 // Replace any uses of the two global variables with uses of the new
690 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
692 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
693 DstGV->eraseFromParent();
695 // Track the source variable so we don't try to link it.
696 DoNotLinkFromSource.insert(SrcGV);
701 /// linkGlobalProto - Loop through the global variables in the src module and
702 /// merge them into the dest module.
703 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
704 GlobalValue *DGV = getLinkedToGlobal(SGV);
705 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
708 // Concatenation of appending linkage variables is magic and handled later.
709 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
710 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
712 // Determine whether linkage of these two globals follows the source
713 // module's definition or the destination module's definition.
714 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
715 GlobalValue::VisibilityTypes NV;
716 bool LinkFromSrc = false;
717 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
721 // If we're not linking from the source, then keep the definition that we
724 // Special case for const propagation.
725 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
726 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
727 DGVar->setConstant(true);
729 // Set calculated linkage and visibility.
730 DGV->setLinkage(NewLinkage);
731 DGV->setVisibility(*NewVisibility);
733 // Make sure to remember this mapping.
734 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
736 // Track the source global so that we don't attempt to copy it over when
737 // processing global initializers.
738 DoNotLinkFromSource.insert(SGV);
744 // No linking to be performed or linking from the source: simply create an
745 // identical version of the symbol over in the dest module... the
746 // initializer will be filled in later by LinkGlobalInits.
747 GlobalVariable *NewDGV =
748 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
749 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
750 SGV->getName(), /*insertbefore*/0,
751 SGV->getThreadLocalMode(),
752 SGV->getType()->getAddressSpace());
753 // Propagate alignment, visibility and section info.
754 copyGVAttributes(NewDGV, SGV);
756 NewDGV->setVisibility(*NewVisibility);
759 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
760 DGV->eraseFromParent();
763 // Make sure to remember this mapping.
764 ValueMap[SGV] = NewDGV;
768 /// linkFunctionProto - Link the function in the source module into the
769 /// destination module if needed, setting up mapping information.
770 bool ModuleLinker::linkFunctionProto(Function *SF) {
771 GlobalValue *DGV = getLinkedToGlobal(SF);
772 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
775 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
776 bool LinkFromSrc = false;
777 GlobalValue::VisibilityTypes NV;
778 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
783 // Set calculated linkage
784 DGV->setLinkage(NewLinkage);
785 DGV->setVisibility(*NewVisibility);
787 // Make sure to remember this mapping.
788 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
790 // Track the function from the source module so we don't attempt to remap
792 DoNotLinkFromSource.insert(SF);
798 // If there is no linkage to be performed or we are linking from the source,
800 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
801 SF->getLinkage(), SF->getName(), DstM);
802 copyGVAttributes(NewDF, SF);
804 NewDF->setVisibility(*NewVisibility);
807 // Any uses of DF need to change to NewDF, with cast.
808 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
809 DGV->eraseFromParent();
811 // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
812 if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
813 SF->hasAvailableExternallyLinkage()) {
814 DoNotLinkFromSource.insert(SF);
815 LazilyLinkFunctions.push_back(SF);
819 ValueMap[SF] = NewDF;
823 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
825 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
826 GlobalValue *DGV = getLinkedToGlobal(SGA);
827 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
830 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
831 GlobalValue::VisibilityTypes NV;
832 bool LinkFromSrc = false;
833 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
838 // Set calculated linkage.
839 DGV->setLinkage(NewLinkage);
840 DGV->setVisibility(*NewVisibility);
842 // Make sure to remember this mapping.
843 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
845 // Track the alias from the source module so we don't attempt to remap it.
846 DoNotLinkFromSource.insert(SGA);
852 // If there is no linkage to be performed or we're linking from the source,
854 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
855 SGA->getLinkage(), SGA->getName(),
857 copyGVAttributes(NewDA, SGA);
859 NewDA->setVisibility(*NewVisibility);
862 // Any uses of DGV need to change to NewDA, with cast.
863 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
864 DGV->eraseFromParent();
867 ValueMap[SGA] = NewDA;
871 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
872 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
874 for (unsigned i = 0; i != NumElements; ++i)
875 Dest.push_back(C->getAggregateElement(i));
878 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
879 // Merge the initializer.
880 SmallVector<Constant*, 16> Elements;
881 getArrayElements(AVI.DstInit, Elements);
883 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
884 getArrayElements(SrcInit, Elements);
886 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
887 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
890 /// linkGlobalInits - Update the initializers in the Dest module now that all
891 /// globals that may be referenced are in Dest.
892 void ModuleLinker::linkGlobalInits() {
893 // Loop over all of the globals in the src module, mapping them over as we go
894 for (Module::const_global_iterator I = SrcM->global_begin(),
895 E = SrcM->global_end(); I != E; ++I) {
897 // Only process initialized GV's or ones not already in dest.
898 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
900 // Grab destination global variable.
901 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
902 // Figure out what the initializer looks like in the dest module.
903 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
908 /// linkFunctionBody - Copy the source function over into the dest function and
909 /// fix up references to values. At this point we know that Dest is an external
910 /// function, and that Src is not.
911 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
912 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
914 // Go through and convert function arguments over, remembering the mapping.
915 Function::arg_iterator DI = Dst->arg_begin();
916 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
918 DI->setName(I->getName()); // Copy the name over.
920 // Add a mapping to our mapping.
924 if (Mode == Linker::DestroySource) {
925 // Splice the body of the source function into the dest function.
926 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
928 // At this point, all of the instructions and values of the function are now
929 // copied over. The only problem is that they are still referencing values in
930 // the Source function as operands. Loop through all of the operands of the
931 // functions and patch them up to point to the local versions.
932 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
933 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
934 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
937 // Clone the body of the function into the dest function.
938 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
939 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
942 // There is no need to map the arguments anymore.
943 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
949 /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
950 void ModuleLinker::linkAliasBodies() {
951 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
953 if (DoNotLinkFromSource.count(I))
955 if (Constant *Aliasee = I->getAliasee()) {
956 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
957 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
962 /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
964 void ModuleLinker::linkNamedMDNodes() {
965 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
966 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
967 E = SrcM->named_metadata_end(); I != E; ++I) {
968 // Don't link module flags here. Do them separately.
969 if (&*I == SrcModFlags) continue;
970 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
971 // Add Src elements into Dest node.
972 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
973 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
978 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
980 bool ModuleLinker::linkModuleFlagsMetadata() {
981 // If the source module has no module flags, we are done.
982 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
983 if (!SrcModFlags) return false;
985 // If the destination module doesn't have module flags yet, then just copy
986 // over the source module's flags.
987 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
988 if (DstModFlags->getNumOperands() == 0) {
989 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
990 DstModFlags->addOperand(SrcModFlags->getOperand(I));
995 // First build a map of the existing module flags and requirements.
996 DenseMap<MDString*, MDNode*> Flags;
997 SmallSetVector<MDNode*, 16> Requirements;
998 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
999 MDNode *Op = DstModFlags->getOperand(I);
1000 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1001 MDString *ID = cast<MDString>(Op->getOperand(1));
1003 if (Behavior->getZExtValue() == Module::Require) {
1004 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1010 // Merge in the flags from the source module, and also collect its set of
1012 bool HasErr = false;
1013 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1014 MDNode *SrcOp = SrcModFlags->getOperand(I);
1015 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1016 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1017 MDNode *DstOp = Flags.lookup(ID);
1018 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1020 // If this is a requirement, add it and continue.
1021 if (SrcBehaviorValue == Module::Require) {
1022 // If the destination module does not already have this requirement, add
1024 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1025 DstModFlags->addOperand(SrcOp);
1030 // If there is no existing flag with this ID, just add it.
1033 DstModFlags->addOperand(SrcOp);
1037 // Otherwise, perform a merge.
1038 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1039 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1041 // If either flag has override behavior, handle it first.
1042 if (DstBehaviorValue == Module::Override) {
1043 // Diagnose inconsistent flags which both have override behavior.
1044 if (SrcBehaviorValue == Module::Override &&
1045 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1046 HasErr |= emitError("linking module flags '" + ID->getString() +
1047 "': IDs have conflicting override values");
1050 } else if (SrcBehaviorValue == Module::Override) {
1051 // Update the destination flag to that of the source.
1052 DstOp->replaceOperandWith(0, SrcBehavior);
1053 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1057 // Diagnose inconsistent merge behavior types.
1058 if (SrcBehaviorValue != DstBehaviorValue) {
1059 HasErr |= emitError("linking module flags '" + ID->getString() +
1060 "': IDs have conflicting behaviors");
1064 // Perform the merge for standard behavior types.
1065 switch (SrcBehaviorValue) {
1066 case Module::Require:
1067 case Module::Override: assert(0 && "not possible"); break;
1068 case Module::Error: {
1069 // Emit an error if the values differ.
1070 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1071 HasErr |= emitError("linking module flags '" + ID->getString() +
1072 "': IDs have conflicting values");
1076 case Module::Warning: {
1077 // Emit a warning if the values differ.
1078 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1079 errs() << "WARNING: linking module flags '" << ID->getString()
1080 << "': IDs have conflicting values";
1084 case Module::Append: {
1085 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1086 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1087 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1088 Value **VP, **Values = VP = new Value*[NumOps];
1089 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1090 *VP = DstValue->getOperand(i);
1091 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1092 *VP = SrcValue->getOperand(i);
1093 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1094 ArrayRef<Value*>(Values,
1099 case Module::AppendUnique: {
1100 SmallSetVector<Value*, 16> Elts;
1101 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1102 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1103 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1104 Elts.insert(DstValue->getOperand(i));
1105 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1106 Elts.insert(SrcValue->getOperand(i));
1107 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1108 ArrayRef<Value*>(Elts.begin(),
1115 // Check all of the requirements.
1116 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1117 MDNode *Requirement = Requirements[I];
1118 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1119 Value *ReqValue = Requirement->getOperand(1);
1121 MDNode *Op = Flags[Flag];
1122 if (!Op || Op->getOperand(2) != ReqValue) {
1123 HasErr |= emitError("linking module flags '" + Flag->getString() +
1124 "': does not have the required value");
1132 bool ModuleLinker::run() {
1133 assert(DstM && "Null destination module");
1134 assert(SrcM && "Null source module");
1136 // Inherit the target data from the source module if the destination module
1137 // doesn't have one already.
1138 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1139 DstM->setDataLayout(SrcM->getDataLayout());
1141 // Copy the target triple from the source to dest if the dest's is empty.
1142 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1143 DstM->setTargetTriple(SrcM->getTargetTriple());
1145 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1146 SrcM->getDataLayout() != DstM->getDataLayout())
1147 errs() << "WARNING: Linking two modules of different data layouts!\n";
1148 if (!SrcM->getTargetTriple().empty() &&
1149 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1150 errs() << "WARNING: Linking two modules of different target triples: ";
1151 if (!SrcM->getModuleIdentifier().empty())
1152 errs() << SrcM->getModuleIdentifier() << ": ";
1153 errs() << "'" << SrcM->getTargetTriple() << "' and '"
1154 << DstM->getTargetTriple() << "'\n";
1157 // Append the module inline asm string.
1158 if (!SrcM->getModuleInlineAsm().empty()) {
1159 if (DstM->getModuleInlineAsm().empty())
1160 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1162 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1163 SrcM->getModuleInlineAsm());
1166 // Loop over all of the linked values to compute type mappings.
1167 computeTypeMapping();
1169 // Insert all of the globals in src into the DstM module... without linking
1170 // initializers (which could refer to functions not yet mapped over).
1171 for (Module::global_iterator I = SrcM->global_begin(),
1172 E = SrcM->global_end(); I != E; ++I)
1173 if (linkGlobalProto(I))
1176 // Link the functions together between the two modules, without doing function
1177 // bodies... this just adds external function prototypes to the DstM
1178 // function... We do this so that when we begin processing function bodies,
1179 // all of the global values that may be referenced are available in our
1181 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1182 if (linkFunctionProto(I))
1185 // If there were any aliases, link them now.
1186 for (Module::alias_iterator I = SrcM->alias_begin(),
1187 E = SrcM->alias_end(); I != E; ++I)
1188 if (linkAliasProto(I))
1191 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1192 linkAppendingVarInit(AppendingVars[i]);
1194 // Update the initializers in the DstM module now that all globals that may
1195 // be referenced are in DstM.
1198 // Link in the function bodies that are defined in the source module into
1200 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1201 // Skip if not linking from source.
1202 if (DoNotLinkFromSource.count(SF)) continue;
1204 // Skip if no body (function is external) or materialize.
1205 if (SF->isDeclaration()) {
1206 if (!SF->isMaterializable())
1208 if (SF->Materialize(&ErrorMsg))
1212 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
1213 SF->Dematerialize();
1216 // Resolve all uses of aliases with aliasees.
1219 // Remap all of the named MDNodes in Src into the DstM module. We do this
1220 // after linking GlobalValues so that MDNodes that reference GlobalValues
1221 // are properly remapped.
1224 // Merge the module flags into the DstM module.
1225 if (linkModuleFlagsMetadata())
1228 // Process vector of lazily linked in functions.
1229 bool LinkedInAnyFunctions;
1231 LinkedInAnyFunctions = false;
1233 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1234 E = LazilyLinkFunctions.end(); I != E; ++I) {
1239 Function *DF = cast<Function>(ValueMap[SF]);
1241 if (!DF->use_empty()) {
1243 // Materialize if necessary.
1244 if (SF->isDeclaration()) {
1245 if (!SF->isMaterializable())
1247 if (SF->Materialize(&ErrorMsg))
1251 // Link in function body.
1252 linkFunctionBody(DF, SF);
1253 SF->Dematerialize();
1255 // "Remove" from vector by setting the element to 0.
1258 // Set flag to indicate we may have more functions to lazily link in
1259 // since we linked in a function.
1260 LinkedInAnyFunctions = true;
1263 } while (LinkedInAnyFunctions);
1265 // Remove any prototypes of functions that were not actually linked in.
1266 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1267 E = LazilyLinkFunctions.end(); I != E; ++I) {
1272 Function *DF = cast<Function>(ValueMap[SF]);
1273 if (DF->use_empty())
1274 DF->eraseFromParent();
1277 // Now that all of the types from the source are used, resolve any structs
1278 // copied over to the dest that didn't exist there.
1279 TypeMap.linkDefinedTypeBodies();
1284 Linker::Linker(Module *M) : Composite(M) {}
1289 bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
1290 ModuleLinker TheLinker(Composite, Src, Mode);
1291 if (TheLinker.run()) {
1293 *ErrorMsg = TheLinker.ErrorMsg;
1299 //===----------------------------------------------------------------------===//
1300 // LinkModules entrypoint.
1301 //===----------------------------------------------------------------------===//
1303 /// LinkModules - This function links two modules together, with the resulting
1304 /// Dest module modified to be the composite of the two input modules. If an
1305 /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1306 /// the problem. Upon failure, the Dest module could be in a modified state,
1307 /// and shouldn't be relied on to be consistent.
1308 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1309 std::string *ErrorMsg) {
1311 return L.linkInModule(Src, Mode, ErrorMsg);
1314 //===----------------------------------------------------------------------===//
1316 //===----------------------------------------------------------------------===//
1318 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1319 LLVMLinkerMode Mode, char **OutMessages) {
1320 std::string Messages;
1321 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1322 Mode, OutMessages? &Messages : 0);
1324 *OutMessages = strdup(Messages.c_str());