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/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
26 #include "llvm/Transforms/Utils/ValueMapper.h"
29 //===----------------------------------------------------------------------===//
30 // TypeMap implementation.
31 //===----------------------------------------------------------------------===//
34 class TypeMapTy : public ValueMapTypeRemapper {
35 /// MappedTypes - This is a mapping from a source type to a destination type
37 DenseMap<Type*, Type*> MappedTypes;
39 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
40 /// we speculatively add types to MappedTypes, but keep track of them here in
41 /// case we need to roll back.
42 SmallVector<Type*, 16> SpeculativeTypes;
44 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
45 /// source module that are mapped to an opaque struct in the destination
47 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
49 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
50 /// destination modules who are getting a body from the source module.
51 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
54 /// addTypeMapping - Indicate that the specified type in the destination
55 /// module is conceptually equivalent to the specified type in the source
57 void addTypeMapping(Type *DstTy, Type *SrcTy);
59 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
60 /// module from a type definition in the source module.
61 void linkDefinedTypeBodies();
63 /// get - Return the mapped type to use for the specified input type from the
65 Type *get(Type *SrcTy);
67 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
70 Type *getImpl(Type *T);
71 /// remapType - Implement the ValueMapTypeRemapper interface.
72 Type *remapType(Type *SrcTy) {
76 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
80 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
81 Type *&Entry = MappedTypes[SrcTy];
89 // Check to see if these types are recursively isomorphic and establish a
90 // mapping between them if so.
91 if (!areTypesIsomorphic(DstTy, SrcTy)) {
92 // Oops, they aren't isomorphic. Just discard this request by rolling out
93 // any speculative mappings we've established.
94 for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
95 MappedTypes.erase(SpeculativeTypes[i]);
97 SpeculativeTypes.clear();
100 /// areTypesIsomorphic - Recursively walk this pair of types, returning true
101 /// if they are isomorphic, false if they are not.
102 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
103 // Two types with differing kinds are clearly not isomorphic.
104 if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
106 // If we have an entry in the MappedTypes table, then we have our answer.
107 Type *&Entry = MappedTypes[SrcTy];
109 return Entry == DstTy;
111 // Two identical types are clearly isomorphic. Remember this
112 // non-speculatively.
113 if (DstTy == SrcTy) {
118 // Okay, we have two types with identical kinds that we haven't seen before.
120 // If this is an opaque struct type, special case it.
121 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
122 // Mapping an opaque type to any struct, just keep the dest struct.
123 if (SSTy->isOpaque()) {
125 SpeculativeTypes.push_back(SrcTy);
129 // Mapping a non-opaque source type to an opaque dest. If this is the first
130 // type that we're mapping onto this destination type then we succeed. Keep
131 // the dest, but fill it in later. This doesn't need to be speculative. If
132 // this is the second (different) type that we're trying to map onto the
133 // same opaque type then we fail.
134 if (cast<StructType>(DstTy)->isOpaque()) {
135 // We can only map one source type onto the opaque destination type.
136 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
138 SrcDefinitionsToResolve.push_back(SSTy);
144 // If the number of subtypes disagree between the two types, then we fail.
145 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
148 // Fail if any of the extra properties (e.g. array size) of the type disagree.
149 if (isa<IntegerType>(DstTy))
150 return false; // bitwidth disagrees.
151 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
152 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
155 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
156 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
158 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
159 StructType *SSTy = cast<StructType>(SrcTy);
160 if (DSTy->isLiteral() != SSTy->isLiteral() ||
161 DSTy->isPacked() != SSTy->isPacked())
163 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
164 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
166 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
167 if (DVTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
171 // Otherwise, we speculate that these two types will line up and recursively
172 // check the subelements.
174 SpeculativeTypes.push_back(SrcTy);
176 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
177 if (!areTypesIsomorphic(DstTy->getContainedType(i),
178 SrcTy->getContainedType(i)))
181 // If everything seems to have lined up, then everything is great.
185 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
186 /// module from a type definition in the source module.
187 void TypeMapTy::linkDefinedTypeBodies() {
188 SmallVector<Type*, 16> Elements;
189 SmallString<16> TmpName;
191 // Note that processing entries in this loop (calling 'get') can add new
192 // entries to the SrcDefinitionsToResolve vector.
193 while (!SrcDefinitionsToResolve.empty()) {
194 StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
195 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
197 // TypeMap is a many-to-one mapping, if there were multiple types that
198 // provide a body for DstSTy then previous iterations of this loop may have
199 // already handled it. Just ignore this case.
200 if (!DstSTy->isOpaque()) continue;
201 assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
203 // Map the body of the source type over to a new body for the dest type.
204 Elements.resize(SrcSTy->getNumElements());
205 for (unsigned i = 0, e = Elements.size(); i != e; ++i)
206 Elements[i] = getImpl(SrcSTy->getElementType(i));
208 DstSTy->setBody(Elements, SrcSTy->isPacked());
210 // If DstSTy has no name or has a longer name than STy, then viciously steal
212 if (!SrcSTy->hasName()) continue;
213 StringRef SrcName = SrcSTy->getName();
215 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
216 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
218 DstSTy->setName(TmpName.str());
223 DstResolvedOpaqueTypes.clear();
227 /// get - Return the mapped type to use for the specified input type from the
229 Type *TypeMapTy::get(Type *Ty) {
230 Type *Result = getImpl(Ty);
232 // If this caused a reference to any struct type, resolve it before returning.
233 if (!SrcDefinitionsToResolve.empty())
234 linkDefinedTypeBodies();
238 /// getImpl - This is the recursive version of get().
239 Type *TypeMapTy::getImpl(Type *Ty) {
240 // If we already have an entry for this type, return it.
241 Type **Entry = &MappedTypes[Ty];
242 if (*Entry) return *Entry;
244 // If this is not a named struct type, then just map all of the elements and
245 // then rebuild the type from inside out.
246 if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
247 // If there are no element types to map, then the type is itself. This is
248 // true for the anonymous {} struct, things like 'float', integers, etc.
249 if (Ty->getNumContainedTypes() == 0)
252 // Remap all of the elements, keeping track of whether any of them change.
253 bool AnyChange = false;
254 SmallVector<Type*, 4> ElementTypes;
255 ElementTypes.resize(Ty->getNumContainedTypes());
256 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
257 ElementTypes[i] = getImpl(Ty->getContainedType(i));
258 AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
261 // If we found our type while recursively processing stuff, just use it.
262 Entry = &MappedTypes[Ty];
263 if (*Entry) return *Entry;
265 // If all of the element types mapped directly over, then the type is usable
270 // Otherwise, rebuild a modified type.
271 switch (Ty->getTypeID()) {
272 default: llvm_unreachable("unknown derived type to remap");
273 case Type::ArrayTyID:
274 return *Entry = ArrayType::get(ElementTypes[0],
275 cast<ArrayType>(Ty)->getNumElements());
276 case Type::VectorTyID:
277 return *Entry = VectorType::get(ElementTypes[0],
278 cast<VectorType>(Ty)->getNumElements());
279 case Type::PointerTyID:
280 return *Entry = PointerType::get(ElementTypes[0],
281 cast<PointerType>(Ty)->getAddressSpace());
282 case Type::FunctionTyID:
283 return *Entry = FunctionType::get(ElementTypes[0],
284 makeArrayRef(ElementTypes).slice(1),
285 cast<FunctionType>(Ty)->isVarArg());
286 case Type::StructTyID:
287 // Note that this is only reached for anonymous structs.
288 return *Entry = StructType::get(Ty->getContext(), ElementTypes,
289 cast<StructType>(Ty)->isPacked());
293 // Otherwise, this is an unmapped named struct. If the struct can be directly
294 // mapped over, just use it as-is. This happens in a case when the linked-in
295 // module has something like:
296 // %T = type {%T*, i32}
297 // @GV = global %T* null
298 // where T does not exist at all in the destination module.
300 // The other case we watch for is when the type is not in the destination
301 // module, but that it has to be rebuilt because it refers to something that
302 // is already mapped. For example, if the destination module has:
304 // and the source module has something like
305 // %A' = type { i32 }
306 // %B = type { %A'* }
307 // @GV = global %B* null
308 // then we want to create a new type: "%B = type { %A*}" and have it take the
309 // pristine "%B" name from the source module.
311 // To determine which case this is, we have to recursively walk the type graph
312 // speculating that we'll be able to reuse it unmodified. Only if this is
313 // safe would we map the entire thing over. Because this is an optimization,
314 // and is not required for the prettiness of the linked module, we just skip
315 // it and always rebuild a type here.
316 StructType *STy = cast<StructType>(Ty);
318 // If the type is opaque, we can just use it directly.
322 // Otherwise we create a new type and resolve its body later. This will be
323 // resolved by the top level of get().
324 SrcDefinitionsToResolve.push_back(STy);
325 StructType *DTy = StructType::create(STy->getContext());
326 DstResolvedOpaqueTypes.insert(DTy);
332 //===----------------------------------------------------------------------===//
333 // ModuleLinker implementation.
334 //===----------------------------------------------------------------------===//
337 /// ModuleLinker - This is an implementation class for the LinkModules
338 /// function, which is the entrypoint for this file.
344 /// ValueMap - Mapping of values from what they used to be in Src, to what
345 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
346 /// some overhead due to the use of Value handles which the Linker doesn't
347 /// actually need, but this allows us to reuse the ValueMapper code.
348 ValueToValueMapTy ValueMap;
350 struct AppendingVarInfo {
351 GlobalVariable *NewGV; // New aggregate global in dest module.
352 Constant *DstInit; // Old initializer from dest module.
353 Constant *SrcInit; // Old initializer from src module.
356 std::vector<AppendingVarInfo> AppendingVars;
358 unsigned Mode; // Mode to treat source module.
360 // Set of items not to link in from source.
361 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
363 // Vector of functions to lazily link in.
364 std::vector<Function*> LazilyLinkFunctions;
367 std::string ErrorMsg;
369 ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
370 : DstM(dstM), SrcM(srcM), Mode(mode) { }
375 /// emitError - Helper method for setting a message and returning an error
377 bool emitError(const Twine &Message) {
378 ErrorMsg = Message.str();
382 /// getLinkageResult - This analyzes the two global values and determines
383 /// what the result will look like in the destination module.
384 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
385 GlobalValue::LinkageTypes <,
386 GlobalValue::VisibilityTypes &Vis,
389 /// getLinkedToGlobal - Given a global in the source module, return the
390 /// global in the destination module that is being linked to, if any.
391 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
392 // If the source has no name it can't link. If it has local linkage,
393 // there is no name match-up going on.
394 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
397 // Otherwise see if we have a match in the destination module's symtab.
398 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
399 if (DGV == 0) return 0;
401 // If we found a global with the same name in the dest module, but it has
402 // internal linkage, we are really not doing any linkage here.
403 if (DGV->hasLocalLinkage())
406 // Otherwise, we do in fact link to the destination global.
410 void computeTypeMapping();
411 bool categorizeModuleFlagNodes(const NamedMDNode *ModFlags,
412 DenseMap<MDString*, MDNode*> &ErrorNode,
413 DenseMap<MDString*, MDNode*> &WarningNode,
414 DenseMap<MDString*, MDNode*> &OverrideNode,
416 SmallSetVector<MDNode*, 8> > &RequireNodes,
417 SmallSetVector<MDString*, 16> &SeenIDs);
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();
435 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
436 /// in the symbol table. This is good for all clients except for us. Go
437 /// through the trouble to force this back.
438 static void forceRenaming(GlobalValue *GV, StringRef Name) {
439 // If the global doesn't force its name or if it already has the right name,
440 // there is nothing for us to do.
441 if (GV->hasLocalLinkage() || GV->getName() == Name)
444 Module *M = GV->getParent();
446 // If there is a conflict, rename the conflict.
447 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
448 GV->takeName(ConflictGV);
449 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
450 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
452 GV->setName(Name); // Force the name back
456 /// CopyGVAttributes - copy additional attributes (those not needed to construct
457 /// a GlobalValue) from the SrcGV to the DestGV.
458 static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
459 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
460 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
461 DestGV->copyAttributesFrom(SrcGV);
462 DestGV->setAlignment(Alignment);
464 forceRenaming(DestGV, SrcGV->getName());
467 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
468 GlobalValue::VisibilityTypes b) {
469 if (a == GlobalValue::HiddenVisibility)
471 if (b == GlobalValue::HiddenVisibility)
473 if (a == GlobalValue::ProtectedVisibility)
475 if (b == GlobalValue::ProtectedVisibility)
480 /// getLinkageResult - This analyzes the two global values and determines what
481 /// the result will look like in the destination module. In particular, it
482 /// computes the resultant linkage type and visibility, computes whether the
483 /// global in the source should be copied over to the destination (replacing
484 /// the existing one), and computes whether this linkage is an error or not.
485 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
486 GlobalValue::LinkageTypes <,
487 GlobalValue::VisibilityTypes &Vis,
489 assert(Dest && "Must have two globals being queried");
490 assert(!Src->hasLocalLinkage() &&
491 "If Src has internal linkage, Dest shouldn't be set!");
493 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
494 bool DestIsDeclaration = Dest->isDeclaration();
496 if (SrcIsDeclaration) {
497 // If Src is external or if both Src & Dest are external.. Just link the
498 // external globals, we aren't adding anything.
499 if (Src->hasDLLImportLinkage()) {
500 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
501 if (DestIsDeclaration) {
503 LT = Src->getLinkage();
505 } else if (Dest->hasExternalWeakLinkage()) {
506 // If the Dest is weak, use the source linkage.
508 LT = Src->getLinkage();
511 LT = Dest->getLinkage();
513 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
514 // If Dest is external but Src is not:
516 LT = Src->getLinkage();
517 } else if (Src->isWeakForLinker()) {
518 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
520 if (Dest->hasExternalWeakLinkage() ||
521 Dest->hasAvailableExternallyLinkage() ||
522 (Dest->hasLinkOnceLinkage() &&
523 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
525 LT = Src->getLinkage();
528 LT = Dest->getLinkage();
530 } else if (Dest->isWeakForLinker()) {
531 // At this point we know that Src has External* or DLL* linkage.
532 if (Src->hasExternalWeakLinkage()) {
534 LT = Dest->getLinkage();
537 LT = GlobalValue::ExternalLinkage;
540 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
541 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
542 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
543 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
544 "Unexpected linkage type!");
545 return emitError("Linking globals named '" + Src->getName() +
546 "': symbol multiply defined!");
549 // Compute the visibility. We follow the rules in the System V Application
551 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
552 Dest->getVisibility() : Src->getVisibility();
556 /// computeTypeMapping - Loop over all of the linked values to compute type
557 /// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
558 /// we have two struct types 'Foo' but one got renamed when the module was
559 /// loaded into the same LLVMContext.
560 void ModuleLinker::computeTypeMapping() {
561 // Incorporate globals.
562 for (Module::global_iterator I = SrcM->global_begin(),
563 E = SrcM->global_end(); I != E; ++I) {
564 GlobalValue *DGV = getLinkedToGlobal(I);
565 if (DGV == 0) continue;
567 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
568 TypeMap.addTypeMapping(DGV->getType(), I->getType());
572 // Unify the element type of appending arrays.
573 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
574 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
575 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
578 // Incorporate functions.
579 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
580 if (GlobalValue *DGV = getLinkedToGlobal(I))
581 TypeMap.addTypeMapping(DGV->getType(), I->getType());
585 // FIXME: This doesn't play well with LTO. We cannot compile LLVM with this
586 // enabled. <rdar://problem/10913281>.
588 // Incorporate types by name, scanning all the types in the source module.
589 // At this point, the destination module may have a type "%foo = { i32 }" for
590 // example. When the source module got loaded into the same LLVMContext, if
591 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
592 // Though it isn't required for correctness, attempt to link these up to clean
594 std::vector<StructType*> SrcStructTypes;
595 SrcM->findUsedStructTypes(SrcStructTypes);
597 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
598 SrcStructTypes.end());
600 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
601 StructType *ST = SrcStructTypes[i];
602 if (!ST->hasName()) continue;
604 // Check to see if there is a dot in the name followed by a digit.
605 size_t DotPos = ST->getName().rfind('.');
606 if (DotPos == 0 || DotPos == StringRef::npos ||
607 ST->getName().back() == '.' || !isdigit(ST->getName()[DotPos+1]))
610 // Check to see if the destination module has a struct with the prefix name.
611 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
612 // Don't use it if this actually came from the source module. They're in
613 // the same LLVMContext after all.
614 if (!SrcStructTypesSet.count(DST))
615 TypeMap.addTypeMapping(DST, ST);
619 // Don't bother incorporating aliases, they aren't generally typed well.
621 // Now that we have discovered all of the type equivalences, get a body for
622 // any 'opaque' types in the dest module that are now resolved.
623 TypeMap.linkDefinedTypeBodies();
626 /// linkAppendingVarProto - If there were any appending global variables, link
627 /// them together now. Return true on error.
628 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
629 GlobalVariable *SrcGV) {
631 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
632 return emitError("Linking globals named '" + SrcGV->getName() +
633 "': can only link appending global with another appending global!");
635 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
637 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
638 Type *EltTy = DstTy->getElementType();
640 // Check to see that they two arrays agree on type.
641 if (EltTy != SrcTy->getElementType())
642 return emitError("Appending variables with different element types!");
643 if (DstGV->isConstant() != SrcGV->isConstant())
644 return emitError("Appending variables linked with different const'ness!");
646 if (DstGV->getAlignment() != SrcGV->getAlignment())
648 "Appending variables with different alignment need to be linked!");
650 if (DstGV->getVisibility() != SrcGV->getVisibility())
652 "Appending variables with different visibility need to be linked!");
654 if (DstGV->getSection() != SrcGV->getSection())
656 "Appending variables with different section name need to be linked!");
658 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
659 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
661 // Create the new global variable.
663 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
664 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
665 DstGV->isThreadLocal(),
666 DstGV->getType()->getAddressSpace());
668 // Propagate alignment, visibility and section info.
669 CopyGVAttributes(NG, DstGV);
671 AppendingVarInfo AVI;
673 AVI.DstInit = DstGV->getInitializer();
674 AVI.SrcInit = SrcGV->getInitializer();
675 AppendingVars.push_back(AVI);
677 // Replace any uses of the two global variables with uses of the new
679 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
681 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
682 DstGV->eraseFromParent();
684 // Track the source variable so we don't try to link it.
685 DoNotLinkFromSource.insert(SrcGV);
690 /// linkGlobalProto - Loop through the global variables in the src module and
691 /// merge them into the dest module.
692 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
693 GlobalValue *DGV = getLinkedToGlobal(SGV);
694 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
697 // Concatenation of appending linkage variables is magic and handled later.
698 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
699 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
701 // Determine whether linkage of these two globals follows the source
702 // module's definition or the destination module's definition.
703 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
704 GlobalValue::VisibilityTypes NV;
705 bool LinkFromSrc = false;
706 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
710 // If we're not linking from the source, then keep the definition that we
713 // Special case for const propagation.
714 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
715 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
716 DGVar->setConstant(true);
718 // Set calculated linkage and visibility.
719 DGV->setLinkage(NewLinkage);
720 DGV->setVisibility(*NewVisibility);
722 // Make sure to remember this mapping.
723 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
725 // Track the source global so that we don't attempt to copy it over when
726 // processing global initializers.
727 DoNotLinkFromSource.insert(SGV);
733 // No linking to be performed or linking from the source: simply create an
734 // identical version of the symbol over in the dest module... the
735 // initializer will be filled in later by LinkGlobalInits.
736 GlobalVariable *NewDGV =
737 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
738 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
739 SGV->getName(), /*insertbefore*/0,
740 SGV->isThreadLocal(),
741 SGV->getType()->getAddressSpace());
742 // Propagate alignment, visibility and section info.
743 CopyGVAttributes(NewDGV, SGV);
745 NewDGV->setVisibility(*NewVisibility);
748 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
749 DGV->eraseFromParent();
752 // Make sure to remember this mapping.
753 ValueMap[SGV] = NewDGV;
757 /// linkFunctionProto - Link the function in the source module into the
758 /// destination module if needed, setting up mapping information.
759 bool ModuleLinker::linkFunctionProto(Function *SF) {
760 GlobalValue *DGV = getLinkedToGlobal(SF);
761 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
764 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
765 bool LinkFromSrc = false;
766 GlobalValue::VisibilityTypes NV;
767 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
772 // Set calculated linkage
773 DGV->setLinkage(NewLinkage);
774 DGV->setVisibility(*NewVisibility);
776 // Make sure to remember this mapping.
777 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
779 // Track the function from the source module so we don't attempt to remap
781 DoNotLinkFromSource.insert(SF);
787 // If there is no linkage to be performed or we are linking from the source,
789 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
790 SF->getLinkage(), SF->getName(), DstM);
791 CopyGVAttributes(NewDF, SF);
793 NewDF->setVisibility(*NewVisibility);
796 // Any uses of DF need to change to NewDF, with cast.
797 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
798 DGV->eraseFromParent();
800 // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
801 if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
802 SF->hasAvailableExternallyLinkage()) {
803 DoNotLinkFromSource.insert(SF);
804 LazilyLinkFunctions.push_back(SF);
808 ValueMap[SF] = NewDF;
812 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
814 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
815 GlobalValue *DGV = getLinkedToGlobal(SGA);
816 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
819 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
820 GlobalValue::VisibilityTypes NV;
821 bool LinkFromSrc = false;
822 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
827 // Set calculated linkage.
828 DGV->setLinkage(NewLinkage);
829 DGV->setVisibility(*NewVisibility);
831 // Make sure to remember this mapping.
832 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
834 // Track the alias from the source module so we don't attempt to remap it.
835 DoNotLinkFromSource.insert(SGA);
841 // If there is no linkage to be performed or we're linking from the source,
843 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
844 SGA->getLinkage(), SGA->getName(),
846 CopyGVAttributes(NewDA, SGA);
848 NewDA->setVisibility(*NewVisibility);
851 // Any uses of DGV need to change to NewDA, with cast.
852 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
853 DGV->eraseFromParent();
856 ValueMap[SGA] = NewDA;
860 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
861 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
863 for (unsigned i = 0; i != NumElements; ++i)
864 Dest.push_back(C->getAggregateElement(i));
867 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
868 // Merge the initializer.
869 SmallVector<Constant*, 16> Elements;
870 getArrayElements(AVI.DstInit, Elements);
872 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
873 getArrayElements(SrcInit, Elements);
875 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
876 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
880 // linkGlobalInits - Update the initializers in the Dest module now that all
881 // globals that may be referenced are in Dest.
882 void ModuleLinker::linkGlobalInits() {
883 // Loop over all of the globals in the src module, mapping them over as we go
884 for (Module::const_global_iterator I = SrcM->global_begin(),
885 E = SrcM->global_end(); I != E; ++I) {
887 // Only process initialized GV's or ones not already in dest.
888 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
890 // Grab destination global variable.
891 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
892 // Figure out what the initializer looks like in the dest module.
893 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
898 // linkFunctionBody - Copy the source function over into the dest function and
899 // fix up references to values. At this point we know that Dest is an external
900 // function, and that Src is not.
901 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
902 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
904 // Go through and convert function arguments over, remembering the mapping.
905 Function::arg_iterator DI = Dst->arg_begin();
906 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
908 DI->setName(I->getName()); // Copy the name over.
910 // Add a mapping to our mapping.
914 if (Mode == Linker::DestroySource) {
915 // Splice the body of the source function into the dest function.
916 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
918 // At this point, all of the instructions and values of the function are now
919 // copied over. The only problem is that they are still referencing values in
920 // the Source function as operands. Loop through all of the operands of the
921 // functions and patch them up to point to the local versions.
922 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
923 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
924 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
927 // Clone the body of the function into the dest function.
928 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
929 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
932 // There is no need to map the arguments anymore.
933 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
940 void ModuleLinker::linkAliasBodies() {
941 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
943 if (DoNotLinkFromSource.count(I))
945 if (Constant *Aliasee = I->getAliasee()) {
946 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
947 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
952 /// linkNamedMDNodes - Insert all of the named mdnodes in Src into the Dest
954 void ModuleLinker::linkNamedMDNodes() {
955 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
956 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
957 E = SrcM->named_metadata_end(); I != E; ++I) {
958 // Don't link module flags here. Do them separately.
959 if (&*I == SrcModFlags) continue;
960 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
961 // Add Src elements into Dest node.
962 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
963 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
968 /// categorizeModuleFlagNodes -
970 categorizeModuleFlagNodes(const NamedMDNode *ModFlags,
971 DenseMap<MDString*, MDNode*> &ErrorNode,
972 DenseMap<MDString*, MDNode*> &WarningNode,
973 DenseMap<MDString*, MDNode*> &OverrideNode,
975 SmallSetVector<MDNode*, 8> > &RequireNodes,
976 SmallSetVector<MDString*, 16> &SeenIDs) {
979 for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
980 MDNode *Op = ModFlags->getOperand(I);
981 assert(Op->getNumOperands() == 3 && "Invalid module flag metadata!");
982 assert(isa<ConstantInt>(Op->getOperand(0)) &&
983 "Module flag's first operand must be an integer!");
984 assert(isa<MDString>(Op->getOperand(1)) &&
985 "Module flag's second operand must be an MDString!");
987 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
988 MDString *ID = cast<MDString>(Op->getOperand(1));
989 Value *Val = Op->getOperand(2);
990 switch (Behavior->getZExtValue()) {
992 assert(false && "Invalid behavior in module flag metadata!");
994 case Module::Error: {
995 MDNode *&ErrNode = ErrorNode[ID];
996 if (!ErrNode) ErrNode = Op;
997 if (ErrNode->getOperand(2) != Val)
998 HasErr = emitError("linking module flags '" + ID->getString() +
999 "': IDs have conflicting values");
1002 case Module::Warning: {
1003 MDNode *&WarnNode = WarningNode[ID];
1004 if (!WarnNode) WarnNode = Op;
1005 if (WarnNode->getOperand(2) != Val)
1006 errs() << "WARNING: linking module flags '" << ID->getString()
1007 << "': IDs have conflicting values";
1010 case Module::Require: RequireNodes[ID].insert(Op); break;
1011 case Module::Override: {
1012 MDNode *&OvrNode = OverrideNode[ID];
1013 if (!OvrNode) OvrNode = Op;
1014 if (OvrNode->getOperand(2) != Val)
1015 HasErr = emitError("linking module flags '" + ID->getString() +
1016 "': IDs have conflicting override values");
1027 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1029 bool ModuleLinker::linkModuleFlagsMetadata() {
1030 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1031 if (!SrcModFlags) return false;
1033 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1035 // If the destination module doesn't have module flags yet, then just copy
1036 // over the source module's flags.
1037 if (DstModFlags->getNumOperands() == 0) {
1038 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1039 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1044 bool HasErr = false;
1046 // Otherwise, we have to merge them based on their behaviors. First,
1047 // categorize all of the nodes in the modules' module flags. If an error or
1048 // warning occurs, then emit the appropriate message(s).
1049 DenseMap<MDString*, MDNode*> ErrorNode;
1050 DenseMap<MDString*, MDNode*> WarningNode;
1051 DenseMap<MDString*, MDNode*> OverrideNode;
1052 DenseMap<MDString*, SmallSetVector<MDNode*, 8> > RequireNodes;
1053 SmallSetVector<MDString*, 16> SeenIDs;
1055 HasErr |= categorizeModuleFlagNodes(SrcModFlags, ErrorNode, WarningNode,
1056 OverrideNode, RequireNodes, SeenIDs);
1057 HasErr |= categorizeModuleFlagNodes(DstModFlags, ErrorNode, WarningNode,
1058 OverrideNode, RequireNodes, SeenIDs);
1060 // Check that there isn't both an error and warning node for a flag.
1061 for (SmallSetVector<MDString*, 16>::iterator
1062 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1064 if (ErrorNode[ID] && WarningNode[ID])
1065 HasErr = emitError("linking module flags '" + ID->getString() +
1066 "': IDs have conflicting behaviors");
1069 // Early exit if we had an error.
1070 if (HasErr) return true;
1072 // Get the destination's module flags ready for new operands.
1073 DstModFlags->dropAllReferences();
1075 // Add all of the module flags to the destination module.
1076 DenseMap<MDString*, SmallVector<MDNode*, 4> > AddedNodes;
1077 for (SmallSetVector<MDString*, 16>::iterator
1078 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1080 if (OverrideNode[ID]) {
1081 DstModFlags->addOperand(OverrideNode[ID]);
1082 AddedNodes[ID].push_back(OverrideNode[ID]);
1083 } else if (ErrorNode[ID]) {
1084 DstModFlags->addOperand(ErrorNode[ID]);
1085 AddedNodes[ID].push_back(ErrorNode[ID]);
1086 } else if (WarningNode[ID]) {
1087 DstModFlags->addOperand(WarningNode[ID]);
1088 AddedNodes[ID].push_back(WarningNode[ID]);
1091 for (SmallSetVector<MDNode*, 8>::iterator
1092 II = RequireNodes[ID].begin(), IE = RequireNodes[ID].end();
1094 DstModFlags->addOperand(*II);
1097 // Now check that all of the requirements have been satisfied.
1098 for (SmallSetVector<MDString*, 16>::iterator
1099 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1101 SmallSetVector<MDNode*, 8> &Set = RequireNodes[ID];
1103 for (SmallSetVector<MDNode*, 8>::iterator
1104 II = Set.begin(), IE = Set.end(); II != IE; ++II) {
1106 assert(isa<MDNode>(Node->getOperand(2)) &&
1107 "Module flag's third operand must be an MDNode!");
1108 MDNode *Val = cast<MDNode>(Node->getOperand(2));
1110 MDString *ReqID = cast<MDString>(Val->getOperand(0));
1111 Value *ReqVal = Val->getOperand(1);
1113 bool HasValue = false;
1114 for (SmallVectorImpl<MDNode*>::iterator
1115 RI = AddedNodes[ReqID].begin(), RE = AddedNodes[ReqID].end();
1117 MDNode *ReqNode = *RI;
1118 if (ReqNode->getOperand(2) == ReqVal) {
1125 HasErr = emitError("linking module flags '" + ReqID->getString() +
1126 "': does not have the required value");
1133 bool ModuleLinker::run() {
1134 assert(DstM && "Null destination module");
1135 assert(SrcM && "Null source module");
1137 // Inherit the target data from the source module if the destination module
1138 // doesn't have one already.
1139 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1140 DstM->setDataLayout(SrcM->getDataLayout());
1142 // Copy the target triple from the source to dest if the dest's is empty.
1143 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1144 DstM->setTargetTriple(SrcM->getTargetTriple());
1146 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1147 SrcM->getDataLayout() != DstM->getDataLayout())
1148 errs() << "WARNING: Linking two modules of different data layouts!\n";
1149 if (!SrcM->getTargetTriple().empty() &&
1150 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1151 errs() << "WARNING: Linking two modules of different target triples: ";
1152 if (!SrcM->getModuleIdentifier().empty())
1153 errs() << SrcM->getModuleIdentifier() << ": ";
1154 errs() << "'" << SrcM->getTargetTriple() << "' and '"
1155 << DstM->getTargetTriple() << "'\n";
1158 // Append the module inline asm string.
1159 if (!SrcM->getModuleInlineAsm().empty()) {
1160 if (DstM->getModuleInlineAsm().empty())
1161 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1163 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1164 SrcM->getModuleInlineAsm());
1167 // Update the destination module's dependent libraries list with the libraries
1168 // from the source module. There's no opportunity for duplicates here as the
1169 // Module ensures that duplicate insertions are discarded.
1170 for (Module::lib_iterator SI = SrcM->lib_begin(), SE = SrcM->lib_end();
1172 DstM->addLibrary(*SI);
1174 // If the source library's module id is in the dependent library list of the
1175 // destination library, remove it since that module is now linked in.
1176 StringRef ModuleId = SrcM->getModuleIdentifier();
1177 if (!ModuleId.empty())
1178 DstM->removeLibrary(sys::path::stem(ModuleId));
1180 // Loop over all of the linked values to compute type mappings.
1181 computeTypeMapping();
1183 // Insert all of the globals in src into the DstM module... without linking
1184 // initializers (which could refer to functions not yet mapped over).
1185 for (Module::global_iterator I = SrcM->global_begin(),
1186 E = SrcM->global_end(); I != E; ++I)
1187 if (linkGlobalProto(I))
1190 // Link the functions together between the two modules, without doing function
1191 // bodies... this just adds external function prototypes to the DstM
1192 // function... We do this so that when we begin processing function bodies,
1193 // all of the global values that may be referenced are available in our
1195 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1196 if (linkFunctionProto(I))
1199 // If there were any aliases, link them now.
1200 for (Module::alias_iterator I = SrcM->alias_begin(),
1201 E = SrcM->alias_end(); I != E; ++I)
1202 if (linkAliasProto(I))
1205 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1206 linkAppendingVarInit(AppendingVars[i]);
1208 // Update the initializers in the DstM module now that all globals that may
1209 // be referenced are in DstM.
1212 // Link in the function bodies that are defined in the source module into
1214 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1215 // Skip if not linking from source.
1216 if (DoNotLinkFromSource.count(SF)) continue;
1218 // Skip if no body (function is external) or materialize.
1219 if (SF->isDeclaration()) {
1220 if (!SF->isMaterializable())
1222 if (SF->Materialize(&ErrorMsg))
1226 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
1229 // Resolve all uses of aliases with aliasees.
1232 // Remap all of the named MDNodes in Src into the DstM module. We do this
1233 // after linking GlobalValues so that MDNodes that reference GlobalValues
1234 // are properly remapped.
1237 // Merge the module flags into the DstM module.
1238 if (linkModuleFlagsMetadata())
1241 // Process vector of lazily linked in functions.
1242 bool LinkedInAnyFunctions;
1244 LinkedInAnyFunctions = false;
1246 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1247 E = LazilyLinkFunctions.end(); I != E; ++I) {
1252 Function *DF = cast<Function>(ValueMap[SF]);
1254 if (!DF->use_empty()) {
1256 // Materialize if necessary.
1257 if (SF->isDeclaration()) {
1258 if (!SF->isMaterializable())
1260 if (SF->Materialize(&ErrorMsg))
1264 // Link in function body.
1265 linkFunctionBody(DF, SF);
1267 // "Remove" from vector by setting the element to 0.
1270 // Set flag to indicate we may have more functions to lazily link in
1271 // since we linked in a function.
1272 LinkedInAnyFunctions = true;
1275 } while (LinkedInAnyFunctions);
1277 // Remove any prototypes of functions that were not actually linked in.
1278 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1279 E = LazilyLinkFunctions.end(); I != E; ++I) {
1284 Function *DF = cast<Function>(ValueMap[SF]);
1285 if (DF->use_empty())
1286 DF->eraseFromParent();
1289 // Now that all of the types from the source are used, resolve any structs
1290 // copied over to the dest that didn't exist there.
1291 TypeMap.linkDefinedTypeBodies();
1296 //===----------------------------------------------------------------------===//
1297 // LinkModules entrypoint.
1298 //===----------------------------------------------------------------------===//
1300 // LinkModules - This function links two modules together, with the resulting
1301 // left module modified to be the composite of the two input modules. If an
1302 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1303 // the problem. Upon failure, the Dest module could be in a modified state, and
1304 // shouldn't be relied on to be consistent.
1305 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1306 std::string *ErrorMsg) {
1307 ModuleLinker TheLinker(Dest, Src, Mode);
1308 if (TheLinker.run()) {
1309 if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;