LinkModules.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  1. //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
  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 LLVM module linker.
  11. //
  12. // Specifically, this:
  13. // * Merges global variables between the two modules
  14. // * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
  15. // * Merges functions between two modules
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/Linker.h"
  19. #include "llvm/Constants.h"
  20. #include "llvm/DerivedTypes.h"
  21. #include "llvm/LLVMContext.h"
  22. #include "llvm/Module.h"
  23. #include "llvm/TypeSymbolTable.h"
  24. #include "llvm/ValueSymbolTable.h"
  25. #include "llvm/Instructions.h"
  26. #include "llvm/Assembly/Writer.h"
  27. #include "llvm/Support/Streams.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include "llvm/System/Path.h"
  30. #include "llvm/ADT/DenseMap.h"
  31. #include <sstream>
  32. using namespace llvm;
  33. // Error - Simple wrapper function to conditionally assign to E and return true.
  34. // This just makes error return conditions a little bit simpler...
  35. static inline bool Error(std::string *E, const std::string &Message) {
  36. if (E) *E = Message;
  37. return true;
  38. }
  39. // Function: ResolveTypes()
  40. //
  41. // Description:
  42. // Attempt to link the two specified types together.
  43. //
  44. // Inputs:
  45. // DestTy - The type to which we wish to resolve.
  46. // SrcTy - The original type which we want to resolve.
  47. //
  48. // Outputs:
  49. // DestST - The symbol table in which the new type should be placed.
  50. //
  51. // Return value:
  52. // true - There is an error and the types cannot yet be linked.
  53. // false - No errors.
  54. //
  55. static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
  56. if (DestTy == SrcTy) return false; // If already equal, noop
  57. assert(DestTy && SrcTy && "Can't handle null types");
  58. if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
  59. // Type _is_ in module, just opaque...
  60. const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
  61. } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
  62. const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
  63. } else {
  64. return true; // Cannot link types... not-equal and neither is opaque.
  65. }
  66. return false;
  67. }
  68. /// LinkerTypeMap - This implements a map of types that is stable
  69. /// even if types are resolved/refined to other types. This is not a general
  70. /// purpose map, it is specific to the linker's use.
  71. namespace {
  72. class LinkerTypeMap : public AbstractTypeUser {
  73. typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
  74. TheMapTy TheMap;
  75. LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
  76. void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
  77. public:
  78. LinkerTypeMap() {}
  79. ~LinkerTypeMap() {
  80. for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
  81. E = TheMap.end(); I != E; ++I)
  82. I->first->removeAbstractTypeUser(this);
  83. }
  84. /// lookup - Return the value for the specified type or null if it doesn't
  85. /// exist.
  86. const Type *lookup(const Type *Ty) const {
  87. TheMapTy::const_iterator I = TheMap.find(Ty);
  88. if (I != TheMap.end()) return I->second;
  89. return 0;
  90. }
  91. /// erase - Remove the specified type, returning true if it was in the set.
  92. bool erase(const Type *Ty) {
  93. if (!TheMap.erase(Ty))
  94. return false;
  95. if (Ty->isAbstract())
  96. Ty->removeAbstractTypeUser(this);
  97. return true;
  98. }
  99. /// insert - This returns true if the pointer was new to the set, false if it
  100. /// was already in the set.
  101. bool insert(const Type *Src, const Type *Dst) {
  102. if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
  103. return false; // Already in map.
  104. if (Src->isAbstract())
  105. Src->addAbstractTypeUser(this);
  106. return true;
  107. }
  108. protected:
  109. /// refineAbstractType - The callback method invoked when an abstract type is
  110. /// resolved to another type. An object must override this method to update
  111. /// its internal state to reference NewType instead of OldType.
  112. ///
  113. virtual void refineAbstractType(const DerivedType *OldTy,
  114. const Type *NewTy) {
  115. TheMapTy::iterator I = TheMap.find(OldTy);
  116. const Type *DstTy = I->second;
  117. TheMap.erase(I);
  118. if (OldTy->isAbstract())
  119. OldTy->removeAbstractTypeUser(this);
  120. // Don't reinsert into the map if the key is concrete now.
  121. if (NewTy->isAbstract())
  122. insert(NewTy, DstTy);
  123. }
  124. /// The other case which AbstractTypeUsers must be aware of is when a type
  125. /// makes the transition from being abstract (where it has clients on it's
  126. /// AbstractTypeUsers list) to concrete (where it does not). This method
  127. /// notifies ATU's when this occurs for a type.
  128. virtual void typeBecameConcrete(const DerivedType *AbsTy) {
  129. TheMap.erase(AbsTy);
  130. AbsTy->removeAbstractTypeUser(this);
  131. }
  132. // for debugging...
  133. virtual void dump() const {
  134. cerr << "AbstractTypeSet!\n";
  135. }
  136. };
  137. }
  138. // RecursiveResolveTypes - This is just like ResolveTypes, except that it
  139. // recurses down into derived types, merging the used types if the parent types
  140. // are compatible.
  141. static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
  142. LinkerTypeMap &Pointers) {
  143. if (DstTy == SrcTy) return false; // If already equal, noop
  144. // If we found our opaque type, resolve it now!
  145. if (isa<OpaqueType>(DstTy) || isa<OpaqueType>(SrcTy))
  146. return ResolveTypes(DstTy, SrcTy);
  147. // Two types cannot be resolved together if they are of different primitive
  148. // type. For example, we cannot resolve an int to a float.
  149. if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
  150. // If neither type is abstract, then they really are just different types.
  151. if (!DstTy->isAbstract() && !SrcTy->isAbstract())
  152. return true;
  153. // Otherwise, resolve the used type used by this derived type...
  154. switch (DstTy->getTypeID()) {
  155. default:
  156. return true;
  157. case Type::FunctionTyID: {
  158. const FunctionType *DstFT = cast<FunctionType>(DstTy);
  159. const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
  160. if (DstFT->isVarArg() != SrcFT->isVarArg() ||
  161. DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
  162. return true;
  163. // Use TypeHolder's so recursive resolution won't break us.
  164. PATypeHolder ST(SrcFT), DT(DstFT);
  165. for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
  166. const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
  167. if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
  168. return true;
  169. }
  170. return false;
  171. }
  172. case Type::StructTyID: {
  173. const StructType *DstST = cast<StructType>(DstTy);
  174. const StructType *SrcST = cast<StructType>(SrcTy);
  175. if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
  176. return true;
  177. PATypeHolder ST(SrcST), DT(DstST);
  178. for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
  179. const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
  180. if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
  181. return true;
  182. }
  183. return false;
  184. }
  185. case Type::ArrayTyID: {
  186. const ArrayType *DAT = cast<ArrayType>(DstTy);
  187. const ArrayType *SAT = cast<ArrayType>(SrcTy);
  188. if (DAT->getNumElements() != SAT->getNumElements()) return true;
  189. return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
  190. Pointers);
  191. }
  192. case Type::VectorTyID: {
  193. const VectorType *DVT = cast<VectorType>(DstTy);
  194. const VectorType *SVT = cast<VectorType>(SrcTy);
  195. if (DVT->getNumElements() != SVT->getNumElements()) return true;
  196. return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
  197. Pointers);
  198. }
  199. case Type::PointerTyID: {
  200. const PointerType *DstPT = cast<PointerType>(DstTy);
  201. const PointerType *SrcPT = cast<PointerType>(SrcTy);
  202. if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
  203. return true;
  204. // If this is a pointer type, check to see if we have already seen it. If
  205. // so, we are in a recursive branch. Cut off the search now. We cannot use
  206. // an associative container for this search, because the type pointers (keys
  207. // in the container) change whenever types get resolved.
  208. if (SrcPT->isAbstract())
  209. if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
  210. return ExistingDestTy != DstPT;
  211. if (DstPT->isAbstract())
  212. if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
  213. return ExistingSrcTy != SrcPT;
  214. // Otherwise, add the current pointers to the vector to stop recursion on
  215. // this pair.
  216. if (DstPT->isAbstract())
  217. Pointers.insert(DstPT, SrcPT);
  218. if (SrcPT->isAbstract())
  219. Pointers.insert(SrcPT, DstPT);
  220. return RecursiveResolveTypesI(DstPT->getElementType(),
  221. SrcPT->getElementType(), Pointers);
  222. }
  223. }
  224. }
  225. static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
  226. LinkerTypeMap PointerTypes;
  227. return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
  228. }
  229. // LinkTypes - Go through the symbol table of the Src module and see if any
  230. // types are named in the src module that are not named in the Dst module.
  231. // Make sure there are no type name conflicts.
  232. static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
  233. TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
  234. const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
  235. // Look for a type plane for Type's...
  236. TypeSymbolTable::const_iterator TI = SrcST->begin();
  237. TypeSymbolTable::const_iterator TE = SrcST->end();
  238. if (TI == TE) return false; // No named types, do nothing.
  239. // Some types cannot be resolved immediately because they depend on other
  240. // types being resolved to each other first. This contains a list of types we
  241. // are waiting to recheck.
  242. std::vector<std::string> DelayedTypesToResolve;
  243. for ( ; TI != TE; ++TI ) {
  244. const std::string &Name = TI->first;
  245. const Type *RHS = TI->second;
  246. // Check to see if this type name is already in the dest module.
  247. Type *Entry = DestST->lookup(Name);
  248. // If the name is just in the source module, bring it over to the dest.
  249. if (Entry == 0) {
  250. if (!Name.empty())
  251. DestST->insert(Name, const_cast<Type*>(RHS));
  252. } else if (ResolveTypes(Entry, RHS)) {
  253. // They look different, save the types 'till later to resolve.
  254. DelayedTypesToResolve.push_back(Name);
  255. }
  256. }
  257. // Iteratively resolve types while we can...
  258. while (!DelayedTypesToResolve.empty()) {
  259. // Loop over all of the types, attempting to resolve them if possible...
  260. unsigned OldSize = DelayedTypesToResolve.size();
  261. // Try direct resolution by name...
  262. for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
  263. const std::string &Name = DelayedTypesToResolve[i];
  264. Type *T1 = SrcST->lookup(Name);
  265. Type *T2 = DestST->lookup(Name);
  266. if (!ResolveTypes(T2, T1)) {
  267. // We are making progress!
  268. DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
  269. --i;
  270. }
  271. }
  272. // Did we not eliminate any types?
  273. if (DelayedTypesToResolve.size() == OldSize) {
  274. // Attempt to resolve subelements of types. This allows us to merge these
  275. // two types: { int* } and { opaque* }
  276. for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
  277. const std::string &Name = DelayedTypesToResolve[i];
  278. if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
  279. // We are making progress!
  280. DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
  281. // Go back to the main loop, perhaps we can resolve directly by name
  282. // now...
  283. break;
  284. }
  285. }
  286. // If we STILL cannot resolve the types, then there is something wrong.
  287. if (DelayedTypesToResolve.size() == OldSize) {
  288. // Remove the symbol name from the destination.
  289. DelayedTypesToResolve.pop_back();
  290. }
  291. }
  292. }
  293. return false;
  294. }
  295. #ifndef NDEBUG
  296. static void PrintMap(const std::map<const Value*, Value*> &M) {
  297. for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
  298. I != E; ++I) {
  299. cerr << " Fr: " << (void*)I->first << " ";
  300. I->first->dump();
  301. cerr << " To: " << (void*)I->second << " ";
  302. I->second->dump();
  303. cerr << "\n";
  304. }
  305. }
  306. #endif
  307. // RemapOperand - Use ValueMap to convert constants from one module to another.
  308. static Value *RemapOperand(const Value *In,
  309. std::map<const Value*, Value*> &ValueMap,
  310. LLVMContext &Context) {
  311. std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
  312. if (I != ValueMap.end())
  313. return I->second;
  314. // Check to see if it's a constant that we are interested in transforming.
  315. Value *Result = 0;
  316. if (const Constant *CPV = dyn_cast<Constant>(In)) {
  317. if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
  318. isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
  319. return const_cast<Constant*>(CPV); // Simple constants stay identical.
  320. if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
  321. std::vector<Constant*> Operands(CPA->getNumOperands());
  322. for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
  323. Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap,
  324. Context));
  325. Result =
  326. Context.getConstantArray(cast<ArrayType>(CPA->getType()), Operands);
  327. } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
  328. std::vector<Constant*> Operands(CPS->getNumOperands());
  329. for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
  330. Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap,
  331. Context));
  332. Result =
  333. Context.getConstantStruct(cast<StructType>(CPS->getType()), Operands);
  334. } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
  335. Result = const_cast<Constant*>(CPV);
  336. } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
  337. std::vector<Constant*> Operands(CP->getNumOperands());
  338. for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
  339. Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap,
  340. Context));
  341. Result = Context.getConstantVector(Operands);
  342. } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
  343. std::vector<Constant*> Ops;
  344. for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
  345. Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap,
  346. Context)));
  347. Result = CE->getWithOperands(Ops);
  348. } else {
  349. assert(!isa<GlobalValue>(CPV) && "Unmapped global?");
  350. LLVM_UNREACHABLE("Unknown type of derived type constant value!");
  351. }
  352. } else if (isa<InlineAsm>(In)) {
  353. Result = const_cast<Value*>(In);
  354. }
  355. // Cache the mapping in our local map structure
  356. if (Result) {
  357. ValueMap[In] = Result;
  358. return Result;
  359. }
  360. #ifndef NDEBUG
  361. cerr << "LinkModules ValueMap: \n";
  362. PrintMap(ValueMap);
  363. cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
  364. LLVM_UNREACHABLE("Couldn't remap value!");
  365. #endif
  366. return 0;
  367. }
  368. /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
  369. /// in the symbol table. This is good for all clients except for us. Go
  370. /// through the trouble to force this back.
  371. static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
  372. assert(GV->getName() != Name && "Can't force rename to self");
  373. ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
  374. // If there is a conflict, rename the conflict.
  375. if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
  376. assert(ConflictGV->hasLocalLinkage() &&
  377. "Not conflicting with a static global, should link instead!");
  378. GV->takeName(ConflictGV);
  379. ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
  380. assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
  381. } else {
  382. GV->setName(Name); // Force the name back
  383. }
  384. }
  385. /// CopyGVAttributes - copy additional attributes (those not needed to construct
  386. /// a GlobalValue) from the SrcGV to the DestGV.
  387. static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
  388. // Use the maximum alignment, rather than just copying the alignment of SrcGV.
  389. unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
  390. DestGV->copyAttributesFrom(SrcGV);
  391. DestGV->setAlignment(Alignment);
  392. }
  393. /// GetLinkageResult - This analyzes the two global values and determines what
  394. /// the result will look like in the destination module. In particular, it
  395. /// computes the resultant linkage type, computes whether the global in the
  396. /// source should be copied over to the destination (replacing the existing
  397. /// one), and computes whether this linkage is an error or not. It also performs
  398. /// visibility checks: we cannot link together two symbols with different
  399. /// visibilities.
  400. static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
  401. GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
  402. std::string *Err) {
  403. assert((!Dest || !Src->hasLocalLinkage()) &&
  404. "If Src has internal linkage, Dest shouldn't be set!");
  405. if (!Dest) {
  406. // Linking something to nothing.
  407. LinkFromSrc = true;
  408. LT = Src->getLinkage();
  409. } else if (Src->isDeclaration()) {
  410. // If Src is external or if both Src & Dest are external.. Just link the
  411. // external globals, we aren't adding anything.
  412. if (Src->hasDLLImportLinkage()) {
  413. // If one of GVs has DLLImport linkage, result should be dllimport'ed.
  414. if (Dest->isDeclaration()) {
  415. LinkFromSrc = true;
  416. LT = Src->getLinkage();
  417. }
  418. } else if (Dest->hasExternalWeakLinkage()) {
  419. // If the Dest is weak, use the source linkage.
  420. LinkFromSrc = true;
  421. LT = Src->getLinkage();
  422. } else {
  423. LinkFromSrc = false;
  424. LT = Dest->getLinkage();
  425. }
  426. } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
  427. // If Dest is external but Src is not:
  428. LinkFromSrc = true;
  429. LT = Src->getLinkage();
  430. } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
  431. if (Src->getLinkage() != Dest->getLinkage())
  432. return Error(Err, "Linking globals named '" + Src->getName() +
  433. "': can only link appending global with another appending global!");
  434. LinkFromSrc = true; // Special cased.
  435. LT = Src->getLinkage();
  436. } else if (Src->isWeakForLinker()) {
  437. // At this point we know that Dest has LinkOnce, External*, Weak, Common,
  438. // or DLL* linkage.
  439. if (Dest->hasExternalWeakLinkage() ||
  440. Dest->hasAvailableExternallyLinkage() ||
  441. (Dest->hasLinkOnceLinkage() &&
  442. (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
  443. LinkFromSrc = true;
  444. LT = Src->getLinkage();
  445. } else {
  446. LinkFromSrc = false;
  447. LT = Dest->getLinkage();
  448. }
  449. } else if (Dest->isWeakForLinker()) {
  450. // At this point we know that Src has External* or DLL* linkage.
  451. if (Src->hasExternalWeakLinkage()) {
  452. LinkFromSrc = false;
  453. LT = Dest->getLinkage();
  454. } else {
  455. LinkFromSrc = true;
  456. LT = GlobalValue::ExternalLinkage;
  457. }
  458. } else {
  459. assert((Dest->hasExternalLinkage() ||
  460. Dest->hasDLLImportLinkage() ||
  461. Dest->hasDLLExportLinkage() ||
  462. Dest->hasExternalWeakLinkage()) &&
  463. (Src->hasExternalLinkage() ||
  464. Src->hasDLLImportLinkage() ||
  465. Src->hasDLLExportLinkage() ||
  466. Src->hasExternalWeakLinkage()) &&
  467. "Unexpected linkage type!");
  468. return Error(Err, "Linking globals named '" + Src->getName() +
  469. "': symbol multiply defined!");
  470. }
  471. // Check visibility
  472. if (Dest && Src->getVisibility() != Dest->getVisibility())
  473. if (!Src->isDeclaration() && !Dest->isDeclaration())
  474. return Error(Err, "Linking globals named '" + Src->getName() +
  475. "': symbols have different visibilities!");
  476. return false;
  477. }
  478. // LinkGlobals - Loop through the global variables in the src module and merge
  479. // them into the dest module.
  480. static bool LinkGlobals(Module *Dest, const Module *Src,
  481. std::map<const Value*, Value*> &ValueMap,
  482. std::multimap<std::string, GlobalVariable *> &AppendingVars,
  483. std::string *Err) {
  484. ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
  485. LLVMContext &Context = Dest->getContext();
  486. // Loop over all of the globals in the src module, mapping them over as we go
  487. for (Module::const_global_iterator I = Src->global_begin(),
  488. E = Src->global_end(); I != E; ++I) {
  489. const GlobalVariable *SGV = I;
  490. GlobalValue *DGV = 0;
  491. // Check to see if may have to link the global with the global, alias or
  492. // function.
  493. if (SGV->hasName() && !SGV->hasLocalLinkage())
  494. DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getNameStart(),
  495. SGV->getNameEnd()));
  496. // If we found a global with the same name in the dest module, but it has
  497. // internal linkage, we are really not doing any linkage here.
  498. if (DGV && DGV->hasLocalLinkage())
  499. DGV = 0;
  500. // If types don't agree due to opaque types, try to resolve them.
  501. if (DGV && DGV->getType() != SGV->getType())
  502. RecursiveResolveTypes(SGV->getType(), DGV->getType());
  503. assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
  504. SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
  505. "Global must either be external or have an initializer!");
  506. GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
  507. bool LinkFromSrc = false;
  508. if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
  509. return true;
  510. if (DGV == 0) {
  511. // No linking to be performed, simply create an identical version of the
  512. // symbol over in the dest module... the initializer will be filled in
  513. // later by LinkGlobalInits.
  514. GlobalVariable *NewDGV =
  515. new GlobalVariable(*Dest, SGV->getType()->getElementType(),
  516. SGV->isConstant(), SGV->getLinkage(), /*init*/0,
  517. SGV->getName(), 0, false,
  518. SGV->getType()->getAddressSpace());
  519. // Propagate alignment, visibility and section info.
  520. CopyGVAttributes(NewDGV, SGV);
  521. // If the LLVM runtime renamed the global, but it is an externally visible
  522. // symbol, DGV must be an existing global with internal linkage. Rename
  523. // it.
  524. if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
  525. ForceRenaming(NewDGV, SGV->getName());
  526. // Make sure to remember this mapping.
  527. ValueMap[SGV] = NewDGV;
  528. // Keep track that this is an appending variable.
  529. if (SGV->hasAppendingLinkage())
  530. AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
  531. continue;
  532. }
  533. // If the visibilities of the symbols disagree and the destination is a
  534. // prototype, take the visibility of its input.
  535. if (DGV->isDeclaration())
  536. DGV->setVisibility(SGV->getVisibility());
  537. if (DGV->hasAppendingLinkage()) {
  538. // No linking is performed yet. Just insert a new copy of the global, and
  539. // keep track of the fact that it is an appending variable in the
  540. // AppendingVars map. The name is cleared out so that no linkage is
  541. // performed.
  542. GlobalVariable *NewDGV =
  543. new GlobalVariable(*Dest, SGV->getType()->getElementType(),
  544. SGV->isConstant(), SGV->getLinkage(), /*init*/0,
  545. "", 0, false,
  546. SGV->getType()->getAddressSpace());
  547. // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
  548. NewDGV->setAlignment(DGV->getAlignment());
  549. // Propagate alignment, section and visibility info.
  550. CopyGVAttributes(NewDGV, SGV);
  551. // Make sure to remember this mapping...
  552. ValueMap[SGV] = NewDGV;
  553. // Keep track that this is an appending variable...
  554. AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
  555. continue;
  556. }
  557. if (LinkFromSrc) {
  558. if (isa<GlobalAlias>(DGV))
  559. return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
  560. "': symbol multiple defined");
  561. // If the types don't match, and if we are to link from the source, nuke
  562. // DGV and create a new one of the appropriate type. Note that the thing
  563. // we are replacing may be a function (if a prototype, weak, etc) or a
  564. // global variable.
  565. GlobalVariable *NewDGV =
  566. new GlobalVariable(*Dest, SGV->getType()->getElementType(),
  567. SGV->isConstant(), NewLinkage, /*init*/0,
  568. DGV->getName(), 0, false,
  569. SGV->getType()->getAddressSpace());
  570. // Propagate alignment, section, and visibility info.
  571. CopyGVAttributes(NewDGV, SGV);
  572. DGV->replaceAllUsesWith(Context.getConstantExprBitCast(NewDGV,
  573. DGV->getType()));
  574. // DGV will conflict with NewDGV because they both had the same
  575. // name. We must erase this now so ForceRenaming doesn't assert
  576. // because DGV might not have internal linkage.
  577. if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
  578. Var->eraseFromParent();
  579. else
  580. cast<Function>(DGV)->eraseFromParent();
  581. DGV = NewDGV;
  582. // If the symbol table renamed the global, but it is an externally visible
  583. // symbol, DGV must be an existing global with internal linkage. Rename.
  584. if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
  585. ForceRenaming(NewDGV, SGV->getName());
  586. // Inherit const as appropriate.
  587. NewDGV->setConstant(SGV->isConstant());
  588. // Make sure to remember this mapping.
  589. ValueMap[SGV] = NewDGV;
  590. continue;
  591. }
  592. // Not "link from source", keep the one in the DestModule and remap the
  593. // input onto it.
  594. // Special case for const propagation.
  595. if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
  596. if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
  597. DGVar->setConstant(true);
  598. // SGV is global, but DGV is alias.
  599. if (isa<GlobalAlias>(DGV)) {
  600. // The only valid mappings are:
  601. // - SGV is external declaration, which is effectively a no-op.
  602. // - SGV is weak, when we just need to throw SGV out.
  603. if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
  604. return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
  605. "': symbol multiple defined");
  606. }
  607. // Set calculated linkage
  608. DGV->setLinkage(NewLinkage);
  609. // Make sure to remember this mapping...
  610. ValueMap[SGV] = Context.getConstantExprBitCast(DGV, SGV->getType());
  611. }
  612. return false;
  613. }
  614. static GlobalValue::LinkageTypes
  615. CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
  616. GlobalValue::LinkageTypes SL = SGV->getLinkage();
  617. GlobalValue::LinkageTypes DL = DGV->getLinkage();
  618. if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
  619. return GlobalValue::ExternalLinkage;
  620. else if (SL == GlobalValue::WeakAnyLinkage ||
  621. DL == GlobalValue::WeakAnyLinkage)
  622. return GlobalValue::WeakAnyLinkage;
  623. else if (SL == GlobalValue::WeakODRLinkage ||
  624. DL == GlobalValue::WeakODRLinkage)
  625. return GlobalValue::WeakODRLinkage;
  626. else if (SL == GlobalValue::InternalLinkage &&
  627. DL == GlobalValue::InternalLinkage)
  628. return GlobalValue::InternalLinkage;
  629. else {
  630. assert (SL == GlobalValue::PrivateLinkage &&
  631. DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
  632. return GlobalValue::PrivateLinkage;
  633. }
  634. }
  635. // LinkAlias - Loop through the alias in the src module and link them into the
  636. // dest module. We're assuming, that all functions/global variables were already
  637. // linked in.
  638. static bool LinkAlias(Module *Dest, const Module *Src,
  639. std::map<const Value*, Value*> &ValueMap,
  640. std::string *Err) {
  641. LLVMContext &Context = Dest->getContext();
  642. // Loop over all alias in the src module
  643. for (Module::const_alias_iterator I = Src->alias_begin(),
  644. E = Src->alias_end(); I != E; ++I) {
  645. const GlobalAlias *SGA = I;
  646. const GlobalValue *SAliasee = SGA->getAliasedGlobal();
  647. GlobalAlias *NewGA = NULL;
  648. // Globals were already linked, thus we can just query ValueMap for variant
  649. // of SAliasee in Dest.
  650. std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
  651. assert(VMI != ValueMap.end() && "Aliasee not linked");
  652. GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
  653. GlobalValue* DGV = NULL;
  654. // Try to find something 'similar' to SGA in destination module.
  655. if (!DGV && !SGA->hasLocalLinkage()) {
  656. DGV = Dest->getNamedAlias(SGA->getName());
  657. // If types don't agree due to opaque types, try to resolve them.
  658. if (DGV && DGV->getType() != SGA->getType())
  659. RecursiveResolveTypes(SGA->getType(), DGV->getType());
  660. }
  661. if (!DGV && !SGA->hasLocalLinkage()) {
  662. DGV = Dest->getGlobalVariable(SGA->getName());
  663. // If types don't agree due to opaque types, try to resolve them.
  664. if (DGV && DGV->getType() != SGA->getType())
  665. RecursiveResolveTypes(SGA->getType(), DGV->getType());
  666. }
  667. if (!DGV && !SGA->hasLocalLinkage()) {
  668. DGV = Dest->getFunction(SGA->getName());
  669. // If types don't agree due to opaque types, try to resolve them.
  670. if (DGV && DGV->getType() != SGA->getType())
  671. RecursiveResolveTypes(SGA->getType(), DGV->getType());
  672. }
  673. // No linking to be performed on internal stuff.
  674. if (DGV && DGV->hasLocalLinkage())
  675. DGV = NULL;
  676. if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
  677. // Types are known to be the same, check whether aliasees equal. As
  678. // globals are already linked we just need query ValueMap to find the
  679. // mapping.
  680. if (DAliasee == DGA->getAliasedGlobal()) {
  681. // This is just two copies of the same alias. Propagate linkage, if
  682. // necessary.
  683. DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
  684. NewGA = DGA;
  685. // Proceed to 'common' steps
  686. } else
  687. return Error(Err, "Alias Collision on '" + SGA->getName()+
  688. "': aliases have different aliasees");
  689. } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
  690. // The only allowed way is to link alias with external declaration or weak
  691. // symbol..
  692. if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
  693. // But only if aliasee is global too...
  694. if (!isa<GlobalVariable>(DAliasee))
  695. return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
  696. "': aliasee is not global variable");
  697. NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
  698. SGA->getName(), DAliasee, Dest);
  699. CopyGVAttributes(NewGA, SGA);
  700. // Any uses of DGV need to change to NewGA, with cast, if needed.
  701. if (SGA->getType() != DGVar->getType())
  702. DGVar->replaceAllUsesWith(Context.getConstantExprBitCast(NewGA,
  703. DGVar->getType()));
  704. else
  705. DGVar->replaceAllUsesWith(NewGA);
  706. // DGVar will conflict with NewGA because they both had the same
  707. // name. We must erase this now so ForceRenaming doesn't assert
  708. // because DGV might not have internal linkage.
  709. DGVar->eraseFromParent();
  710. // Proceed to 'common' steps
  711. } else
  712. return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
  713. "': symbol multiple defined");
  714. } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
  715. // The only allowed way is to link alias with external declaration or weak
  716. // symbol...
  717. if (DF->isDeclaration() || DF->isWeakForLinker()) {
  718. // But only if aliasee is function too...
  719. if (!isa<Function>(DAliasee))
  720. return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
  721. "': aliasee is not function");
  722. NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
  723. SGA->getName(), DAliasee, Dest);
  724. CopyGVAttributes(NewGA, SGA);
  725. // Any uses of DF need to change to NewGA, with cast, if needed.
  726. if (SGA->getType() != DF->getType())
  727. DF->replaceAllUsesWith(Context.getConstantExprBitCast(NewGA,
  728. DF->getType()));
  729. else
  730. DF->replaceAllUsesWith(NewGA);
  731. // DF will conflict with NewGA because they both had the same
  732. // name. We must erase this now so ForceRenaming doesn't assert
  733. // because DF might not have internal linkage.
  734. DF->eraseFromParent();
  735. // Proceed to 'common' steps
  736. } else
  737. return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
  738. "': symbol multiple defined");
  739. } else {
  740. // No linking to be performed, simply create an identical version of the
  741. // alias over in the dest module...
  742. NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
  743. SGA->getName(), DAliasee, Dest);
  744. CopyGVAttributes(NewGA, SGA);
  745. // Proceed to 'common' steps
  746. }
  747. assert(NewGA && "No alias was created in destination module!");
  748. // If the symbol table renamed the alias, but it is an externally visible
  749. // symbol, DGA must be an global value with internal linkage. Rename it.
  750. if (NewGA->getName() != SGA->getName() &&
  751. !NewGA->hasLocalLinkage())
  752. ForceRenaming(NewGA, SGA->getName());
  753. // Remember this mapping so uses in the source module get remapped
  754. // later by RemapOperand.
  755. ValueMap[SGA] = NewGA;
  756. }
  757. return false;
  758. }
  759. // LinkGlobalInits - Update the initializers in the Dest module now that all
  760. // globals that may be referenced are in Dest.
  761. static bool LinkGlobalInits(Module *Dest, const Module *Src,
  762. std::map<const Value*, Value*> &ValueMap,
  763. std::string *Err) {
  764. // Loop over all of the globals in the src module, mapping them over as we go
  765. for (Module::const_global_iterator I = Src->global_begin(),
  766. E = Src->global_end(); I != E; ++I) {
  767. const GlobalVariable *SGV = I;
  768. if (SGV->hasInitializer()) { // Only process initialized GV's
  769. // Figure out what the initializer looks like in the dest module...
  770. Constant *SInit =
  771. cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap,
  772. Dest->getContext()));
  773. // Grab destination global variable or alias.
  774. GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
  775. // If dest if global variable, check that initializers match.
  776. if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
  777. if (DGVar->hasInitializer()) {
  778. if (SGV->hasExternalLinkage()) {
  779. if (DGVar->getInitializer() != SInit)
  780. return Error(Err, "Global Variable Collision on '" +
  781. SGV->getName() +
  782. "': global variables have different initializers");
  783. } else if (DGVar->isWeakForLinker()) {
  784. // Nothing is required, mapped values will take the new global
  785. // automatically.
  786. } else if (SGV->isWeakForLinker()) {
  787. // Nothing is required, mapped values will take the new global
  788. // automatically.
  789. } else if (DGVar->hasAppendingLinkage()) {
  790. LLVM_UNREACHABLE("Appending linkage unimplemented!");
  791. } else {
  792. LLVM_UNREACHABLE("Unknown linkage!");
  793. }
  794. } else {
  795. // Copy the initializer over now...
  796. DGVar->setInitializer(SInit);
  797. }
  798. } else {
  799. // Destination is alias, the only valid situation is when source is
  800. // weak. Also, note, that we already checked linkage in LinkGlobals(),
  801. // thus we assert here.
  802. // FIXME: Should we weaken this assumption, 'dereference' alias and
  803. // check for initializer of aliasee?
  804. assert(SGV->isWeakForLinker());
  805. }
  806. }
  807. }
  808. return false;
  809. }
  810. // LinkFunctionProtos - Link the functions together between the two modules,
  811. // without doing function bodies... this just adds external function prototypes
  812. // to the Dest function...
  813. //
  814. static bool LinkFunctionProtos(Module *Dest, const Module *Src,
  815. std::map<const Value*, Value*> &ValueMap,
  816. std::string *Err) {
  817. ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
  818. LLVMContext &Context = Dest->getContext();
  819. // Loop over all of the functions in the src module, mapping them over
  820. for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
  821. const Function *SF = I; // SrcFunction
  822. GlobalValue *DGV = 0;
  823. // Check to see if may have to link the function with the global, alias or
  824. // function.
  825. if (SF->hasName() && !SF->hasLocalLinkage())
  826. DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getNameStart(),
  827. SF->getNameEnd()));
  828. // If we found a global with the same name in the dest module, but it has
  829. // internal linkage, we are really not doing any linkage here.
  830. if (DGV && DGV->hasLocalLinkage())
  831. DGV = 0;
  832. // If types don't agree due to opaque types, try to resolve them.
  833. if (DGV && DGV->getType() != SF->getType())
  834. RecursiveResolveTypes(SF->getType(), DGV->getType());
  835. GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
  836. bool LinkFromSrc = false;
  837. if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
  838. return true;
  839. // If there is no linkage to be performed, just bring over SF without
  840. // modifying it.
  841. if (DGV == 0) {
  842. // Function does not already exist, simply insert an function signature
  843. // identical to SF into the dest module.
  844. Function *NewDF = Function::Create(SF->getFunctionType(),
  845. SF->getLinkage(),
  846. SF->getName(), Dest);
  847. CopyGVAttributes(NewDF, SF);
  848. // If the LLVM runtime renamed the function, but it is an externally
  849. // visible symbol, DF must be an existing function with internal linkage.
  850. // Rename it.
  851. if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
  852. ForceRenaming(NewDF, SF->getName());
  853. // ... and remember this mapping...
  854. ValueMap[SF] = NewDF;
  855. continue;
  856. }
  857. // If the visibilities of the symbols disagree and the destination is a
  858. // prototype, take the visibility of its input.
  859. if (DGV->isDeclaration())
  860. DGV->setVisibility(SF->getVisibility());
  861. if (LinkFromSrc) {
  862. if (isa<GlobalAlias>(DGV))
  863. return Error(Err, "Function-Alias Collision on '" + SF->getName() +
  864. "': symbol multiple defined");
  865. // We have a definition of the same name but different type in the
  866. // source module. Copy the prototype to the destination and replace
  867. // uses of the destination's prototype with the new prototype.
  868. Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
  869. SF->getName(), Dest);
  870. CopyGVAttributes(NewDF, SF);
  871. // Any uses of DF need to change to NewDF, with cast
  872. DGV->replaceAllUsesWith(Context.getConstantExprBitCast(NewDF,
  873. DGV->getType()));
  874. // DF will conflict with NewDF because they both had the same. We must
  875. // erase this now so ForceRenaming doesn't assert because DF might
  876. // not have internal linkage.
  877. if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
  878. Var->eraseFromParent();
  879. else
  880. cast<Function>(DGV)->eraseFromParent();
  881. // If the symbol table renamed the function, but it is an externally
  882. // visible symbol, DF must be an existing function with internal
  883. // linkage. Rename it.
  884. if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
  885. ForceRenaming(NewDF, SF->getName());
  886. // Remember this mapping so uses in the source module get remapped
  887. // later by RemapOperand.
  888. ValueMap[SF] = NewDF;
  889. continue;
  890. }
  891. // Not "link from source", keep the one in the DestModule and remap the
  892. // input onto it.
  893. if (isa<GlobalAlias>(DGV)) {
  894. // The only valid mappings are:
  895. // - SF is external declaration, which is effectively a no-op.
  896. // - SF is weak, when we just need to throw SF out.
  897. if (!SF->isDeclaration() && !SF->isWeakForLinker())
  898. return Error(Err, "Function-Alias Collision on '" + SF->getName() +
  899. "': symbol multiple defined");
  900. }
  901. // Set calculated linkage
  902. DGV->setLinkage(NewLinkage);
  903. // Make sure to remember this mapping.
  904. ValueMap[SF] = Context.getConstantExprBitCast(DGV, SF->getType());
  905. }
  906. return false;
  907. }
  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. static bool LinkFunctionBody(Function *Dest, Function *Src,
  912. std::map<const Value*, Value*> &ValueMap,
  913. std::string *Err) {
  914. assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
  915. // Go through and convert function arguments over, remembering the mapping.
  916. Function::arg_iterator DI = Dest->arg_begin();
  917. for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
  918. I != E; ++I, ++DI) {
  919. DI->setName(I->getName()); // Copy the name information over...
  920. // Add a mapping to our local map
  921. ValueMap[I] = DI;
  922. }
  923. // Splice the body of the source function into the dest function.
  924. Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
  925. // At this point, all of the instructions and values of the function are now
  926. // copied over. The only problem is that they are still referencing values in
  927. // the Source function as operands. Loop through all of the operands of the
  928. // functions and patch them up to point to the local versions...
  929. //
  930. for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
  931. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  932. for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
  933. OI != OE; ++OI)
  934. if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
  935. *OI = RemapOperand(*OI, ValueMap, *Dest->getContext());
  936. // There is no need to map the arguments anymore.
  937. for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
  938. I != E; ++I)
  939. ValueMap.erase(I);
  940. return false;
  941. }
  942. // LinkFunctionBodies - Link in the function bodies that are defined in the
  943. // source module into the DestModule. This consists basically of copying the
  944. // function over and fixing up references to values.
  945. static bool LinkFunctionBodies(Module *Dest, Module *Src,
  946. std::map<const Value*, Value*> &ValueMap,
  947. std::string *Err) {
  948. // Loop over all of the functions in the src module, mapping them over as we
  949. // go
  950. for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
  951. if (!SF->isDeclaration()) { // No body if function is external
  952. Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
  953. // DF not external SF external?
  954. if (DF && DF->isDeclaration())
  955. // Only provide the function body if there isn't one already.
  956. if (LinkFunctionBody(DF, SF, ValueMap, Err))
  957. return true;
  958. }
  959. }
  960. return false;
  961. }
  962. // LinkAppendingVars - If there were any appending global variables, link them
  963. // together now. Return true on error.
  964. static bool LinkAppendingVars(Module *M,
  965. std::multimap<std::string, GlobalVariable *> &AppendingVars,
  966. std::string *ErrorMsg) {
  967. if (AppendingVars.empty()) return false; // Nothing to do.
  968. LLVMContext &Context = M->getContext();
  969. // Loop over the multimap of appending vars, processing any variables with the
  970. // same name, forming a new appending global variable with both of the
  971. // initializers merged together, then rewrite references to the old variables
  972. // and delete them.
  973. std::vector<Constant*> Inits;
  974. while (AppendingVars.size() > 1) {
  975. // Get the first two elements in the map...
  976. std::multimap<std::string,
  977. GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
  978. // If the first two elements are for different names, there is no pair...
  979. // Otherwise there is a pair, so link them together...
  980. if (First->first == Second->first) {
  981. GlobalVariable *G1 = First->second, *G2 = Second->second;
  982. const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
  983. const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
  984. // Check to see that they two arrays agree on type...
  985. if (T1->getElementType() != T2->getElementType())
  986. return Error(ErrorMsg,
  987. "Appending variables with different element types need to be linked!");
  988. if (G1->isConstant() != G2->isConstant())
  989. return Error(ErrorMsg,
  990. "Appending variables linked with different const'ness!");
  991. if (G1->getAlignment() != G2->getAlignment())
  992. return Error(ErrorMsg,
  993. "Appending variables with different alignment need to be linked!");
  994. if (G1->getVisibility() != G2->getVisibility())
  995. return Error(ErrorMsg,
  996. "Appending variables with different visibility need to be linked!");
  997. if (G1->getSection() != G2->getSection())
  998. return Error(ErrorMsg,
  999. "Appending variables with different section name need to be linked!");
  1000. unsigned NewSize = T1->getNumElements() + T2->getNumElements();
  1001. ArrayType *NewType = Context.getArrayType(T1->getElementType(),
  1002. NewSize);
  1003. G1->setName(""); // Clear G1's name in case of a conflict!
  1004. // Create the new global variable...
  1005. GlobalVariable *NG =
  1006. new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
  1007. /*init*/0, First->first, 0, G1->isThreadLocal(),
  1008. G1->getType()->getAddressSpace());
  1009. // Propagate alignment, visibility and section info.
  1010. CopyGVAttributes(NG, G1);
  1011. // Merge the initializer...
  1012. Inits.reserve(NewSize);
  1013. if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
  1014. for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
  1015. Inits.push_back(I->getOperand(i));
  1016. } else {
  1017. assert(isa<ConstantAggregateZero>(G1->getInitializer()));
  1018. Constant *CV = Context.getNullValue(T1->getElementType());
  1019. for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
  1020. Inits.push_back(CV);
  1021. }
  1022. if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
  1023. for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
  1024. Inits.push_back(I->getOperand(i));
  1025. } else {
  1026. assert(isa<ConstantAggregateZero>(G2->getInitializer()));
  1027. Constant *CV = Context.getNullValue(T2->getElementType());
  1028. for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
  1029. Inits.push_back(CV);
  1030. }
  1031. NG->setInitializer(Context.getConstantArray(NewType, Inits));
  1032. Inits.clear();
  1033. // Replace any uses of the two global variables with uses of the new
  1034. // global...
  1035. // FIXME: This should rewrite simple/straight-forward uses such as
  1036. // getelementptr instructions to not use the Cast!
  1037. G1->replaceAllUsesWith(Context.getConstantExprBitCast(NG,
  1038. G1->getType()));
  1039. G2->replaceAllUsesWith(Context.getConstantExprBitCast(NG,
  1040. G2->getType()));
  1041. // Remove the two globals from the module now...
  1042. M->getGlobalList().erase(G1);
  1043. M->getGlobalList().erase(G2);
  1044. // Put the new global into the AppendingVars map so that we can handle
  1045. // linking of more than two vars...
  1046. Second->second = NG;
  1047. }
  1048. AppendingVars.erase(First);
  1049. }
  1050. return false;
  1051. }
  1052. static bool ResolveAliases(Module *Dest) {
  1053. for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
  1054. I != E; ++I)
  1055. if (const GlobalValue *GV = I->resolveAliasedGlobal())
  1056. if (GV != I && !GV->isDeclaration())
  1057. I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
  1058. return false;
  1059. }
  1060. // LinkModules - This function links two modules together, with the resulting
  1061. // left module modified to be the composite of the two input modules. If an
  1062. // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
  1063. // the problem. Upon failure, the Dest module could be in a modified state, and
  1064. // shouldn't be relied on to be consistent.
  1065. bool
  1066. Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
  1067. assert(Dest != 0 && "Invalid Destination module");
  1068. assert(Src != 0 && "Invalid Source Module");
  1069. if (Dest->getDataLayout().empty()) {
  1070. if (!Src->getDataLayout().empty()) {
  1071. Dest->setDataLayout(Src->getDataLayout());
  1072. } else {
  1073. std::string DataLayout;
  1074. if (Dest->getEndianness() == Module::AnyEndianness) {
  1075. if (Src->getEndianness() == Module::BigEndian)
  1076. DataLayout.append("E");
  1077. else if (Src->getEndianness() == Module::LittleEndian)
  1078. DataLayout.append("e");
  1079. }
  1080. if (Dest->getPointerSize() == Module::AnyPointerSize) {
  1081. if (Src->getPointerSize() == Module::Pointer64)
  1082. DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
  1083. else if (Src->getPointerSize() == Module::Pointer32)
  1084. DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
  1085. }
  1086. Dest->setDataLayout(DataLayout);
  1087. }
  1088. }
  1089. // Copy the target triple from the source to dest if the dest's is empty.
  1090. if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
  1091. Dest->setTargetTriple(Src->getTargetTriple());
  1092. if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
  1093. Src->getDataLayout() != Dest->getDataLayout())
  1094. cerr << "WARNING: Linking two modules of different data layouts!\n";
  1095. if (!Src->getTargetTriple().empty() &&
  1096. Dest->getTargetTriple() != Src->getTargetTriple())
  1097. cerr << "WARNING: Linking two modules of different target triples!\n";
  1098. // Append the module inline asm string.
  1099. if (!Src->getModuleInlineAsm().empty()) {
  1100. if (Dest->getModuleInlineAsm().empty())
  1101. Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
  1102. else
  1103. Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
  1104. Src->getModuleInlineAsm());
  1105. }
  1106. // Update the destination module's dependent libraries list with the libraries
  1107. // from the source module. There's no opportunity for duplicates here as the
  1108. // Module ensures that duplicate insertions are discarded.
  1109. for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
  1110. SI != SE; ++SI)
  1111. Dest->addLibrary(*SI);
  1112. // LinkTypes - Go through the symbol table of the Src module and see if any
  1113. // types are named in the src module that are not named in the Dst module.
  1114. // Make sure there are no type name conflicts.
  1115. if (LinkTypes(Dest, Src, ErrorMsg))
  1116. return true;
  1117. // ValueMap - Mapping of values from what they used to be in Src, to what they
  1118. // are now in Dest.
  1119. std::map<const Value*, Value*> ValueMap;
  1120. // AppendingVars - Keep track of global variables in the destination module
  1121. // with appending linkage. After the module is linked together, they are
  1122. // appended and the module is rewritten.
  1123. std::multimap<std::string, GlobalVariable *> AppendingVars;
  1124. for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
  1125. I != E; ++I) {
  1126. // Add all of the appending globals already in the Dest module to
  1127. // AppendingVars.
  1128. if (I->hasAppendingLinkage())
  1129. AppendingVars.insert(std::make_pair(I->getName(), I));
  1130. }
  1131. // Insert all of the globals in src into the Dest module... without linking
  1132. // initializers (which could refer to functions not yet mapped over).
  1133. if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
  1134. return true;
  1135. // Link the functions together between the two modules, without doing function
  1136. // bodies... this just adds external function prototypes to the Dest
  1137. // function... We do this so that when we begin processing function bodies,
  1138. // all of the global values that may be referenced are available in our
  1139. // ValueMap.
  1140. if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
  1141. return true;
  1142. // If there were any alias, link them now. We really need to do this now,
  1143. // because all of the aliases that may be referenced need to be available in
  1144. // ValueMap
  1145. if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
  1146. // Update the initializers in the Dest module now that all globals that may
  1147. // be referenced are in Dest.
  1148. if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
  1149. // Link in the function bodies that are defined in the source module into the
  1150. // DestModule. This consists basically of copying the function over and
  1151. // fixing up references to values.
  1152. if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
  1153. // If there were any appending global variables, link them together now.
  1154. if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
  1155. // Resolve all uses of aliases with aliasees
  1156. if (ResolveAliases(Dest)) return true;
  1157. // If the source library's module id is in the dependent library list of the
  1158. // destination library, remove it since that module is now linked in.
  1159. sys::Path modId;
  1160. modId.set(Src->getModuleIdentifier());
  1161. if (!modId.isEmpty())
  1162. Dest->removeLibrary(modId.getBasename());
  1163. return false;
  1164. }
  1165. // vim: sw=2